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