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