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