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