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