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