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