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