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