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