Sync libifa-rpf with RPF 0.10
[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         int derivPadSize;         // maxParam + maxParam*(1+maxParam)/2
29         double *thrDeriv;         // itemParam->cols * derivPadSize * thread
30         int *paramMap;            // itemParam->cols * derivPadSize -> index of free parameter
31         bool rescale;
32         omxMatrix *customPrior;
33         int choleskyError;
34         double *tmpLatentMean;    // maxDims
35         double *tmpLatentCov;     // maxDims * maxDims ; only lower triangle is used
36         int fitCount;
37         int gradientCount;
38         double lastEMLL;
39
40         std::vector< FreeVarGroup* > varGroups;
41         FreeVarGroup *latentFVG;
42
43         BA81FitState();
44 };
45
46 BA81FitState::BA81FitState()
47 {
48         paramMap = NULL;
49         latentFVG = NULL;
50         customPrior = NULL;
51         fitCount = 0;
52         gradientCount = 0;
53 }
54
55 static void buildParamMap(omxFitFunction* oo)
56 {
57         BA81FitState *state = (BA81FitState *) oo->argStruct;
58         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
59         omxMatrix *itemParam = state->itemParam;
60         int size = itemParam->cols * state->derivPadSize;
61
62         state->paramMap = Realloc(NULL, size, int);  // matrix location to free param index
63         for (int px=0; px < size; px++) {
64                 state->paramMap[px] = -1;
65         }
66
67         size_t numFreeParams = oo->freeVarGroup->vars.size();
68         int *pRow = Realloc(NULL, numFreeParams, int);
69         int *pCol = Realloc(NULL, numFreeParams, int);
70
71         for (size_t px=0; px < numFreeParams; px++) {
72                 pRow[px] = -1;
73                 pCol[px] = -1;
74                 omxFreeVar *fv = oo->freeVarGroup->vars[px];
75                 for (size_t lx=0; lx < fv->locations.size(); lx++) {
76                         omxFreeVarLocation *loc = &fv->locations[lx];
77                         if (~loc->matrix == itemParam->matrixNumber) {
78                                 pRow[px] = loc->row;
79                                 pCol[px] = loc->col;
80                                 int at = pCol[px] * state->derivPadSize + pRow[px];
81                                 state->paramMap[at] = px;
82                         }
83                 }
84         }
85
86         for (size_t p1=0; p1 < numFreeParams; p1++) {
87                 for (size_t p2=p1; p2 < numFreeParams; p2++) {
88                         if (pCol[p1] == -1 || pCol[p1] != pCol[p2]) continue;
89                         const double *spec = omxMatrixColumn(estate->itemSpec, pCol[p1]);
90                         int id = spec[RPF_ISpecID];
91                         int numParam = (*rpf_model[id].numParam)(spec);
92                         int r1 = pRow[p1];
93                         int r2 = pRow[p2];
94                         if (r1 > r2) { int tmp=r1; r1=r2; r2=tmp; }
95                         int rowOffset = 0;
96                         for (int rx=1; rx <= r2; rx++) rowOffset += rx;
97                         int at = pCol[p1] * state->derivPadSize + numParam + rowOffset + r1;
98                         state->paramMap[at] = numFreeParams + p1 * numFreeParams + p2;
99                 }
100         }
101
102         Free(pRow);
103         Free(pCol);
104
105         state->thrDeriv = Realloc(NULL, itemParam->cols * state->derivPadSize * Global->numThreads, double);
106 }
107
108 OMXINLINE static double
109 ba81Fit1Ordinate(omxFitFunction* oo, const int *quad, const double *weight, int want)
110 {
111         BA81FitState *state = (BA81FitState*) oo->argStruct;
112         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
113         omxMatrix *itemSpec = estate->itemSpec;
114         omxMatrix *itemParam = state->itemParam;
115         int numItems = itemParam->cols;
116         int maxOutcomes = estate->maxOutcomes;
117         int maxDims = estate->maxDims;
118         double *myDeriv = state->thrDeriv + itemParam->cols * state->derivPadSize * omx_absolute_thread_num();
119         int do_deriv = want & (FF_COMPUTE_GRADIENT | FF_COMPUTE_HESSIAN);
120
121         double where[maxDims];
122         pointToWhere(estate->Qpoint, quad, where, maxDims);
123
124         double *outcomeProb = computeRPF(estate->itemSpec, estate->design, itemParam, estate->maxDims,
125                                          estate->maxOutcomes, quad, estate->Qpoint); // avoid malloc/free? TODO
126         if (!outcomeProb) return 0;
127
128         double thr_ll = 0;
129         for (int ix=0; ix < numItems; ix++) {
130                 const double *spec = omxMatrixColumn(itemSpec, ix);
131                 int id = spec[RPF_ISpecID];
132                 int iOutcomes = spec[RPF_ISpecOutcomes];
133
134                 double area = exp(logAreaProduct(estate, quad, estate->Sgroup[ix]));   // avoid exp() here? TODO
135                 for (int ox=0; ox < iOutcomes; ox++) {
136 #if 0
137 #pragma omp critical(ba81Fit1OrdinateDebug1)
138                         if (!isfinite(outcomeProb[ix * maxOutcomes + ox])) {
139                                 pda(itemParam->data, itemParam->rows, itemParam->cols);
140                                 pda(outcomeProb, outcomes, numItems);
141                                 error("RPF produced NAs");
142                         }
143 #endif
144                         double got = weight[ox] * outcomeProb[ix * maxOutcomes + ox];
145                         thr_ll += got * area;
146                 }
147
148                 if (do_deriv) {
149                         double *iparam = omxMatrixColumn(itemParam, ix);
150                         double *pad = myDeriv + ix * state->derivPadSize;
151                         (*rpf_model[id].dLL1)(spec, iparam, where, area, weight, pad);
152                 }
153                 weight += iOutcomes;
154         }
155
156         Free(outcomeProb);
157
158         return thr_ll;
159 }
160
161 static double
162 ba81ComputeMFit1(omxFitFunction* oo, int want, double *gradient, double *hessian)
163 {
164         BA81FitState *state = (BA81FitState*) oo->argStruct;
165         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
166         omxMatrix *customPrior = state->customPrior;
167         omxMatrix *itemParam = state->itemParam;
168         omxMatrix *itemSpec = estate->itemSpec;
169         int maxDims = estate->maxDims;
170         const int totalOutcomes = estate->totalOutcomes;
171
172         double ll = 0;
173         if (customPrior) {
174                 omxRecompute(customPrior);
175                 ll = customPrior->data[0];
176                 // need deriv adjustment TODO
177         }
178
179         if (!isfinite(ll)) {
180                 omxPrint(itemParam, "item param");
181                 error("Bayesian prior returned %g; do you need to add a lbound/ubound?", ll);
182         }
183
184 #pragma omp parallel for num_threads(Global->numThreads)
185         for (long qx=0; qx < estate->totalQuadPoints; qx++) {
186                 //double area = exp(state->priLogQarea[qx]);  // avoid exp() here? TODO
187                 int quad[maxDims];
188                 decodeLocation(qx, maxDims, estate->quadGridSize, quad);
189                 double *weight = estate->expected + qx * totalOutcomes;
190                 double thr_ll = ba81Fit1Ordinate(oo, quad, weight, want);
191                 
192 #pragma omp atomic
193                 ll += thr_ll;
194         }
195
196         if (gradient) {
197                 double *deriv0 = state->thrDeriv;
198
199                 int perThread = itemParam->cols * state->derivPadSize;
200                 for (int th=1; th < Global->numThreads; th++) {
201                         double *thrD = state->thrDeriv + th * perThread;
202                         for (int ox=0; ox < perThread; ox++) deriv0[ox] += thrD[ox];
203                 }
204
205                 int numItems = itemParam->cols;
206                 for (int ix=0; ix < numItems; ix++) {
207                         const double *spec = omxMatrixColumn(itemSpec, ix);
208                         int id = spec[RPF_ISpecID];
209                         double *iparam = omxMatrixColumn(itemParam, ix);
210                         double *pad = deriv0 + ix * state->derivPadSize;
211                         (*rpf_model[id].dLL2)(spec, iparam, pad);
212                 }
213
214                 int numFreeParams = int(oo->freeVarGroup->vars.size());
215                 int numParams = itemParam->cols * state->derivPadSize;
216                 for (int ox=0; ox < numParams; ox++) {
217                         int to = state->paramMap[ox];
218                         if (to == -1) continue;
219
220                         // Need to check because this can happen if
221                         // lbounds/ubounds are not set appropriately.
222                         if (0 && !isfinite(deriv0[ox])) {
223                                 int item = ox / itemParam->rows;
224                                 mxLog("item parameters:\n");
225                                 const double *spec = omxMatrixColumn(itemSpec, item);
226                                 int id = spec[RPF_ISpecID];
227                                 int numParam = (*rpf_model[id].numParam)(spec);
228                                 double *iparam = omxMatrixColumn(itemParam, item);
229                                 pda(iparam, numParam, 1);
230                                 // Perhaps bounds can be pulled in from librpf? TODO
231                                 error("Deriv %d for item %d is %f; are you missing a lbound/ubound?",
232                                       ox, item, deriv0[ox]);
233                         }
234
235                         if (to < numFreeParams) {
236                                 gradient[to] -= deriv0[ox];
237                         } else {
238                                 hessian[to - numFreeParams] -= deriv0[ox];
239                         }
240                 }
241         }
242
243         return -ll;
244 }
245
246 static void
247 schilling_bock_2005_rescale(omxFitFunction *oo, FitContext *fc)
248 {
249         BA81FitState *state = (BA81FitState*) oo->argStruct;
250         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
251         omxMatrix *itemSpec = estate->itemSpec;
252         omxMatrix *itemParam = state->itemParam;
253         omxMatrix *design = estate->design;
254         double *ElatentMean = estate->ElatentMean;
255         double *ElatentCov = estate->ElatentCov;
256         double *tmpLatentMean = state->tmpLatentMean;
257         double *tmpLatentCov = state->tmpLatentCov;
258         int maxAbilities = estate->maxAbilities;
259         int maxDims = estate->maxDims;
260
261         //mxLog("schilling bock\n");
262         //pda(ElatentMean, maxAbilities, 1);
263         //pda(ElatentCov, maxAbilities, maxAbilities);
264         //omxPrint(design, "design");
265
266         const char triangle = 'L';
267         F77_CALL(dpotrf)(&triangle, &maxAbilities, ElatentCov, &maxAbilities, &state->choleskyError);
268         if (state->choleskyError != 0) {
269                 warning("Cholesky failed with %d; rescaling disabled", state->choleskyError); // make error TODO?
270                 return;
271         }
272
273         //fc->log(FF_COMPUTE_ESTIMATE);
274
275         int numItems = itemParam->cols;
276         for (int ix=0; ix < numItems; ix++) {
277                 const double *spec = omxMatrixColumn(itemSpec, ix);
278                 int id = spec[RPF_ISpecID];
279                 const double *rawDesign = omxMatrixColumn(design, ix);
280                 int idesign[design->rows];
281                 int idx = 0;
282                 for (int dx=0; dx < design->rows; dx++) {
283                         if (isfinite(rawDesign[dx])) {
284                                 idesign[idx++] = rawDesign[dx]-1;
285                         } else {
286                                 idesign[idx++] = -1;
287                         }
288                 }
289                 for (int d1=0; d1 < idx; d1++) {
290                         if (idesign[d1] == -1) {
291                                 tmpLatentMean[d1] = 0;
292                         } else {
293                                 tmpLatentMean[d1] = ElatentMean[idesign[d1]];
294                         }
295                         for (int d2=0; d2 <= d1; d2++) {
296                                 int cell = idesign[d2] * maxAbilities + idesign[d1];
297                                 if (idesign[d1] == -1 || idesign[d2] == -1) {
298                                         tmpLatentCov[d2 * maxDims + d1] = d1==d2? 1 : 0;
299                                 } else {
300                                         tmpLatentCov[d2 * maxDims + d1] = ElatentCov[cell];
301                                 }
302                         }
303                 }
304                 if (1) {  // ease debugging, make optional TODO
305                         for (int d1=idx; d1 < maxDims; d1++) tmpLatentMean[d1] = nan("");
306                         for (int d1=0; d1 < maxDims; d1++) {
307                                 for (int d2=0; d2 < maxDims; d2++) {
308                                         if (d1 < idx && d2 < idx) continue;
309                                         tmpLatentCov[d2 * maxDims + d1] = nan("");
310                                 }
311                         }
312                 }
313                 double *iparam = omxMatrixColumn(itemParam, ix);
314                 int *mask = state->paramMap + state->derivPadSize * ix;
315                 rpf_model[id].rescale(spec, iparam, mask, tmpLatentMean, tmpLatentCov);
316         }
317
318         int numFreeParams = int(oo->freeVarGroup->vars.size());
319         for (int rx=0; rx < itemParam->rows; rx++) {
320                 for (int cx=0; cx < itemParam->cols; cx++) {
321                         int vx = state->paramMap[cx * state->derivPadSize + rx];
322                         if (vx >= 0 && vx < numFreeParams) {
323                                 fc->est[vx] = omxMatrixElement(itemParam, rx, cx);
324                         }
325                 }
326         }
327         fc->copyParamToModel(globalState);
328         //fc->log(FF_COMPUTE_ESTIMATE);
329 }
330
331 OMXINLINE static void
332 updateLatentParam(omxFitFunction* oo, FitContext *fc)
333 {
334         BA81FitState *state = (BA81FitState*) oo->argStruct;
335         BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
336         int maxAbilities = estate->maxAbilities;
337         int meanNum = estate->latentMeanOut->matrixNumber;
338         int covNum = estate->latentCovOut->matrixNumber;
339         FreeVarGroup *latentFVG = state->latentFVG;
340
341         // TODO need denom for multigroup
342         size_t numFreeParams = latentFVG->vars.size();
343         for (size_t px=0; px < numFreeParams; px++) {
344                 omxFreeVar *fv = latentFVG->vars[px];
345                 for (size_t lx=0; lx < fv->locations.size(); ++lx) {
346                         omxFreeVarLocation *loc = &fv->locations[lx];
347                         int matNum = ~loc->matrix;
348                         if (matNum == meanNum) {
349                                 int dx = loc->row * loc->col;
350                                 fc->est[px] = estate->ElatentMean[dx];
351                         } else if (matNum == covNum) {
352                                 int cell = loc->col * maxAbilities + loc->row;
353                                 fc->est[px] = estate->ElatentCov[cell];
354                         }
355                 }
356         }
357         fc->copyParamToModel(globalState);
358 }
359
360 void ba81SetFreeVarGroup(omxFitFunction *oo, FreeVarGroup *fvg) // too ad hoc? TODO
361 {
362         if (!oo->argStruct) { // ugh!
363                 BA81FitState *state = new BA81FitState;
364                 oo->argStruct = state;
365         }
366
367         BA81FitState *state = (BA81FitState*) oo->argStruct;
368
369         state->varGroups.push_back(fvg);
370         if (state->varGroups.size() == 2) {
371                 int small = 0;
372                 if (state->varGroups[0]->vars.size() > state->varGroups[1]->vars.size())
373                         small = 1;
374                 oo->freeVarGroup = state->varGroups[small];
375                 state->latentFVG = state->varGroups[!small];
376         } else if (state->varGroups.size() > 2) {
377                 // ignore
378         }
379 }
380
381 static double
382 ba81ComputeFit(omxFitFunction* oo, int want, FitContext *fc)
383 {
384         if (!want) return 0;
385
386         BA81FitState *state = (BA81FitState*) oo->argStruct;
387
388         if (!state->paramMap) buildParamMap(oo);
389
390         if (want & FF_COMPUTE_PREOPTIMIZE) {
391                 if (state->rescale) schilling_bock_2005_rescale(oo, fc);
392                 return 0;
393         }
394
395         if (want & FF_COMPUTE_FIT) {
396                 ++state->fitCount;
397         }
398
399         if (want & (FF_COMPUTE_GRADIENT|FF_COMPUTE_HESSIAN)) {
400                 // M-step
401
402                 ++state->gradientCount;
403
404                 size_t numFreeParams = oo->freeVarGroup->vars.size();
405                 double *gradient = fc->grad;
406                 double *hessian = fc->hess;
407                 OMXZERO(gradient, numFreeParams);
408                 OMXZERO(hessian, numFreeParams * numFreeParams);
409
410                 omxMatrix *itemParam = state->itemParam;
411                 OMXZERO(state->thrDeriv, state->derivPadSize * itemParam->cols * Global->numThreads);
412
413                 double got = ba81ComputeMFit1(oo, want, gradient, hessian);
414                 state->lastEMLL = got;
415                 return got;
416         } else {
417                 // Major EM iteration, note completely different LL calculation
418
419                 updateLatentParam(oo, fc);
420
421                 BA81Expect *estate = (BA81Expect*) oo->expectation->argStruct;
422                 double *patternLik = estate->patternLik;
423                 int *numIdentical = estate->numIdentical;
424                 int numUnique = estate->numUnique;
425                 double got = 0;
426                 for (int ux=0; ux < numUnique; ux++) {
427                         got += numIdentical[ux] * patternLik[ux];
428                 }
429                 return -2 * got;
430         }
431 }
432
433 static void ba81Compute(omxFitFunction *oo, int want, FitContext *fc)
434 {
435         oo->matrix->data[0] = ba81ComputeFit(oo, want, fc);
436 }
437
438 static void ba81Destroy(omxFitFunction *oo) {
439         BA81FitState *state = (BA81FitState *) oo->argStruct;
440
441         omxFreeAllMatrixData(state->customPrior);
442         Free(state->paramMap);
443         Free(state->thrDeriv);
444         Free(state->tmpLatentMean);
445         Free(state->tmpLatentCov);
446         omxFreeAllMatrixData(state->itemParam);
447         delete state;
448 }
449
450 static omxRListElement *ba81SetFinalReturns(omxFitFunction *oo, int *numReturns)
451 {
452         omxRListElement *ret = ba81EAP(oo->expectation, numReturns);
453
454         return ret;
455 }
456
457 void omxInitFitFunctionBA81(omxFitFunction* oo)
458 {
459         BA81FitState *state = (BA81FitState*) oo->argStruct;
460         SEXP rObj = oo->rObj;
461
462         omxExpectation *expectation = oo->expectation;
463         BA81Expect *estate = (BA81Expect*) expectation->argStruct;
464
465         //newObj->data = oo->expectation->data;
466
467         oo->computeFun = ba81Compute;
468         oo->setVarGroup = ba81SetFreeVarGroup;
469         oo->setFinalReturns = ba81SetFinalReturns;
470         oo->destructFun = ba81Destroy;
471
472         SEXP tmp;
473         PROTECT(tmp = GET_SLOT(rObj, install("rescale")));
474         state->rescale = asLogical(tmp);
475
476         state->itemParam =
477                 omxNewMatrixFromSlot(rObj, globalState, "ItemParam");
478
479         if (estate->EitemParam->rows != state->itemParam->rows ||
480             estate->EitemParam->cols != state->itemParam->cols) {
481                 error("ItemParam and EItemParam matrices must be the same dimension");
482         }
483
484         state->customPrior =
485                 omxNewMatrixFromSlot(rObj, globalState, "CustomPrior");
486         
487         int maxParam = state->itemParam->rows;
488         state->derivPadSize = maxParam + maxParam*(1+maxParam)/2;
489
490         state->tmpLatentMean = Realloc(NULL, estate->maxDims, double);
491         state->tmpLatentCov = Realloc(NULL, estate->maxDims * estate->maxDims, double);
492
493         int numItems = state->itemParam->cols;
494         for (int ix=0; ix < numItems; ix++) {
495                 double *spec = omxMatrixColumn(estate->itemSpec, ix);
496                 int id = spec[RPF_ISpecID];
497                 if (id < 0 || id >= rpf_numModels) {
498                         error("ItemSpec column %d has unknown item model %d", ix, id);
499                 }
500         }
501 }