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