Fix order of multiply to avoid floating point overflow
[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;
556                 state->priQarea[qx] /= totalArea;
557                 //mxLog("%.5g,", state->priQarea[qx]);
558         }
559
560         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
561                 totalArea = 0;
562                 int covCell = (priDims + sgroup) * state->maxAbilities + priDims + sgroup;
563                 double mean = state->latentMeanOut->data[priDims + sgroup];
564                 double var = state->latentCovOut->data[covCell];
565                 //mxLog("setup[%d] %.2f %.2f", sx, mean, var);
566                 for (int qx=0; qx < state->quadGridSize; qx++) {
567                         double den = dnorm(state->Qpoint[qx], mean, sqrt(var), FALSE);
568                         state->speQarea[sIndex(state, sgroup, qx)] = den;
569                         totalArea += den;
570                 }
571                 for (int qx=0; qx < state->quadGridSize; qx++) {
572                         state->speQarea[sIndex(state, sgroup, qx)] *= Largest;
573                         state->speQarea[sIndex(state, sgroup, qx)] /= totalArea;
574                 }
575                 //pda(state->speQarea.data() + sIndex(state, sgroup, 0), 1, state->quadGridSize);
576         }
577
578         // The idea here is to avoid denormalized values if they are
579         // enabled (5e-324 vs 2e-308).  It would be bad if results
580         // changed depending on the denormalization setting.
581         // Moreover, we don't lose too much even if denormalized
582         // values are disabled.
583
584         state->SmallestPatternLik = 1e16 * std::numeric_limits<double>::min();
585
586         state->expected = Realloc(state->expected, state->totalOutcomes * state->totalQuadPoints, double);
587 }
588
589 OMXINLINE static void
590 accumulateScores(BA81Expect *state, int px, int sgroup, double piece, const double *where,
591                  int primaryDims, int covEntries, std::vector<double> *mean, std::vector<double> *cov)
592 {
593         int maxDims = state->maxDims;
594         int maxAbilities = state->maxAbilities;
595
596         if (sgroup == 0) {
597                 int cx=0;
598                 for (int d1=0; d1 < primaryDims; d1++) {
599                         double piece_w1 = piece * where[d1];
600                         double &dest1 = (*mean)[px * maxAbilities + d1];
601                         dest1 += piece_w1;
602                         for (int d2=0; d2 <= d1; d2++) {
603                                 double &dest2 = (*cov)[px * covEntries + cx];
604                                 dest2 += where[d2] * piece_w1;
605                                 ++cx;
606                         }
607                 }
608         }
609
610         if (state->numSpecific) {
611                 int sdim = maxDims + sgroup - 1;
612                 double piece_w1 = piece * where[primaryDims];
613                 double &dest3 = (*mean)[px * maxAbilities + sdim];
614                 dest3 += piece_w1;
615
616                 double &dest4 = (*cov)[px * covEntries + triangleLoc0(sdim)];
617                 dest4 += piece_w1 * where[primaryDims];
618         }
619 }
620
621 // re-factor to share code with E-step TODO
622 static void
623 EAPinternalFast(omxExpectation *oo, std::vector<double> *mean, std::vector<double> *cov)
624 {
625         BA81Expect *state = (BA81Expect*) oo->argStruct;
626         if (state->verbose) mxLog("%s: EAP", oo->name);
627
628         const int numUnique = state->numUnique;
629         const int numSpecific = state->numSpecific;
630         const int maxDims = state->maxDims;
631         const int maxAbilities = state->maxAbilities;
632         const int primaryDims = numSpecific? maxDims-1 : maxDims;
633         const int covEntries = triangleLoc1(maxAbilities);
634         double *patternLik = state->patternLik;
635         const long totalQuadPoints = state->totalQuadPoints;
636         const long totalPrimaryPoints = state->totalPrimaryPoints;
637
638         mean->assign(numUnique * maxAbilities, 0);
639         cov->assign(numUnique * covEntries, 0);
640
641         if (numSpecific == 0) {
642                 omxBuffer<double> thrLxk(totalQuadPoints * Global->numThreads);
643
644 #pragma omp parallel for num_threads(Global->numThreads)
645                 for (int px=0; px < numUnique; px++) {
646                         if (!validPatternLik(state, patternLik[px])) {
647                                 continue;
648                         }
649
650                         int thrId = omx_absolute_thread_num();
651                         double *lxk = thrLxk.data() + thrId * totalQuadPoints;
652                         ba81LikelihoodSlow2(state, px, lxk);
653
654                         for (long qx=0; qx < state->totalQuadPoints; qx++) {
655                                 int quad[maxDims];
656                                 decodeLocation(qx, maxDims, state->quadGridSize, quad);
657                                 double where[maxDims];
658                                 pointToWhere(state, quad, where, maxDims);
659
660                                 double tmp = lxk[qx];
661                                 accumulateScores(state, px, 0, tmp, where, primaryDims, covEntries, mean, cov);
662                         }
663                 }
664         } else {
665                 int sDim = primaryDims;
666                 const long specificPoints = state->quadGridSize;
667                 omxBuffer<double> thrLxk(totalQuadPoints * numSpecific * Global->numThreads);
668                 omxBuffer<double> thrEi(totalPrimaryPoints * Global->numThreads);
669                 omxBuffer<double> thrEis(totalPrimaryPoints * numSpecific * Global->numThreads);
670
671 #pragma omp parallel for num_threads(Global->numThreads)
672                 for (int px=0; px < numUnique; px++) {
673                         if (!validPatternLik(state, patternLik[px])) {
674                                 continue;
675                         }
676
677                         int thrId = omx_absolute_thread_num();
678                         double *lxk = thrLxk.data() + totalQuadPoints * numSpecific * thrId;
679                         double *Eis = thrEis.data() + totalPrimaryPoints * numSpecific * thrId;
680                         double *Ei = thrEi.data() + totalPrimaryPoints * thrId;
681                         cai2010EiEis(state, px, lxk, Eis, Ei);
682
683                         long qloc = 0;
684                         long eisloc = 0;
685                         for (long qx=0; qx < totalPrimaryPoints; qx++) {
686                                 int quad[maxDims];
687                                 decodeLocation(qx, primaryDims, state->quadGridSize, quad);
688                                 for (long sx=0; sx < specificPoints; sx++) {
689                                         for (int Sgroup=0; Sgroup < numSpecific; ++Sgroup) {
690                                                 quad[sDim] = sx;
691                                                 double where[maxDims];
692                                                 pointToWhere(state, quad, where, maxDims);
693                                                 double lxk1 = lxk[qloc];
694                                                 double Eis1 = Eis[eisloc + Sgroup];
695                                                 double tmp = Eis1 * lxk1;
696                                                 accumulateScores(state, px, Sgroup, tmp, where, primaryDims,
697                                                                  covEntries, mean, cov);
698                                                 ++qloc;
699                                         }
700                                 }
701                                 eisloc += numSpecific;
702                         }
703                 }
704         }
705
706         for (int px=0; px < numUnique; px++) {
707                 double denom = patternLik[px];
708                 if (!validPatternLik(state, denom)) {
709                         for (int ax=0; ax < maxAbilities; ++ax) {
710                                 (*mean)[px * maxAbilities + ax] = NA_REAL;
711                         }
712                         for (int cx=0; cx < covEntries; ++cx) {
713                                 (*cov)[px * covEntries + cx] = NA_REAL;
714                         }
715                         continue;
716                 }
717                 for (int ax=0; ax < maxAbilities; ax++) {
718                         (*mean)[px * maxAbilities + ax] /= denom;
719                 }
720                 for (int cx=0; cx < triangleLoc1(primaryDims); ++cx) {
721                         (*cov)[px * covEntries + cx] /= denom;
722                 }
723                 for (int sx=0; sx < numSpecific; sx++) {
724                         (*cov)[px * covEntries + triangleLoc0(primaryDims + sx)] /= denom;
725                 }
726                 int cx=0;
727                 for (int a1=0; a1 < primaryDims; ++a1) {
728                         for (int a2=0; a2 <= a1; ++a2) {
729                                 double ma1 = (*mean)[px * maxAbilities + a1];
730                                 double ma2 = (*mean)[px * maxAbilities + a2];
731                                 (*cov)[px * covEntries + cx] -= ma1 * ma2;
732                                 ++cx;
733                         }
734                 }
735                 for (int sx=0; sx < numSpecific; sx++) {
736                         int sdim = primaryDims + sx;
737                         double ma1 = (*mean)[px * maxAbilities + sdim];
738                         (*cov)[px * covEntries + triangleLoc0(sdim)] -= ma1 * ma1;
739                 }
740         }
741 }
742
743 static void
744 ba81compute(omxExpectation *oo, const char *context)
745 {
746         BA81Expect *state = (BA81Expect *) oo->argStruct;
747
748         if (context) {
749                 if (strcmp(context, "EM")==0) {
750                         state->type = EXPECTATION_AUGMENTED;
751                 } else if (context[0] == 0) {
752                         state->type = EXPECTATION_OBSERVED;
753                 } else {
754                         omxRaiseErrorf(globalState, "Unknown context '%s'", context);
755                 }
756                 return;
757         }
758
759         bool itemClean = state->itemParamVersion == omxGetMatrixVersion(state->itemParam);
760         bool latentClean = state->latentParamVersion == getLatentVersion(state);
761
762         if (state->verbose) {
763                 mxLog("%s: Qinit %d itemClean %d latentClean %d (1=clean)",
764                       oo->name, state->Qpoint.size() != 0, itemClean, latentClean);
765         }
766
767         if (state->Qpoint.size() == 0 || !latentClean) {
768                 ba81SetupQuadrature(oo, state->targetQpoints);
769         }
770         if (!itemClean) {
771                 ba81OutcomeProb(state, TRUE, FALSE);
772                 ba81Estep1(oo);
773         }
774
775         state->itemParamVersion = omxGetMatrixVersion(state->itemParam);
776         state->latentParamVersion = getLatentVersion(state);
777 }
778
779 static void
780 copyScore(int rows, int maxAbilities, std::vector<double> &mean,
781           std::vector<double> &cov, const int rx, double *scores, const int dest)
782 {
783         for (int ax=0; ax < maxAbilities; ++ax) {
784                 scores[rows * ax + dest] = mean[maxAbilities * rx + ax];
785         }
786         for (int ax=0; ax < maxAbilities; ++ax) {
787                 scores[rows * (maxAbilities + ax) + dest] =
788                         sqrt(cov[triangleLoc1(maxAbilities) * rx + triangleLoc0(ax)]);
789         }
790         for (int ax=0; ax < triangleLoc1(maxAbilities); ++ax) {
791                 scores[rows * (2*maxAbilities + ax) + dest] =
792                         cov[triangleLoc1(maxAbilities) * rx + ax];
793         }
794 }
795
796 /**
797  * MAP is not affected by the number of items. EAP is. Likelihood can
798  * get concentrated in a single quadrature ordinate. For 3PL, response
799  * patterns can have a bimodal likelihood. This will confuse MAP and
800  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
801  *
802  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
803  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
804  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
805  */
806 static void
807 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
808 {
809         BA81Expect *state = (BA81Expect *) oo->argStruct;
810         int maxAbilities = state->maxAbilities;
811
812         SEXP Rmean, Rcov;
813         PROTECT(Rmean = allocVector(REALSXP, maxAbilities));
814         memcpy(REAL(Rmean), state->ElatentMean.data(), maxAbilities * sizeof(double));
815
816         PROTECT(Rcov = allocMatrix(REALSXP, maxAbilities, maxAbilities));
817         memcpy(REAL(Rcov), state->ElatentCov.data(), maxAbilities * maxAbilities * sizeof(double));
818
819         setAttrib(robj, install("empirical.mean"), Rmean);
820         setAttrib(robj, install("empirical.cov"), Rcov);
821         setAttrib(robj, install("numStats"), ScalarReal(state->numUnique - 1)); // missingness? latent params? TODO
822
823         if (state->type == EXPECTATION_AUGMENTED) {
824                 const double LogLargest = state->LogLargestDouble;
825                 int numUnique = state->numUnique;
826                 int totalOutcomes = state->totalOutcomes;
827                 SEXP Rlik;
828                 SEXP Rexpected;
829
830                 PROTECT(Rlik = allocVector(REALSXP, numUnique));
831                 memcpy(REAL(Rlik), state->patternLik, sizeof(double) * numUnique);
832                 double *lik_out = REAL(Rlik);
833                 for (int px=0; px < numUnique; ++px) {
834                         // Must return value in log units because it may not be representable otherwise
835                         lik_out[px] = log(lik_out[px]) - LogLargest;
836                 }
837
838                 PROTECT(Rexpected = allocVector(REALSXP, state->totalQuadPoints * totalOutcomes));
839                 memcpy(REAL(Rexpected), state->expected, sizeof(double) * totalOutcomes * state->totalQuadPoints);
840
841                 setAttrib(robj, install("patternLikelihood"), Rlik);
842                 setAttrib(robj, install("em.expected"), Rexpected);
843         }
844
845         if (state->scores == SCORES_OMIT || state->type == EXPECTATION_UNINITIALIZED) return;
846
847         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
848         // model. Journal of Educational Statistics, 12, 339-368.
849
850         /*
851         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
852
853         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
854                 // Thissen & Orlando (2001, p. 136)
855                 warning("EAP requires at least 2*sqrt(items) quadrature points");
856         }
857
858         ba81SetupQuadrature(oo, numQpoints, 0);
859         ba81Estep1(oo);
860         */
861
862         std::vector<double> mean;
863         std::vector<double> cov;
864         EAPinternalFast(oo, &mean, &cov);
865
866         int numUnique = state->numUnique;
867         omxData *data = state->data;
868         int rows = state->scores == SCORES_FULL? data->rows : numUnique;
869         int cols = 2 * maxAbilities + triangleLoc1(maxAbilities);
870         SEXP Rscores;
871         PROTECT(Rscores = allocMatrix(REALSXP, rows, cols));
872         double *scores = REAL(Rscores);
873
874         const int SMALLBUF = 10;
875         char buf[SMALLBUF];
876         SEXP names;
877         PROTECT(names = allocVector(STRSXP, cols));
878         for (int nx=0; nx < maxAbilities; ++nx) {
879                 snprintf(buf, SMALLBUF, "s%d", nx+1);
880                 SET_STRING_ELT(names, nx, mkChar(buf));
881                 snprintf(buf, SMALLBUF, "se%d", nx+1);
882                 SET_STRING_ELT(names, maxAbilities + nx, mkChar(buf));
883         }
884         for (int nx=0; nx < triangleLoc1(maxAbilities); ++nx) {
885                 snprintf(buf, SMALLBUF, "cov%d", nx+1);
886                 SET_STRING_ELT(names, maxAbilities*2 + nx, mkChar(buf));
887         }
888         SEXP dimnames;
889         PROTECT(dimnames = allocVector(VECSXP, 2));
890         SET_VECTOR_ELT(dimnames, 1, names);
891         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
892
893         if (state->scores == SCORES_FULL) {
894 #pragma omp parallel for num_threads(Global->numThreads)
895                 for (int rx=0; rx < numUnique; rx++) {
896                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
897                         for (int dup=0; dup < dups; dup++) {
898                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
899                                 copyScore(rows, maxAbilities, mean, cov, rx, scores, dest);
900                         }
901                 }
902         } else {
903 #pragma omp parallel for num_threads(Global->numThreads)
904                 for (int rx=0; rx < numUnique; rx++) {
905                         copyScore(rows, maxAbilities, mean, cov, rx, scores, rx);
906                 }
907         }
908
909         setAttrib(robj, install("scores.out"), Rscores);
910 }
911
912 static void ba81Destroy(omxExpectation *oo) {
913         if(OMX_DEBUG) {
914                 mxLog("Freeing %s function.", oo->name);
915         }
916         BA81Expect *state = (BA81Expect *) oo->argStruct;
917         omxFreeAllMatrixData(state->design);
918         omxFreeAllMatrixData(state->latentMeanOut);
919         omxFreeAllMatrixData(state->latentCovOut);
920         omxFreeAllMatrixData(state->customPrior);
921         omxFreeAllMatrixData(state->itemParam);
922         Free(state->numIdentical);
923         Free(state->rowMap);
924         Free(state->patternLik);
925         Free(state->Sgroup);
926         Free(state->expected);
927         Free(state->outcomeProb);
928         delete state;
929 }
930
931 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
932 {
933     SEXP matrixDims;
934     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
935     int *dimList = INTEGER(matrixDims);
936     *rows = dimList[0];
937     *cols = dimList[1];
938     UNPROTECT(1);
939 }
940
941 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
942 {}
943
944 void omxInitExpectationBA81(omxExpectation* oo) {
945         omxState* currentState = oo->currentState;      
946         SEXP rObj = oo->rObj;
947         SEXP tmp;
948         
949         if(OMX_DEBUG) {
950                 mxLog("Initializing %s.", oo->name);
951         }
952         if (!rpf_model) {
953                 if (0) {
954                         const int wantVersion = 3;
955                         int version;
956                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
957                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
958                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
959                                                          version, wantVersion);
960                 } else {
961                         rpf_numModels = librpf_numModels;
962                         rpf_model = librpf_model;
963                 }
964         }
965         
966         BA81Expect *state = new BA81Expect;
967
968         // These two constants should be as identical as possible
969         state->LogLargestDouble = log(std::numeric_limits<double>::max()) - 1;
970         state->LargestDouble = exp(state->LogLargestDouble);
971         state->OneOverLargestDouble = 1/state->LargestDouble;
972
973         state->numSpecific = 0;
974         state->excludedPatterns = 0;
975         state->numIdentical = NULL;
976         state->rowMap = NULL;
977         state->design = NULL;
978         state->patternLik = NULL;
979         state->outcomeProb = NULL;
980         state->expected = NULL;
981         state->type = EXPECTATION_UNINITIALIZED;
982         state->scores = SCORES_OMIT;
983         state->itemParam = NULL;
984         state->EitemParam = NULL;
985         state->customPrior = NULL;
986         state->itemParamVersion = 0;
987         state->latentParamVersion = 0;
988         state->quadGridSize = 0;
989         oo->argStruct = (void*) state;
990
991         PROTECT(tmp = GET_SLOT(rObj, install("data")));
992         state->data = omxDataLookupFromState(tmp, currentState);
993
994         if (strcmp(omxDataType(state->data), "raw") != 0) {
995                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", oo->name, omxDataType(state->data));
996                 return;
997         }
998
999         PROTECT(tmp = GET_SLOT(rObj, install("ItemSpec")));
1000         for (int sx=0; sx < length(tmp); ++sx) {
1001                 SEXP model = VECTOR_ELT(tmp, sx);
1002                 if (!OBJECT(model)) {
1003                         error("Item models must inherit rpf.base");
1004                 }
1005                 SEXP spec;
1006                 PROTECT(spec = GET_SLOT(model, install("spec")));
1007                 state->itemSpec.push_back(REAL(spec));
1008         }
1009
1010         PROTECT(tmp = GET_SLOT(rObj, install("design")));
1011         if (!isNull(tmp)) {
1012                 // better to demand integers and not coerce to real TODO
1013                 state->design = omxNewMatrixFromRPrimitive(tmp, globalState, FALSE, 0);
1014         }
1015
1016         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean");
1017         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
1018         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
1019         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
1020
1021         state->itemParam =
1022                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
1023
1024         PROTECT(tmp = GET_SLOT(rObj, install("EItemParam")));
1025         if (!isNull(tmp)) {
1026                 int rows, cols;
1027                 getMatrixDims(tmp, &rows, &cols);
1028                 if (rows != state->itemParam->rows || cols != state->itemParam->cols) {
1029                         error("EItemParam must have same dimensions as ItemParam");
1030                 }
1031                 state->EitemParam = REAL(tmp);
1032         }
1033
1034         oo->computeFun = ba81compute;
1035         oo->setVarGroup = ignoreSetVarGroup;
1036         oo->destructFun = ba81Destroy;
1037         oo->populateAttrFun = ba81PopulateAttributes;
1038         
1039         // TODO: Exactly identical rows do not contribute any information.
1040         // The sorting algorithm ought to remove them so we don't waste RAM.
1041         // The following summary stats would be cheaper to calculate too.
1042
1043         int numUnique = 0;
1044         omxData *data = state->data;
1045         if (omxDataNumFactor(data) != data->cols) {
1046                 // verify they are ordered factors TODO
1047                 omxRaiseErrorf(currentState, "%s: all columns must be factors", oo->name);
1048                 return;
1049         }
1050
1051         for (int rx=0; rx < data->rows;) {
1052                 rx += omxDataNumIdenticalRows(state->data, rx);
1053                 ++numUnique;
1054         }
1055         state->numUnique = numUnique;
1056
1057         state->rowMap = Realloc(NULL, numUnique, int);
1058         state->numIdentical = Realloc(NULL, numUnique, int);
1059
1060         state->customPrior =
1061                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
1062         
1063         int numItems = state->itemParam->cols;
1064         if (data->cols != numItems) {
1065                 error("Data has %d columns for %d items", data->cols, numItems);
1066         }
1067
1068         int maxSpec = 0;
1069         int maxParam = 0;
1070         state->maxDims = 0;
1071
1072         std::vector<int> &itemOutcomes = state->itemOutcomes;
1073         std::vector<int> &cumItemOutcomes = state->cumItemOutcomes;
1074         itemOutcomes.resize(numItems);
1075         cumItemOutcomes.resize(numItems);
1076         int totalOutcomes = 0;
1077         for (int cx = 0; cx < data->cols; cx++) {
1078                 const double *spec = state->itemSpec[cx];
1079                 int id = spec[RPF_ISpecID];
1080                 int dims = spec[RPF_ISpecDims];
1081                 if (state->maxDims < dims)
1082                         state->maxDims = dims;
1083
1084                 int no = spec[RPF_ISpecOutcomes];
1085                 itemOutcomes[cx] = no;
1086                 cumItemOutcomes[cx] = totalOutcomes;
1087                 totalOutcomes += no;
1088
1089                 // TODO this summary stat should be available from omxData
1090                 int dataMax=0;
1091                 for (int rx=0; rx < data->rows; rx++) {
1092                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1093                         if (dataMax < pick)
1094                                 dataMax = pick;
1095                 }
1096                 if (dataMax > no) {
1097                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1098                 } else if (dataMax < no) {
1099                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1100                         // promote to error?
1101                         // should complain if an outcome is not represented in the data TODO
1102                 }
1103
1104                 int numSpec = (*rpf_model[id].numSpec)(spec);
1105                 if (maxSpec < numSpec)
1106                         maxSpec = numSpec;
1107
1108                 int numParam = (*rpf_model[id].numParam)(spec);
1109                 if (maxParam < numParam)
1110                         maxParam = numParam;
1111         }
1112
1113         state->totalOutcomes = totalOutcomes;
1114
1115         if (int(state->itemSpec.size()) != data->cols) {
1116                 omxRaiseErrorf(currentState, "ItemSpec must contain %d item model specifications",
1117                                data->cols);
1118                 return;
1119         }
1120
1121         for (int rx=0, ux=0; rx < data->rows; ux++) {
1122                 int dups = omxDataNumIdenticalRows(state->data, rx);
1123                 state->numIdentical[ux] = dups;
1124                 state->rowMap[ux] = rx;
1125                 rx += dups;
1126         }
1127
1128         if (state->design == NULL) {
1129                 state->maxAbilities = state->maxDims;
1130                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1131                                        TRUE, currentState);
1132                 for (int ix=0; ix < numItems; ix++) {
1133                         const double *spec = state->itemSpec[ix];
1134                         int dims = spec[RPF_ISpecDims];
1135                         for (int dx=0; dx < state->maxDims; dx++) {
1136                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1137                         }
1138                 }
1139         } else {
1140                 omxMatrix *design = state->design;
1141                 if (design->cols != numItems ||
1142                     design->rows != state->maxDims) {
1143                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1144                                        state->maxDims, numItems);
1145                         return;
1146                 }
1147
1148                 state->maxAbilities = 0;
1149                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1150                         double got = design->data[ix];
1151                         if (!R_FINITE(got)) continue;
1152                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1153                         if (state->maxAbilities < got)
1154                                 state->maxAbilities = got;
1155                 }
1156                 for (int ix=0; ix < design->cols; ix++) {
1157                         const double *idesign = omxMatrixColumn(design, ix);
1158                         int ddim = 0;
1159                         for (int rx=0; rx < design->rows; rx++) {
1160                                 if (isfinite(idesign[rx])) ddim += 1;
1161                         }
1162                         const double *spec = state->itemSpec[ix];
1163                         int dims = spec[RPF_ISpecDims];
1164                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1165                 }
1166         }
1167         if (state->maxAbilities <= state->maxDims) {
1168                 state->Sgroup = Calloc(numItems, int);
1169         } else {
1170                 // Not sure if this is correct, revisit TODO
1171                 int Sgroup0 = -1;
1172                 state->Sgroup = Realloc(NULL, numItems, int);
1173                 for (int dx=0; dx < state->maxDims; dx++) {
1174                         for (int ix=0; ix < numItems; ix++) {
1175                                 int ability = omxMatrixElement(state->design, dx, ix);
1176                                 if (dx < state->maxDims - 1) {
1177                                         if (Sgroup0 <= ability)
1178                                                 Sgroup0 = ability+1;
1179                                         continue;
1180                                 }
1181                                 int ss=-1;
1182                                 if (ability >= Sgroup0) {
1183                                         if (ss == -1) {
1184                                                 ss = ability;
1185                                         } else {
1186                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1187                                                                "1 specific dimension (both %d and %d)",
1188                                                                ix, ss, ability);
1189                                                 return;
1190                                         }
1191                                 }
1192                                 if (ss == -1) ss = Sgroup0;
1193                                 state->Sgroup[ix] = ss - Sgroup0;
1194                         }
1195                 }
1196                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1197         }
1198
1199         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1200                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1201                       state->maxAbilities, state->maxAbilities);
1202         }
1203         if (state->latentCovOut->rows != state->maxAbilities ||
1204             state->latentCovOut->cols != state->maxAbilities) {
1205                 error("The cov matrix '%s' must be %dx%d",
1206                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1207         }
1208
1209         PROTECT(tmp = GET_SLOT(rObj, install("verbose")));
1210         state->verbose = asLogical(tmp);
1211
1212         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1213         state->targetQpoints = asReal(tmp);
1214
1215         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1216         state->Qwidth = asReal(tmp);
1217
1218         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1219         const char *score_option = CHAR(asChar(tmp));
1220         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1221         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1222         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1223
1224         state->ElatentMean.resize(state->maxAbilities);
1225         state->ElatentCov.resize(state->maxAbilities * state->maxAbilities);
1226
1227         // verify data bounded between 1 and numOutcomes TODO
1228         // hm, looks like something could be added to omxData for column summary stats?
1229 }