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