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