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