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