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