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