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