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