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