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