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