Test multigroup, multidimensional EAP
[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         state->validExpectation = TRUE;
454 }
455
456 // Attempt G-H grid? http://dbarajassolano.wordpress.com/2012/01/26/on-sparse-grid-quadratures/
457 static void
458 ba81SetupQuadrature(omxExpectation* oo, int gridsize, int flat)
459 {
460         BA81Expect *state = (BA81Expect *) oo->argStruct;
461         int numUnique = state->numUnique;
462         int numThreads = Global->numThreads;
463         int maxDims = state->maxDims;
464         int Qwidth = state->Qwidth;
465         int numSpecific = state->numSpecific;
466         int priDims = maxDims - (numSpecific? 1 : 0);
467
468         // try starting small and increasing to the cap TODO
469         state->quadGridSize = gridsize;
470
471         state->totalQuadPoints = 1;
472         for (int dx=0; dx < maxDims; dx++) {
473                 state->totalQuadPoints *= state->quadGridSize;
474         }
475
476         state->totalPrimaryPoints = state->totalQuadPoints;
477
478         if (numSpecific) {
479                 state->totalPrimaryPoints /= state->quadGridSize;
480                 state->speLogQarea = Realloc(state->speLogQarea, state->quadGridSize * gridsize, double);
481         }
482
483         state->Qpoint = Realloc(state->Qpoint, state->quadGridSize, double);
484         state->priLogQarea = Realloc(state->priLogQarea, state->totalPrimaryPoints, double);
485
486         double qgs = state->quadGridSize-1;
487         for (int px=0; px < state->quadGridSize; px ++) {
488                 state->Qpoint[px] = Qwidth - px * 2 * Qwidth / qgs;
489         }
490
491         if (flat) {
492                 // not sure why this is useful, remove? TODO
493                 double flatd = log(1) - log(state->totalPrimaryPoints);
494                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
495                         state->priLogQarea[qx] = flatd;
496                 }
497                 flatd = log(1) - log(state->quadGridSize);
498                 for (int sx=0; sx < numSpecific; sx++) {
499                         for (int qx=0; qx < state->quadGridSize; qx++) {
500                                 state->speLogQarea[ sx * state->quadGridSize + qx] = flatd;
501                         }
502                 }
503         } else {
504                 if (0) {
505                         pda(state->latentMeanOut->data, 1, state->maxAbilities);
506                         pda(state->latentCovOut->data, state->maxAbilities, state->maxAbilities);
507                 }
508
509                 double totalArea = 0;
510                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
511                         int quad[priDims];
512                         decodeLocation(qx, priDims, state->quadGridSize, quad);
513                         double where[priDims];
514                         pointToWhere(state->Qpoint, quad, where, priDims);
515                         state->priLogQarea[qx] = dmvnorm(priDims, where,
516                                                          state->latentMeanOut->data,
517                                                          state->latentCovOut->data);
518                         totalArea += exp(state->priLogQarea[qx]);
519                 }
520                 totalArea = log(totalArea);
521                 for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
522                         state->priLogQarea[qx] -= totalArea;
523                         //mxLog("%.5g,", state->priLogQarea[qx]);
524                 }
525                 //mxLog("\n");
526
527                 for (int sx=0; sx < numSpecific; sx++) {
528                         totalArea = 0;
529                         for (int qx=0; qx < state->quadGridSize; qx++) {
530                                 int covCell = (priDims + sx) * state->maxAbilities + priDims + sx;
531                                 double den = dnorm(state->Qpoint[qx],
532                                                    state->latentMeanOut->data[priDims + sx],
533                                                    state->latentCovOut->data[covCell], TRUE);
534                                 state->speLogQarea[sx * state->quadGridSize + qx] = den;
535                                 totalArea += exp(den);
536                         }
537                         totalArea = log(totalArea);
538                         for (int qx=0; qx < state->quadGridSize; qx++) {
539                                 state->speLogQarea[sx * state->quadGridSize + qx] -= totalArea;
540                         }
541                 }
542         }
543
544         if (!state->cacheLXK) {
545                 state->lxk = Realloc(state->lxk, numUnique * numThreads, double);
546         } else {
547                 int ns = state->numSpecific;
548                 if (ns == 0) ns = 1;
549                 long numOrdinate = ns * state->totalQuadPoints;
550                 state->lxk = Realloc(state->lxk, numUnique * numOrdinate, double);
551         }
552
553         state->expected = Realloc(state->expected, state->totalOutcomes * state->totalQuadPoints, double);
554 }
555
556 OMXINLINE static void
557 expectedUpdate(omxData *data, const int *rowMap, const int px, const int item,
558                const double observed, const int outcomes, double *out)
559 {
560         int pick = omxIntDataElementUnsafe(data, rowMap[px], item);
561         if (pick == NA_INTEGER) {
562                 double slice = exp(observed - log(outcomes));
563                 for (int ox=0; ox < outcomes; ox++) {
564                         out[ox] += slice;
565                 }
566         } else {
567                 out[pick-1] += exp(observed);
568         }
569 }
570
571 OMXINLINE static void
572 ba81Expected(omxExpectation* oo)
573 {
574         BA81Expect *state = (BA81Expect*) oo->argStruct;
575         omxData *data = state->data;
576         int numSpecific = state->numSpecific;
577         const int *rowMap = state->rowMap;
578         double *patternLik = state->patternLik;
579         double *logNumIdentical = state->logNumIdentical;
580         int numUnique = state->numUnique;
581         int maxDims = state->maxDims;
582         int numItems = state->EitemParam->cols;
583         omxMatrix *itemSpec = state->itemSpec;
584         int totalOutcomes = state->totalOutcomes;
585
586         OMXZERO(state->expected, totalOutcomes * state->totalQuadPoints);
587
588         if (numSpecific == 0) {
589 #pragma omp parallel for num_threads(Global->numThreads)
590                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
591                         int quad[maxDims];
592                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
593                         double *lxk = ba81LikelihoodFast(oo, 0, quad);
594                         for (int px=0; px < numUnique; px++) {
595                                 double *out = state->expected + qx * totalOutcomes;
596                                 double observed = logNumIdentical[px] + lxk[px] - patternLik[px];
597                                 for (int ix=0; ix < numItems; ix++) {
598                                         const double *spec = omxMatrixColumn(itemSpec, ix);
599                                         int outcomes = spec[RPF_ISpecOutcomes];
600                                         expectedUpdate(data, rowMap, px, ix, observed, outcomes, out);
601                                         out += outcomes;
602                                 }
603                         }
604                 }
605         } else {
606                 int sDim = state->maxDims-1;
607                 long specificPoints = state->quadGridSize;
608
609 #pragma omp parallel for num_threads(Global->numThreads)
610                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
611                         int quad[maxDims];
612                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
613
614                         // allSlxk, Slxk only depend on the ordinate of the primary dimensions
615                         double *allSlxk = CALC_ALLSLXK(state, numUnique);
616                         double *Slxk = CALC_SLXK(state, numUnique, numSpecific);
617                         cai2010(oo, !state->cacheLXK, quad, allSlxk, Slxk);
618
619                         for (long sx=0; sx < specificPoints; sx++) {
620                                 quad[sDim] = sx;
621                                 long qloc = encodeLocation(state->maxDims, state->quadGridSize, quad);
622
623                                 for (int sgroup=0; sgroup < numSpecific; sgroup++) {
624                                         double *eis = Slxk + numUnique * sgroup;
625                                         double *lxk = ba81LikelihoodFast(oo, sgroup, quad);
626
627                                         for (int px=0; px < numUnique; px++) {
628                                                 double *out = state->expected + totalOutcomes * qloc;
629
630                                                 for (int ix=0; ix < numItems; ix++) {
631                                                         const double *spec = omxMatrixColumn(itemSpec, ix);
632                                                         int outcomes = spec[RPF_ISpecOutcomes];
633                                                         if (state->Sgroup[ix] == sgroup) {
634                                                                 double observed = logNumIdentical[px] + (allSlxk[px] - eis[px]) +
635                                                                         (lxk[px] - patternLik[px]);
636                                                                 expectedUpdate(data, rowMap, px, ix, observed, outcomes, out);
637                                                         }
638                                                         out += outcomes;
639                                                 }
640                                         }
641                                 }
642                         }
643                 }
644         }
645         //pda(state->expected, state->totalOutcomes, state->totalQuadPoints);
646 }
647
648 static void
649 ba81Estep(omxExpectation *oo, const char *context) {
650         if (!context) return;
651
652         BA81Expect *state = (BA81Expect *) oo->argStruct;
653         omxRecompute(state->EitemParam);
654         omxRecompute(state->latentMeanOut);
655         omxRecompute(state->latentCovOut);
656
657         ba81Estep1(oo);
658         if (strcmp(context, "E")==0) {
659                 // for E-M LL
660                 ba81Expected(oo);
661         } else if (strcmp(context, "M")==0) {
662                 // for regular LL
663                 BA81Expect *state = (BA81Expect *) oo->argStruct;
664                 ba81SetupQuadrature(oo, state->targetQpoints, 0);
665         } else {
666                 error("Unknown context '%s'", context);
667         }
668 }
669
670 static double *
671 realEAP(omxExpectation *oo)
672 {
673         // add openmp parallelization stuff TODO
674
675         BA81Expect *state = (BA81Expect *) oo->argStruct;
676         int numSpecific = state->numSpecific;
677         int maxDims = state->maxDims;
678         int priDims = maxDims - (numSpecific? 1 : 0);
679         int numUnique = state->numUnique;
680         int maxAbilities = state->maxAbilities;
681
682         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
683         // model. Journal of Educational Statistics, 12, 339-368.
684
685         /*
686         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
687
688         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
689                 // Thissen & Orlando (2001, p. 136)
690                 warning("EAP requires at least 2*sqrt(items) quadrature points");
691         }
692
693         ba81SetupQuadrature(oo, numQpoints, 0);
694         ba81Estep1(oo);
695         */
696
697         /*
698         double *cov = NULL;
699         if (maxDims > 1) {
700                 strcpy(out[2].label, "ability.cov");
701                 out[2].numValues = -1;
702                 out[2].rows = maxDims;
703                 out[2].cols = maxDims;
704                 out[2].values = (double*) R_alloc(out[2].rows * out[2].cols, sizeof(double));
705                 cov = out[2].values;
706                 OMXZERO(cov, out[2].rows * out[2].cols);
707         }
708         */
709
710         // Need a separate work space because the destination needs
711         // to be in unsorted order with duplicated rows.
712         double *ability = Calloc(numUnique * maxAbilities * 2, double);
713
714         for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
715                 int quad[priDims];
716                 decodeLocation(qx, priDims, state->quadGridSize, quad);
717                 double where[priDims];
718                 pointToWhere(state->Qpoint, quad, where, priDims);
719                 double logArea = state->priLogQarea[qx];
720
721                 double *lxk;
722                 if (numSpecific == 0) {
723                         lxk = ba81LikelihoodFast(oo, 0, quad);
724                 } else {
725                         double *allSlxk = CALC_ALLSLXK(state, numUnique);
726                         double *Slxk = CALC_SLXK(state, numUnique, numSpecific);
727                         cai2010(oo, FALSE, quad, allSlxk, Slxk);
728                         lxk = allSlxk;
729                 }
730
731                 double *row = ability;
732                 for (int px=0; px < numUnique; px++) {
733                         double plik = exp(logArea + lxk[px]);
734                         for (int dx=0; dx < priDims; dx++) {
735                                 double piece = where[dx] * plik;
736                                 row[dx*2] += piece;
737                                 row[dx*2 + 1] += where[dx] * piece;
738                                 // ignore cov, for now
739                         }
740                         row += 2 * maxAbilities;
741                 }
742         }
743
744         double *ris = Realloc(NULL, numUnique, double);
745         for (int sx=0; sx < numSpecific; sx++) {
746                 for (int sqx=0; sqx < state->quadGridSize; sqx++) {
747                         double area = exp(state->speLogQarea[sx * state->quadGridSize + sqx]);
748                         double ptArea = area * state->Qpoint[sqx];
749                         OMXZERO(ris, numUnique);
750                         for (int qx=0; qx < state->totalPrimaryPoints; qx++) {
751                                 int quad[maxDims];
752                                 decodeLocation(qx, priDims, state->quadGridSize, quad);
753                                 quad[priDims] = sqx;
754
755                                 double *allSlxk = CALC_ALLSLXK(state, numUnique);
756                                 double *Slxk = CALC_SLXK(state, numUnique, numSpecific);
757                                 cai2010(oo, FALSE, quad, allSlxk, Slxk);
758
759                                 double *eis = Slxk + numUnique * sx;
760                                 double *lxk = ba81LikelihoodFast(oo, sx, quad);
761
762                                 double logArea = state->priLogQarea[qx];
763                                 for (int px=0; px < numUnique; px++) {
764                                         ris[px] += exp(logArea + lxk[px] + allSlxk[px] - eis[px]);
765                                 }
766                         }
767                         double *row = ability;
768                         for (int px=0; px < numUnique; px++) {
769                                 double piece = ris[px] * ptArea;
770                                 row[(priDims + sx) * 2] += piece;
771                                 row[(priDims + sx) * 2 + 1] += piece * state->Qpoint[sqx];
772                                 row += 2 * maxAbilities;
773                         }
774                 }
775         }
776         Free(ris);
777
778         double *patternLik = state->patternLik;
779         double *row = ability;
780         for (int px=0; px < numUnique; px++) {
781                 double denom = exp(patternLik[px]);
782                 for (int ax=0; ax < maxAbilities; ax++) {
783                         row[ax * 2] /= denom;
784                         row[ax * 2 + 1] /= denom;
785                         row[ax * 2 + 1] -= row[ax * 2] * row[ax * 2];
786                 }
787                 row += 2 * maxAbilities;
788         }
789
790         /*
791         // make symmetric
792         for (int d1=0; d1 < maxDims; d1++) {
793                 for (int d2=0; d2 < d1; d2++) {
794                         cov[d2 * maxDims + d1] = cov[d1 * maxDims + d2];
795                 }
796         }
797         */
798
799         for (int px=0; px < numUnique; px++) {
800                 double *arow = ability + px * 2 * maxAbilities;
801                 for (int dx=0; dx < maxAbilities; dx++) {
802                         arow[dx*2+1] = sqrt(arow[dx*2+1]);
803                 }
804         }
805
806         return ability;
807 }
808
809 /**
810  * MAP is not affected by the number of items. EAP is. Likelihood can
811  * get concentrated in a single quadrature ordinate. For 3PL, response
812  * patterns can have a bimodal likelihood. This will confuse MAP and
813  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
814  *
815  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
816  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
817  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
818  */
819 static void
820 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
821 {
822         BA81Expect *state = (BA81Expect *) oo->argStruct;
823
824         if (state->scores == SCORES_OMIT || !state->validExpectation) return;
825
826         double *ability = realEAP(oo);
827         int numUnique = state->numUnique;
828         omxData *data = state->data;
829         int maxAbilities = state->maxAbilities;
830         int cols = state->scores == SCORES_FULL? data->rows : numUnique;
831         int rows = 2 * maxAbilities;
832         SEXP Rscores;
833         PROTECT(Rscores = allocMatrix(REALSXP, 2 * maxAbilities, cols));
834         double *scores = REAL(Rscores);
835
836         SEXP names;
837         PROTECT(names = allocVector(STRSXP, 2 * maxAbilities));
838         for (int nx=0; nx < maxAbilities; ++nx) {
839                 const int SMALLBUF = 10;
840                 char buf[SMALLBUF];
841                 snprintf(buf, SMALLBUF, "s%d", nx+1);
842                 SET_STRING_ELT(names, nx*2, mkChar(buf));
843                 snprintf(buf, SMALLBUF, "se%d", nx+1);
844                 SET_STRING_ELT(names, nx*2+1, mkChar(buf));
845         }
846         SEXP dimnames;
847         PROTECT(dimnames = allocVector(VECSXP, 2));
848         SET_VECTOR_ELT(dimnames, 0, names);
849         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
850
851         if (state->scores == SCORES_FULL) {
852                 for (int rx=0; rx < numUnique; rx++) {
853                         double *pa = ability + rx * rows;
854
855                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
856                         for (int dup=0; dup < dups; dup++) {
857                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
858                                 memcpy(scores + dest * rows, pa, sizeof(double) * rows);
859                         }
860                 }
861         } else {
862                 memcpy(scores, ability, sizeof(double) * numUnique * rows);
863         }
864         Free(ability);
865
866         setAttrib(robj, install("scores.out"), Rscores);
867 }
868
869 static void ba81Destroy(omxExpectation *oo) {
870         if(OMX_DEBUG) {
871                 mxLog("Freeing %s function.\n", NAME);
872         }
873         BA81Expect *state = (BA81Expect *) oo->argStruct;
874         omxFreeAllMatrixData(state->itemSpec);
875         omxFreeAllMatrixData(state->EitemParam);
876         omxFreeAllMatrixData(state->design);
877         omxFreeAllMatrixData(state->latentMeanOut);
878         omxFreeAllMatrixData(state->latentCovOut);
879         Free(state->logNumIdentical);
880         Free(state->numIdentical);
881         Free(state->Qpoint);
882         Free(state->priLogQarea);
883         Free(state->rowMap);
884         Free(state->patternLik);
885         Free(state->lxk);
886         Free(state->Slxk);
887         Free(state->allSlxk);
888         Free(state->Sgroup);
889         Free(state->expected);
890         Free(state->ElatentMean);
891         Free(state->ElatentCov);
892         Free(state);
893 }
894
895 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
896 {
897     SEXP matrixDims;
898     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
899     int *dimList = INTEGER(matrixDims);
900     *rows = dimList[0];
901     *cols = dimList[1];
902     UNPROTECT(1);
903 }
904
905 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
906 {}
907
908 void omxInitExpectationBA81(omxExpectation* oo) {
909         omxState* currentState = oo->currentState;      
910         SEXP rObj = oo->rObj;
911         SEXP tmp;
912         
913         if(OMX_DEBUG) {
914                 mxLog("Initializing %s.\n", NAME);
915         }
916         if (!rpf_model) {
917                 if (0) {
918                         const int wantVersion = 3;
919                         int version;
920                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
921                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
922                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
923                                                          version, wantVersion);
924                 } else {
925                         rpf_numModels = librpf_numModels;
926                         rpf_model = librpf_model;
927                 }
928         }
929         
930         BA81Expect *state = Calloc(1, BA81Expect);
931         oo->argStruct = (void*) state;
932
933         PROTECT(tmp = GET_SLOT(rObj, install("data")));
934         state->data = omxDataLookupFromState(tmp, currentState);
935
936         if (strcmp(omxDataType(state->data), "raw") != 0) {
937                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", NAME, omxDataType(state->data));
938                 return;
939         }
940
941         // change to regular matrices instead of MxMatrix TODO
942         state->itemSpec =
943                 omxNewMatrixFromSlot(rObj, currentState, "ItemSpec");
944         state->design =
945                 omxNewMatrixFromSlot(rObj, currentState, "Design");
946
947         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean"); // move to FitFunction? TODO
948         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
949         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
950         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
951
952         state->EitemParam =
953                 omxNewMatrixFromSlot(rObj, currentState, "EItemParam");
954         if (!state->EitemParam) error("Must supply EItemParam");
955
956         oo->computeFun = ba81Estep;
957         oo->setVarGroup = ignoreSetVarGroup;
958         oo->destructFun = ba81Destroy;
959         oo->populateAttrFun = ba81PopulateAttributes;
960         
961         // TODO: Exactly identical rows do not contribute any information.
962         // The sorting algorithm ought to remove them so we don't waste RAM.
963         // The following summary stats would be cheaper to calculate too.
964
965         int numUnique = 0;
966         omxData *data = state->data;
967         if (omxDataNumFactor(data) != data->cols) {
968                 // verify they are ordered factors TODO
969                 omxRaiseErrorf(currentState, "%s: all columns must be factors", NAME);
970                 return;
971         }
972
973         for (int rx=0; rx < data->rows;) {
974                 rx += omxDataNumIdenticalRows(state->data, rx);
975                 ++numUnique;
976         }
977         state->numUnique = numUnique;
978
979         state->rowMap = Realloc(NULL, numUnique, int);
980         state->numIdentical = Realloc(NULL, numUnique, int);
981         state->logNumIdentical = Realloc(NULL, numUnique, double);
982
983         int numItems = state->EitemParam->cols;
984         if (data->cols != numItems) {
985                 error("Data has %d columns for %d items", data->cols, numItems);
986         }
987
988         for (int rx=0, ux=0; rx < data->rows; ux++) {
989                 if (rx == 0) {
990                         // all NA rows will sort to the top
991                         int na=0;
992                         for (int ix=0; ix < numItems; ix++) {
993                                 if (omxIntDataElement(data, 0, ix) == NA_INTEGER) { ++na; }
994                         }
995                         if (na == numItems) {
996                                 omxRaiseErrorf(currentState, "Remove rows with all NAs");
997                                 return;
998                         }
999                 }
1000                 int dups = omxDataNumIdenticalRows(state->data, rx);
1001                 state->numIdentical[ux] = dups;
1002                 state->logNumIdentical[ux] = log(dups);
1003                 state->rowMap[ux] = rx;
1004                 rx += dups;
1005         }
1006
1007         state->patternLik = Realloc(NULL, numUnique, double);
1008
1009         int numThreads = Global->numThreads;
1010
1011         int maxSpec = 0;
1012         int maxParam = 0;
1013         state->maxDims = 0;
1014         state->maxOutcomes = 0;
1015
1016         int totalOutcomes = 0;
1017         for (int cx = 0; cx < data->cols; cx++) {
1018                 const double *spec = omxMatrixColumn(state->itemSpec, cx);
1019                 int id = spec[RPF_ISpecID];
1020                 int dims = spec[RPF_ISpecDims];
1021                 if (state->maxDims < dims)
1022                         state->maxDims = dims;
1023
1024                 int no = spec[RPF_ISpecOutcomes];
1025                 totalOutcomes += no;
1026                 if (state->maxOutcomes < no)
1027                         state->maxOutcomes = no;
1028
1029                 // TODO this summary stat should be available from omxData
1030                 int dataMax=0;
1031                 for (int rx=0; rx < data->rows; rx++) {
1032                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1033                         if (dataMax < pick)
1034                                 dataMax = pick;
1035                 }
1036                 if (dataMax > no) {
1037                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1038                 } else if (dataMax < no) {
1039                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1040                         // promote to error?
1041                         // should complain if an outcome is not represented in the data TODO
1042                 }
1043
1044                 int numSpec = (*rpf_model[id].numSpec)(spec);
1045                 if (maxSpec < numSpec)
1046                         maxSpec = numSpec;
1047
1048                 int numParam = (*rpf_model[id].numParam)(spec);
1049                 if (maxParam < numParam)
1050                         maxParam = numParam;
1051         }
1052
1053         state->totalOutcomes = totalOutcomes;
1054
1055         if (state->itemSpec->cols != data->cols || state->itemSpec->rows != maxSpec) {
1056                 omxRaiseErrorf(currentState, "ItemSpec must have %d item columns and %d rows",
1057                                data->cols, maxSpec);
1058                 return;
1059         }
1060         if (state->EitemParam->rows != maxParam) {
1061                 omxRaiseErrorf(currentState, "ItemParam should have %d rows", maxParam);
1062                 return;
1063         }
1064
1065         if (state->design == NULL) {
1066                 state->maxAbilities = state->maxDims;
1067                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1068                                        TRUE, currentState);
1069                 for (int ix=0; ix < numItems; ix++) {
1070                         const double *spec = omxMatrixColumn(state->itemSpec, ix);
1071                         int dims = spec[RPF_ISpecDims];
1072                         for (int dx=0; dx < state->maxDims; dx++) {
1073                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1074                         }
1075                 }
1076         } else {
1077                 omxMatrix *design = state->design;
1078                 if (design->cols != numItems ||
1079                     design->rows != state->maxDims) {
1080                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1081                                        state->maxDims, numItems);
1082                         return;
1083                 }
1084
1085                 state->maxAbilities = 0;
1086                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1087                         double got = design->data[ix];
1088                         if (!R_FINITE(got)) continue;
1089                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1090                         if (state->maxAbilities < got)
1091                                 state->maxAbilities = got;
1092                 }
1093                 for (int ix=0; ix < design->cols; ix++) {
1094                         const double *idesign = omxMatrixColumn(design, ix);
1095                         int ddim = 0;
1096                         for (int rx=0; rx < design->rows; rx++) {
1097                                 if (isfinite(idesign[rx])) ddim += 1;
1098                         }
1099                         const double *spec = omxMatrixColumn(state->itemSpec, ix);
1100                         int dims = spec[RPF_ISpecDims];
1101                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1102                 }
1103         }
1104         if (state->maxAbilities <= state->maxDims) {
1105                 state->Sgroup = Calloc(numItems, int);
1106         } else {
1107                 // Not sure if this is correct, revisit TODO
1108                 int Sgroup0 = -1;
1109                 state->Sgroup = Realloc(NULL, numItems, int);
1110                 for (int dx=0; dx < state->maxDims; dx++) {
1111                         for (int ix=0; ix < numItems; ix++) {
1112                                 int ability = omxMatrixElement(state->design, dx, ix);
1113                                 if (dx < state->maxDims - 1) {
1114                                         if (Sgroup0 <= ability)
1115                                                 Sgroup0 = ability+1;
1116                                         continue;
1117                                 }
1118                                 int ss=-1;
1119                                 if (ability >= Sgroup0) {
1120                                         if (ss == -1) {
1121                                                 ss = ability;
1122                                         } else {
1123                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1124                                                                "1 specific dimension (both %d and %d)",
1125                                                                ix, ss, ability);
1126                                                 return;
1127                                         }
1128                                 }
1129                                 if (ss == -1) ss = Sgroup0;
1130                                 state->Sgroup[ix] = ss - Sgroup0;
1131                         }
1132                 }
1133                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1134                 state->allSlxk = Realloc(NULL, numUnique * numThreads, double);
1135                 state->Slxk = Realloc(NULL, numUnique * state->numSpecific * numThreads, double);
1136         }
1137
1138         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1139                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1140                       state->maxAbilities, state->maxAbilities);
1141         }
1142         if (state->latentCovOut->rows != state->maxAbilities ||
1143             state->latentCovOut->cols != state->maxAbilities) {
1144                 error("The cov matrix '%s' must be %dx%d",
1145                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1146         }
1147
1148         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1149         state->cacheLXK = asLogical(tmp);
1150
1151         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1152         state->targetQpoints = asReal(tmp);
1153
1154         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1155         state->Qwidth = asReal(tmp);
1156
1157         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1158         const char *score_option = CHAR(asChar(tmp));
1159         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1160         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1161         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1162
1163         state->ElatentMean = Realloc(NULL, state->maxAbilities * numUnique, double);
1164         state->ElatentCov = Realloc(NULL, state->maxAbilities * state->maxAbilities * numUnique, double);
1165
1166         ba81SetupQuadrature(oo, state->targetQpoints, 0);
1167
1168         // verify data bounded between 1 and numOutcomes TODO
1169         // hm, looks like something could be added to omxData for column summary stats?
1170 }