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