Report the empirical mean & cov
[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         int 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         //pda(state->expected, state->totalOutcomes, state->totalQuadPoints);
696 }
697
698 OMXINLINE static void
699 accumulateScores(BA81Expect *state, int px, int sgroup, double piece, const double *where,
700                  int primaryDims, int covEntries, std::vector<double> *mean, std::vector<double> *cov)
701 {
702         int maxDims = state->maxDims;
703         int maxAbilities = state->maxAbilities;
704
705         if (sgroup == 0) {
706                 int cx=0;
707                 for (int d1=0; d1 < primaryDims; d1++) {
708                         double piece_w1 = piece * where[d1];
709                         double &dest1 = (*mean)[px * maxAbilities + d1];
710 #pragma omp atomic
711                         dest1 += piece_w1;
712                         for (int d2=0; d2 <= d1; d2++) {
713                                 double &dest2 = (*cov)[px * covEntries + cx];
714 #pragma omp atomic
715                                 dest2 += where[d2] * piece_w1;
716                                 ++cx;
717                         }
718                 }
719         }
720
721         if (state->numSpecific) {
722                 int sdim = maxDims + sgroup - 1;
723                 double piece_w1 = piece * where[primaryDims];
724                 double &dest3 = (*mean)[px * maxAbilities + sdim];
725 #pragma omp atomic
726                 dest3 += piece_w1;
727
728                 double &dest4 = (*cov)[px * covEntries + triangleLoc0(sdim)];
729 #pragma omp atomic
730                 dest4 += piece_w1 * where[primaryDims];
731         }
732 }
733
734 static void
735 EAPinternalFast(omxExpectation *oo, std::vector<double> *mean, std::vector<double> *cov)
736 {
737         BA81Expect *state = (BA81Expect*) oo->argStruct;
738         if (state->verbose) mxLog("%s: EAP", oo->name);
739
740         int numUnique = state->numUnique;
741         int numSpecific = state->numSpecific;
742         int maxDims = state->maxDims;
743         int maxAbilities = state->maxAbilities;
744         int primaryDims = maxDims;
745         int covEntries = triangleLoc1(maxAbilities);
746
747         mean->assign(numUnique * maxAbilities, 0);
748         cov->assign(numUnique * covEntries, 0);
749
750         if (numSpecific == 0) {
751 #pragma omp parallel for num_threads(Global->numThreads)
752                 for (long qx=0; qx < state->totalQuadPoints; qx++) {
753                         const int thrId = omx_absolute_thread_num();
754                         int quad[maxDims];
755                         decodeLocation(qx, maxDims, state->quadGridSize, quad);
756                         double where[maxDims];
757                         pointToWhere(state, quad, where, maxDims);
758
759                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, quad);
760
761                         double area = state->priQarea[qx];
762                         for (int px=0; px < numUnique; px++) {
763                                 double tmp = lxk[px] * area;
764                                 accumulateScores(state, px, 0, tmp, where, primaryDims, covEntries, mean, cov);
765                         }
766                 }
767         } else {
768                 primaryDims -= 1;
769                 int sDim = primaryDims;
770                 long specificPoints = state->quadGridSize;
771
772 #pragma omp parallel for num_threads(Global->numThreads)
773                 for (long qx=0; qx < state->totalPrimaryPoints; qx++) {
774                         const int thrId = omx_absolute_thread_num();
775                         int quad[maxDims];
776                         decodeLocation(qx, primaryDims, state->quadGridSize, quad);
777
778                         cai2010(oo, thrId, FALSE, quad);
779                         double *allElxk = eBase(state, thrId);
780                         double *Eslxk = esBase(state, thrId);
781
782                         for (int sgroup=0; sgroup < numSpecific; sgroup++) {
783                                 for (long sx=0; sx < specificPoints; sx++) {
784                                         quad[sDim] = sx;
785                                         double where[maxDims];
786                                         pointToWhere(state, quad, where, maxDims);
787                                         double area = areaProduct(state, quad, sgroup);
788                                         double *lxk = ba81LikelihoodFast(oo, thrId, sgroup, quad);
789                                         for (int px=0; px < numUnique; px++) {
790                                                 double Ei = allElxk[px];
791                                                 double Eis = Eslxk[sgroup * numUnique + px];
792                                                 double tmp = ((Ei / Eis) * lxk[px] * area);
793                                                 accumulateScores(state, px, sgroup, tmp, where, primaryDims,
794                                                                  covEntries, mean, cov);
795                                         }
796                                 }
797                         }
798                 }
799         }
800
801         double *patternLik = state->patternLik;
802         for (int px=0; px < numUnique; px++) {
803                 double denom = patternLik[px];
804                 for (int ax=0; ax < maxAbilities; ax++) {
805                         (*mean)[px * maxAbilities + ax] /= denom;
806                 }
807                 for (int cx=0; cx < triangleLoc1(primaryDims); ++cx) {
808                         (*cov)[px * covEntries + cx] /= denom;
809                 }
810                 for (int sx=0; sx < numSpecific; sx++) {
811                         (*cov)[px * covEntries + triangleLoc0(primaryDims + sx)] /= denom;
812                 }
813                 int cx=0;
814                 for (int a1=0; a1 < primaryDims; ++a1) {
815                         for (int a2=0; a2 <= a1; ++a2) {
816                                 double ma1 = (*mean)[px * maxAbilities + a1];
817                                 double ma2 = (*mean)[px * maxAbilities + a2];
818                                 (*cov)[px * covEntries + cx] -= ma1 * ma2;
819                                 ++cx;
820                         }
821                 }
822                 for (int sx=0; sx < numSpecific; sx++) {
823                         int sdim = primaryDims + sx;
824                         double ma1 = (*mean)[px * maxAbilities + sdim];
825                         (*cov)[px * covEntries + triangleLoc0(sdim)] -= ma1 * ma1;
826                 }
827         }
828 }
829
830 static void recomputePatternLik(omxExpectation *oo)
831 {
832         BA81Expect *estate = (BA81Expect*) oo->argStruct;
833         if (estate->verbose) mxLog("%s: patternLik", oo->name);
834
835         int numUnique = estate->numUnique;
836         int numSpecific = estate->numSpecific;
837         int maxDims = estate->maxDims;
838         int primaryDims = maxDims;
839         double *patternLik = estate->patternLik;
840         OMXZERO(patternLik, numUnique);
841
842         if (numSpecific == 0) {
843 #pragma omp parallel for num_threads(Global->numThreads)
844                 for (long qx=0; qx < estate->totalQuadPoints; qx++) {
845                         const int thrId = omx_absolute_thread_num();
846                         int quad[maxDims];
847                         decodeLocation(qx, maxDims, estate->quadGridSize, quad);
848                         double where[maxDims];
849                         pointToWhere(estate, quad, where, maxDims);
850                         double area = estate->priQarea[qx];
851                         double *lxk = ba81LikelihoodFast(oo, thrId, 0, quad);
852
853                         for (int px=0; px < numUnique; px++) {
854                                 double tmp = (lxk[px] * area);
855 #pragma omp atomic
856                                 patternLik[px] += tmp;
857                         }
858                 }
859         } else {
860                 primaryDims -= 1;
861
862 #pragma omp parallel for num_threads(Global->numThreads)
863                 for (long qx=0; qx < estate->totalPrimaryPoints; qx++) {
864                         const int thrId = omx_absolute_thread_num();
865                         int quad[maxDims];
866                         decodeLocation(qx, primaryDims, estate->quadGridSize, quad);
867
868                         cai2010(oo, thrId, FALSE, quad);
869                         double *allElxk = eBase(estate, thrId);
870
871                         double priArea = estate->priQarea[qx];
872                         for (int px=0; px < numUnique; px++) {
873                                 double Ei = allElxk[px];
874                                 double tmp = (Ei * priArea);
875 #pragma omp atomic
876                                 patternLik[px] += tmp;
877                         }
878                 }
879         }
880 }
881
882 static void
883 ba81compute(omxExpectation *oo, const char *context)
884 {
885         BA81Expect *state = (BA81Expect *) oo->argStruct;
886
887         if (context) {
888                 if (strcmp(context, "EM")==0) {
889                         state->type = EXPECTATION_AUGMENTED;
890                 } else if (context[0] == 0) {
891                         state->type = EXPECTATION_OBSERVED;
892                 } else {
893                         omxRaiseErrorf(globalState, "Unknown context '%s'", context);
894                         return;
895                 }
896         }
897
898         omxRecompute(state->EitemParam);
899
900         bool itemClean = state->itemParamVersion == omxGetMatrixVersion(state->EitemParam);
901         bool latentClean = state->latentParamVersion == getLatentVersion(state);
902
903         if (state->verbose) {
904                 mxLog("%s: Qinit %d itemClean %d latentClean %d (1=clean)",
905                       oo->name, state->Qpoint.size() == 0, itemClean, latentClean);
906         }
907
908         if (state->Qpoint.size() == 0 || !latentClean) {
909                 ba81SetupQuadrature(oo, state->targetQpoints);
910         }
911         if (itemClean) {
912                 ba81buildLXKcache(oo);
913                 if (!latentClean) recomputePatternLik(oo);
914         } else {
915                 ba81Estep1(oo);
916         }
917
918         if (state->type == EXPECTATION_AUGMENTED) {
919                 ba81Expected(oo);
920         }
921
922         state->itemParamVersion = omxGetMatrixVersion(state->EitemParam);
923         state->latentParamVersion = getLatentVersion(state);
924 }
925
926 static void
927 copyScore(int rows, int maxAbilities, std::vector<double> &mean,
928           std::vector<double> &cov, const int rx, double *scores, const int dest)
929 {
930         for (int ax=0; ax < maxAbilities; ++ax) {
931                 scores[rows * ax + dest] = mean[maxAbilities * rx + ax];
932         }
933         for (int ax=0; ax < maxAbilities; ++ax) {
934                 scores[rows * (maxAbilities + ax) + dest] =
935                         sqrt(cov[triangleLoc1(maxAbilities) * rx + triangleLoc0(ax)]);
936         }
937         for (int ax=0; ax < triangleLoc1(maxAbilities); ++ax) {
938                 scores[rows * (2*maxAbilities + ax) + dest] =
939                         cov[triangleLoc1(maxAbilities) * rx + ax];
940         }
941 }
942
943 /**
944  * MAP is not affected by the number of items. EAP is. Likelihood can
945  * get concentrated in a single quadrature ordinate. For 3PL, response
946  * patterns can have a bimodal likelihood. This will confuse MAP and
947  * is a key advantage of EAP (Thissen & Orlando, 2001, p. 136).
948  *
949  * Thissen, D. & Orlando, M. (2001). IRT for items scored in two
950  * categories. In D. Thissen & H. Wainer (Eds.), \emph{Test scoring}
951  * (pp 73-140). Lawrence Erlbaum Associates, Inc.
952  */
953 static void
954 ba81PopulateAttributes(omxExpectation *oo, SEXP robj)
955 {
956         BA81Expect *state = (BA81Expect *) oo->argStruct;
957         int maxAbilities = state->maxAbilities;
958
959         SEXP Rmean, Rcov;
960         PROTECT(Rmean = allocVector(REALSXP, maxAbilities));
961         memcpy(REAL(Rmean), state->ElatentMean.data(), maxAbilities * sizeof(double));
962
963         PROTECT(Rcov = allocMatrix(REALSXP, maxAbilities, maxAbilities));
964         memcpy(REAL(Rcov), state->ElatentCov.data(), maxAbilities * maxAbilities * sizeof(double));
965
966         setAttrib(robj, install("empirical.mean"), Rmean);
967         setAttrib(robj, install("empirical.cov"), Rcov);
968
969         if (state->scores == SCORES_OMIT || state->type == EXPECTATION_UNINITIALIZED) return;
970
971         // TODO Wainer & Thissen. (1987). Estimating ability with the wrong
972         // model. Journal of Educational Statistics, 12, 339-368.
973
974         /*
975         int numQpoints = state->targetQpoints * 2;  // make configurable TODO
976
977         if (numQpoints < 1 + 2.0 * sqrt(state->itemSpec->cols)) {
978                 // Thissen & Orlando (2001, p. 136)
979                 warning("EAP requires at least 2*sqrt(items) quadrature points");
980         }
981
982         ba81SetupQuadrature(oo, numQpoints, 0);
983         ba81Estep1(oo);
984         */
985
986         std::vector<double> mean;
987         std::vector<double> cov;
988         EAPinternalFast(oo, &mean, &cov);
989
990         int numUnique = state->numUnique;
991         omxData *data = state->data;
992         int rows = state->scores == SCORES_FULL? data->rows : numUnique;
993         int cols = 2 * maxAbilities + triangleLoc1(maxAbilities);
994         SEXP Rscores;
995         PROTECT(Rscores = allocMatrix(REALSXP, rows, cols));
996         double *scores = REAL(Rscores);
997
998         const int SMALLBUF = 10;
999         char buf[SMALLBUF];
1000         SEXP names;
1001         PROTECT(names = allocVector(STRSXP, cols));
1002         for (int nx=0; nx < maxAbilities; ++nx) {
1003                 snprintf(buf, SMALLBUF, "s%d", nx+1);
1004                 SET_STRING_ELT(names, nx, mkChar(buf));
1005                 snprintf(buf, SMALLBUF, "se%d", nx+1);
1006                 SET_STRING_ELT(names, maxAbilities + nx, mkChar(buf));
1007         }
1008         for (int nx=0; nx < triangleLoc1(maxAbilities); ++nx) {
1009                 snprintf(buf, SMALLBUF, "cov%d", nx+1);
1010                 SET_STRING_ELT(names, maxAbilities*2 + nx, mkChar(buf));
1011         }
1012         SEXP dimnames;
1013         PROTECT(dimnames = allocVector(VECSXP, 2));
1014         SET_VECTOR_ELT(dimnames, 1, names);
1015         setAttrib(Rscores, R_DimNamesSymbol, dimnames);
1016
1017         if (state->scores == SCORES_FULL) {
1018 #pragma omp parallel for num_threads(Global->numThreads)
1019                 for (int rx=0; rx < numUnique; rx++) {
1020                         int dups = omxDataNumIdenticalRows(state->data, state->rowMap[rx]);
1021                         for (int dup=0; dup < dups; dup++) {
1022                                 int dest = omxDataIndex(data, state->rowMap[rx]+dup);
1023                                 copyScore(rows, maxAbilities, mean, cov, rx, scores, dest);
1024                         }
1025                 }
1026         } else {
1027 #pragma omp parallel for num_threads(Global->numThreads)
1028                 for (int rx=0; rx < numUnique; rx++) {
1029                         copyScore(rows, maxAbilities, mean, cov, rx, scores, rx);
1030                 }
1031         }
1032
1033         setAttrib(robj, install("scores.out"), Rscores);
1034 }
1035
1036 static void ba81Destroy(omxExpectation *oo) {
1037         if(OMX_DEBUG) {
1038                 mxLog("Freeing %s function.", oo->name);
1039         }
1040         BA81Expect *state = (BA81Expect *) oo->argStruct;
1041         omxFreeAllMatrixData(state->EitemParam);
1042         omxFreeAllMatrixData(state->design);
1043         omxFreeAllMatrixData(state->latentMeanOut);
1044         omxFreeAllMatrixData(state->latentCovOut);
1045         omxFreeAllMatrixData(state->customPrior);
1046         omxFreeAllMatrixData(state->itemParam);
1047         Free(state->numIdentical);
1048         Free(state->rowMap);
1049         Free(state->patternLik);
1050         Free(state->lxk);
1051         Free(state->Eslxk);
1052         Free(state->allElxk);
1053         Free(state->Sgroup);
1054         Free(state->expected);
1055         delete state;
1056 }
1057
1058 void getMatrixDims(SEXP r_theta, int *rows, int *cols)
1059 {
1060     SEXP matrixDims;
1061     PROTECT(matrixDims = getAttrib(r_theta, R_DimSymbol));
1062     int *dimList = INTEGER(matrixDims);
1063     *rows = dimList[0];
1064     *cols = dimList[1];
1065     UNPROTECT(1);
1066 }
1067
1068 static void ignoreSetVarGroup(omxExpectation*, FreeVarGroup *)
1069 {}
1070
1071 void omxInitExpectationBA81(omxExpectation* oo) {
1072         omxState* currentState = oo->currentState;      
1073         SEXP rObj = oo->rObj;
1074         SEXP tmp;
1075         
1076         if(OMX_DEBUG) {
1077                 mxLog("Initializing %s.", oo->name);
1078         }
1079         if (!rpf_model) {
1080                 if (0) {
1081                         const int wantVersion = 3;
1082                         int version;
1083                         get_librpf_t get_librpf = (get_librpf_t) R_GetCCallable("rpf", "get_librpf_model_GPL");
1084                         (*get_librpf)(&version, &rpf_numModels, &rpf_model);
1085                         if (version < wantVersion) error("librpf binary API %d installed, at least %d is required",
1086                                                          version, wantVersion);
1087                 } else {
1088                         rpf_numModels = librpf_numModels;
1089                         rpf_model = librpf_model;
1090                 }
1091         }
1092         
1093         BA81Expect *state = new BA81Expect;
1094         state->numSpecific = 0;
1095         state->numIdentical = NULL;
1096         state->rowMap = NULL;
1097         state->design = NULL;
1098         state->lxk = NULL;
1099         state->patternLik = NULL;
1100         state->Eslxk = NULL;
1101         state->allElxk = NULL;
1102         state->expected = NULL;
1103         state->type = EXPECTATION_UNINITIALIZED;
1104         state->scores = SCORES_OMIT;
1105         state->itemParam = NULL;
1106         state->customPrior = NULL;
1107         state->itemParamVersion = 0;
1108         state->latentParamVersion = 0;
1109         oo->argStruct = (void*) state;
1110
1111         PROTECT(tmp = GET_SLOT(rObj, install("data")));
1112         state->data = omxDataLookupFromState(tmp, currentState);
1113
1114         if (strcmp(omxDataType(state->data), "raw") != 0) {
1115                 omxRaiseErrorf(currentState, "%s unable to handle data type %s", oo->name, omxDataType(state->data));
1116                 return;
1117         }
1118
1119         PROTECT(tmp = GET_SLOT(rObj, install("ItemSpec")));
1120         for (int sx=0; sx < length(tmp); ++sx) {
1121                 SEXP model = VECTOR_ELT(tmp, sx);
1122                 if (!OBJECT(model)) {
1123                         error("Item models must inherit rpf.base");
1124                 }
1125                 SEXP spec;
1126                 PROTECT(spec = GET_SLOT(model, install("spec")));
1127                 state->itemSpec.push_back(REAL(spec));
1128         }
1129
1130         PROTECT(tmp = GET_SLOT(rObj, install("design")));
1131         if (!isNull(tmp)) {
1132                 // better to demand integers and not coerce to real TODO
1133                 state->design = omxNewMatrixFromRPrimitive(tmp, globalState, FALSE, 0);
1134         }
1135
1136         state->latentMeanOut = omxNewMatrixFromSlot(rObj, currentState, "mean");
1137         if (!state->latentMeanOut) error("Failed to retrieve mean matrix");
1138         state->latentCovOut  = omxNewMatrixFromSlot(rObj, currentState, "cov");
1139         if (!state->latentCovOut) error("Failed to retrieve cov matrix");
1140
1141         state->EitemParam =
1142                 omxNewMatrixFromSlot(rObj, currentState, "EItemParam");
1143         if (!state->EitemParam) error("Must supply EItemParam");
1144
1145         state->itemParam =
1146                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
1147
1148         if (state->EitemParam->rows != state->itemParam->rows ||
1149             state->EitemParam->cols != state->itemParam->cols) {
1150                 error("ItemParam and EItemParam must be of the same dimension");
1151         }
1152
1153         oo->computeFun = ba81compute;
1154         oo->setVarGroup = ignoreSetVarGroup;
1155         oo->destructFun = ba81Destroy;
1156         oo->populateAttrFun = ba81PopulateAttributes;
1157         
1158         // TODO: Exactly identical rows do not contribute any information.
1159         // The sorting algorithm ought to remove them so we don't waste RAM.
1160         // The following summary stats would be cheaper to calculate too.
1161
1162         int numUnique = 0;
1163         omxData *data = state->data;
1164         if (omxDataNumFactor(data) != data->cols) {
1165                 // verify they are ordered factors TODO
1166                 omxRaiseErrorf(currentState, "%s: all columns must be factors", oo->name);
1167                 return;
1168         }
1169
1170         for (int rx=0; rx < data->rows;) {
1171                 rx += omxDataNumIdenticalRows(state->data, rx);
1172                 ++numUnique;
1173         }
1174         state->numUnique = numUnique;
1175
1176         state->rowMap = Realloc(NULL, numUnique, int);
1177         state->numIdentical = Realloc(NULL, numUnique, int);
1178
1179         state->customPrior =
1180                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
1181         
1182         int numItems = state->EitemParam->cols;
1183         if (data->cols != numItems) {
1184                 error("Data has %d columns for %d items", data->cols, numItems);
1185         }
1186
1187         for (int rx=0, ux=0; rx < data->rows; ux++) {
1188                 if (rx == 0) {
1189                         // all NA rows will sort to the top
1190                         int na=0;
1191                         for (int ix=0; ix < numItems; ix++) {
1192                                 if (omxIntDataElement(data, 0, ix) == NA_INTEGER) { ++na; }
1193                         }
1194                         if (na == numItems) {
1195                                 omxRaiseErrorf(currentState, "Remove rows with all NAs");
1196                                 return;
1197                         }
1198                 }
1199                 int dups = omxDataNumIdenticalRows(state->data, rx);
1200                 state->numIdentical[ux] = dups;
1201                 state->rowMap[ux] = rx;
1202                 rx += dups;
1203         }
1204
1205         int numThreads = Global->numThreads;
1206
1207         int maxSpec = 0;
1208         int maxParam = 0;
1209         state->maxDims = 0;
1210         state->maxOutcomes = 0;
1211
1212         int totalOutcomes = 0;
1213         for (int cx = 0; cx < data->cols; cx++) {
1214                 const double *spec = state->itemSpec[cx];
1215                 int id = spec[RPF_ISpecID];
1216                 int dims = spec[RPF_ISpecDims];
1217                 if (state->maxDims < dims)
1218                         state->maxDims = dims;
1219
1220                 int no = spec[RPF_ISpecOutcomes];
1221                 totalOutcomes += no;
1222                 if (state->maxOutcomes < no)
1223                         state->maxOutcomes = no;
1224
1225                 // TODO this summary stat should be available from omxData
1226                 int dataMax=0;
1227                 for (int rx=0; rx < data->rows; rx++) {
1228                         int pick = omxIntDataElementUnsafe(data, rx, cx);
1229                         if (dataMax < pick)
1230                                 dataMax = pick;
1231                 }
1232                 if (dataMax > no) {
1233                         error("Data for item %d has %d outcomes, not %d", cx+1, dataMax, no);
1234                 } else if (dataMax < no) {
1235                         warning("Data for item %d has only %d outcomes, not %d", cx+1, dataMax, no);
1236                         // promote to error?
1237                         // should complain if an outcome is not represented in the data TODO
1238                 }
1239
1240                 int numSpec = (*rpf_model[id].numSpec)(spec);
1241                 if (maxSpec < numSpec)
1242                         maxSpec = numSpec;
1243
1244                 int numParam = (*rpf_model[id].numParam)(spec);
1245                 if (maxParam < numParam)
1246                         maxParam = numParam;
1247         }
1248
1249         state->totalOutcomes = totalOutcomes;
1250
1251         if (int(state->itemSpec.size()) != data->cols) {
1252                 omxRaiseErrorf(currentState, "ItemSpec must contain %d item model specifications",
1253                                data->cols);
1254                 return;
1255         }
1256         if (state->EitemParam->rows != maxParam) {
1257                 omxRaiseErrorf(currentState, "ItemParam should have %d rows", maxParam);
1258                 return;
1259         }
1260
1261         std::vector<int> &itemOutcomes = state->itemOutcomes;
1262         itemOutcomes.resize(numItems);
1263         for (int ix=0; ix < numItems; ix++) {
1264                 const double *spec = state->itemSpec[ix];
1265                 itemOutcomes[ix] = spec[RPF_ISpecOutcomes];
1266         }
1267
1268         if (state->design == NULL) {
1269                 state->maxAbilities = state->maxDims;
1270                 state->design = omxInitTemporaryMatrix(NULL, state->maxDims, numItems,
1271                                        TRUE, currentState);
1272                 for (int ix=0; ix < numItems; ix++) {
1273                         const double *spec = state->itemSpec[ix];
1274                         int dims = spec[RPF_ISpecDims];
1275                         for (int dx=0; dx < state->maxDims; dx++) {
1276                                 omxSetMatrixElement(state->design, dx, ix, dx < dims? (double)dx+1 : nan(""));
1277                         }
1278                 }
1279         } else {
1280                 omxMatrix *design = state->design;
1281                 if (design->cols != numItems ||
1282                     design->rows != state->maxDims) {
1283                         omxRaiseErrorf(currentState, "Design matrix should have %d rows and %d columns",
1284                                        state->maxDims, numItems);
1285                         return;
1286                 }
1287
1288                 state->maxAbilities = 0;
1289                 for (int ix=0; ix < design->rows * design->cols; ix++) {
1290                         double got = design->data[ix];
1291                         if (!R_FINITE(got)) continue;
1292                         if (round(got) != (int)got) error("Design matrix can only contain integers"); // TODO better way?
1293                         if (state->maxAbilities < got)
1294                                 state->maxAbilities = got;
1295                 }
1296                 for (int ix=0; ix < design->cols; ix++) {
1297                         const double *idesign = omxMatrixColumn(design, ix);
1298                         int ddim = 0;
1299                         for (int rx=0; rx < design->rows; rx++) {
1300                                 if (isfinite(idesign[rx])) ddim += 1;
1301                         }
1302                         const double *spec = state->itemSpec[ix];
1303                         int dims = spec[RPF_ISpecDims];
1304                         if (ddim > dims) error("Item %d has %d dims but design assigns %d", ix, dims, ddim);
1305                 }
1306         }
1307         if (state->maxAbilities <= state->maxDims) {
1308                 state->Sgroup = Calloc(numItems, int);
1309         } else {
1310                 // Not sure if this is correct, revisit TODO
1311                 int Sgroup0 = -1;
1312                 state->Sgroup = Realloc(NULL, numItems, int);
1313                 for (int dx=0; dx < state->maxDims; dx++) {
1314                         for (int ix=0; ix < numItems; ix++) {
1315                                 int ability = omxMatrixElement(state->design, dx, ix);
1316                                 if (dx < state->maxDims - 1) {
1317                                         if (Sgroup0 <= ability)
1318                                                 Sgroup0 = ability+1;
1319                                         continue;
1320                                 }
1321                                 int ss=-1;
1322                                 if (ability >= Sgroup0) {
1323                                         if (ss == -1) {
1324                                                 ss = ability;
1325                                         } else {
1326                                                 omxRaiseErrorf(currentState, "Item %d cannot belong to more than "
1327                                                                "1 specific dimension (both %d and %d)",
1328                                                                ix, ss, ability);
1329                                                 return;
1330                                         }
1331                                 }
1332                                 if (ss == -1) ss = Sgroup0;
1333                                 state->Sgroup[ix] = ss - Sgroup0;
1334                         }
1335                 }
1336                 state->numSpecific = state->maxAbilities - state->maxDims + 1;
1337                 state->allElxk = Realloc(NULL, numUnique * numThreads, double);
1338                 state->Eslxk = Realloc(NULL, numUnique * state->numSpecific * numThreads, double);
1339         }
1340
1341         if (state->latentMeanOut->rows * state->latentMeanOut->cols != state->maxAbilities) {
1342                 error("The mean matrix '%s' must be 1x%d or %dx1", state->latentMeanOut->name,
1343                       state->maxAbilities, state->maxAbilities);
1344         }
1345         if (state->latentCovOut->rows != state->maxAbilities ||
1346             state->latentCovOut->cols != state->maxAbilities) {
1347                 error("The cov matrix '%s' must be %dx%d",
1348                       state->latentCovOut->name, state->maxAbilities, state->maxAbilities);
1349         }
1350
1351         PROTECT(tmp = GET_SLOT(rObj, install("verbose")));
1352         state->verbose = asLogical(tmp);
1353
1354         PROTECT(tmp = GET_SLOT(rObj, install("cache")));
1355         state->cacheLXK = asLogical(tmp);
1356         state->LXKcached = FALSE;
1357
1358         PROTECT(tmp = GET_SLOT(rObj, install("qpoints")));
1359         state->targetQpoints = asReal(tmp);
1360
1361         PROTECT(tmp = GET_SLOT(rObj, install("qwidth")));
1362         state->Qwidth = asReal(tmp);
1363
1364         PROTECT(tmp = GET_SLOT(rObj, install("scores")));
1365         const char *score_option = CHAR(asChar(tmp));
1366         if (strcmp(score_option, "omit")==0) state->scores = SCORES_OMIT;
1367         if (strcmp(score_option, "unique")==0) state->scores = SCORES_UNIQUE;
1368         if (strcmp(score_option, "full")==0) state->scores = SCORES_FULL;
1369
1370         state->ElatentMean.resize(state->maxAbilities);
1371         state->ElatentCov.resize(state->maxAbilities * state->maxAbilities);
1372
1373         // verify data bounded between 1 and numOutcomes TODO
1374         // hm, looks like something could be added to omxData for column summary stats?
1375 }