Sync libifa-rpf with RPF 0.10
[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 // Consider replacing log() with log2() in some places? Not worth it?
19
20 #include <Rmath.h>
21 #include "omxExpectationBA81.h"
22 #include "omxOpenmpWrap.h"
23 #include "npsolWrap.h"
24 #include "libifa-rpf.h"
25 #include "dmvnorm.h"
26
27 static const char *NAME = "ExpectationBA81";
28
29 const struct rpf *rpf_model = NULL;
30 int rpf_numModels;
31 static const double MIN_PATTERNLIK = 1e-100;
32
33 void pda(const double *ar, int rows, int cols)
34 {
35         std::string buf;
36         for (int rx=0; rx < rows; rx++) {   // column major order
37                 for (int cx=0; cx < cols; cx++) {
38                         buf += string_snprintf("%.6g, ", ar[cx * rows + rx]);
39                 }
40                 buf += "\n";
41         }
42         mxLogBig(buf);
43 }
44
45 void pia(const int *ar, int rows, int cols)
46 {
47         std::string buf;
48         for (int rx=0; rx < rows; rx++) {   // column major order
49                 for (int cx=0; cx < cols; cx++) {
50                         buf += string_snprintf("%d, ", ar[cx * rows + rx]);
51                 }
52                 buf += "\n";
53         }
54         mxLogBig(buf);
55 }
56
57 OMXINLINE static void
58 assignDims(omxMatrix *itemSpec, omxMatrix *design, int dims, int maxDims, int ix,
59            const double *theta, double *ptheta)
60 {
61         for (int dx=0; dx < dims; dx++) {
62                 int ability = (int)omxMatrixElement(design, dx, ix) - 1;
63                 if (ability >= maxDims) ability = maxDims-1;
64                 ptheta[dx] = theta[ability];
65         }
66 }
67
68 /**
69  * \param theta Vector of ability parameters, one per ability
70  * \returns A numItems by maxOutcomes colMajor vector of doubles. Caller must Free it.
71  */
72 double *
73 computeRPF(omxMatrix *itemSpec, omxMatrix *design, omxMatrix *itemParam,
74            int maxDims, int maxOutcomes, const int *quad, const double *Qpoint)
75 {
76         int numItems = itemSpec->cols;
77
78         double theta[maxDims];
79         pointToWhere(Qpoint, quad, theta, maxDims);
80
81         double *outcomeProb = Realloc(NULL, numItems * maxOutcomes, double);
82         //double *outcomeProb = Calloc(numItems * maxOutcomes, double);
83
84         for (int ix=0; ix < numItems; ix++) {
85                 const double *spec = omxMatrixColumn(itemSpec, ix);
86                 double *iparam = omxMatrixColumn(itemParam, ix);
87                 double *out = outcomeProb + ix * maxOutcomes;
88                 int id = spec[RPF_ISpecID];
89                 int dims = spec[RPF_ISpecDims];
90                 double ptheta[dims];
91                 assignDims(itemSpec, design, dims, maxDims, ix, theta, ptheta);
92                 (*rpf_model[id].logprob)(spec, iparam, ptheta, out);
93 #if 0
94                 for (int ox=0; ox < spec[RPF_ISpecOutcomes]; ox++) {
95                         if (!isfinite(out[ox]) || out[ox] > 0) {
96                                 mxLog("spec\n");
97                                 pda(spec, itemSpec->rows, 1);
98                                 mxLog("item param\n");
99                                 pda(iparam, itemParam->rows, 1);
100                                 mxLog("where\n");
101                                 pda(ptheta, dims, 1);
102                                 error("RPF returned %20.20f", out[ox]);
103                         }
104                 }
105 #endif
106         }
107
108         return outcomeProb;
109 }
110
111 OMXINLINE static double *
112 getLXKcache(BA81Expect *state, const int *quad, const int specific)
113 {
114         long ordinate;
115         if (state->numSpecific == 0) {
116                 ordinate = encodeLocation(state->maxDims, state->quadGridSize, quad);
117         } else {
118                 ordinate = (specific * state->totalQuadPoints +
119                             encodeLocation(state->maxDims, state->quadGridSize, quad));
120         }
121         return state->lxk + state->numUnique * ordinate;
122 }
123
124 OMXINLINE static double *
125 ba81Likelihood(omxExpectation *oo, int specific, const int *quad)
126 {
127         BA81Expect *state = (BA81Expect*) oo->argStruct;
128         int numUnique = state->numUnique;
129         int maxOutcomes = state->maxOutcomes;
130         omxData *data = state->data;
131         int numItems = state->itemSpec->cols;
132         int *Sgroup = state->Sgroup;
133         double *lxk;
134
135         if (!state->cacheLXK) {
136                 lxk = state->lxk + numUnique * omx_absolute_thread_num();
137         } else {
138                 lxk = getLXKcache(state, quad, specific);
139         }
140
141         const double *outcomeProb = computeRPF(state->itemSpec, state->design, state->EitemParam,
142                                                state->maxDims, state->maxOutcomes, quad, state->Qpoint);
143         if (!outcomeProb) {
144                 OMXZERO(lxk, numUnique);
145                 return lxk;
146         }
147
148         const int *rowMap = state->rowMap;
149         for (int px=0; px < numUnique; px++) {
150                 double lxk1 = 0;
151                 for (int ix=0; ix < numItems; ix++) {
152                         if (specific != Sgroup[ix]) continue;
153                         int pick = omxIntDataElementUnsafe(data, rowMap[px], ix);
154                         if (pick == NA_INTEGER) continue;
155                         double piece = outcomeProb[ix * maxOutcomes + pick-1];  // move -1 elsewhere TODO
156                         lxk1 += piece;
157                 }
158 #if 0
159 #pragma omp critical(ba81LikelihoodDebug1)
160                 if (!isfinite(lxk1) || lxk1 > numItems) {
161                         mxLog("where\n");
162                         double where[state->maxDims];
163                         pointToWhere(state->Qpoint, quad, where, state->maxDims);
164                         pda(where, state->maxDims, 1);
165                         mxLog("prob\n");
166                         pda(outcomeProb, numItems, maxOutcomes);
167                         error("Likelihood of row %d is %f", rowMap[px], lxk1);
168                 }
169 #endif
170                 lxk[px] = lxk1;
171         }
172
173         Free(outcomeProb);
174
175         return lxk;
176 }
177
178 OMXINLINE static double *
179 ba81LikelihoodFast(omxExpectation *oo, int specific, const int *quad)
180 {
181         BA81Expect *state = (BA81Expect*) oo->argStruct;
182         if (!state->cacheLXK) {
183                 return ba81Likelihood(oo, specific, quad);
184         } else {
185                 return getLXKcache(state, quad, specific);
186         }
187
188 }
189
190 OMXINLINE static void
191 mapLatentSpace(BA81Expect *state, int px, int sgroup, double piece, const double *where)
192 {
193         double *ElatentMean = state->ElatentMean;
194         double *ElatentCov = state->ElatentCov;
195         int maxDims = state->maxDims;
196         int maxAbilities = state->maxAbilities;
197         int pmax = maxDims;
198         if (state->numSpecific) pmax -= 1;
199
200         if (sgroup == 0) {
201                 for (int d1=0; d1 < pmax; d1++) {
202                         double piece_w1 = piece * where[d1];
203                         int mloc = px * maxAbilities + d1;
204 #pragma omp atomic
205                         ElatentMean[mloc] += piece_w1;
206                         for (int d2=0; d2 <= d1; d2++) {
207                                 int loc = px * maxAbilities * maxAbilities + d2 * maxAbilities + d1;
208                                 double piece_cov = piece_w1 * where[d2];
209 #pragma omp atomic
210                                 ElatentCov[loc] += piece_cov;
211                         }
212                 }
213         }
214
215         if (state->numSpecific) {
216                 int sdim = maxDims + sgroup - 1;
217
218                 double piece_w1 = piece * where[maxDims-1];
219                 int mloc = px * maxAbilities + sdim;
220 #pragma omp atomic
221                 ElatentMean[mloc] += piece_w1;
222
223                 int loc = px * maxAbilities * maxAbilities + sdim * maxAbilities + sdim;
224                 double piece_var = piece_w1 * where[maxDims-1];
225 #pragma omp atomic
226                 ElatentCov[loc] += piece_var;
227         }
228 }
229
230 #define CALC_ALLSLXK(state, numUnique) \
231         (state->allSlxk + omx_absolute_thread_num() * (numUnique))
232
233 #define CALC_SLXK(state, numUnique, numSpecific) \
234         (state->Slxk + omx_absolute_thread_num() * (numUnique) * (numSpecific))
235
236 OMXINLINE static void
237 cai2010(omxExpectation* oo, int recompute, const int *primaryQuad,
238         double *allSlxk, double *Slxk)
239 {
240         BA81Expect *state = (BA81Expect*) oo->argStruct;
241         int numUnique = state->numUnique;
242         int numSpecific = state->numSpecific;
243         int maxDims = state->maxDims;
244         int sDim = maxDims-1;
245
246         int quad[maxDims];
247         memcpy(quad, primaryQuad, sizeof(int)*sDim);
248
249         OMXZERO(Slxk, numUnique * numSpecific);
250         OMXZERO(allSlxk, numUnique);
251
252         for (int sx=0; sx < numSpecific; sx++) {
253                 double *eis = Slxk + numUnique * sx;
254                 int quadGridSize = state->quadGridSize;
255
256                 for (int qx=0; qx < quadGridSize; qx++) {
257                         quad[sDim] = qx;
258                         double where[maxDims];
259                         pointToWhere(state->Qpoint, quad, where, maxDims);
260
261                         double *lxk;
262                         if (recompute) {
263                                 lxk = ba81Likelihood(oo, sx, quad);
264                         } else {
265                                 lxk = getLXKcache(state, quad, sx);
266                         }
267
268                         for (int ix=0; ix < numUnique; ix++) {
269                                 eis[ix] += exp(lxk[ix] + state->priLogQarea[qx]);
270                         }
271                 }
272
273                 for (int px=0; px < numUnique; px++) {
274                         eis[px] = log(eis[px]);
275                         allSlxk[px] += eis[px];
276                 }
277         }
278 }
279
280 static void
281 ba81Estep1(omxExpectation *oo) {
282         if(OMX_DEBUG) {mxLog("Beginning %s Computation.\n", NAME);}
283
284         BA81Expect *state = (BA81Expect*) oo->argStruct;
285         double *patternLik = state->patternLik;
286         int numUnique = state->numUnique;
287         int numSpecific = state->numSpecific;
288         double *ElatentMean = state->ElatentMean;
289         double *ElatentCov = state->ElatentCov;
290         int maxDims = state->maxDims;
291         int maxAbilities = state->maxAbilities;
292         int primaryDims = maxDims;
293
294         OMXZERO(patternLik, numUnique);
295         OMXZERO(ElatentMean, numUnique * maxAbilities);
296         OMXZERO(ElatentCov, numUnique * maxAbilities * maxAbilities);
297
298         // E-step, marginalize person ability
299         //
300         // Note: In the notation of Bock & Aitkin (1981) and
301         // Cai~(2010), these loops are reversed.  That is, the inner
302         // loop is over quadrature points and the outer loop is over
303         // all response patterns.
304         //
305         if (numSpecific == 0) {
306 #pragma omp parallel for num_threads(Global->numThreads)
307                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
308                         int quad[maxDims];
309                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
310                         double where[maxDims];
311                         pointToWhere(state->Qpoint, quad, where, maxDims);
312
313                         double *lxk = ba81Likelihood(oo, 0, quad);
314
315                         double logArea = state->priLogQarea[qx];
316 #pragma omp critical(EstepUpdate)
317                         for (int px=0; px < numUnique; px++) {
318                                 double tmp = exp(lxk[px] + logArea);
319 #if 0
320                                 if (!isfinite(tmp)) {
321                                         mxLog("where\n");
322                                         pda(where, maxDims, 1);
323                                         error("Row %d lxk %f logArea %f tmp %f",
324                                               state->rowMap[px], lxk[px], logArea, tmp);
325                                 }
326 #endif
327                                 patternLik[px] += tmp;
328                                 mapLatentSpace(state, px, 0, tmp, where);
329                         }
330                 }
331         } else {
332                 primaryDims -= 1;
333                 int sDim = primaryDims;
334                 long specificPoints = state->quadGridSize;
335
336 #pragma omp parallel for num_threads(Global->numThreads)
337                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
338                         int quad[maxDims];
339                         decodeLocation(qx, primaryDims, state->quadGridSize, quad);
340
341                         double *allSlxk = CALC_ALLSLXK(state, numUnique);
342                         double *Slxk = CALC_SLXK(state, numUnique, numSpecific);
343                         cai2010(oo, TRUE, quad, allSlxk, Slxk);
344
345                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
346                                 double *eis = Slxk + numUnique * sgroup;
347                                 for (long sx=0; sx < specificPoints; sx++) {
348                                         quad[sDim] = sx;
349                                         double where[maxDims];
350                                         pointToWhere(state->Qpoint, quad, where, maxDims);
351                                         double logArea = logAreaProduct(state, quad, sgroup);
352                                         double *lxk = ba81LikelihoodFast(oo, sgroup, quad);
353                                         for (int px=0; px < numUnique; px++) {
354                                                 double tmp = exp((allSlxk[px] - eis[px]) + lxk[px] + logArea);
355                                                 mapLatentSpace(state, px, sgroup, tmp, where);
356                                         }
357                                 }
358                         }
359
360                         double priLogArea = state->priLogQarea[qx];
361 #pragma omp critical(EstepUpdate)
362                         for (int px=0; px < numUnique; px++) {
363                                 double tmp = exp(allSlxk[px] + priLogArea);
364                                 patternLik[px] += tmp;  // is it faster to make this line atomic? TODO
365                         }
366                 }
367         }
368
369         int *numIdentical = state->numIdentical;
370
371         if(0) {
372                 mxLog("weight\n");
373                 for (int px=0; px < numUnique; px++) {
374                         double weight = numIdentical[px] / patternLik[px];
375                         mxLog("%20.20f\n", weight);
376                 }
377
378                 mxLog("per item mean\n");
379                 for (int px=0; px < numUnique; px++) {
380                         mxLog("[%d] %20.20f\n", px, ElatentMean[px * maxAbilities]);
381                 }
382         }
383
384         for (int px=0; px < numUnique; px++) {
385                 if (patternLik[px] < MIN_PATTERNLIK) {
386                         patternLik[px] = MIN_PATTERNLIK;
387                         warning("Likelihood of pattern %d is 0, forcing to %.3g",
388                                 px, MIN_PATTERNLIK);
389                 }
390
391                 double weight = numIdentical[px] / patternLik[px];
392                 for (int d1=0; d1 < primaryDims; d1++) {
393                         ElatentMean[px * maxAbilities + d1] *= weight;
394                         for (int d2=0; d2 <= d1; d2++) {
395                                 int loc = px * maxAbilities * maxAbilities + d2 * maxAbilities + d1;
396                                 ElatentCov[loc] *= weight;
397                         }
398                 }
399                 for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
400                         ElatentMean[px * maxAbilities + sdim] *= weight;
401                         int loc = px * maxAbilities * maxAbilities + sdim * maxAbilities + sdim;
402                         ElatentCov[loc] *= weight;
403                 }
404 #if 0
405                 if (!isfinite(patternLik[px])) {
406                         error("Likelihood of row %d is %f", state->rowMap[px], patternLik[px]);
407                 }
408 #endif
409                 patternLik[px] = log(patternLik[px]);
410         }
411
412         for (int px=1; px < numUnique; px++) {
413                 for (int d1=0; d1 < primaryDims; d1++) {
414                         ElatentMean[d1] += ElatentMean[px * maxAbilities + d1];
415                         for (int d2=0; d2 <= d1; d2++) {
416                                 int cell = d2 * maxAbilities + d1;
417                                 int loc = px * maxAbilities * maxAbilities + cell;
418                                 ElatentCov[cell] += ElatentCov[loc];
419                         }
420                 }
421                 for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
422                         ElatentMean[sdim] += ElatentMean[px * maxAbilities + sdim];
423                         int cell = sdim * maxAbilities + sdim;
424                         int loc = px * maxAbilities * maxAbilities + cell;
425                         ElatentCov[cell] += ElatentCov[loc];
426                 }
427         }
428
429         //pda(ElatentMean, state->maxAbilities, 1);
430         //pda(ElatentCov, state->maxAbilities, state->maxAbilities);
431
432         omxData *data = state->data;
433         for (int d1=0; d1 < maxAbilities; d1++) {
434                 ElatentMean[d1] /= data->rows;
435         }
436
437         for (int d1=0; d1 < primaryDims; d1++) {
438                 for (int d2=0; d2 <= d1; d2++) {
439                         int cell = d2 * maxAbilities + d1;
440                         int tcell = d1 * maxAbilities + d2;
441                         ElatentCov[tcell] = ElatentCov[cell] =
442                                 ElatentCov[cell] / data->rows - ElatentMean[d1] * ElatentMean[d2];
443                 }
444         }
445         for (int sdim=primaryDims; sdim < maxAbilities; sdim++) {
446                 int cell = sdim * maxAbilities + sdim;
447                 ElatentCov[cell] = ElatentCov[cell] / data->rows - ElatentMean[sdim] * ElatentMean[sdim];
448         }
449
450         //mxLog("E-step\n");
451         //pda(ElatentMean, state->maxAbilities, 1);
452         //pda(ElatentCov, state->maxAbilities, state->maxAbilities);
453 }
454
455 // Attempt G-H grid? http://dbarajassolano.wordpress.com/2012/01/26/on-sparse-grid-quadratures/
456 static void
457 ba81SetupQuadrature(omxExpectation* oo, int gridsize, int flat)
458 {
459         BA81Expect *state = (BA81Expect *) oo->argStruct;
460         int numUnique = state->numUnique;
461         int numThreads = Global->numThreads;
462         int maxDims = state->maxDims;
463         int Qwidth = state->Qwidth;
464         int numSpecific = state->numSpecific;
465         int priDims = maxDims - (numSpecific? 1 : 0);
466
467         // try starting small and increasing to the cap TODO
468         state->quadGridSize = gridsize;
469
470         state->totalQuadPoints = 1;
471         for (int dx=0; dx < maxDims; dx++) {
472                 state->totalQuadPoints *= state->quadGridSize;
473         }
474
475         state->totalPrimaryPoints = state->totalQuadPoints;
476
477         if (numSpecific) {
478                 state->totalPrimaryPoints /= state->quadGridSize;
479                 state->speLogQarea = Realloc(state->speLogQarea, state->quadGridSize * gridsize, double);
480         }
481
482         state->Qpoint = Realloc(state->Qpoint, state->quadGridSize, double);
483         state->priLogQarea = Realloc(state->priLogQarea, state->totalPrimaryPoints, double);
484
485         for (int px=0; px < state->quadGridSize; px ++) {
486                 state->Qpoint[px] = Qwidth - px * 2 * Qwidth / (state->quadGridSize-1);
487         }
488
489         if (flat) {
490                 // not sure why this is useful, remove? TODO
491                 double flatd = log(1) - log(state->totalPrimaryPoints);
492                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
493                         state->priLogQarea[qx] = flatd;
494                 }
495                 flatd = log(1) - log(state->quadGridSize);
496                 for (int sx=0; sx < numSpecific; sx++) {
497                         for (int qx=0; qx < state->quadGridSize; qx++) {
498                                 state->speLogQarea[ sx * state->quadGridSize + qx] = flatd;
499                         }
500                 }
501         } else {
502                 double totalArea = 0;
503                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
504                         int quad[priDims];
505                         decodeLocation(qx, priDims, state->quadGridSize, quad);
506                         double where[priDims];
507                         pointToWhere(state->Qpoint, quad, where, priDims);
508                         state->priLogQarea[qx] = dmvnorm(priDims, where,
509                                                          state->latentMeanOut->data,
510                                                          state->latentCovOut->data);
511                         totalArea += exp(state->priLogQarea[qx]);
512                 }
513                 totalArea = log(totalArea);
514                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
515                         state->priLogQarea[qx] -= totalArea;
516                         //mxLog("%.5g,", state->priLogQarea[qx]);
517                 }
518                 //mxLog("\n");
519
520                 for (int sx=0; sx < numSpecific; sx++) {
521                         totalArea = 0;
522                         for (int qx=0; qx < state->quadGridSize; qx++) {
523                                 int covCell = (priDims + sx) * state->maxAbilities + priDims + sx;
524                                 double den = dnorm(state->Qpoint[qx],
525                                                    state->latentMeanOut->data[priDims + sx],
526                                                    state->latentCovOut->data[covCell], TRUE);
527                                 state->speLogQarea[sx * state->quadGridSize + qx] = den;
528                                 totalArea += exp(den);
529                         }
530                         totalArea = log(totalArea);
531                         for (int qx=0; qx < state->quadGridSize; qx++) {
532                                 state->speLogQarea[sx * state->quadGridSize + qx] -= totalArea;
533                         }
534                 }
535         }
536
537         if (!state->cacheLXK) {
538                 state->lxk = Realloc(state->lxk, numUnique * numThreads, double);
539         } else {
540                 int ns = state->numSpecific;
541                 if (ns == 0) ns = 1;
542                 long numOrdinate = ns * state->totalQuadPoints;
543                 state->lxk = Realloc(state->lxk, numUnique * numOrdinate, double);
544         }
545
546         state->expected = Realloc(state->expected, state->totalOutcomes * state->totalQuadPoints, double);
547 }
548
549 OMXINLINE static void
550 expectedUpdate(omxData *data, const int *rowMap, const int px, const int item,
551                const double observed, const int outcomes, double *out)
552 {
553         int pick = omxIntDataElementUnsafe(data, rowMap[px], item);
554         if (pick == NA_INTEGER) {
555                 double slice = exp(observed - log(outcomes));
556                 for (int ox=0; ox < outcomes; ox++) {
557                         out[ox] += slice;
558                 }
559         } else {
560                 out[pick-1] += exp(observed);
561         }
562 }
563
564 OMXINLINE static void
565 ba81Expected(omxExpectation* oo)
566 {
567         BA81Expect *state = (BA81Expect*) oo->argStruct;
568         omxData *data = state->data;
569         int numSpecific = state->numSpecific;
570         const int *rowMap = state->rowMap;
571         double *patternLik = state->patternLik;
572         double *logNumIdentical = state->logNumIdentical;
573         int numUnique = state->numUnique;
574         int maxDims = state->maxDims;
575         int numItems = state->EitemParam->cols;
576         omxMatrix *itemSpec = state->itemSpec;
577         int totalOutcomes = state->totalOutcomes;
578
579         OMXZERO(state->expected, totalOutcomes * state->totalQuadPoints);
580
581         if (numSpecific == 0) {
582 #pragma omp parallel for num_threads(Global->numThreads)
583                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
584                         int quad[maxDims];
585                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
586                         double *lxk = ba81LikelihoodFast(oo, 0, quad);
587                         for (int px=0; px < numUnique; px++) {
588                                 double *out = state->expected + qx * totalOutcomes;
589                                 double observed = logNumIdentical[px] + lxk[px] - patternLik[px];
590                                 for (int ix=0; ix < numItems; ix++) {
591                                         const double *spec = omxMatrixColumn(itemSpec, ix);
592                                         int outcomes = spec[RPF_ISpecOutcomes];
593                                         expectedUpdate(data, rowMap, px, ix, observed, outcomes, out);
594                                         out += outcomes;
595                                 }
596                         }
597                 }
598         } else {
599                 int sDim = state->maxDims-1;
600                 long specificPoints = state->quadGridSize;
601
602 #pragma omp parallel for num_threads(Global->numThreads)
603                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
604                         int quad[maxDims];
605                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
606
607                         // allSlxk, Slxk only depend on the ordinate of the primary dimensions
608                         double *allSlxk = CALC_ALLSLXK(state, numUnique);
609                         double *Slxk = CALC_SLXK(state, numUnique, numSpecific);
610                         cai2010(oo, !state->cacheLXK, quad, allSlxk, Slxk);
611
612                         for (long sx=0; sx < specificPoints; sx++) {
613                                 quad[sDim] = sx;
614                                 long qloc = encodeLocation(state->maxDims, state->quadGridSize, quad);
615
616                                 for (int sgroup=0; sgroup < numSpecific; sgroup++) {
617                                         double *eis = Slxk + numUnique * sgroup;
618                                         double *lxk = ba81LikelihoodFast(oo, sgroup, quad);
619
620                                         for (int px=0; px < numUnique; px++) {
621                                                 double *out = state->expected + totalOutcomes * qloc;
622
623                                                 for (int ix=0; ix < numItems; ix++) {
624                                                         const double *spec = omxMatrixColumn(itemSpec, ix);
625                                                         int outcomes = spec[RPF_ISpecOutcomes];
626                                                         if (state->Sgroup[ix] == sgroup) {
627                                                                 double observed = logNumIdentical[px] + (allSlxk[px] - eis[px]) +
628                                                                         (lxk[px] - patternLik[px]);
629                                                                 expectedUpdate(data, rowMap, px, ix, observed, outcomes, out);
630                                                         }
631                                                         out += outcomes;
632                                                 }
633                                         }
634                                 }
635                         }
636                 }
637         }
638         //pda(state->expected, state->totalOutcomes, state->totalQuadPoints);
639 }
640
641 static void
642 ba81Estep(omxExpectation *oo, const char *context) {
643         if (!context) return;
644
645         ba81Estep1(oo);
646         if (strcmp(context, "E")==0) {
647                 // for E-M LL
648                 ba81Expected(oo);
649         } else if (strcmp(context, "M")==0) {
650                 // for regular LL
651                 BA81Expect *state = (BA81Expect *) oo->argStruct;
652                 ba81SetupQuadrature(oo, state->targetQpoints, 0);
653         } else {
654                 error("Unknown context '%s'", context);
655         }
656 }
657
658 static double *
659 realEAP(omxExpectation *oo)
660 {
661         // add openmp parallelization stuff TODO
662
663         BA81Expect *state = (BA81Expect *) oo->argStruct;
664         int numSpecific = state->numSpecific;
665         int maxDims = state->maxDims;
666         int priDims = maxDims - (numSpecific? 1 : 0);
667         int numUnique = state->numUnique;
668         int maxAbilities = state->maxAbilities;
669
670         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
671         // model. Journal of Educational Statistics, 12, 339-368.
672
673         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
674
675         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
676                 // Thissen & Orlando (2001, p. 136)
677                 warning("EAP requires at least 2*sqrt(items) quadrature points");
678         }
679
680         ba81SetupQuadrature(oo, numQpoints, 0);
681         ba81Estep1(oo);
682
683         /*
684         double *cov = NULL;
685         if (maxDims > 1) {
686                 strcpy(out[2].label, "ability.cov");
687                 out[2].numValues = -1;
688                 out[2].rows = maxDims;
689                 out[2].cols = maxDims;
690                 out[2].values = (double*) R_alloc(out[2].rows * out[2].cols, sizeof(double));
691                 cov = out[2].values;
692                 OMXZERO(cov, out[2].rows * out[2].cols);
693         }
694         */
695
696         // Need a separate work space because the destination needs
697         // to be in unsorted order with duplicated rows.
698         double *ability = Calloc(numUnique * maxAbilities * 2, double);
699
700         for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
701                 int quad[priDims];
702                 decodeLocation(qx, priDims, state->quadGridSize, quad);
703                 double where[priDims];
704                 pointToWhere(state->Qpoint, quad, where, priDims);
705                 double logArea = state->priLogQarea[qx];
706
707                 double *lxk;
708                 if (numSpecific == 0) {
709                         lxk = ba81LikelihoodFast(oo, 0, quad);
710                 } else {
711                         double *allSlxk = CALC_ALLSLXK(state, numUnique);
712                         double *Slxk = CALC_SLXK(state, numUnique, numSpecific);
713                         cai2010(oo, FALSE, quad, allSlxk, Slxk);
714                         lxk = allSlxk;
715                 }
716
717                 double *row = ability;
718                 for (int px=0; px < numUnique; px++) {
719                         double plik = exp(logArea + lxk[px]);
720                         for (int dx=0; dx < priDims; dx++) {
721                                 double piece = where[dx] * plik;
722                                 row[dx*2] += piece;
723                                 row[dx*2 + 1] += where[dx] * piece;
724                                 // ignore cov, for now
725                         }
726                         row += 2 * maxAbilities;
727                 }
728         }
729
730         double *ris = Realloc(NULL, numUnique, double);
731         for (int sx=0; sx < numSpecific; sx++) {
732                 for (int sqx=0; sqx < state->quadGridSize; sqx++) {
733                         double area = exp(state->speLogQarea[sx * state->quadGridSize + sqx]);
734                         double ptArea = area * state->Qpoint[sqx];
735                         OMXZERO(ris, numUnique);
736                         for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
737                                 int quad[maxDims];
738                                 decodeLocation(qx, priDims, state->quadGridSize, quad);
739                                 quad[priDims] = sqx;
740
741                                 double *allSlxk = CALC_ALLSLXK(state, numUnique);
742                                 double *Slxk = CALC_SLXK(state, numUnique, numSpecific);
743                                 cai2010(oo, FALSE, quad, allSlxk, Slxk);
744
745                                 double *eis = Slxk + numUnique * sx;
746                                 double *lxk = ba81LikelihoodFast(oo, sx, quad);
747
748                                 double logArea = state->priLogQarea[qx];
749                                 for (int px=0; px < numUnique; px++) {
750                                         ris[px] += exp(logArea + lxk[px] + allSlxk[px] - eis[px]);
751                                 }
752                         }
753                         double *row = ability;
754                         for (int px=0; px < numUnique; px++) {
755                                 double piece = ris[px] * ptArea;
756                                 row[(priDims + sx) * 2] += piece;
757                                 row[(priDims + sx) * 2 + 1] += piece * state->Qpoint[sqx];
758                                 row += 2 * maxAbilities;
759                         }
760                 }
761         }
762         Free(ris);
763
764         double *patternLik = state->patternLik;
765         double *row = ability;
766         for (int px=0; px < numUnique; px++) {
767                 double denom = exp(patternLik[px]);
768                 for (int ax=0; ax < maxAbilities; ax++) {
769                         row[ax * 2] /= denom;
770                         row[ax * 2 + 1] /= denom;
771                         row[ax * 2 + 1] -= row[ax * 2] * row[ax * 2];
772                 }
773                 row += 2 * maxAbilities;
774         }
775
776         /*
777         // make symmetric
778         for (int d1=0; d1 < maxDims; d1++) {
779                 for (int d2=0; d2 < d1; d2++) {
780                         cov[d2 * maxDims + d1] = cov[d1 * maxDims + d2];
781                 }
782         }
783         */
784
785         for (int px=0; px < numUnique; px++) {
786                 double *arow = ability + px * 2 * maxAbilities;
787                 for (int dx=0; dx < maxAbilities; dx++) {
788                         arow[dx*2+1] = sqrt(arow[dx*2+1]);
789                 }
790         }
791
792         return ability;
793 }
794
795 /**
796  * MAP is not affected by the number of items. EAP is. Likelihood can
797  * get concentrated in a single quadrature ordinate. For 3PL, response
798  * patterns can have a bimodal likelihood. This will confuse MAP and
799  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
800  *
801  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
802  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
803  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
804  */
805 omxRListElement *
806 ba81EAP(omxExpectation *oo, int *numReturns)   // rename to "return stuff to user"
807 {
808         BA81Expect *state = (BA81Expect *) oo->argStruct;
809         int maxAbilities = state->maxAbilities;
810
811         *numReturns = 1 + (state->scores != SCORES_OMIT);
812         omxRListElement *out = (omxRListElement*) R_alloc(*numReturns, sizeof(omxRListElement));
813         int ox=0;
814
815         out[ox].numValues = 1;
816         strcpy(out[ox].label, "EM.LL");
817         //      out[ox].values = &state->lastEMLL;  TODO
818         out[ox].values = NULL;
819         ++ox;
820
821         if (state->scores != SCORES_OMIT) {
822                 double *ability = realEAP(oo);
823                 int numUnique = state->numUnique;
824                 omxData *data = state->data;
825
826                 int cols = state->scores == SCORES_FULL? data->rows : numUnique;
827
828                 strcpy(out[ox].label, "ability");
829                 out[ox].numValues = -1;
830                 out[ox].rows = 2 * maxAbilities;
831                 out[ox].cols = cols;
832                 out[ox].values = (double*) R_alloc(out[ox].rows * out[ox].cols, sizeof(double));
833
834                 if (state->scores == SCORES_FULL) {
835                         for (int rx=0; rx < numUnique; rx++) {
836                                 double *pa = ability + rx * 2 * maxAbilities;
837
838                                 int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
839                                 for (int dup=0; dup < dups; dup++) {
840                                         int dest = omxDataIndex(data, state->rowMap[rx]+dup);
841                                         memcpy(out[ox].values + dest * out[ox].rows, pa, sizeof(double) * 2 * maxAbilities);
842                                 }
843                         }
844                 } else {
845                         memcpy(out[ox].values, ability, sizeof(double) * numUnique * 2 * maxAbilities);
846                 }
847                 Free(ability);
848                 ++ox;
849         }
850
851         return out;
852 }
853
854 static void ba81Destroy(omxExpectation *oo) {
855         if(OMX_DEBUG) {
856                 mxLog("Freeing %s function.\n", NAME);
857         }
858         BA81Expect *state = (BA81Expect *) oo->argStruct;
859         omxFreeAllMatrixData(state->itemSpec);
860         omxFreeAllMatrixData(state->EitemParam);
861         omxFreeAllMatrixData(state->design);
862         omxFreeAllMatrixData(state->latentMeanOut);
863         omxFreeAllMatrixData(state->latentCovOut);
864         Free(state->logNumIdentical);
865         Free(state->numIdentical);
866         Free(state->Qpoint);
867         Free(state->priLogQarea);
868         Free(state->rowMap);
869         Free(state->patternLik);
870         Free(state->lxk);
871         Free(state->Slxk);
872         Free(state->allSlxk);
873         Free(state->Sgroup);
874         Free(state->expected);
875         Free(state->ElatentMean);
876         Free(state->ElatentCov);
877         Free(state);
878 }
879
880 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
881 {
882     SEXP matrixDims;
883     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
884     int *dimList = INTEGER(matrixDims);
885     *rows = dimList[0];
886     *cols = dimList[1];
887     UNPROTECT(1);
888 }
889
890 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
891 {}
892
893 void omxInitExpectationBA81(omxExpectation* oo) {
894         omxState* currentState = oo->currentState;      
895         SEXP rObj = oo->rObj;
896         SEXP tmp;
897         
898         if(OMX_DEBUG) {
899                 mxLog("Initializing %s.\n", NAME);
900         }
901         if (!rpf_model) {
902                 if (0) {
903                         const int wantVersion = 3;
904                         int version;
905                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
906                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
907                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
908                                                          version, wantVersion);
909                 } else {
910                         rpf_numModels = librpf_numModels;
911                         rpf_model = librpf_model;
912                 }
913         }
914         
915         BA81Expect *state = Calloc(1, BA81Expect);
916         oo->argStruct = (void*) state;
917
918         PROTECT(tmp = GET_SLOT(rObj, install("data")));
919         state->data = omxDataLookupFromState(tmp, currentState);
920
921         if (strcmp(omxDataType(state->data), "raw") != 0) {
922                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", NAME, omxDataType(state->data));
923                 return;
924         }
925
926         state->itemSpec =
927                 omxNewMatrixFromSlot(rObj, currentState, "ItemSpec");
928         state->design =
929                 omxNewMatrixFromSlot(rObj, currentState, "Design");
930
931         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean"); // move to FitFunction? TODO
932         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
933         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
934         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
935
936         state->EitemParam =
937                 omxNewMatrixFromSlot(rObj, currentState, "EItemParam");
938         if (!state->EitemParam) error("Must supply EItemParam MxMatrix");
939
940         oo->computeFun = ba81Estep;
941         oo->setVarGroup = ignoreSetVarGroup;
942         oo->destructFun = ba81Destroy;
943         
944         // TODO: Exactly identical rows do not contribute any information.
945         // The sorting algorithm ought to remove them so we don't waste RAM.
946         // The following summary stats would be cheaper to calculate too.
947
948         int numUnique = 0;
949         omxData *data = state->data;
950         if (omxDataNumFactor(data) != data->cols) {
951                 // verify they are ordered factors TODO
952                 omxRaiseErrorf(currentState, "%s: all columns must be factors", NAME);
953                 return;
954         }
955
956         for (int rx=0; rx < data->rows;) {
957                 rx += omxDataNumIdenticalRows(state->data, rx);
958                 ++numUnique;
959         }
960         state->numUnique = numUnique;
961
962         state->rowMap = Realloc(NULL, numUnique, int);
963         state->numIdentical = Realloc(NULL, numUnique, int);
964         state->logNumIdentical = Realloc(NULL, numUnique, double);
965
966         int numItems = state->EitemParam->cols;
967         if (data->cols != numItems) {
968                 error("Data has %d columns for %d items", data->cols, numItems);
969         }
970
971         for (int rx=0, ux=0; rx < data->rows; ux++) {
972                 if (rx == 0) {
973                         // all NA rows will sort to the top
974                         int na=0;
975                         for (int ix=0; ix < numItems; ix++) {
976                                 if (omxIntDataElement(data, 0, ix) == NA_INTEGER) { ++na; }
977                         }
978                         if (na == numItems) {
979                                 omxRaiseErrorf(currentState, "Remove rows with all NAs");
980                                 return;
981                         }
982                 }
983                 int dups = omxDataNumIdenticalRows(state->data, rx);
984                 state->numIdentical[ux] = dups;
985                 state->logNumIdentical[ux] = log(dups);
986                 state->rowMap[ux] = rx;
987                 rx += dups;
988         }
989
990         state->patternLik = Realloc(NULL, numUnique, double);
991
992         int numThreads = Global->numThreads;
993
994         int maxSpec = 0;
995         int maxParam = 0;
996         state->maxDims = 0;
997         state->maxOutcomes = 0;
998
999         int totalOutcomes = 0;
1000         for (int cx = 0; cx < data->cols; cx++) {
1001                 const double *spec = omxMatrixColumn(state->itemSpec, cx);
1002                 int id = spec[RPF_ISpecID];
1003                 int dims = spec[RPF_ISpecDims];
1004                 if (state->maxDims < dims)
1005                         state->maxDims = dims;
1006
1007                 int no = spec[RPF_ISpecOutcomes];
1008                 totalOutcomes += no;
1009                 if (state->maxOutcomes < no)
1010                         state->maxOutcomes = no;
1011
1012                 // TODO this summary stat should be available from omxData
1013                 int dataMax=0;
1014                 for (int rx=0; rx < data->rows; rx++) {
1015                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1016                         if (dataMax < pick)
1017                                 dataMax = pick;
1018                 }
1019                 if (dataMax > no) {
1020                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1021                 } else if (dataMax < no) {
1022                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1023                         // promote to error?
1024                         // should complain if an outcome is not represented in the data TODO
1025                 }
1026
1027                 int numSpec = (*rpf_model[id].numSpec)(spec);
1028                 if (maxSpec < numSpec)
1029                         maxSpec = numSpec;
1030
1031                 int numParam = (*rpf_model[id].numParam)(spec);
1032                 if (maxParam < numParam)
1033                         maxParam = numParam;
1034         }
1035
1036         state->totalOutcomes = totalOutcomes;
1037
1038         if (state->itemSpec->cols != data->cols || state->itemSpec->rows != maxSpec) {
1039                 omxRaiseErrorf(currentState, "ItemSpec must have %d item columns and %d rows",
1040                                data->cols, maxSpec);
1041                 return;
1042         }
1043         if (state->EitemParam->rows != maxParam) {
1044                 omxRaiseErrorf(currentState, "ItemParam should have %d rows", maxParam);
1045                 return;
1046         }
1047
1048         if (state->design == NULL) {
1049                 state->maxAbilities = state->maxDims;
1050                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1051                                        TRUE, currentState);
1052                 for (int ix=0; ix < numItems; ix++) {
1053                         const double *spec = omxMatrixColumn(state->itemSpec, ix);
1054                         int dims = spec[RPF_ISpecDims];
1055                         for (int dx=0; dx < state->maxDims; dx++) {
1056                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1057                         }
1058                 }
1059         } else {
1060                 omxMatrix *design = state->design;
1061                 if (design->cols != numItems ||
1062                     design->rows != state->maxDims) {
1063                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1064                                        state->maxDims, numItems);
1065                         return;
1066                 }
1067
1068                 state->maxAbilities = 0;
1069                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1070                         double got = design->data[ix];
1071                         if (!R_FINITE(got)) continue;
1072                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1073                         if (state->maxAbilities < got)
1074                                 state->maxAbilities = got;
1075                 }
1076                 for (int ix=0; ix < design->cols; ix++) {
1077                         const double *idesign = omxMatrixColumn(design, ix);
1078                         int ddim = 0;
1079                         for (int rx=0; rx < design->rows; rx++) {
1080                                 if (isfinite(idesign[rx])) ddim += 1;
1081                         }
1082                         const double *spec = omxMatrixColumn(state->itemSpec, ix);
1083                         int dims = spec[RPF_ISpecDims];
1084                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1085                 }
1086         }
1087         if (state->maxAbilities <= state->maxDims) {
1088                 state->Sgroup = Calloc(numItems, int);
1089         } else {
1090                 // Not sure if this is correct, revisit TODO
1091                 int Sgroup0 = -1;
1092                 state->Sgroup = Realloc(NULL, numItems, int);
1093                 for (int dx=0; dx < state->maxDims; dx++) {
1094                         for (int ix=0; ix < numItems; ix++) {
1095                                 int ability = omxMatrixElement(state->design, dx, ix);
1096                                 if (dx < state->maxDims - 1) {
1097                                         if (Sgroup0 <= ability)
1098                                                 Sgroup0 = ability+1;
1099                                         continue;
1100                                 }
1101                                 int ss=-1;
1102                                 if (ability >= Sgroup0) {
1103                                         if (ss == -1) {
1104                                                 ss = ability;
1105                                         } else {
1106                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1107                                                                "1 specific dimension (both %d and %d)",
1108                                                                ix, ss, ability);
1109                                                 return;
1110                                         }
1111                                 }
1112                                 if (ss == -1) ss = Sgroup0;
1113                                 state->Sgroup[ix] = ss - Sgroup0;
1114                         }
1115                 }
1116                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1117                 state->allSlxk = Realloc(NULL, numUnique * numThreads, double);
1118                 state->Slxk = Realloc(NULL, numUnique * state->numSpecific * numThreads, double);
1119         }
1120
1121         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1122                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1123                       state->maxAbilities, state->maxAbilities);
1124         }
1125         if (state->latentCovOut->rows != state->maxAbilities ||
1126             state->latentCovOut->cols != state->maxAbilities) {
1127                 error("The cov matrix '%s' must be %dx%d",
1128                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1129         }
1130
1131         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1132         state->cacheLXK = asLogical(tmp);
1133
1134         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1135         state->targetQpoints = asReal(tmp);
1136
1137         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1138         state->Qwidth = asReal(tmp);
1139
1140         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1141         const char *score_option = CHAR(asChar(tmp));
1142         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1143         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1144         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1145
1146         state->ElatentMean = Realloc(NULL, state->maxAbilities * numUnique, double);
1147         state->ElatentCov = Realloc(NULL, state->maxAbilities * state->maxAbilities * numUnique, double);
1148
1149         ba81SetupQuadrature(oo, state->targetQpoints, 0);
1150
1151         // verify data bounded between 1 and numOutcomes TODO
1152         // hm, looks like something could be added to omxData for column summary stats?
1153 }