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