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