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