OpenMP tweaks
[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         long qloc = 0;
152         for (int sgroup=0; sgroup < numSpecific; ++sgroup) {
153                 for (long qx=0; qx < totalPrimaryPoints; qx++) {
154                         Eis[qloc] = Ei[qx] / Eis[qloc];
155                         ++qloc;
156                 }
157         }
158 }
159
160 static OMXINLINE double *
161 ba81LikelihoodFast2(BA81Expect *state, int px, double *buf)
162 {
163         long totalQuadPoints = state->totalQuadPoints;
164         int numSpecific = state->numSpecific;
165
166         if (state->cacheLXK) {
167                 if (numSpecific == 0) {
168                         return state->lxk + px * totalQuadPoints;
169                 } else {
170                         return state->lxk + px * numSpecific * totalQuadPoints;
171                 }
172         } else {
173                 ba81LikelihoodSlow2(state, px, buf);
174                 return buf;
175         }
176 }
177
178 OMXINLINE static void
179 mapLatentSpace(BA81Expect *state, int sgroup, double piece, const double *where,
180                const double *whereGram, double *latentDist)
181 {
182         int maxDims = state->maxDims;
183         int maxAbilities = state->maxAbilities;
184         int pmax = maxDims;
185         if (state->numSpecific) pmax -= 1;
186
187         if (sgroup == 0) {
188                 int gx = 0;
189                 int cx = maxAbilities;
190                 for (int d1=0; d1 < pmax; d1++) {
191                         double piece_w1 = piece * where[d1];
192                         latentDist[d1] += piece_w1;
193                         for (int d2=0; d2 <= d1; d2++) {
194                                 double piece_cov = piece * whereGram[gx];
195                                 latentDist[cx] += piece_cov;
196                                 ++cx; ++gx;
197                         }
198                 }
199         }
200
201         if (state->numSpecific) {
202                 int sdim = pmax + sgroup;
203                 double piece_w1 = piece * where[pmax];
204                 latentDist[sdim] += piece_w1;
205
206                 double piece_var = piece * whereGram[triangleLoc0(pmax)];
207                 int to = maxAbilities + triangleLoc0(sdim);
208                 latentDist[to] += piece_var;
209         }
210 }
211
212 static void ba81OutcomeProb(BA81Expect *state)
213 {
214         std::vector<int> &itemOutcomes = state->itemOutcomes;
215         std::vector<int> &cumItemOutcomes = state->cumItemOutcomes;
216         omxMatrix *itemParam = state->itemParam;
217         omxMatrix *design = state->design;
218         int maxDims = state->maxDims;
219         const size_t numItems = state->itemSpec.size();
220         state->outcomeProb = Realloc(state->outcomeProb, state->totalOutcomes * state->totalQuadPoints, double);
221
222 #pragma omp parallel for num_threads(Global->numThreads)
223         for (size_t ix=0; ix < numItems; ix++) {
224                 double *qProb = state->outcomeProb + cumItemOutcomes[ix] * state->totalQuadPoints;
225                 const double *spec = state->itemSpec[ix];
226                 int id = spec[RPF_ISpecID];
227                 int dims = spec[RPF_ISpecDims];
228                 double *iparam = omxMatrixColumn(itemParam, ix);
229                 rpf_prob_t prob_fn = rpf_model[id].prob;
230
231                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
232                         int quad[maxDims];
233                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
234                         double where[maxDims];
235                         pointToWhere(state, quad, where, maxDims);
236
237                         double ptheta[dims];
238                         for (int dx=0; dx < dims; dx++) {
239                                 int ability = (int)omxMatrixElement(design, dx, ix) - 1;
240                                 if (ability >= maxDims) ability = maxDims-1;
241                                 ptheta[dx] = where[ability];
242                         }
243
244                         (*prob_fn)(spec, iparam, ptheta, qProb);
245
246                         qProb += itemOutcomes[ix];
247                 }
248         }
249 }
250
251 static void ba81Estep1(omxExpectation *oo)
252 {
253         if(OMX_DEBUG) {mxLog("Beginning %s Computation.", oo->name);}
254
255         BA81Expect *state = (BA81Expect*) oo->argStruct;
256         const int numUnique = state->numUnique;
257         const int numSpecific = state->numSpecific;
258         const int maxDims = state->maxDims;
259         const int maxAbilities = state->maxAbilities;
260         const int primaryDims = numSpecific? maxDims-1 : maxDims;
261         omxData *data = state->data;
262         int *numIdentical = state->numIdentical;
263         const long totalQuadPoints = state->totalQuadPoints;
264
265         state->excludedPatterns = 0;
266         state->patternLik = Realloc(state->patternLik, numUnique, double);
267         double *patternLik = state->patternLik;
268
269         int numLatents = maxAbilities + triangleLoc1(maxAbilities);
270         int numLatentsPerThread = numUnique * numLatents;
271         std::vector<double> latentDist(numUnique * numLatents * Global->numThreads);
272
273         const int whereChunk = maxDims + triangleLoc1(maxDims);
274         omxBuffer<double> wherePrep(totalQuadPoints * whereChunk);
275         for (long qx=0; qx < totalQuadPoints; qx++) {
276                 double *wh = wherePrep.data() + qx * whereChunk;
277                 int quad[maxDims];
278                 decodeLocation(qx, maxDims, state->quadGridSize, quad);
279                 pointToWhere(state, quad, wh, maxDims);
280                 gramProduct(wh, maxDims, wh + maxDims);
281         }
282
283         if (numSpecific == 0) {
284                 omxBuffer<double> thrLxk(totalQuadPoints * Global->numThreads);
285
286 #pragma omp parallel for num_threads(Global->numThreads)
287                 for (int px=0; px < numUnique; px++) {
288                         int thrId = omx_absolute_thread_num();
289                         double *thrLatentDist = latentDist.data() + thrId * numLatentsPerThread;
290                         double *lxk = thrLxk.data() + thrId * totalQuadPoints;
291                         if (state->cacheLXK) lxk = getLXKcache(state, px);
292                         ba81LikelihoodSlow2(state, px, lxk);
293
294                         double patternLik1 = 0;
295                         double *wh = wherePrep.data();
296                         for (long qx=0; qx < totalQuadPoints; qx++) {
297                                 double area = state->priQarea[qx];
298                                 double tmp = lxk[qx] * area;
299                                 patternLik1 += tmp;
300                                 mapLatentSpace(state, 0, tmp, wh, wh + maxDims,
301                                                thrLatentDist + px * numLatents);
302                                 wh += whereChunk;
303                         }
304
305                         patternLik[px] = patternLik1;
306                 }
307         } else {
308                 omxBuffer<double> thrLxk(totalQuadPoints * numSpecific * Global->numThreads);
309                 long totalPrimaryPoints = state->totalPrimaryPoints;
310                 long specificPoints = state->quadGridSize;
311                 double *EiCache = state->EiCache;
312                 omxBuffer<double> thrEis(totalPrimaryPoints * numSpecific * Global->numThreads);
313
314 #pragma omp parallel for num_threads(Global->numThreads)
315                 for (int px=0; px < numUnique; px++) {
316                         int thrId = omx_absolute_thread_num();
317                         double *thrLatentDist = latentDist.data() + thrId * numLatentsPerThread;
318
319                         double *lxk = thrLxk.data() + totalQuadPoints * numSpecific * thrId;
320                         if (state->cacheLXK) lxk = getLXKcache(state, px);
321                         ba81LikelihoodSlow2(state, px, lxk);
322
323                         double *myEi = EiCache + px * totalPrimaryPoints;
324                         double *Eis = thrEis.data() + totalPrimaryPoints * numSpecific * thrId;
325                         cai2010EiEis(state, px, lxk, Eis, myEi);
326
327                         double patternLik1 = 0;
328                         double *wh = wherePrep.data();
329                         for (long qx=0, qloc=0; qx < totalPrimaryPoints; ++qx) {
330                                 double priArea = state->priQarea[qx];
331                                 double EiArea = myEi[qx] * priArea;
332                                 patternLik1 += EiArea;
333                                 for (long sx=0; sx < specificPoints; sx++) {
334                                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
335                                                 double area = priArea * state->speQarea[sgroup * specificPoints + sx];
336                                                 double lxk1 = lxk[totalQuadPoints * sgroup + qloc];
337                                                 double Eis1 = Eis[totalPrimaryPoints * sgroup + qx];
338                                                 double tmp = Eis1 * lxk1 * area;
339                                                 mapLatentSpace(state, sgroup, tmp, wh, wh + maxDims,
340                                                                thrLatentDist + px * numLatents);
341                                         }
342                                         wh += whereChunk;
343                                         ++qloc;
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 sx=0; sx < numSpecific; sx++) {
520                 totalArea = 0;
521                 int covCell = (priDims + sx) * state->maxAbilities + priDims + sx;
522                 double mean = state->latentMeanOut->data[priDims + sx];
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, sx, qx)] = den;
528                         totalArea += den;
529                 }
530                 for (int qx=0; qx < state->quadGridSize; qx++) {
531                         state->speQarea[sIndex(state, sx, qx)] /= totalArea;
532                 }
533                 //pda(state->speQarea.data() + sIndex(state, sx, 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                         int sloc = 0;
654                         for (int Sgroup=0; Sgroup < numSpecific; ++Sgroup) {
655                                 for (long qx=0; qx < totalPrimaryPoints; qx++) {
656                                         for (long sx=0; sx < specificPoints; sx++) {
657                                                 //double area = areaProduct(state, qx, sx, Sgroup);
658                                                 double area = priQarea[qx] * speQarea[sloc + sx];
659                                                 double lxk1 = lxk[qloc];
660                                                 double Eis1 = Eis[eisloc];
661                                                 Qweight[qloc] = weight * Eis1 * lxk1 * area;
662                                                 ++qloc;
663                                         }
664                                         ++eisloc;
665                                 }
666                                 sloc += specificPoints;
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         const long expectedSize = totalQuadPoints * totalOutcomes;
690         OMXZERO(state->expected, expectedSize);
691
692         double *e1 = thrExpected.data();
693         for (int tx=0; tx < Global->numThreads; ++tx) {
694                 for (long ex=0; ex < expectedSize; ++ex) {
695                         state->expected[ex] += *e1;
696                         ++e1;
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)
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)
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                                         for (long sx=0; sx < specificPoints; sx++) {
804                                                 quad[sDim] = sx;
805                                                 double where[maxDims];
806                                                 pointToWhere(state, quad, where, maxDims);
807                                                 double area = areaProduct(state, qx, sx, Sgroup);
808                                                 double lxk1 = lxk[totalQuadPoints * Sgroup + qloc];
809                                                 double Eis1 = Eis[totalPrimaryPoints * Sgroup + qx];
810                                                 double tmp = Eis1 * lxk1 * area;
811                                                 accumulateScores(state, px, Sgroup, tmp, where, primaryDims,
812                                                                  covEntries, mean, cov);
813                                                 ++qloc;
814                                         }
815                                 }
816                         }
817                 }
818         }
819
820         for (int px=0; px < numUnique; px++) {
821                 double denom = patternLik[px];
822                 if (!validPatternLik(state, denom)) {
823                         for (int ax=0; ax < maxAbilities; ++ax) {
824                                 (*mean)[px * maxAbilities + ax] = NA_REAL;
825                         }
826                         for (int cx=0; cx < covEntries; ++cx) {
827                                 (*cov)[px * covEntries + cx] = NA_REAL;
828                         }
829                         continue;
830                 }
831                 for (int ax=0; ax < maxAbilities; ax++) {
832                         (*mean)[px * maxAbilities + ax] /= denom;
833                 }
834                 for (int cx=0; cx < triangleLoc1(primaryDims); ++cx) {
835                         (*cov)[px * covEntries + cx] /= denom;
836                 }
837                 for (int sx=0; sx < numSpecific; sx++) {
838                         (*cov)[px * covEntries + triangleLoc0(primaryDims + sx)] /= denom;
839                 }
840                 int cx=0;
841                 for (int a1=0; a1 < primaryDims; ++a1) {
842                         for (int a2=0; a2 <= a1; ++a2) {
843                                 double ma1 = (*mean)[px * maxAbilities + a1];
844                                 double ma2 = (*mean)[px * maxAbilities + a2];
845                                 (*cov)[px * covEntries + cx] -= ma1 * ma2;
846                                 ++cx;
847                         }
848                 }
849                 for (int sx=0; sx < numSpecific; sx++) {
850                         int sdim = primaryDims + sx;
851                         double ma1 = (*mean)[px * maxAbilities + sdim];
852                         (*cov)[px * covEntries + triangleLoc0(sdim)] -= ma1 * ma1;
853                 }
854         }
855 }
856
857 static void recomputePatternLik(omxExpectation *oo)
858 {
859         BA81Expect *state = (BA81Expect*) oo->argStruct;
860         int numUnique = state->numUnique;
861         long totalQuadPoints = state->totalQuadPoints;
862         state->excludedPatterns = 0;
863         double *patternLik = state->patternLik;
864         OMXZERO(patternLik, numUnique);
865
866         if (state->numSpecific == 0) {
867                 omxBuffer<double> thrLxk(totalQuadPoints * Global->numThreads);
868
869 #pragma omp parallel for num_threads(Global->numThreads)
870                 for (int px=0; px < numUnique; px++) {
871                         int thrId = omx_absolute_thread_num();
872                         double *lxkBuf = thrLxk.data() + thrId * totalQuadPoints;
873                         double *lxk = ba81LikelihoodFast2(state, px, lxkBuf);
874                         for (long qx=0; qx < totalQuadPoints; qx++) {
875                                 patternLik[px] += lxk[qx] * state->priQarea[qx];
876                         }
877                         if (!validPatternLik(state, patternLik[px])) {
878 #pragma omp atomic
879                                 state->excludedPatterns += 1;
880                         }
881                 }
882         } else {
883                 double *EiCache = state->EiCache;
884                 long totalPrimaryPoints = state->totalPrimaryPoints;
885
886 #pragma omp parallel for num_threads(Global->numThreads)
887                 for (int px=0; px < numUnique; px++) {
888                         double *Ei = EiCache + totalPrimaryPoints * px;
889                         for (long qx=0; qx < totalPrimaryPoints; qx++) {
890                                 patternLik[px] += Ei[qx] * state->priQarea[qx];
891                         }
892                         if (!validPatternLik(state, patternLik[px])) {
893 #pragma omp atomic
894                                 state->excludedPatterns += 1;
895                         }
896                 }
897         }
898
899         if (state->verbose) mxLog("%s: patternLik (%d/%d excluded)",
900                                   oo->name, state->excludedPatterns, numUnique);
901 }
902
903 static void
904 ba81compute(omxExpectation *oo, const char *context)
905 {
906         BA81Expect *state = (BA81Expect *) oo->argStruct;
907
908         if (context) {
909                 if (strcmp(context, "EM")==0) {
910                         state->type = EXPECTATION_AUGMENTED;
911                 } else if (context[0] == 0) {
912                         state->type = EXPECTATION_OBSERVED;
913                 } else {
914                         omxRaiseErrorf(globalState, "Unknown context '%s'", context);
915                         return;
916                 }
917         }
918
919         bool itemClean = state->itemParamVersion == omxGetMatrixVersion(state->itemParam);
920         bool latentClean = state->latentParamVersion == getLatentVersion(state);
921
922         if (state->verbose) {
923                 mxLog("%s: Qinit %d itemClean %d latentClean %d (1=clean)",
924                       oo->name, state->Qpoint.size() != 0, itemClean, latentClean);
925         }
926
927         if (state->Qpoint.size() == 0 || !latentClean) {
928                 ba81SetupQuadrature(oo, state->targetQpoints);
929         }
930         if (itemClean) {
931                 ba81buildLXKcache(oo);
932                 if (!latentClean) recomputePatternLik(oo);
933         } else {
934                 ba81OutcomeProb(state);
935                 ba81Estep1(oo);
936         }
937
938         if (state->type == EXPECTATION_AUGMENTED) {
939                 ba81Expected(oo);
940         }
941
942         state->itemParamVersion = omxGetMatrixVersion(state->itemParam);
943         state->latentParamVersion = getLatentVersion(state);
944 }
945
946 static void
947 copyScore(int rows, int maxAbilities, std::vector<double> &mean,
948           std::vector<double> &cov, const int rx, double *scores, const int dest)
949 {
950         for (int ax=0; ax < maxAbilities; ++ax) {
951                 scores[rows * ax + dest] = mean[maxAbilities * rx + ax];
952         }
953         for (int ax=0; ax < maxAbilities; ++ax) {
954                 scores[rows * (maxAbilities + ax) + dest] =
955                         sqrt(cov[triangleLoc1(maxAbilities) * rx + triangleLoc0(ax)]);
956         }
957         for (int ax=0; ax < triangleLoc1(maxAbilities); ++ax) {
958                 scores[rows * (2*maxAbilities + ax) + dest] =
959                         cov[triangleLoc1(maxAbilities) * rx + ax];
960         }
961 }
962
963 /**
964  * MAP is not affected by the number of items. EAP is. Likelihood can
965  * get concentrated in a single quadrature ordinate. For 3PL, response
966  * patterns can have a bimodal likelihood. This will confuse MAP and
967  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
968  *
969  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
970  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
971  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
972  */
973 static void
974 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
975 {
976         BA81Expect *state = (BA81Expect *) oo->argStruct;
977         int maxAbilities = state->maxAbilities;
978
979         SEXP Rmean, Rcov;
980         PROTECT(Rmean = allocVector(REALSXP, maxAbilities));
981         memcpy(REAL(Rmean), state->ElatentMean.data(), maxAbilities * sizeof(double));
982
983         PROTECT(Rcov = allocMatrix(REALSXP, maxAbilities, maxAbilities));
984         memcpy(REAL(Rcov), state->ElatentCov.data(), maxAbilities * maxAbilities * sizeof(double));
985
986         setAttrib(robj, install("empirical.mean"), Rmean);
987         setAttrib(robj, install("empirical.cov"), Rcov);
988         setAttrib(robj, install("numStats"), ScalarReal(state->numUnique - 1)); // missingness? latent params? TODO
989
990         if (state->type == EXPECTATION_AUGMENTED) {
991                 const double LogLargest = state->LogLargestDouble;
992                 int numUnique = state->numUnique;
993                 int totalOutcomes = state->totalOutcomes;
994                 SEXP Rlik;
995                 SEXP Rexpected;
996
997                 PROTECT(Rlik = allocVector(REALSXP, numUnique));
998                 memcpy(REAL(Rlik), state->patternLik, sizeof(double) * numUnique);
999                 double *lik_out = REAL(Rlik);
1000                 for (int px=0; px < numUnique; ++px) {
1001                         // Must return value in log units because it may not be representable otherwise
1002                         lik_out[px] = log(lik_out[px]) - LogLargest;
1003                 }
1004
1005                 PROTECT(Rexpected = allocVector(REALSXP, state->totalQuadPoints * totalOutcomes));
1006                 memcpy(REAL(Rexpected), state->expected, sizeof(double) * totalOutcomes * state->totalQuadPoints);
1007
1008                 setAttrib(robj, install("patternLikelihood"), Rlik);
1009                 setAttrib(robj, install("em.expected"), Rexpected);
1010         }
1011
1012         if (state->scores == SCORES_OMIT || state->type == EXPECTATION_UNINITIALIZED) return;
1013
1014         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
1015         // model. Journal of Educational Statistics, 12, 339-368.
1016
1017         /*
1018         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
1019
1020         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
1021                 // Thissen & Orlando (2001, p. 136)
1022                 warning("EAP requires at least 2*sqrt(items) quadrature points");
1023         }
1024
1025         ba81SetupQuadrature(oo, numQpoints, 0);
1026         ba81Estep1(oo);
1027         */
1028
1029         std::vector<double> mean;
1030         std::vector<double> cov;
1031         EAPinternalFast(oo, &mean, &cov);
1032
1033         int numUnique = state->numUnique;
1034         omxData *data = state->data;
1035         int rows = state->scores == SCORES_FULL? data->rows : numUnique;
1036         int cols = 2 * maxAbilities + triangleLoc1(maxAbilities);
1037         SEXP Rscores;
1038         PROTECT(Rscores = allocMatrix(REALSXP, rows, cols));
1039         double *scores = REAL(Rscores);
1040
1041         const int SMALLBUF = 10;
1042         char buf[SMALLBUF];
1043         SEXP names;
1044         PROTECT(names = allocVector(STRSXP, cols));
1045         for (int nx=0; nx < maxAbilities; ++nx) {
1046                 snprintf(buf, SMALLBUF, "s%d", nx+1);
1047                 SET_STRING_ELT(names, nx, mkChar(buf));
1048                 snprintf(buf, SMALLBUF, "se%d", nx+1);
1049                 SET_STRING_ELT(names, maxAbilities + nx, mkChar(buf));
1050         }
1051         for (int nx=0; nx < triangleLoc1(maxAbilities); ++nx) {
1052                 snprintf(buf, SMALLBUF, "cov%d", nx+1);
1053                 SET_STRING_ELT(names, maxAbilities*2 + nx, mkChar(buf));
1054         }
1055         SEXP dimnames;
1056         PROTECT(dimnames = allocVector(VECSXP, 2));
1057         SET_VECTOR_ELT(dimnames, 1, names);
1058         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
1059
1060         if (state->scores == SCORES_FULL) {
1061 #pragma omp parallel for num_threads(Global->numThreads)
1062                 for (int rx=0; rx < numUnique; rx++) {
1063                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
1064                         for (int dup=0; dup < dups; dup++) {
1065                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
1066                                 copyScore(rows, maxAbilities, mean, cov, rx, scores, dest);
1067                         }
1068                 }
1069         } else {
1070 #pragma omp parallel for num_threads(Global->numThreads)
1071                 for (int rx=0; rx < numUnique; rx++) {
1072                         copyScore(rows, maxAbilities, mean, cov, rx, scores, rx);
1073                 }
1074         }
1075
1076         setAttrib(robj, install("scores.out"), Rscores);
1077 }
1078
1079 static void ba81Destroy(omxExpectation *oo) {
1080         if(OMX_DEBUG) {
1081                 mxLog("Freeing %s function.", oo->name);
1082         }
1083         BA81Expect *state = (BA81Expect *) oo->argStruct;
1084         omxFreeAllMatrixData(state->design);
1085         omxFreeAllMatrixData(state->latentMeanOut);
1086         omxFreeAllMatrixData(state->latentCovOut);
1087         omxFreeAllMatrixData(state->customPrior);
1088         omxFreeAllMatrixData(state->itemParam);
1089         Free(state->numIdentical);
1090         Free(state->rowMap);
1091         Free(state->patternLik);
1092         Free(state->lxk);
1093         Free(state->Eslxk);
1094         Free(state->allElxk);
1095         Free(state->Sgroup);
1096         Free(state->expected);
1097         Free(state->outcomeProb);
1098         Free(state->EiCache);
1099         delete state;
1100 }
1101
1102 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
1103 {
1104     SEXP matrixDims;
1105     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
1106     int *dimList = INTEGER(matrixDims);
1107     *rows = dimList[0];
1108     *cols = dimList[1];
1109     UNPROTECT(1);
1110 }
1111
1112 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
1113 {}
1114
1115 void omxInitExpectationBA81(omxExpectation* oo) {
1116         omxState* currentState = oo->currentState;      
1117         SEXP rObj = oo->rObj;
1118         SEXP tmp;
1119         
1120         if(OMX_DEBUG) {
1121                 mxLog("Initializing %s.", oo->name);
1122         }
1123         if (!rpf_model) {
1124                 if (0) {
1125                         const int wantVersion = 3;
1126                         int version;
1127                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
1128                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
1129                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
1130                                                          version, wantVersion);
1131                 } else {
1132                         rpf_numModels = librpf_numModels;
1133                         rpf_model = librpf_model;
1134                 }
1135         }
1136         
1137         BA81Expect *state = new BA81Expect;
1138
1139         // These two constants should be as identical as possible
1140         state->LogLargestDouble = log(std::numeric_limits<double>::max()) - 1;
1141         state->LargestDouble = exp(state->LogLargestDouble);
1142         state->OneOverLargestDouble = 1/state->LargestDouble;
1143
1144         state->numSpecific = 0;
1145         state->excludedPatterns = 0;
1146         state->numIdentical = NULL;
1147         state->rowMap = NULL;
1148         state->design = NULL;
1149         state->lxk = NULL;
1150         state->patternLik = NULL;
1151         state->Eslxk = NULL;
1152         state->allElxk = NULL;
1153         state->outcomeProb = NULL;
1154         state->expected = NULL;
1155         state->type = EXPECTATION_UNINITIALIZED;
1156         state->scores = SCORES_OMIT;
1157         state->itemParam = NULL;
1158         state->customPrior = NULL;
1159         state->itemParamVersion = 0;
1160         state->latentParamVersion = 0;
1161         state->EiCache = NULL;
1162         oo->argStruct = (void*) state;
1163
1164         PROTECT(tmp = GET_SLOT(rObj, install("data")));
1165         state->data = omxDataLookupFromState(tmp, currentState);
1166
1167         if (strcmp(omxDataType(state->data), "raw") != 0) {
1168                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", oo->name, omxDataType(state->data));
1169                 return;
1170         }
1171
1172         PROTECT(tmp = GET_SLOT(rObj, install("ItemSpec")));
1173         for (int sx=0; sx < length(tmp); ++sx) {
1174                 SEXP model = VECTOR_ELT(tmp, sx);
1175                 if (!OBJECT(model)) {
1176                         error("Item models must inherit rpf.base");
1177                 }
1178                 SEXP spec;
1179                 PROTECT(spec = GET_SLOT(model, install("spec")));
1180                 state->itemSpec.push_back(REAL(spec));
1181         }
1182
1183         PROTECT(tmp = GET_SLOT(rObj, install("design")));
1184         if (!isNull(tmp)) {
1185                 // better to demand integers and not coerce to real TODO
1186                 state->design = omxNewMatrixFromRPrimitive(tmp, globalState, FALSE, 0);
1187         }
1188
1189         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean");
1190         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
1191         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
1192         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
1193
1194         state->itemParam =
1195                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
1196
1197         oo->computeFun = ba81compute;
1198         oo->setVarGroup = ignoreSetVarGroup;
1199         oo->destructFun = ba81Destroy;
1200         oo->populateAttrFun = ba81PopulateAttributes;
1201         
1202         // TODO: Exactly identical rows do not contribute any information.
1203         // The sorting algorithm ought to remove them so we don't waste RAM.
1204         // The following summary stats would be cheaper to calculate too.
1205
1206         int numUnique = 0;
1207         omxData *data = state->data;
1208         if (omxDataNumFactor(data) != data->cols) {
1209                 // verify they are ordered factors TODO
1210                 omxRaiseErrorf(currentState, "%s: all columns must be factors", oo->name);
1211                 return;
1212         }
1213
1214         for (int rx=0; rx < data->rows;) {
1215                 rx += omxDataNumIdenticalRows(state->data, rx);
1216                 ++numUnique;
1217         }
1218         state->numUnique = numUnique;
1219
1220         state->rowMap = Realloc(NULL, numUnique, int);
1221         state->numIdentical = Realloc(NULL, numUnique, int);
1222
1223         state->customPrior =
1224                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
1225         
1226         int numItems = state->itemParam->cols;
1227         if (data->cols != numItems) {
1228                 error("Data has %d columns for %d items", data->cols, numItems);
1229         }
1230
1231         int numThreads = Global->numThreads;
1232
1233         int maxSpec = 0;
1234         int maxParam = 0;
1235         state->maxDims = 0;
1236
1237         std::vector<int> &itemOutcomes = state->itemOutcomes;
1238         std::vector<int> &cumItemOutcomes = state->cumItemOutcomes;
1239         itemOutcomes.resize(numItems);
1240         cumItemOutcomes.resize(numItems);
1241         int totalOutcomes = 0;
1242         for (int cx = 0; cx < data->cols; cx++) {
1243                 const double *spec = state->itemSpec[cx];
1244                 int id = spec[RPF_ISpecID];
1245                 int dims = spec[RPF_ISpecDims];
1246                 if (state->maxDims < dims)
1247                         state->maxDims = dims;
1248
1249                 int no = spec[RPF_ISpecOutcomes];
1250                 itemOutcomes[cx] = no;
1251                 cumItemOutcomes[cx] = totalOutcomes;
1252                 totalOutcomes += no;
1253
1254                 // TODO this summary stat should be available from omxData
1255                 int dataMax=0;
1256                 for (int rx=0; rx < data->rows; rx++) {
1257                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1258                         if (dataMax < pick)
1259                                 dataMax = pick;
1260                 }
1261                 if (dataMax > no) {
1262                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1263                 } else if (dataMax < no) {
1264                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1265                         // promote to error?
1266                         // should complain if an outcome is not represented in the data TODO
1267                 }
1268
1269                 int numSpec = (*rpf_model[id].numSpec)(spec);
1270                 if (maxSpec < numSpec)
1271                         maxSpec = numSpec;
1272
1273                 int numParam = (*rpf_model[id].numParam)(spec);
1274                 if (maxParam < numParam)
1275                         maxParam = numParam;
1276         }
1277
1278         state->totalOutcomes = totalOutcomes;
1279
1280         if (int(state->itemSpec.size()) != data->cols) {
1281                 omxRaiseErrorf(currentState, "ItemSpec must contain %d item model specifications",
1282                                data->cols);
1283                 return;
1284         }
1285         std::vector<bool> byOutcome(totalOutcomes, false);
1286         int outcomesSeen = 0;
1287         for (int rx=0, ux=0; rx < data->rows; ux++) {
1288                 int dups = omxDataNumIdenticalRows(state->data, rx);
1289                 state->numIdentical[ux] = dups;
1290                 state->rowMap[ux] = rx;
1291                 rx += dups;
1292
1293                 if (outcomesSeen < totalOutcomes) {
1294                         // Since the data is sorted, this will scan at least half the data -> ugh
1295                         for (int ix=0, outcomeBase=0; ix < numItems; outcomeBase += itemOutcomes[ix], ++ix) {
1296                                 int pick = omxIntDataElementUnsafe(data, rx, ix);
1297                                 if (pick == NA_INTEGER) continue;
1298                                 --pick;
1299                                 if (!byOutcome[outcomeBase + pick]) {
1300                                         byOutcome[outcomeBase + pick] = true;
1301                                         if (++outcomesSeen == totalOutcomes) break;
1302                                 }
1303                         }
1304                 }
1305         }
1306
1307         if (outcomesSeen < totalOutcomes) {
1308                 std::string buf;
1309                 for (int ix=0, outcomeBase=0; ix < numItems; outcomeBase += itemOutcomes[ix], ++ix) {
1310                         for (int pick=0; pick < itemOutcomes[ix]; ++pick) {
1311                                 if (byOutcome[outcomeBase + pick]) continue;
1312                                 buf += string_snprintf(" item %d outcome %d", 1+ix, 1+pick);
1313                         }
1314                 }
1315                 omxRaiseErrorf(globalState, "Never endorsed:%s\n"
1316                                "You must collapse categories or omit items to estimate item parameters.",
1317                                buf.c_str());
1318         }
1319
1320         if (state->design == NULL) {
1321                 state->maxAbilities = state->maxDims;
1322                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1323                                        TRUE, currentState);
1324                 for (int ix=0; ix < numItems; ix++) {
1325                         const double *spec = state->itemSpec[ix];
1326                         int dims = spec[RPF_ISpecDims];
1327                         for (int dx=0; dx < state->maxDims; dx++) {
1328                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1329                         }
1330                 }
1331         } else {
1332                 omxMatrix *design = state->design;
1333                 if (design->cols != numItems ||
1334                     design->rows != state->maxDims) {
1335                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1336                                        state->maxDims, numItems);
1337                         return;
1338                 }
1339
1340                 state->maxAbilities = 0;
1341                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1342                         double got = design->data[ix];
1343                         if (!R_FINITE(got)) continue;
1344                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1345                         if (state->maxAbilities < got)
1346                                 state->maxAbilities = got;
1347                 }
1348                 for (int ix=0; ix < design->cols; ix++) {
1349                         const double *idesign = omxMatrixColumn(design, ix);
1350                         int ddim = 0;
1351                         for (int rx=0; rx < design->rows; rx++) {
1352                                 if (isfinite(idesign[rx])) ddim += 1;
1353                         }
1354                         const double *spec = state->itemSpec[ix];
1355                         int dims = spec[RPF_ISpecDims];
1356                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1357                 }
1358         }
1359         if (state->maxAbilities <= state->maxDims) {
1360                 state->Sgroup = Calloc(numItems, int);
1361         } else {
1362                 // Not sure if this is correct, revisit TODO
1363                 int Sgroup0 = -1;
1364                 state->Sgroup = Realloc(NULL, numItems, int);
1365                 for (int dx=0; dx < state->maxDims; dx++) {
1366                         for (int ix=0; ix < numItems; ix++) {
1367                                 int ability = omxMatrixElement(state->design, dx, ix);
1368                                 if (dx < state->maxDims - 1) {
1369                                         if (Sgroup0 <= ability)
1370                                                 Sgroup0 = ability+1;
1371                                         continue;
1372                                 }
1373                                 int ss=-1;
1374                                 if (ability >= Sgroup0) {
1375                                         if (ss == -1) {
1376                                                 ss = ability;
1377                                         } else {
1378                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1379                                                                "1 specific dimension (both %d and %d)",
1380                                                                ix, ss, ability);
1381                                                 return;
1382                                         }
1383                                 }
1384                                 if (ss == -1) ss = Sgroup0;
1385                                 state->Sgroup[ix] = ss - Sgroup0;
1386                         }
1387                 }
1388                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1389                 state->allElxk = Realloc(NULL, numUnique * numThreads, double);
1390                 state->Eslxk = Realloc(NULL, numUnique * state->numSpecific * numThreads, double);
1391         }
1392
1393         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1394                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1395                       state->maxAbilities, state->maxAbilities);
1396         }
1397         if (state->latentCovOut->rows != state->maxAbilities ||
1398             state->latentCovOut->cols != state->maxAbilities) {
1399                 error("The cov matrix '%s' must be %dx%d",
1400                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1401         }
1402
1403         PROTECT(tmp = GET_SLOT(rObj, install("verbose")));
1404         state->verbose = asLogical(tmp);
1405
1406         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1407         state->cacheLXK = asLogical(tmp);
1408         state->LXKcached = FALSE;
1409
1410         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1411         state->targetQpoints = asReal(tmp);
1412
1413         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1414         state->Qwidth = asReal(tmp);
1415
1416         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1417         const char *score_option = CHAR(asChar(tmp));
1418         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1419         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1420         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1421
1422         state->ElatentMean.resize(state->maxAbilities);
1423         state->ElatentCov.resize(state->maxAbilities * state->maxAbilities);
1424
1425         // verify data bounded between 1 and numOutcomes TODO
1426         // hm, looks like something could be added to omxData for column summary stats?
1427 }