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