Reorg E step 3/9
[openmx:openmx.git] / src / omxExpectationBA81.cpp
1 /*
2   Copyright 2012-2013 Joshua Nathaniel Pritikin and contributors
3
4   This is free software: you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation, either version 3 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License
15   along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <valarray>
19 #include <Rmath.h>
20
21 #include "omxExpectationBA81.h"
22 #include "glue.h"
23 #include "libifa-rpf.h"
24 #include "dmvnorm.h"
25
26 const struct rpf *rpf_model = NULL;
27 int rpf_numModels;
28
29 void pda(const double *ar, int rows, int cols)
30 {
31         std::string buf;
32         for (int rx=0; rx < rows; rx++) {   // column major order
33                 for (int cx=0; cx < cols; cx++) {
34                         buf += string_snprintf("%.6g, ", ar[cx * rows + rx]);
35                 }
36                 buf += "\n";
37         }
38         mxLogBig(buf);
39 }
40
41 void pia(const int *ar, int rows, int cols)
42 {
43         std::string buf;
44         for (int rx=0; rx < rows; rx++) {   // column major order
45                 for (int cx=0; cx < cols; cx++) {
46                         buf += string_snprintf("%d, ", ar[cx * rows + rx]);
47                 }
48                 buf += "\n";
49         }
50         mxLogBig(buf);
51 }
52
53 // state->speQarea[sIndex(state, sx, qx)]
54 OMXINLINE static
55 int sIndex(BA81Expect *state, int sx, int qx)
56 {
57         //if (sx < 0 || sx >= state->numSpecific) error("Out of domain");
58         //if (qx < 0 || qx >= state->quadGridSize) error("Out of domain");
59         return sx * state->quadGridSize + qx;
60 }
61
62 // Depends on item parameters, but not latent distribution
63 void computeRPF(BA81Expect *state, omxMatrix *itemParam, const int *quad,
64                 const bool wantlog, double *out)
65 {
66         omxMatrix *design = state->design;
67         int maxDims = state->maxDims;
68         size_t numItems = state->itemSpec.size();
69
70         double theta[maxDims];
71         pointToWhere(state, quad, theta, maxDims);
72
73         for (size_t ix=0; ix < numItems; ix++) {
74                 const double *spec = state->itemSpec[ix];
75                 int id = spec[RPF_ISpecID];
76                 int dims = spec[RPF_ISpecDims];
77                 double ptheta[dims];
78
79                 for (int dx=0; dx < dims; dx++) {
80                         int ability = (int)omxMatrixElement(design, dx, ix) - 1;
81                         if (ability >= maxDims) ability = maxDims-1;
82                         ptheta[dx] = theta[ability];
83                 }
84
85                 double *iparam = omxMatrixColumn(itemParam, ix);
86                 if (wantlog) {
87                         (*rpf_model[id].logprob)(spec, iparam, ptheta, out);
88                 } else {
89                         (*rpf_model[id].prob)(spec, iparam, ptheta, out);
90                 }
91 #if 0
92                 for (int ox=0; ox < state->itemOutcomes[ix]; ox++) {
93                         if (!isfinite(out[ox]) || out[ox] > 0) {
94                                 mxLog("item param");
95                                 pda(iparam, itemParam->rows, 1);
96                                 mxLog("where");
97                                 pda(ptheta, dims, 1);
98                                 error("RPF returned %20.20f", out[ox]);
99                         }
100                 }
101 #endif
102                 out += state->itemOutcomes[ix];
103         }
104 }
105
106 OMXINLINE static double *
107 getLXKcache(BA81Expect *state, const long qx, const int specific)
108 {
109         long ordinate;
110         if (state->numSpecific == 0) {
111                 ordinate = qx;
112         } else {
113                 ordinate = specific * state->totalQuadPoints + qx;
114         }
115         return state->lxk + state->numUnique * ordinate;
116 }
117
118 OMXINLINE static double *
119 ba81Likelihood(omxExpectation *oo, const int thrId, int specific, const long qx)
120 {
121         BA81Expect *state = (BA81Expect*) oo->argStruct;
122         int numUnique = state->numUnique;
123         std::vector<int> &itemOutcomes = state->itemOutcomes;
124         omxData *data = state->data;
125         size_t numItems = state->itemSpec.size();
126         int *Sgroup = state->Sgroup;
127         double *lxk;
128
129         if (!state->cacheLXK) {
130                 lxk = state->lxk + numUnique * thrId;
131         } else {
132                 lxk = getLXKcache(state, qx, specific);
133         }
134
135         const int *rowMap = state->rowMap;
136         for (int px=0; px < numUnique; px++) {
137                 double lxk1 = 1;
138                 const double *oProb = state->outcomeProb + qx * state->totalOutcomes;
139                 for (size_t ix=0; ix < numItems; ix++) {
140                         int pick = omxIntDataElementUnsafe(data, rowMap[px], ix);
141                         if (specific == Sgroup[ix] && pick != NA_INTEGER) {
142                                 double piece = oProb[pick-1];  // move -1 elsewhere TODO
143                                 lxk1 *= piece;
144                                 //mxLog("%d pick %d piece %.7f", ix, pick-1, piece);
145                         }
146                         oProb += itemOutcomes[ix];
147                 }
148                 lxk[px] = lxk1;
149         }
150
151         return lxk;
152 }
153
154 double *ba81LikelihoodFast(omxExpectation *oo, const int thrId, int specific, const long qx)
155 {
156         BA81Expect *state = (BA81Expect*) oo->argStruct;
157         if (!state->cacheLXK) {
158                 double *ret = ba81Likelihood(oo, thrId, specific, qx);
159                 return ret;
160         } else {
161                 return getLXKcache(state, qx, specific);
162         }
163
164 }
165
166 OMXINLINE static void
167 mapLatentSpace(BA81Expect *state, int sgroup, double piece, const double *where,
168                const double *whereGram, double *latentDist)
169 {
170         int maxDims = state->maxDims;
171         int maxAbilities = state->maxAbilities;
172         int pmax = maxDims;
173         if (state->numSpecific) pmax -= 1;
174
175         if (sgroup == 0) {
176                 int gx = 0;
177                 int cx = maxAbilities;
178                 for (int d1=0; d1 < pmax; d1++) {
179                         double piece_w1 = piece * where[d1];
180                         latentDist[d1] += piece_w1;
181                         for (int d2=0; d2 <= d1; d2++) {
182                                 double piece_cov = piece * whereGram[gx];
183                                 latentDist[cx] += piece_cov;
184                                 ++cx; ++gx;
185                         }
186                 }
187         }
188
189         if (state->numSpecific) {
190                 int sdim = pmax + sgroup;
191                 double piece_w1 = piece * where[pmax];
192                 latentDist[sdim] += piece_w1;
193
194                 double piece_var = piece * whereGram[triangleLoc0(pmax)];
195                 int to = maxAbilities + triangleLoc0(sdim);
196                 latentDist[to] += piece_var;
197         }
198 }
199
200 // Eslxk, allElxk (Ei, Eis) depend on the ordinate of the primary dimensions
201 void cai2010(omxExpectation* oo, const int thrId, int recompute, const long primaryQ)
202 {
203         BA81Expect *state = (BA81Expect*) oo->argStruct;
204         int numUnique = state->numUnique;
205         int numSpecific = state->numSpecific;
206         int quadGridSize = state->quadGridSize;
207         double *allElxk = eBase(state, thrId);
208         double *Eslxk = esBase(state, thrId);
209
210         for (int px=0; px < numUnique; px++) {
211                 allElxk[px] = 1;
212                 for (int sx=0; sx < numSpecific; sx++) {
213                         Eslxk[sx * numUnique + px] = 0;
214                 }
215         }
216
217         if (!state->cacheLXK) recompute = TRUE;
218
219         for (int sx=0; sx < quadGridSize; sx++) {
220                 long qloc = primaryQ * quadGridSize + sx;
221
222                 for (int sgroup=0; sgroup < numSpecific; sgroup++) {
223                         double *myEslxk = Eslxk + sgroup * numUnique;
224                         double *lxk;     // a.k.a. "L_is"
225                         if (recompute) {
226                                 lxk = ba81Likelihood(oo, thrId, sgroup, qloc);
227                         } else {
228                                 lxk = getLXKcache(state, qloc, sgroup);
229                         }
230
231                         for (int ix=0; ix < numUnique; ix++) {
232                                 double area = state->speQarea[sIndex(state, sgroup, sx)];
233                                 double piece = lxk[ix] * area;
234                                 //mxLog("E.is(%d) (%ld,%d) %.6f + %.6f = %.6f",
235                                 //  sgroup, primaryQ, sx, lxk[ix], area, piece);
236                                 myEslxk[ix] += piece;
237                         }
238                 }
239         }
240
241         for (int sx=0; sx < numSpecific; sx++) {
242                 for (int px=0; px < numUnique; px++) {
243                         //mxLog("E.is(%d) at (%ld) %.6f", sx, primaryQ,
244                         //  Eslxk[sx * numUnique + px]);
245                         allElxk[px] *= Eslxk[sx * numUnique + px];  // allSlxk a.k.a. "E_i"
246                 }
247         }
248 }
249
250 static void ba81OutcomeProb(BA81Expect *state)
251 {
252         int maxDims = state->maxDims;
253         double *qProb = state->outcomeProb =
254                 Realloc(state->outcomeProb, state->totalOutcomes * state->totalQuadPoints, double);
255         for (long qx=0; qx < state->totalQuadPoints; qx++) {
256                 int quad[maxDims];
257                 decodeLocation(qx, maxDims, state->quadGridSize, quad);
258                 double where[maxDims];
259                 pointToWhere(state, quad, where, maxDims);
260                 computeRPF(state, state->EitemParam, quad, FALSE, qProb);
261                 qProb += state->totalOutcomes;
262         }
263 }
264
265 static void ba81Estep1(omxExpectation *oo)
266 {
267         if(OMX_DEBUG) {mxLog("Beginning %s Computation.", oo->name);}
268
269         BA81Expect *state = (BA81Expect*) oo->argStruct;
270         if (state->verbose) {
271                 mxLog("%s: lxk(%d) patternLik ElatentMean ElatentCov",
272                       oo->name, omxGetMatrixVersion(state->EitemParam));
273         }
274
275         int numUnique = state->numUnique;
276         size_t numItems = state->itemSpec.size();
277         int numSpecific = state->numSpecific;
278         int maxDims = state->maxDims;
279         int maxAbilities = state->maxAbilities;
280         int primaryDims = maxDims;
281         int totalOutcomes = state->totalOutcomes;
282         omxData *data = state->data;
283         int *numIdentical = state->numIdentical;
284         long totalQuadPoints = state->totalQuadPoints;
285
286         state->patternLik = Realloc(state->patternLik, numUnique, double);
287         double *patternLik = state->patternLik;
288         std::vector<double> thrExpected(totalOutcomes * totalQuadPoints * Global->numThreads);
289
290         int numLatents = maxAbilities + triangleLoc1(maxAbilities);
291         int numLatentsPerThread = numUnique * numLatents;
292         double *latentDist = Calloc(numUnique * numLatents * Global->numThreads, double);
293
294         const int *rowMap = state->rowMap;
295         std::vector<int> &itemOutcomes = state->itemOutcomes;
296
297         int whereChunk = maxDims + triangleLoc1(maxDims);
298         std::vector<double> wherePrep(totalQuadPoints * whereChunk);
299         for (long qx=0; qx < totalQuadPoints; qx++) {
300                 double *wh = wherePrep.data() + qx * whereChunk;
301                 int quad[maxDims];
302                 decodeLocation(qx, maxDims, state->quadGridSize, quad);
303                 pointToWhere(state, quad, wh, maxDims);
304                 gramProduct(wh, maxDims, wh + maxDims);
305         }
306
307         if (numSpecific == 0) {
308 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,32)
309                 for (int px=0; px < numUnique; px++) {
310                         int thrId = omx_absolute_thread_num();
311                         double *thrLatentDist = latentDist + thrId * numLatentsPerThread;
312                         double *myExpected = thrExpected.data() + thrId * totalOutcomes * totalQuadPoints;
313
314                         std::valarray<double> lxk(1, totalQuadPoints);
315                         int outcomeBase = -itemOutcomes[0];
316
317                         for (size_t ix=0; ix < numItems; ix++) {
318                                 outcomeBase += itemOutcomes[ix];
319                                 int pick = omxIntDataElementUnsafe(data, rowMap[px], ix);
320                                 if (pick == NA_INTEGER) continue;
321                                 pick -= 1;
322
323                                 double *oProb = state->outcomeProb + outcomeBase;
324                                 for (long qx=0; qx < totalQuadPoints; ++qx) {
325                                         lxk[qx] *= oProb[pick];
326                                         oProb += totalOutcomes;
327                                 }
328                         }
329                         
330                         double *lxkCache = state->cacheLXK? state->lxk + px : NULL;
331                         double patternLik1 = 0;
332                         double *wh = wherePrep.data();
333                         for (long qx=0; qx < totalQuadPoints; qx++) {
334                                 double area = state->priQarea[qx];
335                                 double tmp = lxk[qx] * area;
336                                 patternLik1 += tmp;
337                                 mapLatentSpace(state, 0, tmp, wh, wh + maxDims,
338                                                thrLatentDist + px * numLatents);
339
340                                 if (lxkCache) {
341                                         *lxkCache = lxk[qx];
342                                         lxkCache += numUnique;
343                                 }
344                                 wh += whereChunk;
345                         }
346
347                         patternLik[px] = patternLik1;
348                         double weight = numIdentical[px] / patternLik1;
349
350                         outcomeBase = -itemOutcomes[0];
351                         for (size_t ix=0; ix < numItems; ix++) {
352                                 outcomeBase += itemOutcomes[ix];
353                                 int pick = omxIntDataElementUnsafe(data, rowMap[px], ix);
354                                 if (pick == NA_INTEGER) continue;
355                                 pick -= 1;
356
357                                 double *out = myExpected + outcomeBase;
358                                 for (long qx=0; qx < totalQuadPoints; ++qx) {
359                                         out[pick] += weight * lxk[qx];
360                                         out += totalOutcomes;
361                                 }
362                         }
363                 }
364         } else {
365                 primaryDims -= 1;
366                 long totalPrimaryPoints = state->totalPrimaryPoints;
367                 long specificPoints = state->quadGridSize;
368
369 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,32)
370                 for (int px=0; px < numUnique; px++) {
371                         int thrId = omx_absolute_thread_num();
372                         double *thrLatentDist = latentDist + thrId * numLatentsPerThread;
373                         double *myExpected = thrExpected.data() + thrId * totalOutcomes * totalQuadPoints;
374
375                         std::valarray<double> lxk(1, totalQuadPoints * numSpecific);
376                         int outcomeBase = -itemOutcomes[0];
377
378                         for (size_t ix=0; ix < numItems; ix++) {
379                                 outcomeBase += itemOutcomes[ix];
380                                 int pick = omxIntDataElementUnsafe(data, rowMap[px], ix);
381                                 if (pick == NA_INTEGER) continue;
382                                 pick -= 1;
383                                 int Sbase = state->Sgroup[ix] * totalQuadPoints;
384                                 double *oProb = state->outcomeProb + outcomeBase;
385                                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
386                                         lxk[Sbase + qx] *= oProb[pick];
387                                         oProb += totalOutcomes;
388                                 }
389                         }
390
391                         std::valarray<double> Eis(0.0, totalPrimaryPoints * numSpecific);
392                         std::valarray<double> Ei(1.0, totalPrimaryPoints);
393                         for (int sgroup=0, Sbase=0; sgroup < numSpecific; ++sgroup, Sbase += totalQuadPoints) {
394                                 long qloc = 0;
395                                 for (long qx=0; qx < totalPrimaryPoints; qx++) {
396                                         for (long sx=0; sx < specificPoints; sx++) {
397                                                 double area = state->speQarea[sIndex(state, sgroup, sx)];
398                                                 double piece = lxk[Sbase + qloc] * area;
399                                                 Eis[totalPrimaryPoints * sgroup + qx] += piece;
400                                                 ++qloc;
401                                         }
402                                         Ei[qx] *= Eis[totalPrimaryPoints * sgroup + qx];
403                                 }
404                         }
405
406                         double patternLik1 = 0;
407                         double *wh = wherePrep.data();
408                         for (long qx=0, qloc=0; qx < totalPrimaryPoints; ++qx) {
409                                 double priArea = state->priQarea[qx];
410                                 double EiArea = Ei[qx] * priArea;
411                                 patternLik1 += EiArea;
412                                 for (long sx=0; sx < specificPoints; sx++) {
413                                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
414                                                 double area = state->speQarea[sgroup * specificPoints + sx];
415                                                 double lxk1 = lxk[totalQuadPoints * sgroup + qloc];
416                                                 double Eis1 = Eis[totalPrimaryPoints * sgroup + qx];
417                                                 double tmp = (EiArea / Eis1) * lxk1 * area;
418                                                 mapLatentSpace(state, sgroup, tmp, wh, wh + maxDims,
419                                                                thrLatentDist + px * numLatents);
420                                                 if (state->cacheLXK) {
421                                                         double *lxkCache = getLXKcache(state, qloc, sgroup);
422                                                         lxkCache[px] = lxk1;
423                                                 }
424                                         }
425                                         wh += whereChunk;
426                                         ++qloc;
427                                 }
428                         }
429
430                         patternLik[px] = patternLik1;
431                         double weight = numIdentical[px] / patternLik1;
432
433                         outcomeBase = -itemOutcomes[0];
434                         for (size_t ix=0; ix < numItems; ix++) {
435                                 outcomeBase += itemOutcomes[ix];
436                                 int pick = omxIntDataElementUnsafe(data, rowMap[px], ix);
437                                 if (pick == NA_INTEGER) continue;
438                                 pick -= 1;
439
440                                 int Sgroup = state->Sgroup[ix];
441
442                                 double *out = myExpected + outcomeBase;
443                                 long qloc = 0;
444                                 for (long qx=0; qx < totalPrimaryPoints; qx++) {
445                                         double Ei1 = Ei[qx];
446                                         for (long sx=0; sx < specificPoints; sx++) {
447                                                 long qloc = qx * specificPoints + sx; // change to ++
448                                                 double *out = myExpected + qloc * totalOutcomes + outcomeBase;
449                                                 double lxk1 = lxk[totalQuadPoints * Sgroup + qloc];
450                                                 double Eis1 = Eis[totalPrimaryPoints * Sgroup + qx];
451                                                 out[pick] += weight * (Ei1 / Eis1) * lxk1;
452                                                 //out += totalOutcomes;
453                                         }
454                                 }
455                         }
456                 }
457         }
458
459         long expectedSize = totalQuadPoints * totalOutcomes;
460 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,64)
461         for (long qx=0; qx < expectedSize; ++qx) {
462                 state->expected[qx] = 0;
463                 double *e1 = thrExpected.data() + qx;
464                 for (int tx=0; tx < Global->numThreads; ++tx) {
465                         state->expected[qx] += *e1;
466                         e1 += expectedSize;
467                 }
468         }
469
470         //mxLog("raw latent");
471         //pda(latentDist, numLatents, numUnique);
472
473 #pragma omp parallel for num_threads(Global->numThreads) schedule(dynamic)
474         for (int lx=0; lx < maxAbilities + triangleLoc1(primaryDims); ++lx) {
475                 for (int tx=1; tx < Global->numThreads; ++tx) {
476                         double *thrLatentDist = latentDist + tx * numLatentsPerThread;
477                         for (int px=0; px < numUnique; px++) {
478                                 int loc = px * numLatents + lx;
479                                 latentDist[loc] += thrLatentDist[loc];
480                         }
481                 }
482         }
483
484 #pragma omp parallel for num_threads(Global->numThreads)
485         for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
486                 for (int tx=1; tx < Global->numThreads; ++tx) {
487                         double *thrLatentDist = latentDist + tx * numLatentsPerThread;
488                         for (int px=0; px < numUnique; px++) {
489                                 int loc = px * numLatents + maxAbilities + triangleLoc0(sdim);
490                                 latentDist[loc] += thrLatentDist[loc];
491                         }
492                 }
493         }
494
495 #pragma omp parallel for num_threads(Global->numThreads)
496         for (int px=0; px < numUnique; px++) {
497                 if (!std::isfinite(patternLik[px])) {
498                         omxRaiseErrorf(globalState, "Likelihood of pattern %d is %.3g",
499                                        px, patternLik[px]);
500                 }
501
502                 double *latentDist1 = latentDist + px * numLatents;
503                 double weight = numIdentical[px] / patternLik[px];
504                 int cx = maxAbilities;
505                 for (int d1=0; d1 < primaryDims; d1++) {
506                         latentDist1[d1] *= weight;
507                         for (int d2=0; d2 <= d1; d2++) {
508                                 latentDist1[cx] *= weight;
509                                 ++cx;
510                         }
511                 }
512                 for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
513                         latentDist1[sdim] *= weight;
514                         int loc = maxAbilities + triangleLoc0(sdim);
515                         latentDist1[loc] *= weight;
516                 }
517 #if 0
518                 if (!isfinite(patternLik[px])) {
519                         error("Likelihood of row %d is %f", state->rowMap[px], patternLik[px]);
520                 }
521 #endif
522         }
523
524         //mxLog("raw latent after weighting");
525         //pda(latentDist, numLatents, numUnique);
526
527         std::vector<double> &ElatentMean = state->ElatentMean;
528         std::vector<double> &ElatentCov = state->ElatentCov;
529         
530         ElatentMean.assign(ElatentMean.size(), 0.0);
531         ElatentCov.assign(ElatentCov.size(), 0.0);
532
533 #pragma omp parallel for num_threads(Global->numThreads)
534         for (int d1=0; d1 < maxAbilities; d1++) {
535                 for (int px=0; px < numUnique; px++) {
536                         double *latentDist1 = latentDist + px * numLatents;
537                         int cx = maxAbilities + triangleLoc1(d1);
538                         if (d1 < primaryDims) {
539                                 ElatentMean[d1] += latentDist1[d1];
540                                 for (int d2=0; d2 <= d1; d2++) {
541                                         int cell = d2 * maxAbilities + d1;
542                                         ElatentCov[cell] += latentDist1[cx];
543                                         ++cx;
544                                 }
545                         } else {
546                                 ElatentMean[d1] += latentDist1[d1];
547                                 int cell = d1 * maxAbilities + d1;
548                                 int loc = maxAbilities + triangleLoc0(d1);
549                                 ElatentCov[cell] += latentDist1[loc];
550                         }
551                 }
552         }
553
554         //pda(ElatentMean.data(), 1, state->maxAbilities);
555         //pda(ElatentCov.data(), state->maxAbilities, state->maxAbilities);
556
557         for (int d1=0; d1 < maxAbilities; d1++) {
558                 ElatentMean[d1] /= data->rows;
559         }
560
561         for (int d1=0; d1 < primaryDims; d1++) {
562                 for (int d2=0; d2 <= d1; d2++) {
563                         int cell = d2 * maxAbilities + d1;
564                         int tcell = d1 * maxAbilities + d2;
565                         ElatentCov[tcell] = ElatentCov[cell] =
566                                 ElatentCov[cell] / data->rows - ElatentMean[d1] * ElatentMean[d2];
567                 }
568         }
569         for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
570                 int cell = sdim * maxAbilities + sdim;
571                 ElatentCov[cell] = ElatentCov[cell] / data->rows - ElatentMean[sdim] * ElatentMean[sdim];
572         }
573
574         if (state->cacheLXK) state->LXKcached = TRUE;
575
576         Free(latentDist);
577
578         //mxLog("E-step");
579         //pda(ElatentMean.data(), 1, state->maxAbilities);
580         //pda(ElatentCov.data(), state->maxAbilities, state->maxAbilities);
581 }
582
583 static int getLatentVersion(BA81Expect *state)
584 {
585         return omxGetMatrixVersion(state->latentMeanOut) + omxGetMatrixVersion(state->latentCovOut);
586 }
587
588 // Attempt G-H grid? http://dbarajassolano.wordpress.com/2012/01/26/on-sparse-grid-quadratures/
589 static void ba81SetupQuadrature(omxExpectation* oo, int gridsize)
590 {
591         BA81Expect *state = (BA81Expect *) oo->argStruct;
592         if (state->verbose) {
593                 mxLog("%s: quadrature(%d)", oo->name, getLatentVersion(state));
594         }
595         int numUnique = state->numUnique;
596         int numThreads = Global->numThreads;
597         int maxDims = state->maxDims;
598         double Qwidth = state->Qwidth;
599         int numSpecific = state->numSpecific;
600         int priDims = maxDims - (numSpecific? 1 : 0);
601
602         // try starting small and increasing to the cap TODO
603         state->quadGridSize = gridsize;
604
605         state->totalQuadPoints = 1;
606         for (int dx=0; dx < maxDims; dx++) {
607                 state->totalQuadPoints *= state->quadGridSize;
608         }
609
610         state->totalPrimaryPoints = state->totalQuadPoints;
611
612         if (numSpecific) {
613                 state->totalPrimaryPoints /= state->quadGridSize;
614                 state->speQarea.resize(gridsize * numSpecific);
615         }
616
617         state->Qpoint.resize(gridsize);
618         state->priQarea.resize(state->totalPrimaryPoints);
619
620         double qgs = state->quadGridSize-1;
621         for (int px=0; px < state->quadGridSize; px ++) {
622                 state->Qpoint[px] = Qwidth - px * 2 * Qwidth / qgs;
623         }
624
625         //pda(state->latentMeanOut->data, 1, state->maxAbilities);
626         //pda(state->latentCovOut->data, state->maxAbilities, state->maxAbilities);
627
628         double totalArea = 0;
629         for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
630                 int quad[priDims];
631                 decodeLocation(qx, priDims, state->quadGridSize, quad);
632                 double where[priDims];
633                 pointToWhere(state, quad, where, priDims);
634                 state->priQarea[qx] = exp(dmvnorm(priDims, where,
635                                                   state->latentMeanOut->data,
636                                                   state->latentCovOut->data));
637                 totalArea += state->priQarea[qx];
638         }
639         for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
640                 state->priQarea[qx] /= totalArea;
641                 //mxLog("%.5g,", state->priQarea[qx]);
642         }
643
644         for (int sx=0; sx < numSpecific; sx++) {
645                 totalArea = 0;
646                 int covCell = (priDims + sx) * state->maxAbilities + priDims + sx;
647                 double mean = state->latentMeanOut->data[priDims + sx];
648                 double var = state->latentCovOut->data[covCell];
649                 //mxLog("setup[%d] %.2f %.2f", sx, mean, var);
650                 for (int qx=0; qx < state->quadGridSize; qx++) {
651                         double den = dnorm(state->Qpoint[qx], mean, sqrt(var), FALSE);
652                         state->speQarea[sIndex(state, sx, qx)] = den;
653                         totalArea += den;
654                 }
655                 for (int qx=0; qx < state->quadGridSize; qx++) {
656                         state->speQarea[sIndex(state, sx, qx)] /= totalArea;
657                 }
658                 //pda(state->speQarea.data() + sIndex(state, sx, 0), 1, state->quadGridSize);
659         }
660
661         if (!state->cacheLXK) {
662                 state->lxk = Realloc(state->lxk, numUnique * numThreads, double);
663         } else {
664                 int ns = state->numSpecific;
665                 if (ns == 0) ns = 1;
666                 long numOrdinate = ns * state->totalQuadPoints;
667                 state->lxk = Realloc(state->lxk, numUnique * numOrdinate, double);
668         }
669
670         state->expected = Realloc(state->expected, state->totalOutcomes * state->totalQuadPoints, double);
671 }
672
673 static void ba81buildLXKcache(omxExpectation *oo)
674 {
675         BA81Expect *state = (BA81Expect *) oo->argStruct;
676         if (!state->cacheLXK || state->LXKcached) return;
677         
678         ba81Estep1(oo);
679 }
680
681 OMXINLINE static void
682 expectedUpdate(omxData *data, const int *rowMap, const int px, const int item,
683                const double observed, double *out)
684 {
685         int pick = omxIntDataElementUnsafe(data, rowMap[px], item);
686         if (pick != NA_INTEGER) {
687                 out[pick-1] += observed;
688         }
689 }
690
691 OMXINLINE static void
692 ba81Expected(omxExpectation* oo)
693 {
694         BA81Expect *state = (BA81Expect*) oo->argStruct;
695         if (state->verbose) mxLog("%s: EM.expected", oo->name);
696
697         omxData *data = state->data;
698         int numSpecific = state->numSpecific;
699         const int *rowMap = state->rowMap;
700         double *patternLik = state->patternLik;
701         int *numIdentical = state->numIdentical;
702         int numUnique = state->numUnique;
703         int numItems = state->EitemParam->cols;
704         int totalOutcomes = state->totalOutcomes;
705         std::vector<int> &itemOutcomes = state->itemOutcomes;
706
707         OMXZERO(state->expected, totalOutcomes * state->totalQuadPoints);
708
709         if (numSpecific == 0) {
710 #pragma omp parallel for num_threads(Global->numThreads)
711                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
712                         int thrId = omx_absolute_thread_num();
713                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, qx);
714                         for (int px=0; px < numUnique; px++) {
715                                 double *out = state->expected + qx * totalOutcomes;
716                                 double observed = numIdentical[px] * lxk[px] / patternLik[px];
717                                 for (int ix=0; ix < numItems; ix++) {
718                                         const int outcomes = itemOutcomes[ix];
719                                         expectedUpdate(data, rowMap, px, ix, observed, out);
720                                         out += outcomes;
721                                 }
722                         }
723                 }
724         } else {
725                 long specificPoints = state->quadGridSize;
726
727 #pragma omp parallel for num_threads(Global->numThreads)
728                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
729                         int thrId = omx_absolute_thread_num();
730
731                         cai2010(oo, thrId, FALSE, qx);
732                         double *allElxk = eBase(state, thrId);
733                         double *Eslxk = esBase(state, thrId);
734
735                         for (long sx=0; sx < specificPoints; sx++) {
736                                 long qloc = qx * specificPoints + sx;
737
738                                 for (int sgroup=0; sgroup < numSpecific; sgroup++) {
739                                         double *lxk = ba81LikelihoodFast(oo, thrId, sgroup, qloc);
740                                         double *myEslxk = Eslxk + sgroup * numUnique;
741
742                                         for (int px=0; px < numUnique; px++) {
743                                                 double *out = state->expected + totalOutcomes * qloc;
744
745                                                 for (int ix=0; ix < numItems; ix++) {
746                                                         const int outcomes = itemOutcomes[ix];
747                                                         if (state->Sgroup[ix] == sgroup) {
748                                                                 double Ei = allElxk[px];
749                                                                 double Eis = myEslxk[px];
750                                                                 double observed = (numIdentical[px] * (Ei / Eis) *
751                                                                                    (lxk[px] / patternLik[px]));
752                                                                 expectedUpdate(data, rowMap, px, ix, observed, out);
753                                                         }
754                                                         out += outcomes;
755                                                 }
756                                         }
757                                 }
758                         }
759                 }
760         }
761
762         if (!state->checkedBadData) {
763                 std::vector<double> byOutcome(totalOutcomes, 0);
764                 for (int ox=0; ox < totalOutcomes; ++ox) {
765                         for (long qx=0; qx < state->totalQuadPoints; qx++) {
766                                 byOutcome[ox] += state->expected[totalOutcomes * qx + ox];
767                         }
768                         if (byOutcome[ox] == 0) {
769                                 int uptoItem = 0;
770                                 for (size_t cx = 0; cx < itemOutcomes.size(); cx++) {
771                                         if (ox < uptoItem + itemOutcomes[cx]) {
772                                                 int bad = ox - uptoItem;
773                                                 omxRaiseErrorf(globalState, "Item %lu outcome %d is never endorsed.\n"
774                                                                "You must collapse categories or omit this item to estimate item parameters.", 1+cx, 1+bad);
775                                                 break;
776                                         }
777                                         uptoItem += itemOutcomes[cx];
778                                 }
779                         }
780                 }
781                 state->checkedBadData = TRUE;
782         }
783         //pda(state->expected, state->totalOutcomes, state->totalQuadPoints);
784 }
785
786 OMXINLINE static void
787 accumulateScores(BA81Expect *state, int px, int sgroup, double piece, const double *where,
788                  int primaryDims, int covEntries, std::vector<double> *mean, std::vector<double> *cov)
789 {
790         int maxDims = state->maxDims;
791         int maxAbilities = state->maxAbilities;
792
793         if (sgroup == 0) {
794                 int cx=0;
795                 for (int d1=0; d1 < primaryDims; d1++) {
796                         double piece_w1 = piece * where[d1];
797                         double &dest1 = (*mean)[px * maxAbilities + d1];
798 #pragma omp atomic
799                         dest1 += piece_w1;
800                         for (int d2=0; d2 <= d1; d2++) {
801                                 double &dest2 = (*cov)[px * covEntries + cx];
802 #pragma omp atomic
803                                 dest2 += where[d2] * piece_w1;
804                                 ++cx;
805                         }
806                 }
807         }
808
809         if (state->numSpecific) {
810                 int sdim = maxDims + sgroup - 1;
811                 double piece_w1 = piece * where[primaryDims];
812                 double &dest3 = (*mean)[px * maxAbilities + sdim];
813 #pragma omp atomic
814                 dest3 += piece_w1;
815
816                 double &dest4 = (*cov)[px * covEntries + triangleLoc0(sdim)];
817 #pragma omp atomic
818                 dest4 += piece_w1 * where[primaryDims];
819         }
820 }
821
822 static void
823 EAPinternalFast(omxExpectation *oo, std::vector<double> *mean, std::vector<double> *cov)
824 {
825         BA81Expect *state = (BA81Expect*) oo->argStruct;
826         if (state->verbose) mxLog("%s: EAP", oo->name);
827
828         int numUnique = state->numUnique;
829         int numSpecific = state->numSpecific;
830         int maxDims = state->maxDims;
831         int maxAbilities = state->maxAbilities;
832         int primaryDims = maxDims;
833         int covEntries = triangleLoc1(maxAbilities);
834
835         mean->assign(numUnique * maxAbilities, 0);
836         cov->assign(numUnique * covEntries, 0);
837
838         if (numSpecific == 0) {
839 #pragma omp parallel for num_threads(Global->numThreads)
840                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
841                         const int thrId = omx_absolute_thread_num();
842                         int quad[maxDims];
843                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
844                         double where[maxDims];
845                         pointToWhere(state, quad, where, maxDims);
846
847                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, qx);
848
849                         double area = state->priQarea[qx];
850                         for (int px=0; px < numUnique; px++) {
851                                 double tmp = lxk[px] * area;
852                                 accumulateScores(state, px, 0, tmp, where, primaryDims, covEntries, mean, cov);
853                         }
854                 }
855         } else {
856                 primaryDims -= 1;
857                 int sDim = primaryDims;
858                 long specificPoints = state->quadGridSize;
859
860 #pragma omp parallel for num_threads(Global->numThreads)
861                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
862                         const int thrId = omx_absolute_thread_num();
863                         int quad[maxDims];
864                         decodeLocation(qx, primaryDims, state->quadGridSize, quad);
865
866                         cai2010(oo, thrId, FALSE, qx);
867                         double *allElxk = eBase(state, thrId);
868                         double *Eslxk = esBase(state, thrId);
869
870                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
871                                 for (long sx=0; sx < specificPoints; sx++) {
872                                         long qloc = qx * specificPoints + sx;
873                                         quad[sDim] = sx;
874                                         double where[maxDims];
875                                         pointToWhere(state, quad, where, maxDims);
876                                         double area = areaProduct(state, qx, sx, sgroup);
877                                         double *lxk = ba81LikelihoodFast(oo, thrId, sgroup, qloc);
878                                         for (int px=0; px < numUnique; px++) {
879                                                 double Ei = allElxk[px];
880                                                 double Eis = Eslxk[sgroup * numUnique + px];
881                                                 double tmp = ((Ei / Eis) * lxk[px] * area);
882                                                 accumulateScores(state, px, sgroup, tmp, where, primaryDims,
883                                                                  covEntries, mean, cov);
884                                         }
885                                 }
886                         }
887                 }
888         }
889
890         double *patternLik = state->patternLik;
891         for (int px=0; px < numUnique; px++) {
892                 double denom = patternLik[px];
893                 for (int ax=0; ax < maxAbilities; ax++) {
894                         (*mean)[px * maxAbilities + ax] /= denom;
895                 }
896                 for (int cx=0; cx < triangleLoc1(primaryDims); ++cx) {
897                         (*cov)[px * covEntries + cx] /= denom;
898                 }
899                 for (int sx=0; sx < numSpecific; sx++) {
900                         (*cov)[px * covEntries + triangleLoc0(primaryDims + sx)] /= denom;
901                 }
902                 int cx=0;
903                 for (int a1=0; a1 < primaryDims; ++a1) {
904                         for (int a2=0; a2 <= a1; ++a2) {
905                                 double ma1 = (*mean)[px * maxAbilities + a1];
906                                 double ma2 = (*mean)[px * maxAbilities + a2];
907                                 (*cov)[px * covEntries + cx] -= ma1 * ma2;
908                                 ++cx;
909                         }
910                 }
911                 for (int sx=0; sx < numSpecific; sx++) {
912                         int sdim = primaryDims + sx;
913                         double ma1 = (*mean)[px * maxAbilities + sdim];
914                         (*cov)[px * covEntries + triangleLoc0(sdim)] -= ma1 * ma1;
915                 }
916         }
917 }
918
919 static void recomputePatternLik(omxExpectation *oo)  // openmp reduction TODO
920 {
921         BA81Expect *estate = (BA81Expect*) oo->argStruct;
922         if (estate->verbose) mxLog("%s: patternLik", oo->name);
923
924         int numUnique = estate->numUnique;
925         int numSpecific = estate->numSpecific;
926         int maxDims = estate->maxDims;
927         int primaryDims = maxDims;
928         double *patternLik = estate->patternLik;
929         OMXZERO(patternLik, numUnique);
930
931         if (numSpecific == 0) {
932 #pragma omp parallel for num_threads(Global->numThreads)
933                 for (long qx=0; qx < estate->totalQuadPoints; qx++) {
934                         const int thrId = omx_absolute_thread_num();
935                         double area = estate->priQarea[qx];
936                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, qx);
937
938                         for (int px=0; px < numUnique; px++) {
939                                 double tmp = (lxk[px] * area);
940 #pragma omp atomic
941                                 patternLik[px] += tmp;
942                         }
943                 }
944         } else {
945                 primaryDims -= 1;
946
947 #pragma omp parallel for num_threads(Global->numThreads)
948                 for (long qx=0; qx < estate->totalPrimaryPoints; qx++) {
949                         const int thrId = omx_absolute_thread_num();
950
951                         cai2010(oo, thrId, FALSE, qx);
952                         double *allElxk = eBase(estate, thrId);
953
954                         double priArea = estate->priQarea[qx];
955                         for (int px=0; px < numUnique; px++) {
956                                 double Ei = allElxk[px];
957                                 double tmp = (Ei * priArea);
958 #pragma omp atomic
959                                 patternLik[px] += tmp;
960                         }
961                 }
962         }
963 }
964
965 static void
966 ba81compute(omxExpectation *oo, const char *context)
967 {
968         BA81Expect *state = (BA81Expect *) oo->argStruct;
969
970         if (context) {
971                 if (strcmp(context, "EM")==0) {
972                         state->type = EXPECTATION_AUGMENTED;
973                 } else if (context[0] == 0) {
974                         state->type = EXPECTATION_OBSERVED;
975                 } else {
976                         omxRaiseErrorf(globalState, "Unknown context '%s'", context);
977                         return;
978                 }
979         }
980
981         omxRecompute(state->EitemParam);
982
983         bool itemClean = state->itemParamVersion == omxGetMatrixVersion(state->EitemParam);
984         bool latentClean = state->latentParamVersion == getLatentVersion(state);
985
986         if (state->verbose) {
987                 mxLog("%s: Qinit %d itemClean %d latentClean %d (1=clean)",
988                       oo->name, state->Qpoint.size() != 0, itemClean, latentClean);
989         }
990
991         if (state->Qpoint.size() == 0 || !latentClean) {
992                 ba81SetupQuadrature(oo, state->targetQpoints);
993         }
994         if (itemClean) {
995                 ba81buildLXKcache(oo);
996                 if (!latentClean) recomputePatternLik(oo);
997         } else {
998                 ba81OutcomeProb(state);
999                 ba81Estep1(oo);
1000         }
1001
1002         if (state->type == EXPECTATION_AUGMENTED) {
1003                 //ba81Expected(oo);
1004         }
1005
1006         state->itemParamVersion = omxGetMatrixVersion(state->EitemParam);
1007         state->latentParamVersion = getLatentVersion(state);
1008 }
1009
1010 static void
1011 copyScore(int rows, int maxAbilities, std::vector<double> &mean,
1012           std::vector<double> &cov, const int rx, double *scores, const int dest)
1013 {
1014         for (int ax=0; ax < maxAbilities; ++ax) {
1015                 scores[rows * ax + dest] = mean[maxAbilities * rx + ax];
1016         }
1017         for (int ax=0; ax < maxAbilities; ++ax) {
1018                 scores[rows * (maxAbilities + ax) + dest] =
1019                         sqrt(cov[triangleLoc1(maxAbilities) * rx + triangleLoc0(ax)]);
1020         }
1021         for (int ax=0; ax < triangleLoc1(maxAbilities); ++ax) {
1022                 scores[rows * (2*maxAbilities + ax) + dest] =
1023                         cov[triangleLoc1(maxAbilities) * rx + ax];
1024         }
1025 }
1026
1027 /**
1028  * MAP is not affected by the number of items. EAP is. Likelihood can
1029  * get concentrated in a single quadrature ordinate. For 3PL, response
1030  * patterns can have a bimodal likelihood. This will confuse MAP and
1031  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
1032  *
1033  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
1034  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
1035  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
1036  */
1037 static void
1038 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
1039 {
1040         BA81Expect *state = (BA81Expect *) oo->argStruct;
1041         int maxAbilities = state->maxAbilities;
1042
1043         SEXP Rmean, Rcov;
1044         PROTECT(Rmean = allocVector(REALSXP, maxAbilities));
1045         memcpy(REAL(Rmean), state->ElatentMean.data(), maxAbilities * sizeof(double));
1046
1047         PROTECT(Rcov = allocMatrix(REALSXP, maxAbilities, maxAbilities));
1048         memcpy(REAL(Rcov), state->ElatentCov.data(), maxAbilities * maxAbilities * sizeof(double));
1049
1050         setAttrib(robj, install("empirical.mean"), Rmean);
1051         setAttrib(robj, install("empirical.cov"), Rcov);
1052
1053         if (state->type == EXPECTATION_AUGMENTED) {
1054                 int numUnique = state->numUnique;
1055                 int totalOutcomes = state->totalOutcomes;
1056                 SEXP Rlik;
1057                 SEXP Rexpected;
1058
1059                 PROTECT(Rlik = allocVector(REALSXP, numUnique));
1060                 memcpy(REAL(Rlik), state->patternLik, sizeof(double) * numUnique);
1061
1062                 PROTECT(Rexpected = allocMatrix(REALSXP, totalOutcomes, state->totalQuadPoints));
1063                 memcpy(REAL(Rexpected), state->expected, sizeof(double) * totalOutcomes * state->totalQuadPoints);
1064
1065                 setAttrib(robj, install("patternLikelihood"), Rlik);
1066                 setAttrib(robj, install("em.expected"), Rexpected);
1067         }
1068
1069         if (state->scores == SCORES_OMIT || state->type == EXPECTATION_UNINITIALIZED) return;
1070
1071         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
1072         // model. Journal of Educational Statistics, 12, 339-368.
1073
1074         /*
1075         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
1076
1077         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
1078                 // Thissen & Orlando (2001, p. 136)
1079                 warning("EAP requires at least 2*sqrt(items) quadrature points");
1080         }
1081
1082         ba81SetupQuadrature(oo, numQpoints, 0);
1083         ba81Estep1(oo);
1084         */
1085
1086         std::vector<double> mean;
1087         std::vector<double> cov;
1088         EAPinternalFast(oo, &mean, &cov);
1089
1090         int numUnique = state->numUnique;
1091         omxData *data = state->data;
1092         int rows = state->scores == SCORES_FULL? data->rows : numUnique;
1093         int cols = 2 * maxAbilities + triangleLoc1(maxAbilities);
1094         SEXP Rscores;
1095         PROTECT(Rscores = allocMatrix(REALSXP, rows, cols));
1096         double *scores = REAL(Rscores);
1097
1098         const int SMALLBUF = 10;
1099         char buf[SMALLBUF];
1100         SEXP names;
1101         PROTECT(names = allocVector(STRSXP, cols));
1102         for (int nx=0; nx < maxAbilities; ++nx) {
1103                 snprintf(buf, SMALLBUF, "s%d", nx+1);
1104                 SET_STRING_ELT(names, nx, mkChar(buf));
1105                 snprintf(buf, SMALLBUF, "se%d", nx+1);
1106                 SET_STRING_ELT(names, maxAbilities + nx, mkChar(buf));
1107         }
1108         for (int nx=0; nx < triangleLoc1(maxAbilities); ++nx) {
1109                 snprintf(buf, SMALLBUF, "cov%d", nx+1);
1110                 SET_STRING_ELT(names, maxAbilities*2 + nx, mkChar(buf));
1111         }
1112         SEXP dimnames;
1113         PROTECT(dimnames = allocVector(VECSXP, 2));
1114         SET_VECTOR_ELT(dimnames, 1, names);
1115         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
1116
1117         if (state->scores == SCORES_FULL) {
1118 #pragma omp parallel for num_threads(Global->numThreads)
1119                 for (int rx=0; rx < numUnique; rx++) {
1120                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
1121                         for (int dup=0; dup < dups; dup++) {
1122                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
1123                                 copyScore(rows, maxAbilities, mean, cov, rx, scores, dest);
1124                         }
1125                 }
1126         } else {
1127 #pragma omp parallel for num_threads(Global->numThreads)
1128                 for (int rx=0; rx < numUnique; rx++) {
1129                         copyScore(rows, maxAbilities, mean, cov, rx, scores, rx);
1130                 }
1131         }
1132
1133         setAttrib(robj, install("scores.out"), Rscores);
1134 }
1135
1136 static void ba81Destroy(omxExpectation *oo) {
1137         if(OMX_DEBUG) {
1138                 mxLog("Freeing %s function.", oo->name);
1139         }
1140         BA81Expect *state = (BA81Expect *) oo->argStruct;
1141         omxFreeAllMatrixData(state->EitemParam);
1142         omxFreeAllMatrixData(state->design);
1143         omxFreeAllMatrixData(state->latentMeanOut);
1144         omxFreeAllMatrixData(state->latentCovOut);
1145         omxFreeAllMatrixData(state->customPrior);
1146         omxFreeAllMatrixData(state->itemParam);
1147         Free(state->numIdentical);
1148         Free(state->rowMap);
1149         Free(state->patternLik);
1150         Free(state->lxk);
1151         Free(state->Eslxk);
1152         Free(state->allElxk);
1153         Free(state->Sgroup);
1154         Free(state->expected);
1155         Free(state->outcomeProb);
1156         delete state;
1157 }
1158
1159 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
1160 {
1161     SEXP matrixDims;
1162     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
1163     int *dimList = INTEGER(matrixDims);
1164     *rows = dimList[0];
1165     *cols = dimList[1];
1166     UNPROTECT(1);
1167 }
1168
1169 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
1170 {}
1171
1172 void omxInitExpectationBA81(omxExpectation* oo) {
1173         omxState* currentState = oo->currentState;      
1174         SEXP rObj = oo->rObj;
1175         SEXP tmp;
1176         
1177         if(OMX_DEBUG) {
1178                 mxLog("Initializing %s.", oo->name);
1179         }
1180         if (!rpf_model) {
1181                 if (0) {
1182                         const int wantVersion = 3;
1183                         int version;
1184                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
1185                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
1186                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
1187                                                          version, wantVersion);
1188                 } else {
1189                         rpf_numModels = librpf_numModels;
1190                         rpf_model = librpf_model;
1191                 }
1192         }
1193         
1194         BA81Expect *state = new BA81Expect;
1195         state->checkedBadData = FALSE;
1196         state->numSpecific = 0;
1197         state->numIdentical = NULL;
1198         state->rowMap = NULL;
1199         state->design = NULL;
1200         state->lxk = NULL;
1201         state->patternLik = NULL;
1202         state->Eslxk = NULL;
1203         state->allElxk = NULL;
1204         state->outcomeProb = NULL;
1205         state->expected = NULL;
1206         state->type = EXPECTATION_UNINITIALIZED;
1207         state->scores = SCORES_OMIT;
1208         state->itemParam = NULL;
1209         state->customPrior = NULL;
1210         state->itemParamVersion = 0;
1211         state->latentParamVersion = 0;
1212         oo->argStruct = (void*) state;
1213
1214         PROTECT(tmp = GET_SLOT(rObj, install("data")));
1215         state->data = omxDataLookupFromState(tmp, currentState);
1216
1217         if (strcmp(omxDataType(state->data), "raw") != 0) {
1218                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", oo->name, omxDataType(state->data));
1219                 return;
1220         }
1221
1222         PROTECT(tmp = GET_SLOT(rObj, install("ItemSpec")));
1223         for (int sx=0; sx < length(tmp); ++sx) {
1224                 SEXP model = VECTOR_ELT(tmp, sx);
1225                 if (!OBJECT(model)) {
1226                         error("Item models must inherit rpf.base");
1227                 }
1228                 SEXP spec;
1229                 PROTECT(spec = GET_SLOT(model, install("spec")));
1230                 state->itemSpec.push_back(REAL(spec));
1231         }
1232
1233         PROTECT(tmp = GET_SLOT(rObj, install("design")));
1234         if (!isNull(tmp)) {
1235                 // better to demand integers and not coerce to real TODO
1236                 state->design = omxNewMatrixFromRPrimitive(tmp, globalState, FALSE, 0);
1237         }
1238
1239         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean");
1240         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
1241         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
1242         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
1243
1244         state->EitemParam =
1245                 omxNewMatrixFromSlot(rObj, currentState, "EItemParam");
1246         if (!state->EitemParam) error("Must supply EItemParam");
1247
1248         state->itemParam =
1249                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
1250
1251         if (state->EitemParam->rows != state->itemParam->rows ||
1252             state->EitemParam->cols != state->itemParam->cols) {
1253                 error("ItemParam and EItemParam must be of the same dimension");
1254         }
1255
1256         oo->computeFun = ba81compute;
1257         oo->setVarGroup = ignoreSetVarGroup;
1258         oo->destructFun = ba81Destroy;
1259         oo->populateAttrFun = ba81PopulateAttributes;
1260         
1261         // TODO: Exactly identical rows do not contribute any information.
1262         // The sorting algorithm ought to remove them so we don't waste RAM.
1263         // The following summary stats would be cheaper to calculate too.
1264
1265         int numUnique = 0;
1266         omxData *data = state->data;
1267         if (omxDataNumFactor(data) != data->cols) {
1268                 // verify they are ordered factors TODO
1269                 omxRaiseErrorf(currentState, "%s: all columns must be factors", oo->name);
1270                 return;
1271         }
1272
1273         for (int rx=0; rx < data->rows;) {
1274                 rx += omxDataNumIdenticalRows(state->data, rx);
1275                 ++numUnique;
1276         }
1277         state->numUnique = numUnique;
1278
1279         state->rowMap = Realloc(NULL, numUnique, int);
1280         state->numIdentical = Realloc(NULL, numUnique, int);
1281
1282         state->customPrior =
1283                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
1284         
1285         int numItems = state->EitemParam->cols;
1286         if (data->cols != numItems) {
1287                 error("Data has %d columns for %d items", data->cols, numItems);
1288         }
1289
1290         for (int rx=0, ux=0; rx < data->rows; ux++) {
1291                 if (rx == 0) {
1292                         // all NA rows will sort to the top
1293                         int na=0;
1294                         for (int ix=0; ix < numItems; ix++) {
1295                                 if (omxIntDataElement(data, 0, ix) == NA_INTEGER) { ++na; }
1296                         }
1297                         if (na == numItems) {
1298                                 omxRaiseErrorf(currentState, "Remove rows with all NAs");
1299                                 return;
1300                         }
1301                 }
1302                 int dups = omxDataNumIdenticalRows(state->data, rx);
1303                 state->numIdentical[ux] = dups;
1304                 state->rowMap[ux] = rx;
1305                 rx += dups;
1306         }
1307
1308         int numThreads = Global->numThreads;
1309
1310         int maxSpec = 0;
1311         int maxParam = 0;
1312         state->maxDims = 0;
1313
1314         std::vector<int> &itemOutcomes = state->itemOutcomes;
1315         itemOutcomes.resize(numItems);
1316         int totalOutcomes = 0;
1317         for (int cx = 0; cx < data->cols; cx++) {
1318                 const double *spec = state->itemSpec[cx];
1319                 int id = spec[RPF_ISpecID];
1320                 int dims = spec[RPF_ISpecDims];
1321                 if (state->maxDims < dims)
1322                         state->maxDims = dims;
1323
1324                 int no = spec[RPF_ISpecOutcomes];
1325                 itemOutcomes[cx] = no;
1326                 totalOutcomes += no;
1327
1328                 // TODO this summary stat should be available from omxData
1329                 int dataMax=0;
1330                 for (int rx=0; rx < data->rows; rx++) {
1331                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1332                         if (dataMax < pick)
1333                                 dataMax = pick;
1334                 }
1335                 if (dataMax > no) {
1336                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1337                 } else if (dataMax < no) {
1338                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1339                         // promote to error?
1340                         // should complain if an outcome is not represented in the data TODO
1341                 }
1342
1343                 int numSpec = (*rpf_model[id].numSpec)(spec);
1344                 if (maxSpec < numSpec)
1345                         maxSpec = numSpec;
1346
1347                 int numParam = (*rpf_model[id].numParam)(spec);
1348                 if (maxParam < numParam)
1349                         maxParam = numParam;
1350         }
1351
1352         state->totalOutcomes = totalOutcomes;
1353
1354         if (int(state->itemSpec.size()) != data->cols) {
1355                 omxRaiseErrorf(currentState, "ItemSpec must contain %d item model specifications",
1356                                data->cols);
1357                 return;
1358         }
1359         if (state->EitemParam->rows != maxParam) {
1360                 omxRaiseErrorf(currentState, "ItemParam should have %d rows", maxParam);
1361                 return;
1362         }
1363
1364         if (state->design == NULL) {
1365                 state->maxAbilities = state->maxDims;
1366                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1367                                        TRUE, currentState);
1368                 for (int ix=0; ix < numItems; ix++) {
1369                         const double *spec = state->itemSpec[ix];
1370                         int dims = spec[RPF_ISpecDims];
1371                         for (int dx=0; dx < state->maxDims; dx++) {
1372                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1373                         }
1374                 }
1375         } else {
1376                 omxMatrix *design = state->design;
1377                 if (design->cols != numItems ||
1378                     design->rows != state->maxDims) {
1379                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1380                                        state->maxDims, numItems);
1381                         return;
1382                 }
1383
1384                 state->maxAbilities = 0;
1385                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1386                         double got = design->data[ix];
1387                         if (!R_FINITE(got)) continue;
1388                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1389                         if (state->maxAbilities < got)
1390                                 state->maxAbilities = got;
1391                 }
1392                 for (int ix=0; ix < design->cols; ix++) {
1393                         const double *idesign = omxMatrixColumn(design, ix);
1394                         int ddim = 0;
1395                         for (int rx=0; rx < design->rows; rx++) {
1396                                 if (std::isfinite(idesign[rx])) ddim += 1;
1397                         }
1398                         const double *spec = state->itemSpec[ix];
1399                         int dims = spec[RPF_ISpecDims];
1400                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1401                 }
1402         }
1403         if (state->maxAbilities <= state->maxDims) {
1404                 state->Sgroup = Calloc(numItems, int);
1405         } else {
1406                 // Not sure if this is correct, revisit TODO
1407                 int Sgroup0 = -1;
1408                 state->Sgroup = Realloc(NULL, numItems, int);
1409                 for (int dx=0; dx < state->maxDims; dx++) {
1410                         for (int ix=0; ix < numItems; ix++) {
1411                                 int ability = omxMatrixElement(state->design, dx, ix);
1412                                 if (dx < state->maxDims - 1) {
1413                                         if (Sgroup0 <= ability)
1414                                                 Sgroup0 = ability+1;
1415                                         continue;
1416                                 }
1417                                 int ss=-1;
1418                                 if (ability >= Sgroup0) {
1419                                         if (ss == -1) {
1420                                                 ss = ability;
1421                                         } else {
1422                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1423                                                                "1 specific dimension (both %d and %d)",
1424                                                                ix, ss, ability);
1425                                                 return;
1426                                         }
1427                                 }
1428                                 if (ss == -1) ss = Sgroup0;
1429                                 state->Sgroup[ix] = ss - Sgroup0;
1430                         }
1431                 }
1432                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1433                 state->allElxk = Realloc(NULL, numUnique * numThreads, double);
1434                 state->Eslxk = Realloc(NULL, numUnique * state->numSpecific * numThreads, double);
1435         }
1436
1437         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1438                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1439                       state->maxAbilities, state->maxAbilities);
1440         }
1441         if (state->latentCovOut->rows != state->maxAbilities ||
1442             state->latentCovOut->cols != state->maxAbilities) {
1443                 error("The cov matrix '%s' must be %dx%d",
1444                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1445         }
1446
1447         PROTECT(tmp = GET_SLOT(rObj, install("verbose")));
1448         state->verbose = asLogical(tmp);
1449
1450         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1451         state->cacheLXK = asLogical(tmp);
1452         state->LXKcached = FALSE;
1453
1454         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1455         state->targetQpoints = asReal(tmp);
1456
1457         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1458         state->Qwidth = asReal(tmp);
1459
1460         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1461         const char *score_option = CHAR(asChar(tmp));
1462         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1463         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1464         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1465
1466         state->ElatentMean.resize(state->maxAbilities);
1467         state->ElatentCov.resize(state->maxAbilities * state->maxAbilities);
1468
1469         // verify data bounded between 1 and numOutcomes TODO
1470         // hm, looks like something could be added to omxData for column summary stats?
1471 }