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