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