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