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