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