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