A few more minor optimizations
[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
634         std::vector<int> itemOutcomes(numItems);
635         for (int ix=0; ix < numItems; ix++) {
636                 const double *spec = state->itemSpec[ix];
637                 itemOutcomes[ix] = spec[RPF_ISpecOutcomes];
638         }
639
640         OMXZERO(state->expected, totalOutcomes * state->totalQuadPoints);
641
642         if (numSpecific == 0) {
643 #pragma omp parallel for num_threads(Global->numThreads)
644                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
645                         int thrId = omx_absolute_thread_num();
646                         int quad[maxDims];
647                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
648                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, quad);
649                         for (int px=0; px < numUnique; px++) {
650                                 double *out = state->expected + qx * totalOutcomes;
651                                 double observed = numIdentical[px] * lxk[px] / patternLik[px];
652                                 for (int ix=0; ix < numItems; ix++) {
653                                         const int outcomes = itemOutcomes[ix];
654                                         expectedUpdate(data, rowMap, px, ix, observed, outcomes, out);
655                                         out += outcomes;
656                                 }
657                         }
658                 }
659         } else {
660                 int sDim = state->maxDims-1;
661                 long specificPoints = state->quadGridSize;
662
663 #pragma omp parallel for num_threads(Global->numThreads)
664                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
665                         int thrId = omx_absolute_thread_num();
666                         int quad[maxDims];
667                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
668
669                         cai2010(oo, thrId, FALSE, quad);
670                         double *allElxk = eBase(state, thrId);
671                         double *Eslxk = esBase(state, thrId);
672
673                         for (long sx=0; sx < specificPoints; sx++) {
674                                 quad[sDim] = sx;
675                                 long qloc = encodeLocation(state->maxDims, state->quadGridSize, quad);
676
677                                 for (int sgroup=0; sgroup < numSpecific; sgroup++) {
678                                         double *lxk = ba81LikelihoodFast(oo, thrId, sgroup, quad);
679                                         double *myEslxk = Eslxk + sgroup * numUnique;
680
681                                         for (int px=0; px < numUnique; px++) {
682                                                 double *out = state->expected + totalOutcomes * qloc;
683
684                                                 for (int ix=0; ix < numItems; ix++) {
685                                                         const int outcomes = itemOutcomes[ix];
686                                                         if (state->Sgroup[ix] == sgroup) {
687                                                                 double Ei = allElxk[px];
688                                                                 double Eis = myEslxk[px];
689                                                                 double observed = (numIdentical[px] * (Ei / Eis) *
690                                                                                    (lxk[px] / patternLik[px]));
691                                                                 expectedUpdate(data, rowMap, px, ix, observed, outcomes, out);
692                                                         }
693                                                         out += outcomes;
694                                                 }
695                                         }
696                                 }
697                         }
698                 }
699         }
700         //pda(state->expected, state->totalOutcomes, state->totalQuadPoints);
701 }
702
703 OMXINLINE static void
704 accumulateScores(BA81Expect *state, int px, int sgroup, double piece, const double *where,
705                  int primaryDims, int covEntries, std::vector<double> *mean, std::vector<double> *cov)
706 {
707         int maxDims = state->maxDims;
708         int maxAbilities = state->maxAbilities;
709
710         if (sgroup == 0) {
711                 int cx=0;
712                 for (int d1=0; d1 < primaryDims; d1++) {
713                         double piece_w1 = piece * where[d1];
714                         double &dest1 = (*mean)[px * maxAbilities + d1];
715 #pragma omp atomic
716                         dest1 += piece_w1;
717                         for (int d2=0; d2 <= d1; d2++) {
718                                 double &dest2 = (*cov)[px * covEntries + cx];
719 #pragma omp atomic
720                                 dest2 += where[d2] * piece_w1;
721                                 ++cx;
722                         }
723                 }
724         }
725
726         if (state->numSpecific) {
727                 int sdim = maxDims + sgroup - 1;
728                 double piece_w1 = piece * where[primaryDims];
729                 double &dest3 = (*mean)[px * maxAbilities + sdim];
730 #pragma omp atomic
731                 dest3 += piece_w1;
732
733                 double &dest4 = (*cov)[px * covEntries + triangleLoc0(sdim)];
734 #pragma omp atomic
735                 dest4 += piece_w1 * where[primaryDims];
736         }
737 }
738
739 static void
740 EAPinternalFast(omxExpectation *oo, std::vector<double> *mean, std::vector<double> *cov)
741 {
742         BA81Expect *state = (BA81Expect*) oo->argStruct;
743         if (state->verbose) mxLog("%s: EAP", oo->name);
744
745         int numUnique = state->numUnique;
746         int numSpecific = state->numSpecific;
747         int maxDims = state->maxDims;
748         int maxAbilities = state->maxAbilities;
749         int primaryDims = maxDims;
750         int covEntries = triangleLoc1(maxAbilities);
751
752         mean->assign(numUnique * maxAbilities, 0);
753         cov->assign(numUnique * covEntries, 0);
754
755         if (numSpecific == 0) {
756 #pragma omp parallel for num_threads(Global->numThreads)
757                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
758                         const int thrId = omx_absolute_thread_num();
759                         int quad[maxDims];
760                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
761                         double where[maxDims];
762                         pointToWhere(state, quad, where, maxDims);
763
764                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, quad);
765
766                         double area = state->priQarea[qx];
767                         for (int px=0; px < numUnique; px++) {
768                                 double tmp = lxk[px] * area;
769                                 accumulateScores(state, px, 0, tmp, where, primaryDims, covEntries, mean, cov);
770                         }
771                 }
772         } else {
773                 primaryDims -= 1;
774                 int sDim = primaryDims;
775                 long specificPoints = state->quadGridSize;
776
777 #pragma omp parallel for num_threads(Global->numThreads)
778                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
779                         const int thrId = omx_absolute_thread_num();
780                         int quad[maxDims];
781                         decodeLocation(qx, primaryDims, state->quadGridSize, quad);
782
783                         cai2010(oo, thrId, FALSE, quad);
784                         double *allElxk = eBase(state, thrId);
785                         double *Eslxk = esBase(state, thrId);
786
787                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
788                                 for (long sx=0; sx < specificPoints; sx++) {
789                                         quad[sDim] = sx;
790                                         double where[maxDims];
791                                         pointToWhere(state, quad, where, maxDims);
792                                         double area = areaProduct(state, quad, sgroup);
793                                         double *lxk = ba81LikelihoodFast(oo, thrId, sgroup, quad);
794                                         for (int px=0; px < numUnique; px++) {
795                                                 double Ei = allElxk[px];
796                                                 double Eis = Eslxk[sgroup * numUnique + px];
797                                                 double tmp = ((Ei / Eis) * lxk[px] * area);
798                                                 accumulateScores(state, px, sgroup, tmp, where, primaryDims,
799                                                                  covEntries, mean, cov);
800                                         }
801                                 }
802                         }
803                 }
804         }
805
806         double *patternLik = state->patternLik;
807         for (int px=0; px < numUnique; px++) {
808                 double denom = patternLik[px];
809                 for (int ax=0; ax < maxAbilities; ax++) {
810                         (*mean)[px * maxAbilities + ax] /= denom;
811                 }
812                 for (int cx=0; cx < triangleLoc1(primaryDims); ++cx) {
813                         (*cov)[px * covEntries + cx] /= denom;
814                 }
815                 for (int sx=0; sx < numSpecific; sx++) {
816                         (*cov)[px * covEntries + triangleLoc0(primaryDims + sx)] /= denom;
817                 }
818                 int cx=0;
819                 for (int a1=0; a1 < primaryDims; ++a1) {
820                         for (int a2=0; a2 <= a1; ++a2) {
821                                 double ma1 = (*mean)[px * maxAbilities + a1];
822                                 double ma2 = (*mean)[px * maxAbilities + a2];
823                                 (*cov)[px * covEntries + cx] -= ma1 * ma2;
824                                 ++cx;
825                         }
826                 }
827                 for (int sx=0; sx < numSpecific; sx++) {
828                         int sdim = primaryDims + sx;
829                         double ma1 = (*mean)[px * maxAbilities + sdim];
830                         (*cov)[px * covEntries + triangleLoc0(sdim)] -= ma1 * ma1;
831                 }
832         }
833 }
834
835 static void recomputePatternLik(omxExpectation *oo)
836 {
837         BA81Expect *estate = (BA81Expect*) oo->argStruct;
838         if (estate->verbose) mxLog("%s: patternLik", oo->name);
839
840         int numUnique = estate->numUnique;
841         int numSpecific = estate->numSpecific;
842         int maxDims = estate->maxDims;
843         int primaryDims = maxDims;
844         double *patternLik = estate->patternLik;
845         OMXZERO(patternLik, numUnique);
846
847         if (numSpecific == 0) {
848 #pragma omp parallel for num_threads(Global->numThreads)
849                 for (long qx=0; qx < estate->totalQuadPoints; qx++) {
850                         const int thrId = omx_absolute_thread_num();
851                         int quad[maxDims];
852                         decodeLocation(qx, maxDims, estate->quadGridSize, quad);
853                         double where[maxDims];
854                         pointToWhere(estate, quad, where, maxDims);
855                         double area = estate->priQarea[qx];
856                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, quad);
857
858                         for (int px=0; px < numUnique; px++) {
859                                 double tmp = (lxk[px] * area);
860 #pragma omp atomic
861                                 patternLik[px] += tmp;
862                         }
863                 }
864         } else {
865                 primaryDims -= 1;
866
867 #pragma omp parallel for num_threads(Global->numThreads)
868                 for (long qx=0; qx < estate->totalPrimaryPoints; qx++) {
869                         const int thrId = omx_absolute_thread_num();
870                         int quad[maxDims];
871                         decodeLocation(qx, primaryDims, estate->quadGridSize, quad);
872
873                         cai2010(oo, thrId, FALSE, quad);
874                         double *allElxk = eBase(estate, thrId);
875
876                         double priArea = estate->priQarea[qx];
877                         for (int px=0; px < numUnique; px++) {
878                                 double Ei = allElxk[px];
879                                 double tmp = (Ei * priArea);
880 #pragma omp atomic
881                                 patternLik[px] += tmp;
882                         }
883                 }
884         }
885 }
886
887 static void
888 ba81compute(omxExpectation *oo, const char *context)
889 {
890         BA81Expect *state = (BA81Expect *) oo->argStruct;
891
892         if (context) {
893                 if (strcmp(context, "EM")==0) {
894                         state->type = EXPECTATION_AUGMENTED;
895                 } else if (context[0] == 0) {
896                         state->type = EXPECTATION_OBSERVED;
897                 } else {
898                         omxRaiseErrorf(globalState, "Unknown context '%s'", context);
899                         return;
900                 }
901         }
902
903         omxRecompute(state->EitemParam);
904
905         bool itemClean = state->itemParamVersion == omxGetMatrixVersion(state->EitemParam);
906         bool latentClean = state->latentParamVersion == getLatentVersion(state);
907
908         if (state->verbose) {
909                 mxLog("%s: Qinit %d itemClean %d latentClean %d (1=clean)",
910                       oo->name, state->Qpoint.size() == 0, itemClean, latentClean);
911         }
912
913         if (state->Qpoint.size() == 0 || !latentClean) {
914                 ba81SetupQuadrature(oo, state->targetQpoints);
915         }
916         if (itemClean) {
917                 ba81buildLXKcache(oo);
918                 if (!latentClean) recomputePatternLik(oo);
919         } else {
920                 ba81Estep1(oo);
921         }
922
923         if (state->type == EXPECTATION_AUGMENTED) {
924                 ba81Expected(oo);
925         }
926
927         state->itemParamVersion = omxGetMatrixVersion(state->EitemParam);
928         state->latentParamVersion = getLatentVersion(state);
929 }
930
931 static void
932 copyScore(int rows, int maxAbilities, std::vector<double> &mean,
933           std::vector<double> &cov, const int rx, double *scores, const int dest)
934 {
935         for (int ax=0; ax < maxAbilities; ++ax) {
936                 scores[rows * ax + dest] = mean[maxAbilities * rx + ax];
937         }
938         for (int ax=0; ax < maxAbilities; ++ax) {
939                 scores[rows * (maxAbilities + ax) + dest] =
940                         sqrt(cov[triangleLoc1(maxAbilities) * rx + triangleLoc0(ax)]);
941         }
942         for (int ax=0; ax < triangleLoc1(maxAbilities); ++ax) {
943                 scores[rows * (2*maxAbilities + ax) + dest] =
944                         cov[triangleLoc1(maxAbilities) * rx + ax];
945         }
946 }
947
948 /**
949  * MAP is not affected by the number of items. EAP is. Likelihood can
950  * get concentrated in a single quadrature ordinate. For 3PL, response
951  * patterns can have a bimodal likelihood. This will confuse MAP and
952  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
953  *
954  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
955  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
956  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
957  */
958 static void
959 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
960 {
961         BA81Expect *state = (BA81Expect *) oo->argStruct;
962
963         if (state->scores == SCORES_OMIT || state->type == EXPECTATION_UNINITIALIZED) return;
964
965         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
966         // model. Journal of Educational Statistics, 12, 339-368.
967
968         /*
969         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
970
971         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
972                 // Thissen & Orlando (2001, p. 136)
973                 warning("EAP requires at least 2*sqrt(items) quadrature points");
974         }
975
976         ba81SetupQuadrature(oo, numQpoints, 0);
977         ba81Estep1(oo);
978         */
979
980         std::vector<double> mean;
981         std::vector<double> cov;
982         EAPinternalFast(oo, &mean, &cov);
983
984         int numUnique = state->numUnique;
985         omxData *data = state->data;
986         int maxAbilities = state->maxAbilities;
987         int rows = state->scores == SCORES_FULL? data->rows : numUnique;
988         int cols = 2 * maxAbilities + triangleLoc1(maxAbilities);
989         SEXP Rscores;
990         PROTECT(Rscores = allocMatrix(REALSXP, rows, cols));
991         double *scores = REAL(Rscores);
992
993         const int SMALLBUF = 10;
994         char buf[SMALLBUF];
995         SEXP names;
996         PROTECT(names = allocVector(STRSXP, cols));
997         for (int nx=0; nx < maxAbilities; ++nx) {
998                 snprintf(buf, SMALLBUF, "s%d", nx+1);
999                 SET_STRING_ELT(names, nx, mkChar(buf));
1000                 snprintf(buf, SMALLBUF, "se%d", nx+1);
1001                 SET_STRING_ELT(names, maxAbilities + nx, mkChar(buf));
1002         }
1003         for (int nx=0; nx < triangleLoc1(maxAbilities); ++nx) {
1004                 snprintf(buf, SMALLBUF, "cov%d", nx+1);
1005                 SET_STRING_ELT(names, maxAbilities*2 + nx, mkChar(buf));
1006         }
1007         SEXP dimnames;
1008         PROTECT(dimnames = allocVector(VECSXP, 2));
1009         SET_VECTOR_ELT(dimnames, 1, names);
1010         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
1011
1012         if (state->scores == SCORES_FULL) {
1013 #pragma omp parallel for num_threads(Global->numThreads)
1014                 for (int rx=0; rx < numUnique; rx++) {
1015                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
1016                         for (int dup=0; dup < dups; dup++) {
1017                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
1018                                 copyScore(rows, maxAbilities, mean, cov, rx, scores, dest);
1019                         }
1020                 }
1021         } else {
1022 #pragma omp parallel for num_threads(Global->numThreads)
1023                 for (int rx=0; rx < numUnique; rx++) {
1024                         copyScore(rows, maxAbilities, mean, cov, rx, scores, rx);
1025                 }
1026         }
1027
1028         setAttrib(robj, install("scores.out"), Rscores);
1029 }
1030
1031 static void ba81Destroy(omxExpectation *oo) {
1032         if(OMX_DEBUG) {
1033                 mxLog("Freeing %s function.", oo->name);
1034         }
1035         BA81Expect *state = (BA81Expect *) oo->argStruct;
1036         omxFreeAllMatrixData(state->EitemParam);
1037         omxFreeAllMatrixData(state->design);
1038         omxFreeAllMatrixData(state->latentMeanOut);
1039         omxFreeAllMatrixData(state->latentCovOut);
1040         omxFreeAllMatrixData(state->customPrior);
1041         omxFreeAllMatrixData(state->itemParam);
1042         Free(state->numIdentical);
1043         Free(state->rowMap);
1044         Free(state->patternLik);
1045         Free(state->lxk);
1046         Free(state->Eslxk);
1047         Free(state->allElxk);
1048         Free(state->Sgroup);
1049         Free(state->expected);
1050         delete state;
1051 }
1052
1053 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
1054 {
1055     SEXP matrixDims;
1056     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
1057     int *dimList = INTEGER(matrixDims);
1058     *rows = dimList[0];
1059     *cols = dimList[1];
1060     UNPROTECT(1);
1061 }
1062
1063 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
1064 {}
1065
1066 void omxInitExpectationBA81(omxExpectation* oo) {
1067         omxState* currentState = oo->currentState;      
1068         SEXP rObj = oo->rObj;
1069         SEXP tmp;
1070         
1071         if(OMX_DEBUG) {
1072                 mxLog("Initializing %s.", oo->name);
1073         }
1074         if (!rpf_model) {
1075                 if (0) {
1076                         const int wantVersion = 3;
1077                         int version;
1078                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
1079                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
1080                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
1081                                                          version, wantVersion);
1082                 } else {
1083                         rpf_numModels = librpf_numModels;
1084                         rpf_model = librpf_model;
1085                 }
1086         }
1087         
1088         BA81Expect *state = new BA81Expect;
1089         state->numSpecific = 0;
1090         state->numIdentical = NULL;
1091         state->rowMap = NULL;
1092         state->design = NULL;
1093         state->lxk = NULL;
1094         state->patternLik = NULL;
1095         state->Eslxk = NULL;
1096         state->allElxk = NULL;
1097         state->expected = NULL;
1098         state->type = EXPECTATION_UNINITIALIZED;
1099         state->scores = SCORES_OMIT;
1100         state->itemParam = NULL;
1101         state->customPrior = NULL;
1102         state->itemParamVersion = 0;
1103         state->latentParamVersion = 0;
1104         oo->argStruct = (void*) state;
1105
1106         PROTECT(tmp = GET_SLOT(rObj, install("data")));
1107         state->data = omxDataLookupFromState(tmp, currentState);
1108
1109         if (strcmp(omxDataType(state->data), "raw") != 0) {
1110                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", oo->name, omxDataType(state->data));
1111                 return;
1112         }
1113
1114         PROTECT(tmp = GET_SLOT(rObj, install("ItemSpec")));
1115         for (int sx=0; sx < length(tmp); ++sx) {
1116                 SEXP model = VECTOR_ELT(tmp, sx);
1117                 if (!OBJECT(model)) {
1118                         error("Item models must inherit rpf.base");
1119                 }
1120                 SEXP spec;
1121                 PROTECT(spec = GET_SLOT(model, install("spec")));
1122                 state->itemSpec.push_back(REAL(spec));
1123         }
1124
1125         PROTECT(tmp = GET_SLOT(rObj, install("design")));
1126         if (!isNull(tmp)) {
1127                 // better to demand integers and not coerce to real TODO
1128                 state->design = omxNewMatrixFromRPrimitive(tmp, globalState, FALSE, 0);
1129         }
1130
1131         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean");
1132         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
1133         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
1134         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
1135
1136         state->EitemParam =
1137                 omxNewMatrixFromSlot(rObj, currentState, "EItemParam");
1138         if (!state->EitemParam) error("Must supply EItemParam");
1139
1140         state->itemParam =
1141                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
1142
1143         if (state->EitemParam->rows != state->itemParam->rows ||
1144             state->EitemParam->cols != state->itemParam->cols) {
1145                 error("ItemParam and EItemParam must be of the same dimension");
1146         }
1147
1148         oo->computeFun = ba81compute;
1149         oo->setVarGroup = ignoreSetVarGroup;
1150         oo->destructFun = ba81Destroy;
1151         oo->populateAttrFun = ba81PopulateAttributes;
1152         
1153         // TODO: Exactly identical rows do not contribute any information.
1154         // The sorting algorithm ought to remove them so we don't waste RAM.
1155         // The following summary stats would be cheaper to calculate too.
1156
1157         int numUnique = 0;
1158         omxData *data = state->data;
1159         if (omxDataNumFactor(data) != data->cols) {
1160                 // verify they are ordered factors TODO
1161                 omxRaiseErrorf(currentState, "%s: all columns must be factors", oo->name);
1162                 return;
1163         }
1164
1165         for (int rx=0; rx < data->rows;) {
1166                 rx += omxDataNumIdenticalRows(state->data, rx);
1167                 ++numUnique;
1168         }
1169         state->numUnique = numUnique;
1170
1171         state->rowMap = Realloc(NULL, numUnique, int);
1172         state->numIdentical = Realloc(NULL, numUnique, int);
1173
1174         state->customPrior =
1175                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
1176         
1177         int numItems = state->EitemParam->cols;
1178         if (data->cols != numItems) {
1179                 error("Data has %d columns for %d items", data->cols, numItems);
1180         }
1181
1182         for (int rx=0, ux=0; rx < data->rows; ux++) {
1183                 if (rx == 0) {
1184                         // all NA rows will sort to the top
1185                         int na=0;
1186                         for (int ix=0; ix < numItems; ix++) {
1187                                 if (omxIntDataElement(data, 0, ix) == NA_INTEGER) { ++na; }
1188                         }
1189                         if (na == numItems) {
1190                                 omxRaiseErrorf(currentState, "Remove rows with all NAs");
1191                                 return;
1192                         }
1193                 }
1194                 int dups = omxDataNumIdenticalRows(state->data, rx);
1195                 state->numIdentical[ux] = dups;
1196                 state->rowMap[ux] = rx;
1197                 rx += dups;
1198         }
1199
1200         int numThreads = Global->numThreads;
1201
1202         int maxSpec = 0;
1203         int maxParam = 0;
1204         state->maxDims = 0;
1205         state->maxOutcomes = 0;
1206
1207         int totalOutcomes = 0;
1208         for (int cx = 0; cx < data->cols; cx++) {
1209                 const double *spec = state->itemSpec[cx];
1210                 int id = spec[RPF_ISpecID];
1211                 int dims = spec[RPF_ISpecDims];
1212                 if (state->maxDims < dims)
1213                         state->maxDims = dims;
1214
1215                 int no = spec[RPF_ISpecOutcomes];
1216                 totalOutcomes += no;
1217                 if (state->maxOutcomes < no)
1218                         state->maxOutcomes = no;
1219
1220                 // TODO this summary stat should be available from omxData
1221                 int dataMax=0;
1222                 for (int rx=0; rx < data->rows; rx++) {
1223                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1224                         if (dataMax < pick)
1225                                 dataMax = pick;
1226                 }
1227                 if (dataMax > no) {
1228                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1229                 } else if (dataMax < no) {
1230                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1231                         // promote to error?
1232                         // should complain if an outcome is not represented in the data TODO
1233                 }
1234
1235                 int numSpec = (*rpf_model[id].numSpec)(spec);
1236                 if (maxSpec < numSpec)
1237                         maxSpec = numSpec;
1238
1239                 int numParam = (*rpf_model[id].numParam)(spec);
1240                 if (maxParam < numParam)
1241                         maxParam = numParam;
1242         }
1243
1244         state->totalOutcomes = totalOutcomes;
1245
1246         if (int(state->itemSpec.size()) != data->cols) {
1247                 omxRaiseErrorf(currentState, "ItemSpec must contain %d item model specifications",
1248                                data->cols);
1249                 return;
1250         }
1251         if (state->EitemParam->rows != maxParam) {
1252                 omxRaiseErrorf(currentState, "ItemParam should have %d rows", maxParam);
1253                 return;
1254         }
1255
1256         if (state->design == NULL) {
1257                 state->maxAbilities = state->maxDims;
1258                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1259                                        TRUE, currentState);
1260                 for (int ix=0; ix < numItems; ix++) {
1261                         const double *spec = state->itemSpec[ix];
1262                         int dims = spec[RPF_ISpecDims];
1263                         for (int dx=0; dx < state->maxDims; dx++) {
1264                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1265                         }
1266                 }
1267         } else {
1268                 omxMatrix *design = state->design;
1269                 if (design->cols != numItems ||
1270                     design->rows != state->maxDims) {
1271                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1272                                        state->maxDims, numItems);
1273                         return;
1274                 }
1275
1276                 state->maxAbilities = 0;
1277                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1278                         double got = design->data[ix];
1279                         if (!R_FINITE(got)) continue;
1280                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1281                         if (state->maxAbilities < got)
1282                                 state->maxAbilities = got;
1283                 }
1284                 for (int ix=0; ix < design->cols; ix++) {
1285                         const double *idesign = omxMatrixColumn(design, ix);
1286                         int ddim = 0;
1287                         for (int rx=0; rx < design->rows; rx++) {
1288                                 if (isfinite(idesign[rx])) ddim += 1;
1289                         }
1290                         const double *spec = state->itemSpec[ix];
1291                         int dims = spec[RPF_ISpecDims];
1292                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1293                 }
1294         }
1295         if (state->maxAbilities <= state->maxDims) {
1296                 state->Sgroup = Calloc(numItems, int);
1297         } else {
1298                 // Not sure if this is correct, revisit TODO
1299                 int Sgroup0 = -1;
1300                 state->Sgroup = Realloc(NULL, numItems, int);
1301                 for (int dx=0; dx < state->maxDims; dx++) {
1302                         for (int ix=0; ix < numItems; ix++) {
1303                                 int ability = omxMatrixElement(state->design, dx, ix);
1304                                 if (dx < state->maxDims - 1) {
1305                                         if (Sgroup0 <= ability)
1306                                                 Sgroup0 = ability+1;
1307                                         continue;
1308                                 }
1309                                 int ss=-1;
1310                                 if (ability >= Sgroup0) {
1311                                         if (ss == -1) {
1312                                                 ss = ability;
1313                                         } else {
1314                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1315                                                                "1 specific dimension (both %d and %d)",
1316                                                                ix, ss, ability);
1317                                                 return;
1318                                         }
1319                                 }
1320                                 if (ss == -1) ss = Sgroup0;
1321                                 state->Sgroup[ix] = ss - Sgroup0;
1322                         }
1323                 }
1324                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1325                 state->allElxk = Realloc(NULL, numUnique * numThreads, double);
1326                 state->Eslxk = Realloc(NULL, numUnique * state->numSpecific * numThreads, double);
1327         }
1328
1329         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1330                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1331                       state->maxAbilities, state->maxAbilities);
1332         }
1333         if (state->latentCovOut->rows != state->maxAbilities ||
1334             state->latentCovOut->cols != state->maxAbilities) {
1335                 error("The cov matrix '%s' must be %dx%d",
1336                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1337         }
1338
1339         PROTECT(tmp = GET_SLOT(rObj, install("verbose")));
1340         state->verbose = asLogical(tmp);
1341
1342         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1343         state->cacheLXK = asLogical(tmp);
1344         state->LXKcached = FALSE;
1345
1346         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1347         state->targetQpoints = asReal(tmp);
1348
1349         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1350         state->Qwidth = asReal(tmp);
1351
1352         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1353         const char *score_option = CHAR(asChar(tmp));
1354         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1355         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1356         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1357
1358         state->ElatentMean.resize(state->maxAbilities);
1359         state->ElatentCov.resize(state->maxAbilities * state->maxAbilities);
1360
1361         // verify data bounded between 1 and numOutcomes TODO
1362         // hm, looks like something could be added to omxData for column summary stats?
1363 }