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