Factor out density multiplication
[openmx:openmx.git] / src / omxFitFunctionBA81.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 "omxFitFunction.h"
19 #include "omxExpectationBA81.h"
20 #include "omxOpenmpWrap.h"
21 #include "libifa-rpf.h"
22
23 struct BA81FitState {
24
25         bool haveLatentMap;
26         std::vector<int> latentMap;
27
28         bool haveItemMap;
29         int itemDerivPadSize;     // maxParam + maxParam*(1+maxParam)/2
30         std::vector<int> paramMap;            // itemParam->cols * itemDerivPadSize -> index of free parameter
31         std::vector<size_t> paramLocations;   // itemParam->cols * itemDerivPadSize -> # of locations
32
33         omxMatrix *cholCov;
34         int choleskyError;
35         double *tmpLatentMean;    // maxDims
36         double *tmpLatentCov;     // maxDims * maxDims ; only lower triangle is used
37         omxMatrix *icov;          // inverse covariance matrix
38
39         std::vector< FreeVarGroup* > varGroups;
40         size_t numItemParam;
41
42         BA81FitState();
43         ~BA81FitState();
44 };
45
46 BA81FitState::BA81FitState()
47 {
48         tmpLatentMean = NULL;
49         tmpLatentCov = NULL;
50         haveItemMap = false;
51         haveLatentMap = false;
52 }
53
54 static void buildLatentParamMap(omxFitFunction* oo, FitContext *fc)
55 {
56         FreeVarGroup *fvg = fc->varGroup;
57         BA81FitState *state = (BA81FitState *) oo->argStruct;
58         std::vector<int> &latentMap = state->latentMap;
59         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
60         int meanNum = estate->latentMeanOut->matrixNumber;
61         int covNum = estate->latentCovOut->matrixNumber;
62         int itemNum = estate->itemParam->matrixNumber;
63         int maxAbilities = estate->maxAbilities;
64         int numLatents = maxAbilities + triangleLoc1(maxAbilities);
65
66         latentMap.assign(numLatents, -1);
67
68         int numParam = int(fvg->vars.size());
69         for (int px=0; px < numParam; px++) {
70                 omxFreeVar *fv = fvg->vars[px];
71                 for (size_t lx=0; lx < fv->locations.size(); lx++) {
72                         omxFreeVarLocation *loc = &fv->locations[lx];
73                         int matNum = ~loc->matrix;
74                         if (matNum == meanNum) {
75                                 latentMap[loc->row + loc->col] = px;
76                         } else if (matNum == covNum) {
77                                 int a1 = loc->row;
78                                 int a2 = loc->col;
79                                 if (a1 < a2) std::swap(a1, a2);
80                                 int cell = maxAbilities + triangleLoc1(a1) + a2;
81                                 if (latentMap[cell] == -1)
82                                         latentMap[cell] = px;
83                                 else if (latentMap[cell] != px) {
84                                         // doesn't work for multigroup constraints TODO
85                                         error("In covariance matrix, %s and %s must be constrained equal to preserve symmetry",
86                                               fvg->vars[latentMap[cell]]->name, fv->name);
87                                 }
88                                 if (a1 == a2 && fv->lbound == NEG_INF) {
89                                         fv->lbound = 1e-6;  // variance must be positive
90                                         if (fc->est[px] < fv->lbound) {
91                                                 error("Starting value for variance %s is negative", fv->name);
92                                         }
93                                 }
94                         } else if (matNum == itemNum) {
95                                 omxRaiseErrorf(globalState, "The fitfunction free.set should consist of "
96                                                "latent distribution parameters, excluding item parameters");
97                         }
98                 }
99         }
100         state->haveLatentMap = TRUE;
101 }
102
103 static void buildItemParamMap(omxFitFunction* oo, FitContext *fc)
104 {
105         FreeVarGroup *fvg = fc->varGroup;
106         BA81FitState *state = (BA81FitState *) oo->argStruct;
107         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
108         omxMatrix *itemParam = estate->itemParam;
109         int size = itemParam->cols * state->itemDerivPadSize;
110         state->paramMap.assign(size, -1);  // matrix location to free param index
111         state->paramLocations.assign(size, 0);
112
113         size_t numFreeParams = state->numItemParam = fvg->vars.size();
114
115         for (size_t px=0; px < numFreeParams; px++) {
116                 omxFreeVar *fv = fvg->vars[px];
117                 for (size_t lx=0; lx < fv->locations.size(); lx++) {
118                         omxFreeVarLocation *loc = &fv->locations[lx];
119                         int matNum = ~loc->matrix;
120                         if (matNum == itemParam->matrixNumber) {
121                                 int at = loc->col * state->itemDerivPadSize + loc->row;
122                                 state->paramMap[at] = px;
123                                 state->paramLocations[at] = fv->locations.size();
124
125                                 const double *spec = estate->itemSpec[loc->col];
126                                 int id = spec[RPF_ISpecID];
127                                 double upper, lower;
128                                 (*rpf_model[id].paramBound)(spec, loc->row, &upper, &lower);
129                                 if (fv->lbound == NEG_INF && isfinite(lower)) {
130                                         fv->lbound = lower;
131                                         if (fc->est[px] < fv->lbound) {
132                                                 error("Starting value %s %f less than lower bound %f",
133                                                       fv->name, fc->est[px], lower);
134                                         }
135                                 }
136                                 if (fv->ubound == INF && isfinite(upper)) {
137                                         fv->ubound = upper;
138                                         if (fc->est[px] > fv->ubound) {
139                                                 error("Starting value %s %f greater than upper bound %f",
140                                                       fv->name, fc->est[px], upper);
141                                         }
142                                 }
143                         }
144                 }
145         }
146
147         for (int cx=0; cx < itemParam->cols; ++cx) {
148                 const double *spec = estate->itemSpec[cx];
149                 int id = spec[RPF_ISpecID];
150                 int numParam = (*rpf_model[id].numParam)(spec);
151
152                 for (int p1=0; p1 < numParam; p1++) {
153                         int at1 = state->paramMap[cx * state->itemDerivPadSize + p1];
154                         if (at1 < 0) continue;
155
156                         for (int p2=0; p2 <= p1; p2++) {
157                                 int at2 = state->paramMap[cx * state->itemDerivPadSize + p2];
158                                 if (at2 < 0) continue;
159
160                                 if (at1 < at2) std::swap(at1, at2);  // lower triangle
161
162                                 //mxLog("Item %d param(%d,%d) -> H[%d,%d]", cx, p1, p2, at1, at2);
163                                 int at = cx * state->itemDerivPadSize + numParam + triangleLoc1(p1) + p2;
164                                 state->paramMap[at] = numFreeParams + at1 * numFreeParams + at2;
165                         }
166                 }
167         }
168
169         state->haveItemMap = TRUE;
170         //pia(state->paramMap.data(), state->itemDerivPadSize, itemParam->cols);
171 }
172
173 OMXINLINE static double
174 ba81Fit1Ordinate(omxFitFunction* oo, const long qx, const int *quad,
175                  const double *weight, int want, double *myDeriv)
176 {
177         BA81FitState *state = (BA81FitState*) oo->argStruct;
178         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
179         omxMatrix *itemParam = estate->itemParam;
180         int numItems = itemParam->cols;
181         int maxDims = estate->maxDims;
182         int do_fit = want & FF_COMPUTE_FIT;
183         int do_deriv = want & (FF_COMPUTE_GRADIENT | FF_COMPUTE_HESSIAN);
184
185         double where[maxDims];
186         pointToWhere(estate, quad, where, maxDims);
187
188         double *outcomeProb = NULL;
189         if (do_fit) {
190                 outcomeProb = Realloc(NULL, estate->totalOutcomes, double); // avoid malloc/free? TODO
191                 computeRPF(estate, itemParam, quad, TRUE, outcomeProb);
192         }
193
194         double thr_ll = 0;
195         const double *oProb = outcomeProb;
196         for (int ix=0; ix < numItems; ix++) {
197                 const double *spec = estate->itemSpec[ix];
198                 int id = spec[RPF_ISpecID];
199                 int iOutcomes = estate->itemOutcomes[ix];
200
201                 if (do_fit) {
202                         for (int ox=0; ox < iOutcomes; ox++) {
203                                 double got = weight[ox] * oProb[ox];
204                                 thr_ll += got;
205                         }
206                 }
207
208                 if (do_deriv) {
209                         double *iparam = omxMatrixColumn(itemParam, ix);
210                         double *pad = myDeriv + ix * state->itemDerivPadSize;
211                         (*rpf_model[id].dLL1)(spec, iparam, where, weight, pad);
212                 }
213                 oProb += iOutcomes;
214                 weight += iOutcomes;
215         }
216
217         Free(outcomeProb);
218
219         return thr_ll;
220 }
221
222 static double
223 ba81ComputeMFit1(omxFitFunction* oo, int want, double *gradient, double *hessian)
224 {
225         BA81FitState *state = (BA81FitState*) oo->argStruct;
226         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
227         if (estate->verbose) mxLog("%s: fit-%d", oo->matrix->name, want);
228
229         omxMatrix *customPrior = estate->customPrior;
230         omxMatrix *itemParam = estate->itemParam;
231         std::vector<const double*> &itemSpec = estate->itemSpec;
232         int maxDims = estate->maxDims;
233         const int totalOutcomes = estate->totalOutcomes;
234
235         double *thrDeriv = Calloc(itemParam->cols * state->itemDerivPadSize * Global->numThreads, double);
236
237         double ll = 0;
238         if (customPrior) {
239                 omxRecompute(customPrior);
240                 ll = customPrior->data[0];
241                 // need deriv adjustment TODO
242         }
243
244         if (!isfinite(ll)) {
245                 omxPrint(itemParam, "item param");
246                 error("Bayesian prior returned %g; do you need to add a lbound/ubound?", ll);
247         }
248
249 #pragma omp parallel for num_threads(Global->numThreads)
250         for (long qx=0; qx < estate->totalQuadPoints; qx++) {
251                 int quad[maxDims];
252                 decodeLocation(qx, maxDims, estate->quadGridSize, quad);
253                 double *weight = estate->expected + qx * totalOutcomes;
254                 double *myDeriv = thrDeriv + itemParam->cols * state->itemDerivPadSize * omx_absolute_thread_num();
255                 double thr_ll = ba81Fit1Ordinate(oo, qx, quad, weight, want, myDeriv);
256                 
257 #pragma omp atomic
258                 ll += thr_ll;
259         }
260
261         if (gradient) {
262                 double *deriv0 = thrDeriv;
263
264                 int perThread = itemParam->cols * state->itemDerivPadSize;
265                 for (int th=1; th < Global->numThreads; th++) {
266                         double *thrD = thrDeriv + th * perThread;
267                         for (int ox=0; ox < perThread; ox++) deriv0[ox] += thrD[ox];
268                 }
269
270                 int numItems = itemParam->cols;
271                 for (int ix=0; ix < numItems; ix++) {
272                         const double *spec = itemSpec[ix];
273                         int id = spec[RPF_ISpecID];
274                         double *iparam = omxMatrixColumn(itemParam, ix);
275                         double *pad = deriv0 + ix * state->itemDerivPadSize;
276                         (*rpf_model[id].dLL2)(spec, iparam, pad);
277                 }
278
279                 int numFreeParams = int(state->numItemParam);
280                 int numParams = itemParam->cols * state->itemDerivPadSize;
281                 for (int ox=0; ox < numParams; ox++) {
282                         int to = state->paramMap[ox];
283                         if (to == -1) continue;
284
285                         // Need to check because this can happen if
286                         // lbounds/ubounds are not set appropriately.
287                         if (0 && !isfinite(deriv0[ox])) {
288                                 int item = ox / itemParam->rows;
289                                 mxLog("item parameters:\n");
290                                 const double *spec = itemSpec[item];
291                                 int id = spec[RPF_ISpecID];
292                                 int numParam = (*rpf_model[id].numParam)(spec);
293                                 double *iparam = omxMatrixColumn(itemParam, item);
294                                 pda(iparam, numParam, 1);
295                                 // Perhaps bounds can be pulled in from librpf? TODO
296                                 error("Deriv %d for item %d is %f; are you missing a lbound/ubound?",
297                                       ox, item, deriv0[ox]);
298                         }
299
300                         if (to < numFreeParams) {
301                                 gradient[to] -= deriv0[ox];
302                         } else {
303                                 int Hto = to - numFreeParams;
304                                 hessian[Hto] -= deriv0[ox];
305                         }
306                 }
307         }
308
309         Free(thrDeriv);
310
311         return -ll;
312 }
313
314 static int
315 moveLatentDistribution(omxFitFunction *oo, FitContext *fc,
316                        double *ElatentMean, double *ElatentCov)
317 {
318         BA81FitState *state = (BA81FitState*) oo->argStruct;
319         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
320         std::vector<const double*> &itemSpec = estate->itemSpec;
321         omxMatrix *itemParam = estate->itemParam;
322         omxMatrix *design = estate->design;
323         double *tmpLatentMean = state->tmpLatentMean;
324         double *tmpLatentCov = state->tmpLatentCov;
325         int maxDims = estate->maxDims;
326         int maxAbilities = estate->maxAbilities;
327         int moveCount = 0;
328
329         int numItems = itemParam->cols;
330         for (int ix=0; ix < numItems; ix++) {
331                 const double *spec = itemSpec[ix];
332                 int id = spec[RPF_ISpecID];
333                 const double *rawDesign = omxMatrixColumn(design, ix);
334                 int idesign[design->rows];
335                 int idx = 0;
336                 for (int dx=0; dx < design->rows; dx++) {
337                         if (isfinite(rawDesign[dx])) {
338                                 idesign[idx++] = rawDesign[dx]-1;
339                         } else {
340                                 idesign[idx++] = -1;
341                         }
342                 }
343                 for (int d1=0; d1 < idx; d1++) {
344                         if (idesign[d1] == -1) {
345                                 tmpLatentMean[d1] = 0;
346                         } else {
347                                 tmpLatentMean[d1] = ElatentMean[idesign[d1]];
348                         }
349                         for (int d2=0; d2 <= d1; d2++) {
350                                 int cell = idesign[d2] * maxAbilities + idesign[d1];
351                                 if (idesign[d1] == -1 || idesign[d2] == -1) {
352                                         tmpLatentCov[d2 * maxDims + d1] = d1==d2? 1 : 0;
353                                 } else {
354                                         tmpLatentCov[d2 * maxDims + d1] = ElatentCov[cell];
355                                 }
356                         }
357                 }
358                 if (1) {  // ease debugging, make optional TODO
359                         for (int d1=idx; d1 < maxDims; d1++) tmpLatentMean[d1] = nan("");
360                         for (int d1=0; d1 < maxDims; d1++) {
361                                 for (int d2=0; d2 < maxDims; d2++) {
362                                         if (d1 < idx && d2 < idx) continue;
363                                         tmpLatentCov[d2 * maxDims + d1] = nan("");
364                                 }
365                         }
366                 }
367                 double *iparam = omxMatrixColumn(itemParam, ix);
368                 int *mask = state->paramMap.data() + state->itemDerivPadSize * ix;
369                 rpf_model[id].rescale(spec, iparam, mask, tmpLatentMean, tmpLatentCov);
370         }
371
372         int numFreeParams = int(fc->varGroup->vars.size());
373         for (int rx=0; rx < itemParam->rows; rx++) {
374                 for (int cx=0; cx < itemParam->cols; cx++) {
375                         int px = cx * state->itemDerivPadSize + rx;
376                         int vx = state->paramMap[px];
377                         if (vx >= 0 && vx < numFreeParams && state->paramLocations[px] == 1) {
378                                 fc->est[vx] = omxMatrixElement(itemParam, rx, cx);
379                                 ++moveCount;
380                         }
381                 }
382         }
383         return moveCount;
384 }
385
386 static void
387 schilling_bock_2005_rescale(omxFitFunction *oo, FitContext *fc)
388 {
389         BA81FitState *state = (BA81FitState*) oo->argStruct;
390         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
391         omxMatrix *cholCov = state->cholCov;
392         int maxAbilities = estate->maxAbilities;
393
394         //pda(ElatentMean, maxAbilities, 1);
395         //pda(estate->ElatentCov.data(), maxAbilities, maxAbilities);
396         //omxPrint(design, "design");
397
398         memcpy(cholCov->data, estate->ElatentCov.data(), sizeof(double) * maxAbilities * maxAbilities);
399
400         const char triangle = 'L';
401         F77_CALL(dpotrf)(&triangle, &maxAbilities, cholCov->data, &maxAbilities, &state->choleskyError);
402         if (state->choleskyError != 0) {
403                 warning("Cholesky failed with %d; rescaling disabled", state->choleskyError); // make error TODO?
404                 return;
405         }
406
407         //pda(cholCov->data, maxAbilities, maxAbilities);
408
409         int moveCount = moveLatentDistribution(oo, fc, estate->ElatentMean.data(), cholCov->data);
410         if (estate->verbose) mxLog("%s: schilling-bock (%d param)", oo->matrix->name, moveCount);
411 }
412
413 void ba81SetFreeVarGroup(omxFitFunction *oo, FreeVarGroup *fvg)
414 {}
415
416 // can use same reorganization to avoid the gram product of where for every pattern TODO
417 static void mapLatentDeriv(BA81FitState *state, BA81Expect *estate, int sgroup, double piece,
418                            const std::vector<double> &derivCoef,
419                            double *derivOut)
420 {
421         int maxAbilities = estate->maxAbilities;
422         int maxDims = estate->maxDims;
423         int pmax = maxDims;
424         if (estate->numSpecific) pmax -= 1;
425
426         if (sgroup == 0) {
427                 int cx = 0;
428                 for (int d1=0; d1 < pmax; ++d1) {
429                         double amt1 = piece * derivCoef[d1];
430 #pragma omp atomic
431                         derivOut[d1] += amt1;
432                         for (int d2=0; d2 <= d1; ++d2) {
433                                 int to = maxAbilities + cx;
434                                 double amt2 = piece * derivCoef[maxDims + cx];
435 #pragma omp atomic
436                                 derivOut[to] += amt2;
437                                 ++cx;
438                         }
439                 }
440         }
441
442         if (estate->numSpecific) {
443                 int sdim = pmax + sgroup;
444                 double amt3 = piece * derivCoef[pmax];
445 #pragma omp atomic
446                 derivOut[sdim] += amt3;
447
448                 double amt4 = piece * derivCoef[maxDims + triangleLoc0(pmax)];
449                 int to = maxAbilities + triangleLoc0(sdim);
450 #pragma omp atomic
451                 derivOut[to] += amt4;
452         }
453 }
454
455 static double *reduceForSpecific(omxMatrix *mat, int maxDims, int sgroup)
456 {
457         double *out = Calloc(maxDims * maxDims, double);
458         for (int d1=0; d1 < maxDims-1; ++d1) {
459                 int cell = d1 * maxDims;
460                 for (int d2=0; d2 < maxDims-1; ++d2) {
461                         out[cell + d2] = omxMatrixElement(mat, d1, d2);
462                 }
463         }
464         int sloc = maxDims-1 + sgroup;
465         out[maxDims*maxDims - 1] = omxMatrixElement(mat, sloc, sloc);
466         return out;
467 }
468
469 static void calcDerivCoef(BA81FitState *state, BA81Expect *estate,
470                           double *where, int sgroup, std::vector<double> *derivCoef)
471 {
472         omxMatrix *mean = estate->latentMeanOut;
473         omxMatrix *cov = estate->latentCovOut;
474         omxMatrix *icov = state->icov;
475         double *covData = cov->data;
476         double *icovData = icov->data;
477         int maxDims = estate->maxDims;
478         const char R='R';
479         const char L='L';
480         const char U='U';
481         const double alpha = 1;
482         const double beta = 0;
483         const int one = 1;
484
485         double *scov = NULL;
486         double *sicov = NULL;
487         if (estate->numSpecific) {
488                 scov = reduceForSpecific(cov, maxDims, sgroup);
489                 covData = scov;
490
491                 sicov = reduceForSpecific(icov, maxDims, sgroup);
492                 icovData = sicov;
493         }
494
495         std::vector<double> whereDiff(maxDims);
496         std::vector<double> whereGram(triangleLoc1(maxDims));
497         for (int d1=0; d1 < maxDims; ++d1) {
498                 whereDiff[d1] = where[d1] - omxVectorElement(mean, d1);
499         }
500         gramProduct(whereDiff.data(), whereDiff.size(), whereGram.data());
501
502         F77_CALL(dsymv)(&U, &maxDims, &alpha, icovData, &maxDims, whereDiff.data(), &one,
503                         &beta, derivCoef->data(), &one);
504
505         std::vector<double> covGrad1(maxDims * maxDims);
506         std::vector<double> covGrad2(maxDims * maxDims);
507
508         int cx=0;
509         for (int d1=0; d1 < maxDims; ++d1) {
510                 for (int d2=0; d2 <= d1; ++d2) {
511                         covGrad1[d2 * maxDims + d1] = covData[d2 * maxDims + d1] - whereGram[cx];
512                         ++cx;
513                 }
514         }
515
516         F77_CALL(dsymm)(&R, &L, &maxDims, &maxDims, &alpha, covGrad1.data(), &maxDims, icovData,
517                         &maxDims, &beta, covGrad2.data(), &maxDims);
518         F77_CALL(dsymm)(&R, &L, &maxDims, &maxDims, &alpha, icovData, &maxDims, covGrad2.data(),
519                         &maxDims, &beta, covGrad1.data(), &maxDims);
520
521         for (int d1=0; d1 < maxDims; ++d1) {
522                 covGrad1[d1 * maxDims + d1] /= 2.0;
523         }
524
525         cx = maxDims;
526         for (int d1=0; d1 < maxDims; ++d1) {
527                 int cell = d1 * maxDims;
528                 for (int d2=0; d2 <= d1; ++d2) {
529                         (*derivCoef)[cx] = -covGrad1[cell + d2];
530                         ++cx;
531                 }
532         }
533
534         Free(scov);
535         Free(sicov);
536 }
537
538 static bool latentDeriv(omxFitFunction *oo, double *gradient)
539 {
540         omxExpectation *expectation = oo->expectation;
541         BA81FitState *state = (BA81FitState*) oo->argStruct;
542         BA81Expect *estate = (BA81Expect*) expectation->argStruct;
543         if (estate->verbose) mxLog("%s: latentDeriv", oo->matrix->name);
544
545         int numUnique = estate->numUnique;
546         int numSpecific = estate->numSpecific;
547         int maxDims = estate->maxDims;
548         int maxAbilities = estate->maxAbilities;
549         int primaryDims = maxDims;
550         omxMatrix *cov = estate->latentCovOut;
551         int *numIdentical = estate->numIdentical;
552         double *patternLik = estate->patternLik;
553
554         OMXZERO(patternLik, numUnique);
555
556         omxCopyMatrix(state->icov, cov);
557
558         int info;
559         omxDPOTRF(state->icov, &info);
560         if (info != 0) {
561                 if (info < 0) error("dpotrf invalid argument %d", -info);
562                 return FALSE;
563         }
564         omxDPOTRI(state->icov, &info);
565         if (info != 0) {
566                 if (info < 0) error("dpotri invalid argument %d", -info);
567                 return FALSE;
568         }
569         // fill in rest from upper triangle
570         for (int rx=1; rx < maxAbilities; ++rx) {
571                 for (int cx=0; cx < rx; ++cx) {
572                         omxSetMatrixElement(state->icov, rx, cx, omxMatrixElement(state->icov, cx, rx));
573                 }
574         }
575
576         int maxDerivCoef = maxDims + triangleLoc1(maxDims);
577         int numLatents = maxAbilities + triangleLoc1(maxAbilities);
578         double *uniqueDeriv = Calloc(numUnique * numLatents, double);
579
580         if (numSpecific == 0) {
581 #pragma omp parallel for num_threads(Global->numThreads)
582                 for (long qx=0; qx < estate->totalQuadPoints; qx++) {
583                         const int thrId = omx_absolute_thread_num();
584                         int quad[maxDims];
585                         decodeLocation(qx, maxDims, estate->quadGridSize, quad);
586                         double where[maxDims];
587                         pointToWhere(estate, quad, where, maxDims);
588                         std::vector<double> derivCoef(maxDerivCoef);
589                         calcDerivCoef(state, estate, where, 0, &derivCoef);
590                         double area = estate->priQarea[qx];
591                         double *lxk = ba81LikelihoodFast1(expectation, thrId, 0, qx);
592
593                         for (int px=0; px < numUnique; px++) {
594                                 double tmp = (lxk[px] * area);
595 #pragma omp atomic
596                                 patternLik[px] += tmp;
597                                 mapLatentDeriv(state, estate, 0, tmp, derivCoef,
598                                                uniqueDeriv + px * numLatents);
599                         }
600                 }
601         } else {
602                 primaryDims -= 1;
603                 int sDim = primaryDims;
604                 long specificPoints = estate->quadGridSize;
605
606 #pragma omp parallel for num_threads(Global->numThreads)
607                 for (long qx=0; qx < estate->totalPrimaryPoints; qx++) {
608                         const int thrId = omx_absolute_thread_num();
609                         int quad[maxDims];
610                         decodeLocation(qx, primaryDims, estate->quadGridSize, quad);
611
612                         cai2010(expectation, thrId, FALSE, qx);
613                         double *allElxk = eBase(estate, thrId);
614                         double *Eslxk = esBase(estate, thrId);
615
616                         for (long sx=0; sx < specificPoints; sx++) {
617                                 long qloc = qx * specificPoints + sx;
618                                 quad[sDim] = sx;
619                                 double where[maxDims];
620                                 pointToWhere(estate, quad, where, maxDims);
621                                 for (int sgroup=0; sgroup < numSpecific; sgroup++) {
622                                         std::vector<double> derivCoef(maxDerivCoef);
623                                         calcDerivCoef(state, estate, where, sgroup, &derivCoef);
624                                         double area = areaProduct(estate, qx, sx, sgroup);
625                                         double *lxk = ba81LikelihoodFast1(expectation, thrId, sgroup, qloc);
626                                         for (int px=0; px < numUnique; px++) {
627                                                 double Ei = allElxk[px];
628                                                 double Eis = Eslxk[sgroup * numUnique + px];
629                                                 double tmp = ((Ei / Eis) * lxk[px] * area);
630                                                 mapLatentDeriv(state, estate, sgroup, tmp, derivCoef,
631                                                                uniqueDeriv + px * numLatents);
632                                         }
633                                 }
634                         }
635
636                         double priArea = estate->priQarea[qx];
637                         for (int px=0; px < numUnique; px++) {
638                                 double Ei = allElxk[px];
639                                 double tmp = (Ei * priArea);
640 #pragma omp atomic
641                                 patternLik[px] += tmp;
642                         }
643                 }
644         }
645
646         /*
647         std::vector<double> hess1(triangleLoc1(numLatents));
648         std::vector<double> hessSum(triangleLoc1(numLatents));
649
650         // could run nicely in parallel with numUnique * triangleLoc(numLatents) buffer
651         for (int px=0; px < numUnique; ++px) {
652                 gramProduct(uniqueDeriv + px * numLatents, numLatents, hess1.data());
653                 double dups = numIdentical[px];
654                 for (int rx=0; rx < triangleLoc1(numLatents); ++rx) {
655                         hessSum[rx] += hess1[rx] * dups;
656                 }
657         }
658         */
659
660 #pragma omp parallel for num_threads(Global->numThreads)
661         for (int px=0; px < numUnique; ++px) {
662                 double weight = numIdentical[px] / patternLik[px];
663                 for (int rx=0; rx < numLatents; ++rx) {
664                         uniqueDeriv[px * numLatents + rx] *= weight;
665                 }
666         }
667
668 #pragma omp parallel for num_threads(Global->numThreads)
669         for (int rx=0; rx < numLatents; ++rx) {
670                 for (int px=1; px < numUnique; ++px) {
671                         uniqueDeriv[rx] += uniqueDeriv[px * numLatents + rx];
672                 }
673         }
674
675         for (int l1=0; l1 < numLatents; ++l1) {
676                 int t1 = state->latentMap[l1];
677                 if (t1 < 0) continue;
678                 gradient[t1] -= 2 * uniqueDeriv[l1];
679
680                 /*
681                 for (int l2=0; l2 <= l1; ++l2) {
682                         int t2 = state->latentMap[l2];
683                         if (t2 < 0) continue;
684                         hessian[numLatents * t1 + t2] -= 2 * hessSum[triangleLoc1(l1) + l2];
685                 }
686                 */
687         }
688
689         Free(uniqueDeriv);
690
691         return TRUE;
692 }
693
694 static void setLatentStartingValues(omxFitFunction *oo, FitContext *fc)
695 {
696         BA81FitState *state = (BA81FitState*) oo->argStruct;
697         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
698         std::vector<int> &latentMap = state->latentMap;
699         std::vector<double> &ElatentMean = estate->ElatentMean;
700         std::vector<double> &ElatentCov = estate->ElatentCov;
701         int maxAbilities = estate->maxAbilities;
702
703         for (int a1 = 0; a1 < maxAbilities; ++a1) {
704                 if (latentMap[a1] >= 0) {
705                         int to = latentMap[a1];
706                         fc->est[to] = ElatentMean[a1];
707                 }
708
709                 for (int a2 = 0; a2 <= a1; ++a2) {
710                         int to = latentMap[maxAbilities + triangleLoc1(a1) + a2];
711                         if (to < 0) continue;
712                         fc->est[to] = ElatentCov[a1 * maxAbilities + a2];
713                 }
714         }
715
716         //fc->log("setLatentStartingValues", FF_COMPUTE_ESTIMATE);
717 }
718
719 static double
720 ba81ComputeFit(omxFitFunction* oo, int want, FitContext *fc)
721 {
722         BA81FitState *state = (BA81FitState*) oo->argStruct;
723         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
724
725         if (want & FF_COMPUTE_POSTOPTIMIZE) return 0;
726
727         if (estate->type == EXPECTATION_AUGMENTED) {
728                 if (!state->haveItemMap) buildItemParamMap(oo, fc);
729
730                 if (want & FF_COMPUTE_PREOPTIMIZE) {
731                         schilling_bock_2005_rescale(oo, fc); // how does this work in multigroup? TODO
732                         return 0;
733                 }
734
735                 if (state->numItemParam != fc->varGroup->vars.size()) error("mismatch"); // remove TODO
736                 double got = ba81ComputeMFit1(oo, want, fc->grad, fc->hess);
737                 return got;
738         } else if (estate->type == EXPECTATION_OBSERVED) {
739                 if (!state->haveLatentMap) buildLatentParamMap(oo, fc);
740
741                 if (want & FF_COMPUTE_PREOPTIMIZE) {
742                         setLatentStartingValues(oo, fc);
743                         return 0;
744                 }
745
746                 omxExpectationCompute(oo->expectation, NULL);
747
748                 if (want & FF_COMPUTE_GRADIENT) {
749                         if (!latentDeriv(oo, fc->grad)) {
750                                 return INFINITY;
751                         }
752                 }
753
754                 if (want & FF_COMPUTE_HESSIAN) {
755                         warning("%s: Hessian is not available for latent distribution parameters", oo->matrix->name);
756                 }
757
758                 if (want & FF_COMPUTE_FIT) {
759                         if (estate->verbose) mxLog("%s: fit", oo->matrix->name);
760                         double *patternLik = estate->patternLik;
761                         int *numIdentical = estate->numIdentical;
762                         int numUnique = estate->numUnique;
763                         double got = 0;
764 #pragma omp parallel for num_threads(Global->numThreads) schedule(static,64) reduction(+:got)
765                         for (int ux=0; ux < numUnique; ux++) {
766                                 got += numIdentical[ux] * log(patternLik[ux]);
767                         }
768                         //mxLog("fit %.2f", -2 * got);
769                         return -2 * got;
770                 }
771
772                 // if (want & FF_COMPUTE_POSTOPTIMIZE)  discard lxk cache? TODO
773
774                 return 0;
775         } else {
776                 error("Confused");
777         }
778 }
779
780 static void ba81Compute(omxFitFunction *oo, int want, FitContext *fc)
781 {
782         if (!want) return;
783         double got = ba81ComputeFit(oo, want, fc);
784         if (got) oo->matrix->data[0] = got;
785 }
786
787 BA81FitState::~BA81FitState()
788 {
789         Free(tmpLatentMean);
790         Free(tmpLatentCov);
791         omxFreeAllMatrixData(icov);
792         omxFreeAllMatrixData(cholCov);
793 }
794
795 static void ba81Destroy(omxFitFunction *oo) {
796         BA81FitState *state = (BA81FitState *) oo->argStruct;
797         delete state;
798 }
799
800 void omxInitFitFunctionBA81(omxFitFunction* oo)
801 {
802         if (!oo->argStruct) { // ugh!
803                 BA81FitState *state = new BA81FitState;
804                 oo->argStruct = state;
805         }
806
807         BA81FitState *state = (BA81FitState*) oo->argStruct;
808
809         omxExpectation *expectation = oo->expectation;
810         BA81Expect *estate = (BA81Expect*) expectation->argStruct;
811
812         //newObj->data = oo->expectation->data;
813
814         oo->computeFun = ba81Compute;
815         oo->setVarGroup = ba81SetFreeVarGroup;
816         oo->destructFun = ba81Destroy;
817         oo->gradientAvailable = TRUE;
818         oo->hessianAvailable = TRUE;
819
820         int maxParam = estate->itemParam->rows;
821         state->itemDerivPadSize = maxParam + triangleLoc1(maxParam);
822
823         int maxAbilities = estate->maxAbilities;
824
825         state->tmpLatentMean = Realloc(NULL, estate->maxDims, double);
826         state->tmpLatentCov = Realloc(NULL, estate->maxDims * estate->maxDims, double);
827
828         int numItems = estate->itemParam->cols;
829         for (int ix=0; ix < numItems; ix++) {
830                 const double *spec = estate->itemSpec[ix];
831                 int id = spec[RPF_ISpecID];
832                 if (id < 0 || id >= rpf_numModels) {
833                         error("ItemSpec %d has unknown item model %d", ix, id);
834                 }
835         }
836
837         state->icov = omxInitMatrix(NULL, maxAbilities, maxAbilities, TRUE, globalState);
838         state->cholCov = omxInitMatrix(NULL, maxAbilities, maxAbilities, TRUE, globalState);
839 }