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