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