Reorg E step 7/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 ex=0; ex < expectedSize; ++ex) {
794                 state->expected[ex] = 0;
795                 double *e1 = thrExpected.data() + ex;
796                 for (int tx=0; tx < Global->numThreads; ++tx) {
797                         state->expected[ex] += *e1;
798                         e1 += expectedSize;
799                 }
800         }
801         //pda(state->expected, state->totalOutcomes, state->totalQuadPoints);
802 }
803
804 OMXINLINE static void
805 accumulateScores(BA81Expect *state, int px, int sgroup, double piece, const double *where,
806                  int primaryDims, int covEntries, std::vector<double> *mean, std::vector<double> *cov)
807 {
808         int maxDims = state->maxDims;
809         int maxAbilities = state->maxAbilities;
810
811         if (sgroup == 0) {
812                 int cx=0;
813                 for (int d1=0; d1 < primaryDims; d1++) {
814                         double piece_w1 = piece * where[d1];
815                         double &dest1 = (*mean)[px * maxAbilities + d1];
816 #pragma omp atomic
817                         dest1 += piece_w1;
818                         for (int d2=0; d2 <= d1; d2++) {
819                                 double &dest2 = (*cov)[px * covEntries + cx];
820 #pragma omp atomic
821                                 dest2 += where[d2] * piece_w1;
822                                 ++cx;
823                         }
824                 }
825         }
826
827         if (state->numSpecific) {
828                 int sdim = maxDims + sgroup - 1;
829                 double piece_w1 = piece * where[primaryDims];
830                 double &dest3 = (*mean)[px * maxAbilities + sdim];
831 #pragma omp atomic
832                 dest3 += piece_w1;
833
834                 double &dest4 = (*cov)[px * covEntries + triangleLoc0(sdim)];
835 #pragma omp atomic
836                 dest4 += piece_w1 * where[primaryDims];
837         }
838 }
839
840 static void
841 EAPinternalFast(omxExpectation *oo, std::vector<double> *mean, std::vector<double> *cov)
842 {
843         BA81Expect *state = (BA81Expect*) oo->argStruct;
844         if (state->verbose) mxLog("%s: EAP", oo->name);
845
846         int numUnique = state->numUnique;
847         int numSpecific = state->numSpecific;
848         int maxDims = state->maxDims;
849         int maxAbilities = state->maxAbilities;
850         int primaryDims = maxDims;
851         int covEntries = triangleLoc1(maxAbilities);
852
853         mean->assign(numUnique * maxAbilities, 0);
854         cov->assign(numUnique * covEntries, 0);
855
856         if (numSpecific == 0) {
857 #pragma omp parallel for num_threads(Global->numThreads)
858                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
859                         const int thrId = omx_absolute_thread_num();
860                         int quad[maxDims];
861                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
862                         double where[maxDims];
863                         pointToWhere(state, quad, where, maxDims);
864
865                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, qx);
866
867                         double area = state->priQarea[qx];
868                         for (int px=0; px < numUnique; px++) {
869                                 double tmp = lxk[px] * area;
870                                 accumulateScores(state, px, 0, tmp, where, primaryDims, covEntries, mean, cov);
871                         }
872                 }
873         } else {
874                 primaryDims -= 1;
875                 int sDim = primaryDims;
876                 long specificPoints = state->quadGridSize;
877
878 #pragma omp parallel for num_threads(Global->numThreads)
879                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
880                         const int thrId = omx_absolute_thread_num();
881                         int quad[maxDims];
882                         decodeLocation(qx, primaryDims, state->quadGridSize, quad);
883
884                         cai2010(oo, thrId, FALSE, qx);
885                         double *allElxk = eBase(state, thrId);
886                         double *Eslxk = esBase(state, thrId);
887
888                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
889                                 for (long sx=0; sx < specificPoints; sx++) {
890                                         long qloc = qx * specificPoints + sx;
891                                         quad[sDim] = sx;
892                                         double where[maxDims];
893                                         pointToWhere(state, quad, where, maxDims);
894                                         double area = areaProduct(state, qx, sx, sgroup);
895                                         double *lxk = ba81LikelihoodFast(oo, thrId, sgroup, qloc);
896                                         for (int px=0; px < numUnique; px++) {
897                                                 double Ei = allElxk[px];
898                                                 double Eis = Eslxk[sgroup * numUnique + px];
899                                                 double tmp = ((Ei / Eis) * lxk[px] * area);
900                                                 accumulateScores(state, px, sgroup, tmp, where, primaryDims,
901                                                                  covEntries, mean, cov);
902                                         }
903                                 }
904                         }
905                 }
906         }
907
908         double *patternLik = state->patternLik;
909         for (int px=0; px < numUnique; px++) {
910                 double denom = patternLik[px];
911                 for (int ax=0; ax < maxAbilities; ax++) {
912                         (*mean)[px * maxAbilities + ax] /= denom;
913                 }
914                 for (int cx=0; cx < triangleLoc1(primaryDims); ++cx) {
915                         (*cov)[px * covEntries + cx] /= denom;
916                 }
917                 for (int sx=0; sx < numSpecific; sx++) {
918                         (*cov)[px * covEntries + triangleLoc0(primaryDims + sx)] /= denom;
919                 }
920                 int cx=0;
921                 for (int a1=0; a1 < primaryDims; ++a1) {
922                         for (int a2=0; a2 <= a1; ++a2) {
923                                 double ma1 = (*mean)[px * maxAbilities + a1];
924                                 double ma2 = (*mean)[px * maxAbilities + a2];
925                                 (*cov)[px * covEntries + cx] -= ma1 * ma2;
926                                 ++cx;
927                         }
928                 }
929                 for (int sx=0; sx < numSpecific; sx++) {
930                         int sdim = primaryDims + sx;
931                         double ma1 = (*mean)[px * maxAbilities + sdim];
932                         (*cov)[px * covEntries + triangleLoc0(sdim)] -= ma1 * ma1;
933                 }
934         }
935 }
936
937 static void recomputePatternLik(omxExpectation *oo)  // openmp reduction TODO
938 {
939         BA81Expect *estate = (BA81Expect*) oo->argStruct;
940         if (estate->verbose) mxLog("%s: patternLik", oo->name);
941
942         int numUnique = estate->numUnique;
943         int numSpecific = estate->numSpecific;
944         int maxDims = estate->maxDims;
945         int primaryDims = maxDims;
946         double *patternLik = estate->patternLik;
947         OMXZERO(patternLik, numUnique);
948
949         if (numSpecific == 0) {
950 #pragma omp parallel for num_threads(Global->numThreads)
951                 for (long qx=0; qx < estate->totalQuadPoints; qx++) {
952                         const int thrId = omx_absolute_thread_num();
953                         double area = estate->priQarea[qx];
954                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, qx);
955
956                         for (int px=0; px < numUnique; px++) {
957                                 double tmp = (lxk[px] * area);
958 #pragma omp atomic
959                                 patternLik[px] += tmp;
960                         }
961                 }
962         } else {
963                 primaryDims -= 1;
964
965 #pragma omp parallel for num_threads(Global->numThreads)
966                 for (long qx=0; qx < estate->totalPrimaryPoints; qx++) {
967                         const int thrId = omx_absolute_thread_num();
968
969                         cai2010(oo, thrId, FALSE, qx);
970                         double *allElxk = eBase(estate, thrId);
971
972                         double priArea = estate->priQarea[qx];
973                         for (int px=0; px < numUnique; px++) {
974                                 double Ei = allElxk[px];
975                                 double tmp = (Ei * priArea);
976 #pragma omp atomic
977                                 patternLik[px] += tmp;
978                         }
979                 }
980         }
981 }
982
983 static void
984 ba81compute(omxExpectation *oo, const char *context)
985 {
986         BA81Expect *state = (BA81Expect *) oo->argStruct;
987
988         if (context) {
989                 if (strcmp(context, "EM")==0) {
990                         state->type = EXPECTATION_AUGMENTED;
991                 } else if (context[0] == 0) {
992                         state->type = EXPECTATION_OBSERVED;
993                 } else {
994                         omxRaiseErrorf(globalState, "Unknown context '%s'", context);
995                         return;
996                 }
997         }
998
999         omxRecompute(state->EitemParam);
1000
1001         bool itemClean = state->itemParamVersion == omxGetMatrixVersion(state->EitemParam);
1002         bool latentClean = state->latentParamVersion == getLatentVersion(state);
1003
1004         if (state->verbose) {
1005                 mxLog("%s: Qinit %d itemClean %d latentClean %d (1=clean)",
1006                       oo->name, state->Qpoint.size() != 0, itemClean, latentClean);
1007         }
1008
1009         if (state->Qpoint.size() == 0 || !latentClean) {
1010                 ba81SetupQuadrature(oo, state->targetQpoints);
1011         }
1012         if (itemClean) {
1013                 ba81buildLXKcache(oo);
1014                 if (!latentClean) recomputePatternLik(oo);
1015         } else {
1016                 ba81OutcomeProb(state);
1017                 ba81Estep1(oo);
1018         }
1019
1020         if (state->type == EXPECTATION_AUGMENTED) {
1021                 ba81Expected(oo);
1022         }
1023
1024         state->itemParamVersion = omxGetMatrixVersion(state->EitemParam);
1025         state->latentParamVersion = getLatentVersion(state);
1026 }
1027
1028 static void
1029 copyScore(int rows, int maxAbilities, std::vector<double> &mean,
1030           std::vector<double> &cov, const int rx, double *scores, const int dest)
1031 {
1032         for (int ax=0; ax < maxAbilities; ++ax) {
1033                 scores[rows * ax + dest] = mean[maxAbilities * rx + ax];
1034         }
1035         for (int ax=0; ax < maxAbilities; ++ax) {
1036                 scores[rows * (maxAbilities + ax) + dest] =
1037                         sqrt(cov[triangleLoc1(maxAbilities) * rx + triangleLoc0(ax)]);
1038         }
1039         for (int ax=0; ax < triangleLoc1(maxAbilities); ++ax) {
1040                 scores[rows * (2*maxAbilities + ax) + dest] =
1041                         cov[triangleLoc1(maxAbilities) * rx + ax];
1042         }
1043 }
1044
1045 /**
1046  * MAP is not affected by the number of items. EAP is. Likelihood can
1047  * get concentrated in a single quadrature ordinate. For 3PL, response
1048  * patterns can have a bimodal likelihood. This will confuse MAP and
1049  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
1050  *
1051  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
1052  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
1053  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
1054  */
1055 static void
1056 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
1057 {
1058         BA81Expect *state = (BA81Expect *) oo->argStruct;
1059         int maxAbilities = state->maxAbilities;
1060
1061         SEXP Rmean, Rcov;
1062         PROTECT(Rmean = allocVector(REALSXP, maxAbilities));
1063         memcpy(REAL(Rmean), state->ElatentMean.data(), maxAbilities * sizeof(double));
1064
1065         PROTECT(Rcov = allocMatrix(REALSXP, maxAbilities, maxAbilities));
1066         memcpy(REAL(Rcov), state->ElatentCov.data(), maxAbilities * maxAbilities * sizeof(double));
1067
1068         setAttrib(robj, install("empirical.mean"), Rmean);
1069         setAttrib(robj, install("empirical.cov"), Rcov);
1070
1071         if (state->type == EXPECTATION_AUGMENTED) {
1072                 int numUnique = state->numUnique;
1073                 int totalOutcomes = state->totalOutcomes;
1074                 SEXP Rlik;
1075                 SEXP Rexpected;
1076
1077                 PROTECT(Rlik = allocVector(REALSXP, numUnique));
1078                 memcpy(REAL(Rlik), state->patternLik, sizeof(double) * numUnique);
1079
1080                 PROTECT(Rexpected = allocMatrix(REALSXP, totalOutcomes, state->totalQuadPoints));
1081                 memcpy(REAL(Rexpected), state->expected, sizeof(double) * totalOutcomes * state->totalQuadPoints);
1082
1083                 setAttrib(robj, install("patternLikelihood"), Rlik);
1084                 setAttrib(robj, install("em.expected"), Rexpected);
1085         }
1086
1087         if (state->scores == SCORES_OMIT || state->type == EXPECTATION_UNINITIALIZED) return;
1088
1089         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
1090         // model. Journal of Educational Statistics, 12, 339-368.
1091
1092         /*
1093         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
1094
1095         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
1096                 // Thissen & Orlando (2001, p. 136)
1097                 warning("EAP requires at least 2*sqrt(items) quadrature points");
1098         }
1099
1100         ba81SetupQuadrature(oo, numQpoints, 0);
1101         ba81Estep1(oo);
1102         */
1103
1104         std::vector<double> mean;
1105         std::vector<double> cov;
1106         EAPinternalFast(oo, &mean, &cov);
1107
1108         int numUnique = state->numUnique;
1109         omxData *data = state->data;
1110         int rows = state->scores == SCORES_FULL? data->rows : numUnique;
1111         int cols = 2 * maxAbilities + triangleLoc1(maxAbilities);
1112         SEXP Rscores;
1113         PROTECT(Rscores = allocMatrix(REALSXP, rows, cols));
1114         double *scores = REAL(Rscores);
1115
1116         const int SMALLBUF = 10;
1117         char buf[SMALLBUF];
1118         SEXP names;
1119         PROTECT(names = allocVector(STRSXP, cols));
1120         for (int nx=0; nx < maxAbilities; ++nx) {
1121                 snprintf(buf, SMALLBUF, "s%d", nx+1);
1122                 SET_STRING_ELT(names, nx, mkChar(buf));
1123                 snprintf(buf, SMALLBUF, "se%d", nx+1);
1124                 SET_STRING_ELT(names, maxAbilities + nx, mkChar(buf));
1125         }
1126         for (int nx=0; nx < triangleLoc1(maxAbilities); ++nx) {
1127                 snprintf(buf, SMALLBUF, "cov%d", nx+1);
1128                 SET_STRING_ELT(names, maxAbilities*2 + nx, mkChar(buf));
1129         }
1130         SEXP dimnames;
1131         PROTECT(dimnames = allocVector(VECSXP, 2));
1132         SET_VECTOR_ELT(dimnames, 1, names);
1133         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
1134
1135         if (state->scores == SCORES_FULL) {
1136 #pragma omp parallel for num_threads(Global->numThreads)
1137                 for (int rx=0; rx < numUnique; rx++) {
1138                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
1139                         for (int dup=0; dup < dups; dup++) {
1140                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
1141                                 copyScore(rows, maxAbilities, mean, cov, rx, scores, dest);
1142                         }
1143                 }
1144         } else {
1145 #pragma omp parallel for num_threads(Global->numThreads)
1146                 for (int rx=0; rx < numUnique; rx++) {
1147                         copyScore(rows, maxAbilities, mean, cov, rx, scores, rx);
1148                 }
1149         }
1150
1151         setAttrib(robj, install("scores.out"), Rscores);
1152 }
1153
1154 static void ba81Destroy(omxExpectation *oo) {
1155         if(OMX_DEBUG) {
1156                 mxLog("Freeing %s function.", oo->name);
1157         }
1158         BA81Expect *state = (BA81Expect *) oo->argStruct;
1159         omxFreeAllMatrixData(state->EitemParam);
1160         omxFreeAllMatrixData(state->design);
1161         omxFreeAllMatrixData(state->latentMeanOut);
1162         omxFreeAllMatrixData(state->latentCovOut);
1163         omxFreeAllMatrixData(state->customPrior);
1164         omxFreeAllMatrixData(state->itemParam);
1165         Free(state->numIdentical);
1166         Free(state->rowMap);
1167         Free(state->patternLik);
1168         Free(state->lxk);
1169         Free(state->Eslxk);
1170         Free(state->allElxk);
1171         Free(state->Sgroup);
1172         Free(state->expected);
1173         Free(state->outcomeProb);
1174         delete state;
1175 }
1176
1177 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
1178 {
1179     SEXP matrixDims;
1180     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
1181     int *dimList = INTEGER(matrixDims);
1182     *rows = dimList[0];
1183     *cols = dimList[1];
1184     UNPROTECT(1);
1185 }
1186
1187 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
1188 {}
1189
1190 void omxInitExpectationBA81(omxExpectation* oo) {
1191         omxState* currentState = oo->currentState;      
1192         SEXP rObj = oo->rObj;
1193         SEXP tmp;
1194         
1195         if(OMX_DEBUG) {
1196                 mxLog("Initializing %s.", oo->name);
1197         }
1198         if (!rpf_model) {
1199                 if (0) {
1200                         const int wantVersion = 3;
1201                         int version;
1202                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
1203                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
1204                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
1205                                                          version, wantVersion);
1206                 } else {
1207                         rpf_numModels = librpf_numModels;
1208                         rpf_model = librpf_model;
1209                 }
1210         }
1211         
1212         BA81Expect *state = new BA81Expect;
1213         state->numSpecific = 0;
1214         state->numIdentical = NULL;
1215         state->rowMap = NULL;
1216         state->design = NULL;
1217         state->lxk = NULL;
1218         state->patternLik = NULL;
1219         state->Eslxk = NULL;
1220         state->allElxk = NULL;
1221         state->outcomeProb = NULL;
1222         state->expected = NULL;
1223         state->type = EXPECTATION_UNINITIALIZED;
1224         state->scores = SCORES_OMIT;
1225         state->itemParam = NULL;
1226         state->customPrior = NULL;
1227         state->itemParamVersion = 0;
1228         state->latentParamVersion = 0;
1229         oo->argStruct = (void*) state;
1230
1231         PROTECT(tmp = GET_SLOT(rObj, install("data")));
1232         state->data = omxDataLookupFromState(tmp, currentState);
1233
1234         if (strcmp(omxDataType(state->data), "raw") != 0) {
1235                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", oo->name, omxDataType(state->data));
1236                 return;
1237         }
1238
1239         PROTECT(tmp = GET_SLOT(rObj, install("ItemSpec")));
1240         for (int sx=0; sx < length(tmp); ++sx) {
1241                 SEXP model = VECTOR_ELT(tmp, sx);
1242                 if (!OBJECT(model)) {
1243                         error("Item models must inherit rpf.base");
1244                 }
1245                 SEXP spec;
1246                 PROTECT(spec = GET_SLOT(model, install("spec")));
1247                 state->itemSpec.push_back(REAL(spec));
1248         }
1249
1250         PROTECT(tmp = GET_SLOT(rObj, install("design")));
1251         if (!isNull(tmp)) {
1252                 // better to demand integers and not coerce to real TODO
1253                 state->design = omxNewMatrixFromRPrimitive(tmp, globalState, FALSE, 0);
1254         }
1255
1256         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean");
1257         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
1258         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
1259         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
1260
1261         state->EitemParam =
1262                 omxNewMatrixFromSlot(rObj, currentState, "EItemParam");
1263         if (!state->EitemParam) error("Must supply EItemParam");
1264
1265         state->itemParam =
1266                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
1267
1268         if (state->EitemParam->rows != state->itemParam->rows ||
1269             state->EitemParam->cols != state->itemParam->cols) {
1270                 error("ItemParam and EItemParam must be of the same dimension");
1271         }
1272
1273         oo->computeFun = ba81compute;
1274         oo->setVarGroup = ignoreSetVarGroup;
1275         oo->destructFun = ba81Destroy;
1276         oo->populateAttrFun = ba81PopulateAttributes;
1277         
1278         // TODO: Exactly identical rows do not contribute any information.
1279         // The sorting algorithm ought to remove them so we don't waste RAM.
1280         // The following summary stats would be cheaper to calculate too.
1281
1282         int numUnique = 0;
1283         omxData *data = state->data;
1284         if (omxDataNumFactor(data) != data->cols) {
1285                 // verify they are ordered factors TODO
1286                 omxRaiseErrorf(currentState, "%s: all columns must be factors", oo->name);
1287                 return;
1288         }
1289
1290         for (int rx=0; rx < data->rows;) {
1291                 rx += omxDataNumIdenticalRows(state->data, rx);
1292                 ++numUnique;
1293         }
1294         state->numUnique = numUnique;
1295
1296         state->rowMap = Realloc(NULL, numUnique, int);
1297         state->numIdentical = Realloc(NULL, numUnique, int);
1298
1299         state->customPrior =
1300                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
1301         
1302         int numItems = state->EitemParam->cols;
1303         if (data->cols != numItems) {
1304                 error("Data has %d columns for %d items", data->cols, numItems);
1305         }
1306
1307         int numThreads = Global->numThreads;
1308
1309         int maxSpec = 0;
1310         int maxParam = 0;
1311         state->maxDims = 0;
1312
1313         std::vector<int> &itemOutcomes = state->itemOutcomes;
1314         itemOutcomes.resize(numItems);
1315         int totalOutcomes = 0;
1316         for (int cx = 0; cx < data->cols; cx++) {
1317                 const double *spec = state->itemSpec[cx];
1318                 int id = spec[RPF_ISpecID];
1319                 int dims = spec[RPF_ISpecDims];
1320                 if (state->maxDims < dims)
1321                         state->maxDims = dims;
1322
1323                 int no = spec[RPF_ISpecOutcomes];
1324                 itemOutcomes[cx] = no;
1325                 totalOutcomes += no;
1326
1327                 // TODO this summary stat should be available from omxData
1328                 int dataMax=0;
1329                 for (int rx=0; rx < data->rows; rx++) {
1330                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1331                         if (dataMax < pick)
1332                                 dataMax = pick;
1333                 }
1334                 if (dataMax > no) {
1335                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1336                 } else if (dataMax < no) {
1337                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1338                         // promote to error?
1339                         // should complain if an outcome is not represented in the data TODO
1340                 }
1341
1342                 int numSpec = (*rpf_model[id].numSpec)(spec);
1343                 if (maxSpec < numSpec)
1344                         maxSpec = numSpec;
1345
1346                 int numParam = (*rpf_model[id].numParam)(spec);
1347                 if (maxParam < numParam)
1348                         maxParam = numParam;
1349         }
1350
1351         state->totalOutcomes = totalOutcomes;
1352
1353         if (int(state->itemSpec.size()) != data->cols) {
1354                 omxRaiseErrorf(currentState, "ItemSpec must contain %d item model specifications",
1355                                data->cols);
1356                 return;
1357         }
1358         if (state->EitemParam->rows != maxParam) {
1359                 omxRaiseErrorf(currentState, "ItemParam should have %d rows", maxParam);
1360                 return;
1361         }
1362
1363         std::vector<bool> byOutcome(totalOutcomes, false);
1364         int outcomesSeen = 0;
1365         for (int rx=0, ux=0; rx < data->rows; ux++) {
1366                 if (rx == 0) {
1367                         // all NA rows will sort to the top
1368                         int na=0;
1369                         for (int ix=0; ix < numItems; ix++) {
1370                                 if (omxIntDataElement(data, 0, ix) == NA_INTEGER) { ++na; }
1371                         }
1372                         if (na == numItems) {
1373                                 omxRaiseErrorf(currentState, "Remove rows with all NAs");
1374                                 return;
1375                         }
1376                 }
1377                 int dups = omxDataNumIdenticalRows(state->data, rx);
1378                 state->numIdentical[ux] = dups;
1379                 state->rowMap[ux] = rx;
1380                 rx += dups;
1381
1382                 if (outcomesSeen < totalOutcomes) {
1383                         for (int ix=0, outcomeBase=0; ix < numItems; outcomeBase += itemOutcomes[ix], ++ix) {
1384                                 int pick = omxIntDataElementUnsafe(data, rx, ix);
1385                                 if (pick == NA_INTEGER) continue;
1386                                 --pick;
1387                                 if (!byOutcome[outcomeBase + pick]) {
1388                                         byOutcome[outcomeBase + pick] = true;
1389                                         if (++outcomesSeen == totalOutcomes) break;
1390                                 }
1391                         }
1392                 }
1393         }
1394
1395         if (outcomesSeen < totalOutcomes) {
1396                 std::string buf;
1397                 for (int ix=0, outcomeBase=0; ix < numItems; outcomeBase += itemOutcomes[ix], ++ix) {
1398                         for (int pick=0; pick < itemOutcomes[ix]; ++pick) {
1399                                 if (byOutcome[outcomeBase + pick]) continue;
1400                                 buf += string_snprintf(" item %d outcome %d", 1+ix, 1+pick);
1401                         }
1402                 }
1403                 omxRaiseErrorf(globalState, "Never endorsed:%s\n"
1404                                "You must collapse categories or omit items to estimate item parameters.",
1405                                buf.c_str());
1406         }
1407
1408         if (state->design == NULL) {
1409                 state->maxAbilities = state->maxDims;
1410                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1411                                        TRUE, currentState);
1412                 for (int ix=0; ix < numItems; ix++) {
1413                         const double *spec = state->itemSpec[ix];
1414                         int dims = spec[RPF_ISpecDims];
1415                         for (int dx=0; dx < state->maxDims; dx++) {
1416                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1417                         }
1418                 }
1419         } else {
1420                 omxMatrix *design = state->design;
1421                 if (design->cols != numItems ||
1422                     design->rows != state->maxDims) {
1423                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1424                                        state->maxDims, numItems);
1425                         return;
1426                 }
1427
1428                 state->maxAbilities = 0;
1429                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1430                         double got = design->data[ix];
1431                         if (!R_FINITE(got)) continue;
1432                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1433                         if (state->maxAbilities < got)
1434                                 state->maxAbilities = got;
1435                 }
1436                 for (int ix=0; ix < design->cols; ix++) {
1437                         const double *idesign = omxMatrixColumn(design, ix);
1438                         int ddim = 0;
1439                         for (int rx=0; rx < design->rows; rx++) {
1440                                 if (isfinite(idesign[rx])) ddim += 1;
1441                         }
1442                         const double *spec = state->itemSpec[ix];
1443                         int dims = spec[RPF_ISpecDims];
1444                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1445                 }
1446         }
1447         if (state->maxAbilities <= state->maxDims) {
1448                 state->Sgroup = Calloc(numItems, int);
1449         } else {
1450                 // Not sure if this is correct, revisit TODO
1451                 int Sgroup0 = -1;
1452                 state->Sgroup = Realloc(NULL, numItems, int);
1453                 for (int dx=0; dx < state->maxDims; dx++) {
1454                         for (int ix=0; ix < numItems; ix++) {
1455                                 int ability = omxMatrixElement(state->design, dx, ix);
1456                                 if (dx < state->maxDims - 1) {
1457                                         if (Sgroup0 <= ability)
1458                                                 Sgroup0 = ability+1;
1459                                         continue;
1460                                 }
1461                                 int ss=-1;
1462                                 if (ability >= Sgroup0) {
1463                                         if (ss == -1) {
1464                                                 ss = ability;
1465                                         } else {
1466                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1467                                                                "1 specific dimension (both %d and %d)",
1468                                                                ix, ss, ability);
1469                                                 return;
1470                                         }
1471                                 }
1472                                 if (ss == -1) ss = Sgroup0;
1473                                 state->Sgroup[ix] = ss - Sgroup0;
1474                         }
1475                 }
1476                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1477                 state->allElxk = Realloc(NULL, numUnique * numThreads, double);
1478                 state->Eslxk = Realloc(NULL, numUnique * state->numSpecific * numThreads, double);
1479         }
1480
1481         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1482                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1483                       state->maxAbilities, state->maxAbilities);
1484         }
1485         if (state->latentCovOut->rows != state->maxAbilities ||
1486             state->latentCovOut->cols != state->maxAbilities) {
1487                 error("The cov matrix '%s' must be %dx%d",
1488                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1489         }
1490
1491         PROTECT(tmp = GET_SLOT(rObj, install("verbose")));
1492         state->verbose = asLogical(tmp);
1493
1494         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1495         state->cacheLXK = asLogical(tmp);
1496         state->LXKcached = FALSE;
1497
1498         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1499         state->targetQpoints = asReal(tmp);
1500
1501         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1502         state->Qwidth = asReal(tmp);
1503
1504         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1505         const char *score_option = CHAR(asChar(tmp));
1506         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1507         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1508         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1509
1510         state->ElatentMean.resize(state->maxAbilities);
1511         state->ElatentCov.resize(state->maxAbilities * state->maxAbilities);
1512
1513         // verify data bounded between 1 and numOutcomes TODO
1514         // hm, looks like something could be added to omxData for column summary stats?
1515 }