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