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