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