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