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