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