Rewrite EM fit for new loop order
[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> paramFlavor;        // freeParam
31         std::vector<int> paramMap;           // itemParam->cols * itemDerivPadSize -> index of free parameter
32         std::vector<int> paramLocations;     // param# -> count of appearances in ItemParam
33         std::vector<int> itemParamFree;      // itemParam->cols * itemParam->rows
34         std::vector<int> ihessDivisor;       // freeParam * freeParam
35
36         omxMatrix *cholCov;
37         int choleskyError;
38         double *tmpLatentMean;    // maxDims
39         double *tmpLatentCov;     // maxDims * maxDims ; only lower triangle is used
40         omxMatrix *icov;          // inverse covariance matrix
41
42         std::vector< FreeVarGroup* > varGroups;
43         size_t numItemParam;
44
45         BA81FitState();
46         ~BA81FitState();
47 };
48
49 BA81FitState::BA81FitState()
50 {
51         tmpLatentMean = NULL;
52         tmpLatentCov = NULL;
53         haveItemMap = false;
54         haveLatentMap = false;
55 }
56
57 static void buildLatentParamMap(omxFitFunction* oo, FitContext *fc)
58 {
59         FreeVarGroup *fvg = fc->varGroup;
60         BA81FitState *state = (BA81FitState *) oo->argStruct;
61         std::vector<int> &latentMap = state->latentMap;
62         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
63         int meanNum = estate->latentMeanOut->matrixNumber;
64         int covNum = estate->latentCovOut->matrixNumber;
65         int itemNum = estate->itemParam->matrixNumber;
66         int maxAbilities = estate->maxAbilities;
67         int numLatents = maxAbilities + triangleLoc1(maxAbilities);
68
69         latentMap.assign(numLatents, -1);
70
71         int numParam = int(fvg->vars.size());
72         for (int px=0; px < numParam; px++) {
73                 omxFreeVar *fv = fvg->vars[px];
74                 for (size_t lx=0; lx < fv->locations.size(); lx++) {
75                         omxFreeVarLocation *loc = &fv->locations[lx];
76                         int matNum = ~loc->matrix;
77                         if (matNum == meanNum) {
78                                 latentMap[loc->row + loc->col] = px;
79                         } else if (matNum == covNum) {
80                                 int a1 = loc->row;
81                                 int a2 = loc->col;
82                                 if (a1 < a2) std::swap(a1, a2);
83                                 int cell = maxAbilities + triangleLoc1(a1) + a2;
84                                 if (latentMap[cell] == -1) {
85                                         latentMap[cell] = px;
86
87                                         if (a1 == a2 && fv->lbound == NEG_INF) {
88                                                 fv->lbound = 1e-6;  // variance must be positive
89                                                 if (fc->est[px] < fv->lbound) {
90                                                         error("Starting value for variance %s is negative", fv->name);
91                                                 }
92                                         }
93                                 } else if (latentMap[cell] != px) {
94                                         // doesn't work for multigroup constraints TODO
95                                         error("In covariance matrix, %s and %s must be constrained equal to preserve symmetry",
96                                               fvg->vars[latentMap[cell]]->name, fv->name);
97                                 }
98                         } else if (matNum == itemNum) {
99                                 omxRaiseErrorf(globalState, "The fitfunction free.set should consist of "
100                                                "latent distribution parameters, excluding item parameters");
101                         }
102                 }
103         }
104         state->haveLatentMap = TRUE;
105 }
106
107 static void buildItemParamMap(omxFitFunction* oo, FitContext *fc)
108 {
109         FreeVarGroup *fvg = fc->varGroup;
110         BA81FitState *state = (BA81FitState *) oo->argStruct;
111         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
112         omxMatrix *itemParam = estate->itemParam;
113         int size = itemParam->cols * state->itemDerivPadSize;
114         state->paramMap.assign(size, -1);  // matrix location to free param index
115         state->itemParamFree.assign(itemParam->rows * itemParam->cols, FALSE);
116
117         size_t numFreeParams = state->numItemParam = fvg->vars.size();
118         state->paramLocations.assign(numFreeParams, 0);
119         state->paramFlavor.assign(numFreeParams, -1);
120
121         for (size_t px=0; px < numFreeParams; px++) {
122                 omxFreeVar *fv = fvg->vars[px];
123                 state->paramLocations[px] = int(fv->locations.size());
124                 for (size_t lx=0; lx < fv->locations.size(); lx++) {
125                         omxFreeVarLocation *loc = &fv->locations[lx];
126                         int matNum = ~loc->matrix;
127                         // prohibit mean & cov TODO
128                         if (matNum == itemParam->matrixNumber) {
129                                 int at = loc->col * state->itemDerivPadSize + loc->row;
130                                 state->paramMap[at] = px;
131                                 state->itemParamFree[loc->col * itemParam->rows + loc->row] = TRUE;
132
133                                 const double *spec = estate->itemSpec[loc->col];
134                                 int id = spec[RPF_ISpecID];
135                                 int flavor;
136                                 double upper, lower;
137                                 (*rpf_model[id].paramInfo)(spec, loc->row, &flavor, &upper, &lower);
138                                 if (state->paramFlavor[px] < 0) {
139                                         state->paramFlavor[px] = flavor;
140                                 } else if (state->paramFlavor[px] != flavor) {
141                                         error("Cannot equate %s with %s[%d,%d]", fv->name,
142                                               itemParam->name, loc->row, loc->col);
143                                 }
144                                 if (fv->lbound == NEG_INF && isfinite(lower)) {
145                                         fv->lbound = lower;
146                                         if (fc->est[px] < fv->lbound) {
147                                                 error("Starting value %s %f less than lower bound %f",
148                                                       fv->name, fc->est[px], lower);
149                                         }
150                                 }
151                                 if (fv->ubound == INF && isfinite(upper)) {
152                                         fv->ubound = upper;
153                                         if (fc->est[px] > fv->ubound) {
154                                                 error("Starting value %s %f greater than upper bound %f",
155                                                       fv->name, fc->est[px], upper);
156                                         }
157                                 }
158                         }
159                 }
160         }
161
162         state->ihessDivisor.resize(size);
163
164         for (int cx=0; cx < itemParam->cols; ++cx) {
165                 const double *spec = estate->itemSpec[cx];
166                 int id = spec[RPF_ISpecID];
167                 int numParam = (*rpf_model[id].numParam)(spec);
168
169                 for (int p1=0; p1 < numParam; p1++) {
170                         int at1 = state->paramMap[cx * state->itemDerivPadSize + p1];
171                         if (at1 < 0) continue;
172
173                         for (int p2=0; p2 <= p1; p2++) {
174                                 int at2 = state->paramMap[cx * state->itemDerivPadSize + p2];
175                                 if (at2 < 0) continue;
176
177                                 if (at1 < at2) std::swap(at1, at2);  // lower triangle
178
179                                 //mxLog("Item %d param(%d,%d) -> H[%d,%d]", cx, p1, p2, at1, at2);
180                                 int at = cx * state->itemDerivPadSize + numParam + triangleLoc1(p1) + p2;
181                                 state->paramMap[at] = numFreeParams + at1 * numFreeParams + at2;
182
183                                 state->ihessDivisor[at] =
184                                         state->paramLocations[at1] * state->paramLocations[at2];
185                         }
186                 }
187         }
188
189         state->haveItemMap = TRUE;
190         //pia(state->paramMap.data(), state->itemDerivPadSize, itemParam->cols);
191 }
192
193 static double
194 ba81ComputeEMFit(omxFitFunction* oo, int want, FitContext *fc)
195 {
196         BA81FitState *state = (BA81FitState*) oo->argStruct;
197         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
198         omxMatrix *customPrior = estate->customPrior;
199         omxMatrix *itemParam = estate->itemParam;
200         std::vector<const double*> &itemSpec = estate->itemSpec;
201         std::vector<int> &cumItemOutcomes = estate->cumItemOutcomes;
202         const int maxDims = estate->maxDims;
203         const size_t numItems = estate->itemSpec.size();
204         const int do_fit = want & FF_COMPUTE_FIT;
205         const int do_deriv = want & (FF_COMPUTE_GRADIENT | FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN);
206
207         if (estate->verbose) mxLog("%s: em.fit(want fit=%d deriv=%d)", oo->matrix->name, do_fit, do_deriv);
208
209         double ll = 0;
210         if (customPrior) {
211                 omxRecompute(customPrior);
212                 ll = customPrior->data[0];
213                 // need deriv adjustment TODO
214         }
215
216         if (!isfinite(ll)) {
217                 omxPrint(itemParam, "item param");
218                 error("Bayesian prior returned %g; do you need to add a lbound/ubound?", ll);
219         }
220
221         if (do_fit) ba81OutcomeProb(estate, TRUE);
222
223         const int thrDerivSize = itemParam->cols * state->itemDerivPadSize;
224         std::vector<double> thrDeriv(thrDerivSize * Global->numThreads);
225
226 #pragma omp parallel for num_threads(Global->numThreads) reduction(+:ll)
227         for (size_t ix=0; ix < numItems; ix++) {
228                 const int thrId = omx_absolute_thread_num();
229                 const double *spec = estate->itemSpec[ix];
230                 const int id = spec[RPF_ISpecID];
231                 const rpf_dLL1_t dLL1 = rpf_model[id].dLL1;
232                 const int iOutcomes = estate->itemOutcomes[ix];
233                 const int outcomeBase = cumItemOutcomes[ix] * estate->totalQuadPoints;
234                 const double *weight = estate->expected + outcomeBase;
235                 const double *oProb = estate->outcomeProb + outcomeBase;
236                 const double *iparam = omxMatrixColumn(itemParam, ix);
237                 double *myDeriv = thrDeriv.data() + thrDerivSize * thrId + ix * state->itemDerivPadSize;
238
239                 for (long qx=0; qx < estate->totalQuadPoints; qx++) {
240                         if (do_fit) {
241                                 for (int ox=0; ox < iOutcomes; ox++) {
242                                         ll += weight[ox] * oProb[ox];
243                                 }
244                         }
245                         if (do_deriv) {
246                                 int quad[maxDims];
247                                 decodeLocation(qx, maxDims, estate->quadGridSize, quad);
248                                 double where[maxDims];
249                                 pointToWhere(estate, quad, where, maxDims);
250                                 (*dLL1)(spec, iparam, where, weight, myDeriv);
251                         }
252                         weight += iOutcomes;
253                         oProb += iOutcomes;
254                 }
255         }
256
257         int excluded = 0;
258
259         if (do_deriv) {
260                 double *deriv0 = thrDeriv.data();
261
262                 int perThread = itemParam->cols * state->itemDerivPadSize;
263                 for (int th=1; th < Global->numThreads; th++) {
264                         double *thrD = thrDeriv.data() + th * perThread;
265                         for (int ox=0; ox < perThread; ox++) deriv0[ox] += thrD[ox];
266                 }
267
268                 for (size_t ix=0; ix < numItems; ix++) {
269                         const double *spec = itemSpec[ix];
270                         int id = spec[RPF_ISpecID];
271                         double *iparam = omxMatrixColumn(itemParam, ix);
272                         double *pad = deriv0 + ix * state->itemDerivPadSize;
273                         (*rpf_model[id].dLL2)(spec, iparam, pad);
274                 }
275
276                 int numFreeParams = int(state->numItemParam);
277                 int numParams = itemParam->cols * state->itemDerivPadSize;
278                 for (int ox=0; ox < numParams; ox++) {
279                         int to = state->paramMap[ox];
280                         if (to == -1) continue;
281
282                         // Need to check because this can happen if
283                         // lbounds/ubounds are not set appropriately.
284                         if (0 && !isfinite(deriv0[ox])) {
285                                 int item = ox / itemParam->rows;
286                                 mxLog("item parameters:\n");
287                                 const double *spec = itemSpec[item];
288                                 int id = spec[RPF_ISpecID];
289                                 int numParam = (*rpf_model[id].numParam)(spec);
290                                 double *iparam = omxMatrixColumn(itemParam, item);
291                                 pda(iparam, numParam, 1);
292                                 // Perhaps bounds can be pulled in from librpf? TODO
293                                 error("Deriv %d for item %d is %f; are you missing a lbound/ubound?",
294                                       ox, item, deriv0[ox]);
295                         }
296
297                         if (to < numFreeParams) {
298                                 if (want & FF_COMPUTE_GRADIENT) {
299                                         fc->grad[to] += deriv0[ox];
300                                 }
301                         } else {
302                                 if (want & FF_COMPUTE_HESSIAN) {
303                                         int Hto = to - numFreeParams;
304                                         fc->hess[Hto] += deriv0[ox];
305                                 }
306                         }
307                 }
308
309                 if (want & FF_COMPUTE_IHESSIAN) {
310                         for (size_t ix=0; ix < numItems; ix++) {
311                                 const double *spec = itemSpec[ix];
312                                 int id = spec[RPF_ISpecID];
313                                 int iParams = (*rpf_model[id].numParam)(spec);
314                                 double *pad = deriv0 + ix * state->itemDerivPadSize + iParams;
315                                 int *mask = state->itemParamFree.data() + ix * itemParam->rows;
316                                 double stress;
317                                 omxApproxInvertPackedPosDefTriangular(iParams, mask, pad, &stress);
318                                 if (stress) ++excluded;
319                         }
320
321                         for (int ox=0; ox < numParams; ox++) {
322                                 int to = state->paramMap[ox];
323                                 if (to == -1) continue;
324                                 if (to >= numFreeParams) {
325                                         int Hto = to - numFreeParams;
326                                         fc->ihess[Hto] += deriv0[ox] / state->ihessDivisor[ox];
327                                 }
328                         }
329
330                 }
331         }
332
333         if (excluded && estate->verbose >= 1) {
334                 mxLog("%s: Hessian not positive definite for %d/%lu items",
335                       oo->matrix->name, excluded, numItems);
336         }
337         if (excluded > numItems/2) {
338                 // maybe not fatal, but investigation needed
339                 omxRaiseErrorf(globalState, "Hessian not positive definite for %d/%lu items",
340                                excluded, numItems);
341         }
342
343         return -ll;
344 }
345
346 void ba81SetFreeVarGroup(omxFitFunction *oo, FreeVarGroup *fvg)
347 {}
348
349 static void setLatentStartingValues(omxFitFunction *oo, FitContext *fc)
350 {
351         BA81FitState *state = (BA81FitState*) oo->argStruct;
352         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
353         std::vector<int> &latentMap = state->latentMap;
354         std::vector<double> &ElatentMean = estate->ElatentMean;
355         std::vector<double> &ElatentCov = estate->ElatentCov;
356         int maxAbilities = estate->maxAbilities;
357
358         for (int a1 = 0; a1 < maxAbilities; ++a1) {
359                 if (latentMap[a1] >= 0) {
360                         int to = latentMap[a1];
361                         fc->est[to] = ElatentMean[a1];
362                 }
363
364                 for (int a2 = 0; a2 <= a1; ++a2) {
365                         int to = latentMap[maxAbilities + triangleLoc1(a1) + a2];
366                         if (to < 0) continue;
367                         fc->est[to] = ElatentCov[a1 * maxAbilities + a2];
368                 }
369         }
370
371         //fc->log("setLatentStartingValues", FF_COMPUTE_ESTIMATE);
372 }
373
374 static double
375 ba81ComputeFit(omxFitFunction* oo, int want, FitContext *fc)
376 {
377         BA81FitState *state = (BA81FitState*) oo->argStruct;
378         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
379
380         if (want & FF_COMPUTE_POSTOPTIMIZE) return 0;
381
382         if (estate->type == EXPECTATION_AUGMENTED) {
383                 if (!state->haveItemMap) buildItemParamMap(oo, fc);
384
385                 if (state->numItemParam != fc->varGroup->vars.size()) error("mismatch"); // remove TODO
386
387                 if (want & FF_COMPUTE_PARAMFLAVOR) {
388                         for (size_t px=0; px < state->numItemParam; ++px) {
389                                 if (state->paramFlavor[px] < 0) continue;
390                                 fc->flavor[px] = state->paramFlavor[px];
391                         }
392                         return 0;
393                 }
394
395                 if (want & FF_COMPUTE_PREOPTIMIZE) {
396                         // schilling_bock_2005_rescale(oo, fc); seems counterproductive
397                         return 0;
398                 }
399
400                 double got = ba81ComputeEMFit(oo, want, fc);
401                 return got;
402         } else if (estate->type == EXPECTATION_OBSERVED) {
403                 if (!state->haveLatentMap) buildLatentParamMap(oo, fc);
404
405                 if (want & FF_COMPUTE_PREOPTIMIZE) {
406                         setLatentStartingValues(oo, fc);
407                         return 0;
408                 }
409
410                 omxExpectationCompute(oo->expectation, NULL);
411
412                 if (want & (FF_COMPUTE_GRADIENT|FF_COMPUTE_HESSIAN)) {
413                         warning("%s: Derivs are not available for latent distribution parameters", oo->matrix->name);
414                 }
415
416                 if (want & FF_COMPUTE_FIT) {
417                         double *patternLik = estate->patternLik;
418                         int *numIdentical = estate->numIdentical;
419                         int numUnique = estate->numUnique;
420                         estate->excludedPatterns = 0;
421                         const double LogLargest = estate->LogLargestDouble;
422                         double got = 0;
423 #pragma omp parallel for num_threads(Global->numThreads) reduction(+:got)
424                         for (int ux=0; ux < numUnique; ux++) {
425                                 if (!validPatternLik(estate, patternLik[ux])) {
426 #pragma omp atomic
427                                         ++estate->excludedPatterns;
428                                         // somehow indicate that this -2LL is provisional TODO
429                                         continue;
430                                 }
431                                 got += numIdentical[ux] * (log(patternLik[ux]) - LogLargest);
432                         }
433                         if (estate->verbose) mxLog("%s: fit (%d/%d excluded)",
434                                                    oo->matrix->name, estate->excludedPatterns, numUnique);
435                         //mxLog("fit %.4f", -2 * got);
436                         return -2 * got;
437                 }
438
439                 // if (want & FF_COMPUTE_POSTOPTIMIZE)  discard lxk cache? TODO
440
441                 return 0;
442         } else {
443                 error("Confused");
444         }
445 }
446
447 static void ba81Compute(omxFitFunction *oo, int want, FitContext *fc)
448 {
449         if (!want) return;
450         double got = ba81ComputeFit(oo, want, fc);
451         if (got) oo->matrix->data[0] = got;
452 }
453
454 BA81FitState::~BA81FitState()
455 {
456         Free(tmpLatentMean);
457         Free(tmpLatentCov);
458         omxFreeAllMatrixData(icov);
459         omxFreeAllMatrixData(cholCov);
460 }
461
462 static void ba81Destroy(omxFitFunction *oo) {
463         BA81FitState *state = (BA81FitState *) oo->argStruct;
464         delete state;
465 }
466
467 void omxInitFitFunctionBA81(omxFitFunction* oo)
468 {
469         if (!oo->argStruct) { // ugh!
470                 BA81FitState *state = new BA81FitState;
471                 oo->argStruct = state;
472         }
473
474         BA81FitState *state = (BA81FitState*) oo->argStruct;
475
476         omxExpectation *expectation = oo->expectation;
477         BA81Expect *estate = (BA81Expect*) expectation->argStruct;
478
479         //newObj->data = oo->expectation->data;
480
481         oo->computeFun = ba81Compute;
482         oo->setVarGroup = ba81SetFreeVarGroup;
483         oo->destructFun = ba81Destroy;
484         oo->gradientAvailable = TRUE;
485         oo->hessianAvailable = TRUE;
486         oo->parametersHaveFlavor = TRUE;
487
488         int maxParam = estate->itemParam->rows;
489         state->itemDerivPadSize = maxParam + triangleLoc1(maxParam);
490
491         int maxAbilities = estate->maxAbilities;
492
493         state->tmpLatentMean = Realloc(NULL, estate->maxDims, double);
494         state->tmpLatentCov = Realloc(NULL, estate->maxDims * estate->maxDims, double);
495
496         int numItems = estate->itemParam->cols;
497         for (int ix=0; ix < numItems; ix++) {
498                 const double *spec = estate->itemSpec[ix];
499                 int id = spec[RPF_ISpecID];
500                 if (id < 0 || id >= rpf_numModels) {
501                         error("ItemSpec %d has unknown item model %d", ix, id);
502                 }
503         }
504
505         state->icov = omxInitMatrix(NULL, maxAbilities, maxAbilities, TRUE, globalState);
506         state->cholCov = omxInitMatrix(NULL, maxAbilities, maxAbilities, TRUE, globalState);
507 }