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