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