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