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