Avoid exp(); more than doubles performance; no detectable loss in accuracy
[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->speLogQarea[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->speLogQarea.resize(gridsize * numSpecific);
489                 state->speQarea.resize(gridsize * numSpecific);
490         }
491
492         state->Qpoint.resize(gridsize);
493         state->priLogQarea.resize(state->totalPrimaryPoints);
494         state->priQarea.resize(state->totalPrimaryPoints);
495
496         double qgs = state->quadGridSize-1;
497         for (int px=0; px < state->quadGridSize; px ++) {
498                 state->Qpoint[px] = Qwidth - px * 2 * Qwidth / qgs;
499         }
500
501         if (flat) {
502                 // not sure why this is useful, remove? TODO
503                 double flatd = log(1) - log(state->totalPrimaryPoints);
504                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
505                         state->priLogQarea[qx] = flatd;
506                 }
507                 flatd = log(1) - log(state->quadGridSize);
508                 for (int sx=0; sx < numSpecific; sx++) {
509                         for (int qx=0; qx < state->quadGridSize; qx++) {
510                                 state->speLogQarea[sIndex(state, sx, qx)] = flatd;
511                         }
512                 }
513         } else {
514                 //pda(state->latentMeanOut->data, 1, state->maxAbilities);
515                 //pda(state->latentCovOut->data, state->maxAbilities, state->maxAbilities);
516
517                 double totalArea = 0;
518                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
519                         int quad[priDims];
520                         decodeLocation(qx, priDims, state->quadGridSize, quad);
521                         double where[priDims];
522                         pointToWhere(state, quad, where, priDims);
523                         state->priLogQarea[qx] = dmvnorm(priDims, where,
524                                                          state->latentMeanOut->data,
525                                                          state->latentCovOut->data);
526                         totalArea += exp(state->priLogQarea[qx]);
527                 }
528                 totalArea = log(totalArea);
529                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
530                         state->priLogQarea[qx] -= totalArea;
531                         state->priQarea[qx] = exp(state->priLogQarea[qx]);
532                         //mxLog("%.5g,", state->priLogQarea[qx]);
533                 }
534
535                 for (int sx=0; sx < numSpecific; sx++) {
536                         totalArea = 0;
537                         int covCell = (priDims + sx) * state->maxAbilities + priDims + sx;
538                         double mean = state->latentMeanOut->data[priDims + sx];
539                         double var = state->latentCovOut->data[covCell];
540                         //mxLog("setup[%d] %.2f %.2f", sx, mean, var);
541                         for (int qx=0; qx < state->quadGridSize; qx++) {
542                                 double den = dnorm(state->Qpoint[qx], mean, sqrt(var), TRUE);
543                                 state->speLogQarea[sIndex(state, sx, qx)] = den;
544                                 totalArea += exp(den);
545                         }
546                         totalArea = log(totalArea);
547                         for (int qx=0; qx < state->quadGridSize; qx++) {
548                                 state->speLogQarea[sIndex(state, sx, qx)] -= totalArea;
549                                 state->speQarea[sIndex(state, sx, qx)] = exp(state->speLogQarea[sIndex(state, sx, qx)]);
550                         }
551                         //pda(state->speLogQarea.data() + sIndex(state, sx, 0), 1, state->quadGridSize);
552                 }
553         }
554
555         if (!state->cacheLXK) {
556                 state->lxk = Realloc(state->lxk, numUnique * numThreads, double);
557         } else {
558                 int ns = state->numSpecific;
559                 if (ns == 0) ns = 1;
560                 long numOrdinate = ns * state->totalQuadPoints;
561                 state->lxk = Realloc(state->lxk, numUnique * numOrdinate, double);
562         }
563
564         state->expected = Realloc(state->expected, state->totalOutcomes * state->totalQuadPoints, double);
565 }
566
567 void ba81buildLXKcache(omxExpectation *oo)
568 {
569         BA81Expect *state = (BA81Expect *) oo->argStruct;
570         if (!state->cacheLXK || state->LXKcached) return;
571         
572         ba81Estep1(oo);
573 }
574
575 OMXINLINE static void
576 expectedUpdate(omxData *data, const int *rowMap, const int px, const int item,
577                const double observed, const int outcomes, double *out)
578 {
579         int pick = omxIntDataElementUnsafe(data, rowMap[px], item);
580         if (pick == NA_INTEGER) {
581                 double slice = observed / outcomes;
582                 for (int ox=0; ox < outcomes; ox++) {
583                         out[ox] += slice;
584                 }
585         } else {
586                 out[pick-1] += observed;
587         }
588 }
589
590 double *getLogPatternLik(omxExpectation* oo)
591 {
592         BA81Expect *state = (BA81Expect*) oo->argStruct;
593         if (state->_logPatternLik) return state->_logPatternLik;
594
595         int numUnique = state->numUnique;
596         state->_logPatternLik = Realloc(NULL, numUnique, double);
597
598         if (!state->patternLik) {
599                 ba81SetupQuadrature(oo, state->targetQpoints, 0);
600                 ba81Estep1(oo);
601         }
602
603 #pragma omp parallel for num_threads(Global->numThreads)
604         for (int px=0; px < numUnique; ++px) {
605                 state->_logPatternLik[px] = log(state->patternLik[px]);
606         }
607
608         return state->_logPatternLik;
609 }
610
611 OMXINLINE static void
612 ba81Expected(omxExpectation* oo)
613 {
614         BA81Expect *state = (BA81Expect*) oo->argStruct;
615         omxData *data = state->data;
616         int numSpecific = state->numSpecific;
617         const int *rowMap = state->rowMap;
618         double *patternLik = state->patternLik;
619         int *numIdentical = state->numIdentical;
620         int numUnique = state->numUnique;
621         int maxDims = state->maxDims;
622         int numItems = state->EitemParam->cols;
623         int totalOutcomes = state->totalOutcomes;
624
625         OMXZERO(state->expected, totalOutcomes * state->totalQuadPoints);
626
627         if (numSpecific == 0) {
628 #pragma omp parallel for num_threads(Global->numThreads)
629                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
630                         int thrId = omx_absolute_thread_num();
631                         int quad[maxDims];
632                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
633                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, quad);
634                         for (int px=0; px < numUnique; px++) {
635                                 double *out = state->expected + qx * totalOutcomes;
636                                 double observed = numIdentical[px] * lxk[px] / patternLik[px];
637                                 for (int ix=0; ix < numItems; ix++) {
638                                         const double *spec = state->itemSpec[ix];
639                                         int outcomes = spec[RPF_ISpecOutcomes];
640                                         expectedUpdate(data, rowMap, px, ix, observed, outcomes, out);
641                                         out += outcomes;
642                                 }
643                         }
644                 }
645         } else {
646                 int sDim = state->maxDims-1;
647                 long specificPoints = state->quadGridSize;
648
649 #pragma omp parallel for num_threads(Global->numThreads)
650                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
651                         int thrId = omx_absolute_thread_num();
652                         int quad[maxDims];
653                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
654
655                         cai2010(oo, thrId, FALSE, quad);
656
657                         for (long sx=0; sx < specificPoints; sx++) {
658                                 quad[sDim] = sx;
659                                 long qloc = encodeLocation(state->maxDims, state->quadGridSize, quad);
660
661                                 for (int sgroup=0; sgroup < numSpecific; sgroup++) {
662                                         double *lxk = ba81LikelihoodFast(oo, thrId, sgroup, quad);
663
664                                         for (int px=0; px < numUnique; px++) {
665                                                 double *out = state->expected + totalOutcomes * qloc;
666
667                                                 for (int ix=0; ix < numItems; ix++) {
668                                                         const double *spec = state->itemSpec[ix];
669                                                         int outcomes = spec[RPF_ISpecOutcomes];
670                                                         if (state->Sgroup[ix] == sgroup) {
671                                                                 double Ei = state->allElxk[eIndex(state, thrId, px)];
672                                                                 double Eis = state->Eslxk[esIndex(state, thrId, sgroup, px)];
673                                                                 double observed = (numIdentical[px] * (Ei / Eis) *
674                                                                                    (lxk[px] / patternLik[px]));
675                                                                 expectedUpdate(data, rowMap, px, ix, observed, outcomes, out);
676                                                         }
677                                                         out += outcomes;
678                                                 }
679                                         }
680                                 }
681                         }
682                 }
683         }
684         //pda(state->expected, state->totalOutcomes, state->totalQuadPoints);
685 }
686
687 OMXINLINE static void
688 accumulateScores(BA81Expect *state, int px, int sgroup, double piece, const double *where,
689                  int primaryDims, int covEntries, std::vector<double> *mean, std::vector<double> *cov)
690 {
691         int maxDims = state->maxDims;
692         int maxAbilities = state->maxAbilities;
693
694         if (sgroup == 0) {
695                 int cx=0;
696                 for (int d1=0; d1 < primaryDims; d1++) {
697                         double piece_w1 = piece * where[d1];
698                         double &dest1 = (*mean)[px * maxAbilities + d1];
699 #pragma omp atomic
700                         dest1 += piece_w1;
701                         for (int d2=0; d2 <= d1; d2++) {
702                                 double &dest2 = (*cov)[px * covEntries + cx];
703 #pragma omp atomic
704                                 dest2 += where[d2] * piece_w1;
705                                 ++cx;
706                         }
707                 }
708         }
709
710         if (state->numSpecific) {
711                 int sdim = maxDims + sgroup - 1;
712                 double piece_w1 = piece * where[primaryDims];
713                 double &dest3 = (*mean)[px * maxAbilities + sdim];
714 #pragma omp atomic
715                 dest3 += piece_w1;
716
717                 double &dest4 = (*cov)[px * covEntries + triangleLoc0(sdim)];
718 #pragma omp atomic
719                 dest4 += piece_w1 * where[primaryDims];
720         }
721 }
722
723 static void
724 EAPinternalFast(omxExpectation *oo, std::vector<double> *mean, std::vector<double> *cov)
725 {
726         BA81Expect *state = (BA81Expect*) oo->argStruct;
727         int numUnique = state->numUnique;
728         int numSpecific = state->numSpecific;
729         int maxDims = state->maxDims;
730         int maxAbilities = state->maxAbilities;
731         int primaryDims = maxDims;
732         int covEntries = triangleLoc1(maxAbilities);
733
734         mean->assign(numUnique * maxAbilities, 0);
735         cov->assign(numUnique * covEntries, 0);
736
737         if (numSpecific == 0) {
738 #pragma omp parallel for num_threads(Global->numThreads)
739                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
740                         const int thrId = omx_absolute_thread_num();
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, thrId, 0, quad);
747
748                         double area = state->priQarea[qx];
749                         for (int px=0; px < numUnique; px++) {
750                                 double tmp = lxk[px] * area;
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                         const int thrId = omx_absolute_thread_num();
762                         int quad[maxDims];
763                         decodeLocation(qx, primaryDims, state->quadGridSize, quad);
764
765                         cai2010(oo, thrId, FALSE, quad);
766
767                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
768                                 for (long sx=0; sx < specificPoints; sx++) {
769                                         quad[sDim] = sx;
770                                         double where[maxDims];
771                                         pointToWhere(state, quad, where, maxDims);
772                                         double area = areaProduct(state, quad, sgroup);
773                                         double *lxk = ba81LikelihoodFast(oo, thrId, sgroup, quad);
774                                         for (int px=0; px < numUnique; px++) {
775                                                 double Ei = state->allElxk[eIndex(state, thrId, px)];
776                                                 double Eis = state->Eslxk[esIndex(state, thrId, sgroup, px)];
777                                                 double tmp = ((Ei / Eis) * lxk[px] * area);
778                                                 accumulateScores(state, px, sgroup, tmp, where, primaryDims,
779                                                                  covEntries, mean, cov);
780                                         }
781                                 }
782                         }
783                 }
784         }
785
786         double *patternLik = state->patternLik;
787         for (int px=0; px < numUnique; px++) {
788                 double denom = patternLik[px];
789                 for (int ax=0; ax < maxAbilities; ax++) {
790                         (*mean)[px * maxAbilities + ax] /= denom;
791                 }
792                 for (int cx=0; cx < triangleLoc1(primaryDims); ++cx) {
793                         (*cov)[px * covEntries + cx] /= denom;
794                 }
795                 for (int sx=0; sx < numSpecific; sx++) {
796                         (*cov)[px * covEntries + triangleLoc0(primaryDims + sx)] /= denom;
797                 }
798                 int cx=0;
799                 for (int a1=0; a1 < primaryDims; ++a1) {
800                         for (int a2=0; a2 <= a1; ++a2) {
801                                 double ma1 = (*mean)[px * maxAbilities + a1];
802                                 double ma2 = (*mean)[px * maxAbilities + a2];
803                                 (*cov)[px * covEntries + cx] -= ma1 * ma2;
804                                 ++cx;
805                         }
806                 }
807                 for (int sx=0; sx < numSpecific; sx++) {
808                         int sdim = primaryDims + sx;
809                         double ma1 = (*mean)[px * maxAbilities + sdim];
810                         (*cov)[px * covEntries + triangleLoc0(sdim)] -= ma1 * ma1;
811                 }
812         }
813 }
814
815 static void
816 ba81Estep(omxExpectation *oo, const char *context)
817 {
818         if (!context) {
819                 //warning("%s: No context specified hence expectation cannot be evaluated", NAME);
820                 return;
821         }
822
823         BA81Expect *state = (BA81Expect *) oo->argStruct;
824
825         if (strcmp(context, "EM")==0) {
826                 state->type = EXPECTATION_AUGMENTED;
827         } else if (context[0] == 0) {
828                 state->type = EXPECTATION_OBSERVED;
829         } else {
830                 omxRaiseErrorf(globalState, "Unknown context '%s'", context);
831                 return;
832         }
833
834         omxRecompute(state->EitemParam);
835         omxRecompute(state->latentMeanOut);
836         omxRecompute(state->latentCovOut);
837
838         if (state->type == EXPECTATION_AUGMENTED) {
839                 if (state->Qpoint.size() == 0) {
840                         ba81SetupQuadrature(oo, state->targetQpoints, 0);
841                 }
842                 ba81Estep1(oo);
843                 ba81Expected(oo);
844         }
845 }
846
847 static void
848 copyScore(int rows, int maxAbilities, std::vector<double> &mean,
849           std::vector<double> &cov, const int rx, double *scores, const int dest)
850 {
851         for (int ax=0; ax < maxAbilities; ++ax) {
852                 scores[rows * ax + dest] = mean[maxAbilities * rx + ax];
853         }
854         for (int ax=0; ax < maxAbilities; ++ax) {
855                 scores[rows * (maxAbilities + ax) + dest] =
856                         sqrt(cov[triangleLoc1(maxAbilities) * rx + triangleLoc0(ax)]);
857         }
858         for (int ax=0; ax < triangleLoc1(maxAbilities); ++ax) {
859                 scores[rows * (2*maxAbilities + ax) + dest] =
860                         cov[triangleLoc1(maxAbilities) * rx + ax];
861         }
862 }
863
864 /**
865  * MAP is not affected by the number of items. EAP is. Likelihood can
866  * get concentrated in a single quadrature ordinate. For 3PL, response
867  * patterns can have a bimodal likelihood. This will confuse MAP and
868  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
869  *
870  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
871  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
872  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
873  */
874 static void
875 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
876 {
877         BA81Expect *state = (BA81Expect *) oo->argStruct;
878
879         if (state->scores == SCORES_OMIT || state->type == EXPECTATION_UNINITIALIZED) return;
880
881         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
882         // model. Journal of Educational Statistics, 12, 339-368.
883
884         /*
885         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
886
887         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
888                 // Thissen & Orlando (2001, p. 136)
889                 warning("EAP requires at least 2*sqrt(items) quadrature points");
890         }
891
892         ba81SetupQuadrature(oo, numQpoints, 0);
893         ba81Estep1(oo);
894         */
895
896         std::vector<double> mean;
897         std::vector<double> cov;
898         EAPinternalFast(oo, &mean, &cov);
899
900         int numUnique = state->numUnique;
901         omxData *data = state->data;
902         int maxAbilities = state->maxAbilities;
903         int rows = state->scores == SCORES_FULL? data->rows : numUnique;
904         int cols = 2 * maxAbilities + triangleLoc1(maxAbilities);
905         SEXP Rscores;
906         PROTECT(Rscores = allocMatrix(REALSXP, rows, cols));
907         double *scores = REAL(Rscores);
908
909         const int SMALLBUF = 10;
910         char buf[SMALLBUF];
911         SEXP names;
912         PROTECT(names = allocVector(STRSXP, cols));
913         for (int nx=0; nx < maxAbilities; ++nx) {
914                 snprintf(buf, SMALLBUF, "s%d", nx+1);
915                 SET_STRING_ELT(names, nx, mkChar(buf));
916                 snprintf(buf, SMALLBUF, "se%d", nx+1);
917                 SET_STRING_ELT(names, maxAbilities + nx, mkChar(buf));
918         }
919         for (int nx=0; nx < triangleLoc1(maxAbilities); ++nx) {
920                 snprintf(buf, SMALLBUF, "cov%d", nx+1);
921                 SET_STRING_ELT(names, maxAbilities*2 + nx, mkChar(buf));
922         }
923         SEXP dimnames;
924         PROTECT(dimnames = allocVector(VECSXP, 2));
925         SET_VECTOR_ELT(dimnames, 1, names);
926         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
927
928         if (state->scores == SCORES_FULL) {
929 #pragma omp parallel for num_threads(Global->numThreads)
930                 for (int rx=0; rx < numUnique; rx++) {
931                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
932                         for (int dup=0; dup < dups; dup++) {
933                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
934                                 copyScore(rows, maxAbilities, mean, cov, rx, scores, dest);
935                         }
936                 }
937         } else {
938 #pragma omp parallel for num_threads(Global->numThreads)
939                 for (int rx=0; rx < numUnique; rx++) {
940                         copyScore(rows, maxAbilities, mean, cov, rx, scores, rx);
941                 }
942         }
943
944         setAttrib(robj, install("scores.out"), Rscores);
945 }
946
947 static void ba81Destroy(omxExpectation *oo) {
948         if(OMX_DEBUG) {
949                 mxLog("Freeing %s function.", NAME);
950         }
951         BA81Expect *state = (BA81Expect *) oo->argStruct;
952         omxFreeAllMatrixData(state->EitemParam);
953         omxFreeAllMatrixData(state->design);
954         omxFreeAllMatrixData(state->latentMeanOut);
955         omxFreeAllMatrixData(state->latentCovOut);
956         omxFreeAllMatrixData(state->customPrior);
957         omxFreeAllMatrixData(state->itemParam);
958         Free(state->logNumIdentical);
959         Free(state->numIdentical);
960         Free(state->rowMap);
961         Free(state->patternLik);
962         Free(state->_logPatternLik);
963         Free(state->lxk);
964         Free(state->Sgroup);
965         Free(state->expected);
966         Free(state->ElatentMean);
967         Free(state->ElatentCov);
968         delete state;
969 }
970
971 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
972 {
973     SEXP matrixDims;
974     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
975     int *dimList = INTEGER(matrixDims);
976     *rows = dimList[0];
977     *cols = dimList[1];
978     UNPROTECT(1);
979 }
980
981 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
982 {}
983
984 void omxInitExpectationBA81(omxExpectation* oo) {
985         omxState* currentState = oo->currentState;      
986         SEXP rObj = oo->rObj;
987         SEXP tmp;
988         
989         if(OMX_DEBUG) {
990                 mxLog("Initializing %s.", NAME);
991         }
992         if (!rpf_model) {
993                 if (0) {
994                         const int wantVersion = 3;
995                         int version;
996                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
997                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
998                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
999                                                          version, wantVersion);
1000                 } else {
1001                         rpf_numModels = librpf_numModels;
1002                         rpf_model = librpf_model;
1003                 }
1004         }
1005         
1006         BA81Expect *state = new BA81Expect;
1007         state->numSpecific = 0;
1008         state->numIdentical = NULL;
1009         state->logNumIdentical = NULL;
1010         state->rowMap = NULL;
1011         state->design = NULL;
1012         state->lxk = NULL;
1013         state->patternLik = NULL;
1014         state->_logPatternLik = NULL;
1015         state->expected = NULL;
1016         state->ElatentMean = NULL;
1017         state->ElatentCov = NULL;
1018         state->type = EXPECTATION_UNINITIALIZED;
1019         state->scores = SCORES_OMIT;
1020         state->itemParam = NULL;
1021         state->customPrior = NULL;
1022         oo->argStruct = (void*) state;
1023
1024         PROTECT(tmp = GET_SLOT(rObj, install("data")));
1025         state->data = omxDataLookupFromState(tmp, currentState);
1026
1027         if (strcmp(omxDataType(state->data), "raw") != 0) {
1028                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", NAME, omxDataType(state->data));
1029                 return;
1030         }
1031
1032         PROTECT(tmp = GET_SLOT(rObj, install("ItemSpec")));
1033         for (int sx=0; sx < length(tmp); ++sx) {
1034                 SEXP model = VECTOR_ELT(tmp, sx);
1035                 if (!OBJECT(model)) {
1036                         error("Item models must inherit rpf.base");
1037                 }
1038                 SEXP spec;
1039                 PROTECT(spec = GET_SLOT(model, install("spec")));
1040                 state->itemSpec.push_back(REAL(spec));
1041         }
1042
1043         PROTECT(tmp = GET_SLOT(rObj, install("design")));
1044         if (!isNull(tmp)) {
1045                 // better to demand integers and not coerce to real TODO
1046                 state->design = omxNewMatrixFromRPrimitive(tmp, globalState, FALSE, 0);
1047         }
1048
1049         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean");
1050         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
1051         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
1052         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
1053
1054         state->EitemParam =
1055                 omxNewMatrixFromSlot(rObj, currentState, "EItemParam");
1056         if (!state->EitemParam) error("Must supply EItemParam");
1057
1058         state->itemParam =
1059                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
1060
1061         if (state->EitemParam->rows != state->itemParam->rows ||
1062             state->EitemParam->cols != state->itemParam->cols) {
1063                 error("ItemParam and EItemParam must be of the same dimension");
1064         }
1065
1066         oo->computeFun = ba81Estep;
1067         oo->setVarGroup = ignoreSetVarGroup;
1068         oo->destructFun = ba81Destroy;
1069         oo->populateAttrFun = ba81PopulateAttributes;
1070         
1071         // TODO: Exactly identical rows do not contribute any information.
1072         // The sorting algorithm ought to remove them so we don't waste RAM.
1073         // The following summary stats would be cheaper to calculate too.
1074
1075         int numUnique = 0;
1076         omxData *data = state->data;
1077         if (omxDataNumFactor(data) != data->cols) {
1078                 // verify they are ordered factors TODO
1079                 omxRaiseErrorf(currentState, "%s: all columns must be factors", NAME);
1080                 return;
1081         }
1082
1083         for (int rx=0; rx < data->rows;) {
1084                 rx += omxDataNumIdenticalRows(state->data, rx);
1085                 ++numUnique;
1086         }
1087         state->numUnique = numUnique;
1088
1089         state->rowMap = Realloc(NULL, numUnique, int);
1090         state->numIdentical = Realloc(NULL, numUnique, int);
1091         state->logNumIdentical = Realloc(NULL, numUnique, double);
1092
1093         state->customPrior =
1094                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
1095         
1096         int numItems = state->EitemParam->cols;
1097         if (data->cols != numItems) {
1098                 error("Data has %d columns for %d items", data->cols, numItems);
1099         }
1100
1101         for (int rx=0, ux=0; rx < data->rows; ux++) {
1102                 if (rx == 0) {
1103                         // all NA rows will sort to the top
1104                         int na=0;
1105                         for (int ix=0; ix < numItems; ix++) {
1106                                 if (omxIntDataElement(data, 0, ix) == NA_INTEGER) { ++na; }
1107                         }
1108                         if (na == numItems) {
1109                                 omxRaiseErrorf(currentState, "Remove rows with all NAs");
1110                                 return;
1111                         }
1112                 }
1113                 int dups = omxDataNumIdenticalRows(state->data, rx);
1114                 state->numIdentical[ux] = dups;
1115                 state->logNumIdentical[ux] = log(dups);
1116                 state->rowMap[ux] = rx;
1117                 rx += dups;
1118         }
1119
1120         int numThreads = Global->numThreads;
1121
1122         int maxSpec = 0;
1123         int maxParam = 0;
1124         state->maxDims = 0;
1125         state->maxOutcomes = 0;
1126
1127         int totalOutcomes = 0;
1128         for (int cx = 0; cx < data->cols; cx++) {
1129                 const double *spec = state->itemSpec[cx];
1130                 int id = spec[RPF_ISpecID];
1131                 int dims = spec[RPF_ISpecDims];
1132                 if (state->maxDims < dims)
1133                         state->maxDims = dims;
1134
1135                 int no = spec[RPF_ISpecOutcomes];
1136                 totalOutcomes += no;
1137                 if (state->maxOutcomes < no)
1138                         state->maxOutcomes = no;
1139
1140                 // TODO this summary stat should be available from omxData
1141                 int dataMax=0;
1142                 for (int rx=0; rx < data->rows; rx++) {
1143                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1144                         if (dataMax < pick)
1145                                 dataMax = pick;
1146                 }
1147                 if (dataMax > no) {
1148                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1149                 } else if (dataMax < no) {
1150                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1151                         // promote to error?
1152                         // should complain if an outcome is not represented in the data TODO
1153                 }
1154
1155                 int numSpec = (*rpf_model[id].numSpec)(spec);
1156                 if (maxSpec < numSpec)
1157                         maxSpec = numSpec;
1158
1159                 int numParam = (*rpf_model[id].numParam)(spec);
1160                 if (maxParam < numParam)
1161                         maxParam = numParam;
1162         }
1163
1164         state->totalOutcomes = totalOutcomes;
1165
1166         if (int(state->itemSpec.size()) != data->cols) {
1167                 omxRaiseErrorf(currentState, "ItemSpec must contain %d item model specifications",
1168                                data->cols);
1169                 return;
1170         }
1171         if (state->EitemParam->rows != maxParam) {
1172                 omxRaiseErrorf(currentState, "ItemParam should have %d rows", maxParam);
1173                 return;
1174         }
1175
1176         if (state->design == NULL) {
1177                 state->maxAbilities = state->maxDims;
1178                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1179                                        TRUE, currentState);
1180                 for (int ix=0; ix < numItems; ix++) {
1181                         const double *spec = state->itemSpec[ix];
1182                         int dims = spec[RPF_ISpecDims];
1183                         for (int dx=0; dx < state->maxDims; dx++) {
1184                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1185                         }
1186                 }
1187         } else {
1188                 omxMatrix *design = state->design;
1189                 if (design->cols != numItems ||
1190                     design->rows != state->maxDims) {
1191                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1192                                        state->maxDims, numItems);
1193                         return;
1194                 }
1195
1196                 state->maxAbilities = 0;
1197                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1198                         double got = design->data[ix];
1199                         if (!R_FINITE(got)) continue;
1200                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1201                         if (state->maxAbilities < got)
1202                                 state->maxAbilities = got;
1203                 }
1204                 for (int ix=0; ix < design->cols; ix++) {
1205                         const double *idesign = omxMatrixColumn(design, ix);
1206                         int ddim = 0;
1207                         for (int rx=0; rx < design->rows; rx++) {
1208                                 if (isfinite(idesign[rx])) ddim += 1;
1209                         }
1210                         const double *spec = state->itemSpec[ix];
1211                         int dims = spec[RPF_ISpecDims];
1212                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1213                 }
1214         }
1215         if (state->maxAbilities <= state->maxDims) {
1216                 state->Sgroup = Calloc(numItems, int);
1217         } else {
1218                 // Not sure if this is correct, revisit TODO
1219                 int Sgroup0 = -1;
1220                 state->Sgroup = Realloc(NULL, numItems, int);
1221                 for (int dx=0; dx < state->maxDims; dx++) {
1222                         for (int ix=0; ix < numItems; ix++) {
1223                                 int ability = omxMatrixElement(state->design, dx, ix);
1224                                 if (dx < state->maxDims - 1) {
1225                                         if (Sgroup0 <= ability)
1226                                                 Sgroup0 = ability+1;
1227                                         continue;
1228                                 }
1229                                 int ss=-1;
1230                                 if (ability >= Sgroup0) {
1231                                         if (ss == -1) {
1232                                                 ss = ability;
1233                                         } else {
1234                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1235                                                                "1 specific dimension (both %d and %d)",
1236                                                                ix, ss, ability);
1237                                                 return;
1238                                         }
1239                                 }
1240                                 if (ss == -1) ss = Sgroup0;
1241                                 state->Sgroup[ix] = ss - Sgroup0;
1242                         }
1243                 }
1244                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1245                 state->allElxk.resize(numUnique * numThreads);
1246                 state->Eslxk.resize(numUnique * state->numSpecific * numThreads);
1247         }
1248
1249         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1250                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1251                       state->maxAbilities, state->maxAbilities);
1252         }
1253         if (state->latentCovOut->rows != state->maxAbilities ||
1254             state->latentCovOut->cols != state->maxAbilities) {
1255                 error("The cov matrix '%s' must be %dx%d",
1256                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1257         }
1258
1259         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1260         state->cacheLXK = asLogical(tmp);
1261         state->LXKcached = FALSE;
1262
1263         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1264         state->targetQpoints = asReal(tmp);
1265
1266         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1267         state->Qwidth = asReal(tmp);
1268
1269         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1270         const char *score_option = CHAR(asChar(tmp));
1271         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1272         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1273         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1274
1275         state->ElatentMean = Realloc(NULL, state->maxAbilities * numUnique, double);
1276         state->ElatentCov = Realloc(NULL, state->maxAbilities * state->maxAbilities * numUnique, double);
1277
1278         // verify data bounded between 1 and numOutcomes TODO
1279         // hm, looks like something could be added to omxData for column summary stats?
1280 }