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