Reorg E step 6/9
[openmx:openmx.git] / src / omxExpectationBA81.cpp
1 /*
2   Copyright 2012-2013 Joshua Nathaniel Pritikin and contributors
3
4   This is free software: you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation, either version 3 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License
15   along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <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 ba81Likelihood(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 *ba81LikelihoodFast(omxExpectation *oo, const int thrId, int specific, const long qx)
154 {
155         BA81Expect *state = (BA81Expect*) oo->argStruct;
156         if (!state->cacheLXK) {
157                 double *ret = ba81Likelihood(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 = ba81Likelihood(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         if (state->verbose) {
367                 mxLog("%s: lxk(%d) patternLik ElatentMean ElatentCov",
368                       oo->name, omxGetMatrixVersion(state->EitemParam));
369         }
370
371         int numUnique = state->numUnique;
372         int numSpecific = state->numSpecific;
373         int maxDims = state->maxDims;
374         int maxAbilities = state->maxAbilities;
375         int primaryDims = maxDims;
376         int totalOutcomes = state->totalOutcomes;
377         omxData *data = state->data;
378         int *numIdentical = state->numIdentical;
379         long totalQuadPoints = state->totalQuadPoints;
380
381         state->patternLik = Realloc(state->patternLik, numUnique, double);
382         double *patternLik = state->patternLik;
383         std::vector<double> thrExpected(totalOutcomes * totalQuadPoints * Global->numThreads);
384
385         int numLatents = maxAbilities + triangleLoc1(maxAbilities);
386         int numLatentsPerThread = numUnique * numLatents;
387         double *latentDist = Calloc(numUnique * numLatents * Global->numThreads, double);
388
389         int whereChunk = maxDims + triangleLoc1(maxDims);
390         std::vector<double> wherePrep(totalQuadPoints * whereChunk);
391         for (long qx=0; qx < totalQuadPoints; qx++) {
392                 double *wh = wherePrep.data() + qx * whereChunk;
393                 int quad[maxDims];
394                 decodeLocation(qx, maxDims, state->quadGridSize, quad);
395                 pointToWhere(state, quad, wh, maxDims);
396                 gramProduct(wh, maxDims, wh + maxDims);
397         }
398
399         if (numSpecific == 0) {
400 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,32)
401                 for (int px=0; px < numUnique; px++) {
402                         int thrId = omx_absolute_thread_num();
403                         double *thrLatentDist = latentDist + thrId * numLatentsPerThread;
404
405                         std::vector<double> lxk(totalQuadPoints); // make thread local TODO
406                         ba81LikelihoodSlow2(state, px, lxk.data());
407
408                         double *lxkCache = state->cacheLXK? state->lxk + px : NULL;
409                         double patternLik1 = 0;
410                         double *wh = wherePrep.data();
411                         for (long qx=0; qx < totalQuadPoints; qx++) {
412                                 double area = state->priQarea[qx];
413                                 double tmp = lxk[qx] * area;
414                                 patternLik1 += tmp;
415                                 mapLatentSpace(state, 0, tmp, wh, wh + maxDims,
416                                                thrLatentDist + px * numLatents);
417
418                                 if (lxkCache) {
419                                         *lxkCache = lxk[qx];
420                                         lxkCache += numUnique;
421                                 }
422                                 wh += whereChunk;
423                         }
424
425                         patternLik[px] = patternLik1;
426                 }
427         } else {
428                 primaryDims -= 1;
429                 long totalPrimaryPoints = state->totalPrimaryPoints;
430                 long specificPoints = state->quadGridSize;
431
432 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,32)
433                 for (int px=0; px < numUnique; px++) {
434                         int thrId = omx_absolute_thread_num();
435                         double *thrLatentDist = latentDist + thrId * numLatentsPerThread;
436
437                         std::vector<double> lxk(totalQuadPoints * numSpecific);
438                         ba81LikelihoodSlow2(state, px, lxk.data());
439
440                         std::vector<double> Eis(totalPrimaryPoints * numSpecific, 0.0);
441                         std::vector<double> Ei(totalPrimaryPoints, 1.0);
442                         cai2010EiEis(state, px, lxk.data(), Eis.data(), Ei.data());
443
444                         double patternLik1 = 0;
445                         double *wh = wherePrep.data();
446                         for (long qx=0, qloc=0; qx < totalPrimaryPoints; ++qx) {
447                                 double priArea = state->priQarea[qx];
448                                 double EiArea = Ei[qx] * priArea;
449                                 patternLik1 += EiArea;
450                                 for (long sx=0; sx < specificPoints; sx++) {
451                                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
452                                                 double area = state->speQarea[sgroup * specificPoints + sx];
453                                                 double lxk1 = lxk[totalQuadPoints * sgroup + qloc];
454                                                 double Eis1 = Eis[totalPrimaryPoints * sgroup + qx];
455                                                 double tmp = (EiArea / Eis1) * lxk1 * area;
456                                                 mapLatentSpace(state, sgroup, tmp, wh, wh + maxDims,
457                                                                thrLatentDist + px * numLatents);
458                                                 if (state->cacheLXK) {
459                                                         double *lxkCache = getLXKcache(state, qloc, sgroup);
460                                                         lxkCache[px] = lxk1;
461                                                 }
462                                         }
463                                         wh += whereChunk;
464                                         ++qloc;
465                                 }
466                         }
467
468                         patternLik[px] = patternLik1;
469                 }
470         }
471
472         long expectedSize = totalQuadPoints * totalOutcomes;
473 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,64)
474         for (long qx=0; qx < expectedSize; ++qx) {
475                 state->expected[qx] = 0;
476                 double *e1 = thrExpected.data() + qx;
477                 for (int tx=0; tx < Global->numThreads; ++tx) {
478                         state->expected[qx] += *e1;
479                         e1 += expectedSize;
480                 }
481         }
482
483         //mxLog("raw latent");
484         //pda(latentDist, numLatents, numUnique);
485
486 #pragma omp parallel for num_threads(Global->numThreads) schedule(dynamic)
487         for (int lx=0; lx < maxAbilities + triangleLoc1(primaryDims); ++lx) {
488                 for (int tx=1; tx < Global->numThreads; ++tx) {
489                         double *thrLatentDist = latentDist + tx * numLatentsPerThread;
490                         for (int px=0; px < numUnique; px++) {
491                                 int loc = px * numLatents + lx;
492                                 latentDist[loc] += thrLatentDist[loc];
493                         }
494                 }
495         }
496
497 #pragma omp parallel for num_threads(Global->numThreads)
498         for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
499                 for (int tx=1; tx < Global->numThreads; ++tx) {
500                         double *thrLatentDist = latentDist + tx * numLatentsPerThread;
501                         for (int px=0; px < numUnique; px++) {
502                                 int loc = px * numLatents + maxAbilities + triangleLoc0(sdim);
503                                 latentDist[loc] += thrLatentDist[loc];
504                         }
505                 }
506         }
507
508 #pragma omp parallel for num_threads(Global->numThreads)
509         for (int px=0; px < numUnique; px++) {
510                 if (!isfinite(patternLik[px])) {
511                         omxRaiseErrorf(globalState, "Likelihood of pattern %d is %.3g",
512                                        px, patternLik[px]);
513                 }
514
515                 double *latentDist1 = latentDist + px * numLatents;
516                 double weight = numIdentical[px] / patternLik[px];
517                 int cx = maxAbilities;
518                 for (int d1=0; d1 < primaryDims; d1++) {
519                         latentDist1[d1] *= weight;
520                         for (int d2=0; d2 <= d1; d2++) {
521                                 latentDist1[cx] *= weight;
522                                 ++cx;
523                         }
524                 }
525                 for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
526                         latentDist1[sdim] *= weight;
527                         int loc = maxAbilities + triangleLoc0(sdim);
528                         latentDist1[loc] *= weight;
529                 }
530 #if 0
531                 if (!isfinite(patternLik[px])) {
532                         error("Likelihood of row %d is %f", state->rowMap[px], patternLik[px]);
533                 }
534 #endif
535         }
536
537         //mxLog("raw latent after weighting");
538         //pda(latentDist, numLatents, numUnique);
539
540         std::vector<double> &ElatentMean = state->ElatentMean;
541         std::vector<double> &ElatentCov = state->ElatentCov;
542         
543         ElatentMean.assign(ElatentMean.size(), 0.0);
544         ElatentCov.assign(ElatentCov.size(), 0.0);
545
546 #pragma omp parallel for num_threads(Global->numThreads)
547         for (int d1=0; d1 < maxAbilities; d1++) {
548                 for (int px=0; px < numUnique; px++) {
549                         double *latentDist1 = latentDist + px * numLatents;
550                         int cx = maxAbilities + triangleLoc1(d1);
551                         if (d1 < primaryDims) {
552                                 ElatentMean[d1] += latentDist1[d1];
553                                 for (int d2=0; d2 <= d1; d2++) {
554                                         int cell = d2 * maxAbilities + d1;
555                                         ElatentCov[cell] += latentDist1[cx];
556                                         ++cx;
557                                 }
558                         } else {
559                                 ElatentMean[d1] += latentDist1[d1];
560                                 int cell = d1 * maxAbilities + d1;
561                                 int loc = maxAbilities + triangleLoc0(d1);
562                                 ElatentCov[cell] += latentDist1[loc];
563                         }
564                 }
565         }
566
567         //pda(ElatentMean.data(), 1, state->maxAbilities);
568         //pda(ElatentCov.data(), state->maxAbilities, state->maxAbilities);
569
570         for (int d1=0; d1 < maxAbilities; d1++) {
571                 ElatentMean[d1] /= data->rows;
572         }
573
574         for (int d1=0; d1 < primaryDims; d1++) {
575                 for (int d2=0; d2 <= d1; d2++) {
576                         int cell = d2 * maxAbilities + d1;
577                         int tcell = d1 * maxAbilities + d2;
578                         ElatentCov[tcell] = ElatentCov[cell] =
579                                 ElatentCov[cell] / data->rows - ElatentMean[d1] * ElatentMean[d2];
580                 }
581         }
582         for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
583                 int cell = sdim * maxAbilities + sdim;
584                 ElatentCov[cell] = ElatentCov[cell] / data->rows - ElatentMean[sdim] * ElatentMean[sdim];
585         }
586
587         if (state->cacheLXK) state->LXKcached = TRUE;
588
589         Free(latentDist);
590
591         //mxLog("E-step");
592         //pda(ElatentMean.data(), 1, state->maxAbilities);
593         //pda(ElatentCov.data(), state->maxAbilities, state->maxAbilities);
594 }
595
596 static int getLatentVersion(BA81Expect *state)
597 {
598         return omxGetMatrixVersion(state->latentMeanOut) + omxGetMatrixVersion(state->latentCovOut);
599 }
600
601 // Attempt G-H grid? http://dbarajassolano.wordpress.com/2012/01/26/on-sparse-grid-quadratures/
602 static void ba81SetupQuadrature(omxExpectation* oo, int gridsize)
603 {
604         BA81Expect *state = (BA81Expect *) oo->argStruct;
605         if (state->verbose) {
606                 mxLog("%s: quadrature(%d)", oo->name, getLatentVersion(state));
607         }
608         int numUnique = state->numUnique;
609         int numThreads = Global->numThreads;
610         int maxDims = state->maxDims;
611         double Qwidth = state->Qwidth;
612         int numSpecific = state->numSpecific;
613         int priDims = maxDims - (numSpecific? 1 : 0);
614
615         // try starting small and increasing to the cap TODO
616         state->quadGridSize = gridsize;
617
618         state->totalQuadPoints = 1;
619         for (int dx=0; dx < maxDims; dx++) {
620                 state->totalQuadPoints *= state->quadGridSize;
621         }
622
623         state->totalPrimaryPoints = state->totalQuadPoints;
624
625         if (numSpecific) {
626                 state->totalPrimaryPoints /= state->quadGridSize;
627                 state->speQarea.resize(gridsize * numSpecific);
628         }
629
630         state->Qpoint.resize(gridsize);
631         state->priQarea.resize(state->totalPrimaryPoints);
632
633         double qgs = state->quadGridSize-1;
634         for (int px=0; px < state->quadGridSize; px ++) {
635                 state->Qpoint[px] = Qwidth - px * 2 * Qwidth / qgs;
636         }
637
638         //pda(state->latentMeanOut->data, 1, state->maxAbilities);
639         //pda(state->latentCovOut->data, state->maxAbilities, state->maxAbilities);
640
641         double totalArea = 0;
642         for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
643                 int quad[priDims];
644                 decodeLocation(qx, priDims, state->quadGridSize, quad);
645                 double where[priDims];
646                 pointToWhere(state, quad, where, priDims);
647                 state->priQarea[qx] = exp(dmvnorm(priDims, where,
648                                                   state->latentMeanOut->data,
649                                                   state->latentCovOut->data));
650                 totalArea += state->priQarea[qx];
651         }
652         for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
653                 state->priQarea[qx] /= totalArea;
654                 //mxLog("%.5g,", state->priQarea[qx]);
655         }
656
657         for (int sx=0; sx < numSpecific; sx++) {
658                 totalArea = 0;
659                 int covCell = (priDims + sx) * state->maxAbilities + priDims + sx;
660                 double mean = state->latentMeanOut->data[priDims + sx];
661                 double var = state->latentCovOut->data[covCell];
662                 //mxLog("setup[%d] %.2f %.2f", sx, mean, var);
663                 for (int qx=0; qx < state->quadGridSize; qx++) {
664                         double den = dnorm(state->Qpoint[qx], mean, sqrt(var), FALSE);
665                         state->speQarea[sIndex(state, sx, qx)] = den;
666                         totalArea += den;
667                 }
668                 for (int qx=0; qx < state->quadGridSize; qx++) {
669                         state->speQarea[sIndex(state, sx, qx)] /= totalArea;
670                 }
671                 //pda(state->speQarea.data() + sIndex(state, sx, 0), 1, state->quadGridSize);
672         }
673
674         if (!state->cacheLXK) {
675                 state->lxk = Realloc(state->lxk, numUnique * numThreads, double);
676         } else {
677                 int ns = state->numSpecific;
678                 if (ns == 0) ns = 1;
679                 long numOrdinate = ns * state->totalQuadPoints;
680                 state->lxk = Realloc(state->lxk, numUnique * numOrdinate, double);
681         }
682
683         state->expected = Realloc(state->expected, state->totalOutcomes * state->totalQuadPoints, double);
684 }
685
686 static void ba81buildLXKcache(omxExpectation *oo)
687 {
688         BA81Expect *state = (BA81Expect *) oo->argStruct;
689         if (!state->cacheLXK || state->LXKcached) return;
690         
691         ba81Estep1(oo);
692 }
693
694 OMXINLINE static void
695 expectedUpdate(omxData *data, const int *rowMap, const int px, const int item,
696                const double observed, double *out)
697 {
698         int pick = omxIntDataElementUnsafe(data, rowMap[px], item);
699         if (pick != NA_INTEGER) {
700                 out[pick-1] += observed;
701         }
702 }
703
704 OMXINLINE static void
705 ba81Expected(omxExpectation* oo)
706 {
707         BA81Expect *state = (BA81Expect*) oo->argStruct;
708         if (state->verbose) mxLog("%s: EM.expected", oo->name);
709
710         omxData *data = state->data;
711         int numSpecific = state->numSpecific;
712         const int *rowMap = state->rowMap;
713         double *patternLik = state->patternLik;
714         int *numIdentical = state->numIdentical;
715         int numUnique = state->numUnique;
716         int numItems = state->EitemParam->cols;
717         int totalOutcomes = state->totalOutcomes;
718         std::vector<int> &itemOutcomes = state->itemOutcomes;
719         long totalQuadPoints = state->totalQuadPoints;
720         long totalPrimaryPoints = state->totalPrimaryPoints;
721         long specificPoints = state->quadGridSize;
722
723         OMXZERO(state->expected, totalOutcomes * totalQuadPoints);
724         std::vector<double> thrExpected(totalOutcomes * totalQuadPoints * Global->numThreads);
725
726         if (numSpecific == 0) {
727 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,32)
728                 for (int px=0; px < numUnique; px++) {
729                         int thrId = omx_absolute_thread_num();
730                         double *myExpected = thrExpected.data() + thrId * totalOutcomes * totalQuadPoints;
731
732                         std::vector<double> lxk(totalQuadPoints);
733                         ba81LikelihoodFast2(state, px, lxk.data());
734
735                         double weight = numIdentical[px] / patternLik[px];
736
737                         int outcomeBase = -itemOutcomes[0];
738                         for (int ix=0; ix < numItems; ix++) {
739                                 outcomeBase += itemOutcomes[ix];
740                                 int pick = omxIntDataElementUnsafe(data, rowMap[px], ix);
741                                 if (pick == NA_INTEGER) continue;
742                                 pick -= 1;
743
744                                 double *out = myExpected + outcomeBase;
745                                 for (long qx=0; qx < totalQuadPoints; ++qx) {
746                                         out[pick] += weight * lxk[qx];
747                                         out += totalOutcomes;
748                                 }
749                         }
750                 }
751         } else {
752 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,32)
753                 for (int px=0; px < numUnique; px++) {
754                         int thrId = omx_absolute_thread_num();
755                         double *myExpected = thrExpected.data() + thrId * totalOutcomes * totalQuadPoints;
756
757                         std::vector<double> lxk(totalQuadPoints * numSpecific);
758                         ba81LikelihoodFast2(state, px, lxk.data());
759
760                         std::vector<double> Eis(totalPrimaryPoints * numSpecific, 0.0);
761                         std::vector<double> Ei(totalPrimaryPoints, 1.0);
762                         cai2010EiEis(state, px, lxk.data(), Eis.data(), Ei.data());
763
764                         double weight = numIdentical[px] / patternLik[px];
765
766                         int outcomeBase = -itemOutcomes[0];
767                         for (int ix=0; ix < numItems; ix++) {
768                                 outcomeBase += itemOutcomes[ix];
769                                 int pick = omxIntDataElementUnsafe(data, rowMap[px], ix);
770                                 if (pick == NA_INTEGER) continue;
771                                 pick -= 1;
772
773                                 int Sgroup = state->Sgroup[ix];
774
775                                 double *out = myExpected + outcomeBase;
776                                 long qloc = 0;
777                                 for (long qx=0; qx < totalPrimaryPoints; qx++) {
778                                         double Ei1 = Ei[qx];
779                                         for (long sx=0; sx < specificPoints; sx++) {
780                                                 double lxk1 = lxk[totalQuadPoints * Sgroup + qloc];
781                                                 double Eis1 = Eis[totalPrimaryPoints * Sgroup + qx];
782                                                 out[pick] += weight * (Ei1 / Eis1) * lxk1;
783                                                 out += totalOutcomes;
784                                                 ++qloc;
785                                         }
786                                 }
787                         }
788                 }
789         }
790
791         long expectedSize = totalQuadPoints * totalOutcomes;
792 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,64)
793         for (long qx=0; qx < expectedSize; ++qx) {
794                 state->expected[qx] = 0;
795                 double *e1 = thrExpected.data() + qx;
796                 for (int tx=0; tx < Global->numThreads; ++tx) {
797                         state->expected[qx] += *e1;
798                         e1 += expectedSize;
799                 }
800         }
801
802         if (!state->checkedBadData) {
803                 std::vector<double> byOutcome(totalOutcomes, 0);
804                 for (int ox=0; ox < totalOutcomes; ++ox) {
805                         for (long qx=0; qx < state->totalQuadPoints; qx++) {
806                                 byOutcome[ox] += state->expected[totalOutcomes * qx + ox];
807                         }
808                         if (byOutcome[ox] == 0) {
809                                 int uptoItem = 0;
810                                 for (size_t cx = 0; cx < itemOutcomes.size(); cx++) {
811                                         if (ox < uptoItem + itemOutcomes[cx]) {
812                                                 int bad = ox - uptoItem;
813                                                 omxRaiseErrorf(globalState, "Item %lu outcome %d is never endorsed.\n"
814                                                                "You must collapse categories or omit this item to estimate item parameters.", 1+cx, 1+bad);
815                                                 break;
816                                         }
817                                         uptoItem += itemOutcomes[cx];
818                                 }
819                         }
820                 }
821                 state->checkedBadData = TRUE;
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 = ba81LikelihoodFast(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 = ba81LikelihoodFast(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)  // openmp reduction TODO
960 {
961         BA81Expect *estate = (BA81Expect*) oo->argStruct;
962         if (estate->verbose) mxLog("%s: patternLik", oo->name);
963
964         int numUnique = estate->numUnique;
965         int numSpecific = estate->numSpecific;
966         int maxDims = estate->maxDims;
967         int primaryDims = maxDims;
968         double *patternLik = estate->patternLik;
969         OMXZERO(patternLik, numUnique);
970
971         if (numSpecific == 0) {
972 #pragma omp parallel for num_threads(Global->numThreads)
973                 for (long qx=0; qx < estate->totalQuadPoints; qx++) {
974                         const int thrId = omx_absolute_thread_num();
975                         double area = estate->priQarea[qx];
976                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, qx);
977
978                         for (int px=0; px < numUnique; px++) {
979                                 double tmp = (lxk[px] * area);
980 #pragma omp atomic
981                                 patternLik[px] += tmp;
982                         }
983                 }
984         } else {
985                 primaryDims -= 1;
986
987 #pragma omp parallel for num_threads(Global->numThreads)
988                 for (long qx=0; qx < estate->totalPrimaryPoints; qx++) {
989                         const int thrId = omx_absolute_thread_num();
990
991                         cai2010(oo, thrId, FALSE, qx);
992                         double *allElxk = eBase(estate, thrId);
993
994                         double priArea = estate->priQarea[qx];
995                         for (int px=0; px < numUnique; px++) {
996                                 double Ei = allElxk[px];
997                                 double tmp = (Ei * priArea);
998 #pragma omp atomic
999                                 patternLik[px] += tmp;
1000                         }
1001                 }
1002         }
1003 }
1004
1005 static void
1006 ba81compute(omxExpectation *oo, const char *context)
1007 {
1008         BA81Expect *state = (BA81Expect *) oo->argStruct;
1009
1010         if (context) {
1011                 if (strcmp(context, "EM")==0) {
1012                         state->type = EXPECTATION_AUGMENTED;
1013                 } else if (context[0] == 0) {
1014                         state->type = EXPECTATION_OBSERVED;
1015                 } else {
1016                         omxRaiseErrorf(globalState, "Unknown context '%s'", context);
1017                         return;
1018                 }
1019         }
1020
1021         omxRecompute(state->EitemParam);
1022
1023         bool itemClean = state->itemParamVersion == omxGetMatrixVersion(state->EitemParam);
1024         bool latentClean = state->latentParamVersion == getLatentVersion(state);
1025
1026         if (state->verbose) {
1027                 mxLog("%s: Qinit %d itemClean %d latentClean %d (1=clean)",
1028                       oo->name, state->Qpoint.size() != 0, itemClean, latentClean);
1029         }
1030
1031         if (state->Qpoint.size() == 0 || !latentClean) {
1032                 ba81SetupQuadrature(oo, state->targetQpoints);
1033         }
1034         if (itemClean) {
1035                 ba81buildLXKcache(oo);
1036                 if (!latentClean) recomputePatternLik(oo);
1037         } else {
1038                 ba81OutcomeProb(state);
1039                 ba81Estep1(oo);
1040         }
1041
1042         if (state->type == EXPECTATION_AUGMENTED) {
1043                 ba81Expected(oo);
1044         }
1045
1046         state->itemParamVersion = omxGetMatrixVersion(state->EitemParam);
1047         state->latentParamVersion = getLatentVersion(state);
1048 }
1049
1050 static void
1051 copyScore(int rows, int maxAbilities, std::vector<double> &mean,
1052           std::vector<double> &cov, const int rx, double *scores, const int dest)
1053 {
1054         for (int ax=0; ax < maxAbilities; ++ax) {
1055                 scores[rows * ax + dest] = mean[maxAbilities * rx + ax];
1056         }
1057         for (int ax=0; ax < maxAbilities; ++ax) {
1058                 scores[rows * (maxAbilities + ax) + dest] =
1059                         sqrt(cov[triangleLoc1(maxAbilities) * rx + triangleLoc0(ax)]);
1060         }
1061         for (int ax=0; ax < triangleLoc1(maxAbilities); ++ax) {
1062                 scores[rows * (2*maxAbilities + ax) + dest] =
1063                         cov[triangleLoc1(maxAbilities) * rx + ax];
1064         }
1065 }
1066
1067 /**
1068  * MAP is not affected by the number of items. EAP is. Likelihood can
1069  * get concentrated in a single quadrature ordinate. For 3PL, response
1070  * patterns can have a bimodal likelihood. This will confuse MAP and
1071  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
1072  *
1073  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
1074  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
1075  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
1076  */
1077 static void
1078 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
1079 {
1080         BA81Expect *state = (BA81Expect *) oo->argStruct;
1081         int maxAbilities = state->maxAbilities;
1082
1083         SEXP Rmean, Rcov;
1084         PROTECT(Rmean = allocVector(REALSXP, maxAbilities));
1085         memcpy(REAL(Rmean), state->ElatentMean.data(), maxAbilities * sizeof(double));
1086
1087         PROTECT(Rcov = allocMatrix(REALSXP, maxAbilities, maxAbilities));
1088         memcpy(REAL(Rcov), state->ElatentCov.data(), maxAbilities * maxAbilities * sizeof(double));
1089
1090         setAttrib(robj, install("empirical.mean"), Rmean);
1091         setAttrib(robj, install("empirical.cov"), Rcov);
1092
1093         if (state->type == EXPECTATION_AUGMENTED) {
1094                 int numUnique = state->numUnique;
1095                 int totalOutcomes = state->totalOutcomes;
1096                 SEXP Rlik;
1097                 SEXP Rexpected;
1098
1099                 PROTECT(Rlik = allocVector(REALSXP, numUnique));
1100                 memcpy(REAL(Rlik), state->patternLik, sizeof(double) * numUnique);
1101
1102                 PROTECT(Rexpected = allocMatrix(REALSXP, totalOutcomes, state->totalQuadPoints));
1103                 memcpy(REAL(Rexpected), state->expected, sizeof(double) * totalOutcomes * state->totalQuadPoints);
1104
1105                 setAttrib(robj, install("patternLikelihood"), Rlik);
1106                 setAttrib(robj, install("em.expected"), Rexpected);
1107         }
1108
1109         if (state->scores == SCORES_OMIT || state->type == EXPECTATION_UNINITIALIZED) return;
1110
1111         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
1112         // model. Journal of Educational Statistics, 12, 339-368.
1113
1114         /*
1115         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
1116
1117         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
1118                 // Thissen & Orlando (2001, p. 136)
1119                 warning("EAP requires at least 2*sqrt(items) quadrature points");
1120         }
1121
1122         ba81SetupQuadrature(oo, numQpoints, 0);
1123         ba81Estep1(oo);
1124         */
1125
1126         std::vector<double> mean;
1127         std::vector<double> cov;
1128         EAPinternalFast(oo, &mean, &cov);
1129
1130         int numUnique = state->numUnique;
1131         omxData *data = state->data;
1132         int rows = state->scores == SCORES_FULL? data->rows : numUnique;
1133         int cols = 2 * maxAbilities + triangleLoc1(maxAbilities);
1134         SEXP Rscores;
1135         PROTECT(Rscores = allocMatrix(REALSXP, rows, cols));
1136         double *scores = REAL(Rscores);
1137
1138         const int SMALLBUF = 10;
1139         char buf[SMALLBUF];
1140         SEXP names;
1141         PROTECT(names = allocVector(STRSXP, cols));
1142         for (int nx=0; nx < maxAbilities; ++nx) {
1143                 snprintf(buf, SMALLBUF, "s%d", nx+1);
1144                 SET_STRING_ELT(names, nx, mkChar(buf));
1145                 snprintf(buf, SMALLBUF, "se%d", nx+1);
1146                 SET_STRING_ELT(names, maxAbilities + nx, mkChar(buf));
1147         }
1148         for (int nx=0; nx < triangleLoc1(maxAbilities); ++nx) {
1149                 snprintf(buf, SMALLBUF, "cov%d", nx+1);
1150                 SET_STRING_ELT(names, maxAbilities*2 + nx, mkChar(buf));
1151         }
1152         SEXP dimnames;
1153         PROTECT(dimnames = allocVector(VECSXP, 2));
1154         SET_VECTOR_ELT(dimnames, 1, names);
1155         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
1156
1157         if (state->scores == SCORES_FULL) {
1158 #pragma omp parallel for num_threads(Global->numThreads)
1159                 for (int rx=0; rx < numUnique; rx++) {
1160                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
1161                         for (int dup=0; dup < dups; dup++) {
1162                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
1163                                 copyScore(rows, maxAbilities, mean, cov, rx, scores, dest);
1164                         }
1165                 }
1166         } else {
1167 #pragma omp parallel for num_threads(Global->numThreads)
1168                 for (int rx=0; rx < numUnique; rx++) {
1169                         copyScore(rows, maxAbilities, mean, cov, rx, scores, rx);
1170                 }
1171         }
1172
1173         setAttrib(robj, install("scores.out"), Rscores);
1174 }
1175
1176 static void ba81Destroy(omxExpectation *oo) {
1177         if(OMX_DEBUG) {
1178                 mxLog("Freeing %s function.", oo->name);
1179         }
1180         BA81Expect *state = (BA81Expect *) oo->argStruct;
1181         omxFreeAllMatrixData(state->EitemParam);
1182         omxFreeAllMatrixData(state->design);
1183         omxFreeAllMatrixData(state->latentMeanOut);
1184         omxFreeAllMatrixData(state->latentCovOut);
1185         omxFreeAllMatrixData(state->customPrior);
1186         omxFreeAllMatrixData(state->itemParam);
1187         Free(state->numIdentical);
1188         Free(state->rowMap);
1189         Free(state->patternLik);
1190         Free(state->lxk);
1191         Free(state->Eslxk);
1192         Free(state->allElxk);
1193         Free(state->Sgroup);
1194         Free(state->expected);
1195         Free(state->outcomeProb);
1196         delete state;
1197 }
1198
1199 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
1200 {
1201     SEXP matrixDims;
1202     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
1203     int *dimList = INTEGER(matrixDims);
1204     *rows = dimList[0];
1205     *cols = dimList[1];
1206     UNPROTECT(1);
1207 }
1208
1209 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
1210 {}
1211
1212 void omxInitExpectationBA81(omxExpectation* oo) {
1213         omxState* currentState = oo->currentState;      
1214         SEXP rObj = oo->rObj;
1215         SEXP tmp;
1216         
1217         if(OMX_DEBUG) {
1218                 mxLog("Initializing %s.", oo->name);
1219         }
1220         if (!rpf_model) {
1221                 if (0) {
1222                         const int wantVersion = 3;
1223                         int version;
1224                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
1225                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
1226                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
1227                                                          version, wantVersion);
1228                 } else {
1229                         rpf_numModels = librpf_numModels;
1230                         rpf_model = librpf_model;
1231                 }
1232         }
1233         
1234         BA81Expect *state = new BA81Expect;
1235         state->checkedBadData = FALSE;
1236         state->numSpecific = 0;
1237         state->numIdentical = NULL;
1238         state->rowMap = NULL;
1239         state->design = NULL;
1240         state->lxk = NULL;
1241         state->patternLik = NULL;
1242         state->Eslxk = NULL;
1243         state->allElxk = NULL;
1244         state->outcomeProb = NULL;
1245         state->expected = NULL;
1246         state->type = EXPECTATION_UNINITIALIZED;
1247         state->scores = SCORES_OMIT;
1248         state->itemParam = NULL;
1249         state->customPrior = NULL;
1250         state->itemParamVersion = 0;
1251         state->latentParamVersion = 0;
1252         oo->argStruct = (void*) state;
1253
1254         PROTECT(tmp = GET_SLOT(rObj, install("data")));
1255         state->data = omxDataLookupFromState(tmp, currentState);
1256
1257         if (strcmp(omxDataType(state->data), "raw") != 0) {
1258                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", oo->name, omxDataType(state->data));
1259                 return;
1260         }
1261
1262         PROTECT(tmp = GET_SLOT(rObj, install("ItemSpec")));
1263         for (int sx=0; sx < length(tmp); ++sx) {
1264                 SEXP model = VECTOR_ELT(tmp, sx);
1265                 if (!OBJECT(model)) {
1266                         error("Item models must inherit rpf.base");
1267                 }
1268                 SEXP spec;
1269                 PROTECT(spec = GET_SLOT(model, install("spec")));
1270                 state->itemSpec.push_back(REAL(spec));
1271         }
1272
1273         PROTECT(tmp = GET_SLOT(rObj, install("design")));
1274         if (!isNull(tmp)) {
1275                 // better to demand integers and not coerce to real TODO
1276                 state->design = omxNewMatrixFromRPrimitive(tmp, globalState, FALSE, 0);
1277         }
1278
1279         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean");
1280         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
1281         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
1282         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
1283
1284         state->EitemParam =
1285                 omxNewMatrixFromSlot(rObj, currentState, "EItemParam");
1286         if (!state->EitemParam) error("Must supply EItemParam");
1287
1288         state->itemParam =
1289                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
1290
1291         if (state->EitemParam->rows != state->itemParam->rows ||
1292             state->EitemParam->cols != state->itemParam->cols) {
1293                 error("ItemParam and EItemParam must be of the same dimension");
1294         }
1295
1296         oo->computeFun = ba81compute;
1297         oo->setVarGroup = ignoreSetVarGroup;
1298         oo->destructFun = ba81Destroy;
1299         oo->populateAttrFun = ba81PopulateAttributes;
1300         
1301         // TODO: Exactly identical rows do not contribute any information.
1302         // The sorting algorithm ought to remove them so we don't waste RAM.
1303         // The following summary stats would be cheaper to calculate too.
1304
1305         int numUnique = 0;
1306         omxData *data = state->data;
1307         if (omxDataNumFactor(data) != data->cols) {
1308                 // verify they are ordered factors TODO
1309                 omxRaiseErrorf(currentState, "%s: all columns must be factors", oo->name);
1310                 return;
1311         }
1312
1313         for (int rx=0; rx < data->rows;) {
1314                 rx += omxDataNumIdenticalRows(state->data, rx);
1315                 ++numUnique;
1316         }
1317         state->numUnique = numUnique;
1318
1319         state->rowMap = Realloc(NULL, numUnique, int);
1320         state->numIdentical = Realloc(NULL, numUnique, int);
1321
1322         state->customPrior =
1323                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
1324         
1325         int numItems = state->EitemParam->cols;
1326         if (data->cols != numItems) {
1327                 error("Data has %d columns for %d items", data->cols, numItems);
1328         }
1329
1330         for (int rx=0, ux=0; rx < data->rows; ux++) {
1331                 if (rx == 0) {
1332                         // all NA rows will sort to the top
1333                         int na=0;
1334                         for (int ix=0; ix < numItems; ix++) {
1335                                 if (omxIntDataElement(data, 0, ix) == NA_INTEGER) { ++na; }
1336                         }
1337                         if (na == numItems) {
1338                                 omxRaiseErrorf(currentState, "Remove rows with all NAs");
1339                                 return;
1340                         }
1341                 }
1342                 int dups = omxDataNumIdenticalRows(state->data, rx);
1343                 state->numIdentical[ux] = dups;
1344                 state->rowMap[ux] = rx;
1345                 rx += dups;
1346         }
1347
1348         int numThreads = Global->numThreads;
1349
1350         int maxSpec = 0;
1351         int maxParam = 0;
1352         state->maxDims = 0;
1353
1354         std::vector<int> &itemOutcomes = state->itemOutcomes;
1355         itemOutcomes.resize(numItems);
1356         int totalOutcomes = 0;
1357         for (int cx = 0; cx < data->cols; cx++) {
1358                 const double *spec = state->itemSpec[cx];
1359                 int id = spec[RPF_ISpecID];
1360                 int dims = spec[RPF_ISpecDims];
1361                 if (state->maxDims < dims)
1362                         state->maxDims = dims;
1363
1364                 int no = spec[RPF_ISpecOutcomes];
1365                 itemOutcomes[cx] = no;
1366                 totalOutcomes += no;
1367
1368                 // TODO this summary stat should be available from omxData
1369                 int dataMax=0;
1370                 for (int rx=0; rx < data->rows; rx++) {
1371                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1372                         if (dataMax < pick)
1373                                 dataMax = pick;
1374                 }
1375                 if (dataMax > no) {
1376                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1377                 } else if (dataMax < no) {
1378                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1379                         // promote to error?
1380                         // should complain if an outcome is not represented in the data TODO
1381                 }
1382
1383                 int numSpec = (*rpf_model[id].numSpec)(spec);
1384                 if (maxSpec < numSpec)
1385                         maxSpec = numSpec;
1386
1387                 int numParam = (*rpf_model[id].numParam)(spec);
1388                 if (maxParam < numParam)
1389                         maxParam = numParam;
1390         }
1391
1392         state->totalOutcomes = totalOutcomes;
1393
1394         if (int(state->itemSpec.size()) != data->cols) {
1395                 omxRaiseErrorf(currentState, "ItemSpec must contain %d item model specifications",
1396                                data->cols);
1397                 return;
1398         }
1399         if (state->EitemParam->rows != maxParam) {
1400                 omxRaiseErrorf(currentState, "ItemParam should have %d rows", maxParam);
1401                 return;
1402         }
1403
1404         if (state->design == NULL) {
1405                 state->maxAbilities = state->maxDims;
1406                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1407                                        TRUE, currentState);
1408                 for (int ix=0; ix < numItems; ix++) {
1409                         const double *spec = state->itemSpec[ix];
1410                         int dims = spec[RPF_ISpecDims];
1411                         for (int dx=0; dx < state->maxDims; dx++) {
1412                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1413                         }
1414                 }
1415         } else {
1416                 omxMatrix *design = state->design;
1417                 if (design->cols != numItems ||
1418                     design->rows != state->maxDims) {
1419                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1420                                        state->maxDims, numItems);
1421                         return;
1422                 }
1423
1424                 state->maxAbilities = 0;
1425                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1426                         double got = design->data[ix];
1427                         if (!R_FINITE(got)) continue;
1428                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1429                         if (state->maxAbilities < got)
1430                                 state->maxAbilities = got;
1431                 }
1432                 for (int ix=0; ix < design->cols; ix++) {
1433                         const double *idesign = omxMatrixColumn(design, ix);
1434                         int ddim = 0;
1435                         for (int rx=0; rx < design->rows; rx++) {
1436                                 if (isfinite(idesign[rx])) ddim += 1;
1437                         }
1438                         const double *spec = state->itemSpec[ix];
1439                         int dims = spec[RPF_ISpecDims];
1440                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1441                 }
1442         }
1443         if (state->maxAbilities <= state->maxDims) {
1444                 state->Sgroup = Calloc(numItems, int);
1445         } else {
1446                 // Not sure if this is correct, revisit TODO
1447                 int Sgroup0 = -1;
1448                 state->Sgroup = Realloc(NULL, numItems, int);
1449                 for (int dx=0; dx < state->maxDims; dx++) {
1450                         for (int ix=0; ix < numItems; ix++) {
1451                                 int ability = omxMatrixElement(state->design, dx, ix);
1452                                 if (dx < state->maxDims - 1) {
1453                                         if (Sgroup0 <= ability)
1454                                                 Sgroup0 = ability+1;
1455                                         continue;
1456                                 }
1457                                 int ss=-1;
1458                                 if (ability >= Sgroup0) {
1459                                         if (ss == -1) {
1460                                                 ss = ability;
1461                                         } else {
1462                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1463                                                                "1 specific dimension (both %d and %d)",
1464                                                                ix, ss, ability);
1465                                                 return;
1466                                         }
1467                                 }
1468                                 if (ss == -1) ss = Sgroup0;
1469                                 state->Sgroup[ix] = ss - Sgroup0;
1470                         }
1471                 }
1472                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1473                 state->allElxk = Realloc(NULL, numUnique * numThreads, double);
1474                 state->Eslxk = Realloc(NULL, numUnique * state->numSpecific * numThreads, double);
1475         }
1476
1477         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1478                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1479                       state->maxAbilities, state->maxAbilities);
1480         }
1481         if (state->latentCovOut->rows != state->maxAbilities ||
1482             state->latentCovOut->cols != state->maxAbilities) {
1483                 error("The cov matrix '%s' must be %dx%d",
1484                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1485         }
1486
1487         PROTECT(tmp = GET_SLOT(rObj, install("verbose")));
1488         state->verbose = asLogical(tmp);
1489
1490         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1491         state->cacheLXK = asLogical(tmp);
1492         state->LXKcached = FALSE;
1493
1494         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1495         state->targetQpoints = asReal(tmp);
1496
1497         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1498         state->Qwidth = asReal(tmp);
1499
1500         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1501         const char *score_option = CHAR(asChar(tmp));
1502         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1503         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1504         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1505
1506         state->ElatentMean.resize(state->maxAbilities);
1507         state->ElatentCov.resize(state->maxAbilities * state->maxAbilities);
1508
1509         // verify data bounded between 1 and numOutcomes TODO
1510         // hm, looks like something could be added to omxData for column summary stats?
1511 }