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