Split BA81 into a fit function and expectation
[openmx:openmx.git] / src / omxFitFunction.cpp
1 /*
2  *  Copyright 2007-2013 The OpenMx Project
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *       http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  */
16
17 /***********************************************************
18
19 *  omxFitFunction.cc
20 *
21 *  Created: Timothy R. Brick    Date: 2008-11-13 12:33:06
22 *
23 *       FitFunction objects are a subclass of data matrix that evaluates
24 *   itself anew at each iteration, so that any changes to
25 *   free parameters can be incorporated into the update.
26 *   // Question: Should FitFunction be a ``subtype'' of 
27 *   // omxAlgebra or a separate beast entirely?
28 *
29 **********************************************************/
30
31 #include "omxFitFunction.h"
32 #include "fitMultigroup.h"
33
34 typedef struct omxFitFunctionTableEntry omxFitFunctionTableEntry;
35
36 struct omxFitFunctionTableEntry {
37
38         char name[32];
39         void (*initFun)(omxFitFunction*);
40         void (*setVarGroup)(omxFitFunction*, FreeVarGroup *);  // TODO ugh, just convert to C++
41
42 };
43
44 static void defaultSetFreeVarGroup(omxFitFunction *ff, FreeVarGroup *fvg)
45 {
46         if (ff->freeVarGroup && ff->freeVarGroup != fvg) {
47                 error("setFreeVarGroup called with different group on %p", ff);
48         }
49         ff->freeVarGroup = fvg;
50 }
51
52 static const omxFitFunctionTableEntry omxFitFunctionSymbolTable[] = {
53         {"MxFitFunctionAlgebra",                        &omxInitAlgebraFitFunction, defaultSetFreeVarGroup},
54         {"MxFitFunctionWLS",                            &omxInitWLSFitFunction, defaultSetFreeVarGroup},
55         {"MxFitFunctionRow",                            &omxInitRowFitFunction, defaultSetFreeVarGroup},
56         {"MxFitFunctionML",                             &omxInitMLFitFunction, defaultSetFreeVarGroup},
57         {"imxFitFunctionFIML", &omxInitFIMLFitFunction, defaultSetFreeVarGroup},
58         {"MxFitFunctionR",                                      &omxInitRFitFunction, defaultSetFreeVarGroup},
59         {"MxFitFunctionMultigroup", &initFitMultigroup, defaultSetFreeVarGroup},
60         {"MxFitFunctionBA81", &omxInitFitFunctionBA81, ba81SetFreeVarGroup}
61 };
62
63 void omxFreeFitFunctionArgs(omxFitFunction *off) {
64         if(off==NULL) return;
65     
66         /* Completely destroy the fit function structures */
67         if(OMX_DEBUG) {mxLog("Freeing fit function object at 0x%x.", off);}
68         if(off->matrix != NULL) {
69                 if(off->destructFun != NULL) {
70                         if(OMX_DEBUG) {mxLog("Calling fit function destructor for 0x%x.", off);}
71                         off->destructFun(off);
72                 }
73                 off->matrix = NULL;
74         }
75 }
76
77 void omxFitFunctionCreateChildren(omxState *globalState)
78 {
79         if (Global->numThreads <= 1) return;
80
81         int numThreads = Global->numChildren = Global->numThreads;
82
83         globalState->childList = (omxState**) Calloc(numThreads, omxState*);
84
85         for(int ii = 0; ii < numThreads; ii++) {
86                 globalState->childList[ii] = new omxState;
87                 omxInitState(globalState->childList[ii]);
88                 omxDuplicateState(globalState->childList[ii], globalState);
89         }
90 }
91
92 void omxDuplicateFitMatrix(omxMatrix *tgt, const omxMatrix *src, omxState* newState) {
93
94         if(tgt == NULL || src == NULL) return;
95
96         omxFitFunction *ff = src->fitFunction;
97         if(ff == NULL) return;
98     
99         omxFillMatrixFromMxFitFunction(tgt, ff->fitType, src->matrixNumber);
100         setFreeVarGroup(tgt->fitFunction, src->fitFunction->freeVarGroup);
101         tgt->fitFunction->rObj = ff->rObj;
102         omxCompleteFitFunction(tgt);
103 }
104
105 void omxFitFunctionCompute(omxFitFunction *off, int want, FitContext *fc)
106 {
107         if (!off->initialized) error("FitFunction not initialized");
108
109         if(OMX_DEBUG_ALGEBRA) { 
110             mxLog("FitFunction compute: 0x%0x (needed: %s).", off, (off->matrix->isDirty?"Yes":"No"));
111         }
112
113         off->computeFun(off, want, fc);
114
115         omxMarkClean(off->matrix);
116 }
117
118 void omxFillMatrixFromMxFitFunction(omxMatrix* om, const char *fitType, int matrixNumber)
119 {
120         omxFitFunction *obj = (omxFitFunction*) R_alloc(1, sizeof(omxFitFunction));
121         memset(obj, 0, sizeof(omxFitFunction));
122
123         /* Register FitFunction and Matrix with each other */
124         obj->matrix = om;
125         omxResizeMatrix(om, 1, 1, FALSE);                                       // FitFunction matrices MUST be 1x1.
126         om->fitFunction = obj;
127         om->hasMatrixNumber = TRUE;
128         om->matrixNumber = matrixNumber;
129         
130         for (size_t fx=0; fx < OMX_STATIC_ARRAY_SIZE(omxFitFunctionSymbolTable); fx++) {
131                 const omxFitFunctionTableEntry *entry = omxFitFunctionSymbolTable + fx;
132                 if(strcmp(fitType, entry->name) == 0) {
133                         obj->fitType = entry->name;
134                         obj->initFun = entry->initFun;
135                         obj->setVarGroup = entry->setVarGroup; // ugh!
136                         break;
137                 }
138         }
139
140         if (obj->initFun == NULL) error("Fit function %s not implemented", fitType);
141 }
142
143 void omxCompleteFitFunction(omxMatrix *om)
144 {
145         omxFitFunction *obj = om->fitFunction;
146         if (obj->initialized) return;
147         SEXP rObj = obj->rObj;
148
149         SEXP slotValue;
150         PROTECT(slotValue = GET_SLOT(rObj, install("expectation")));
151         if (LENGTH(slotValue) == 1) {
152                 int expNumber = INTEGER(slotValue)[0];  
153                 if(expNumber != NA_INTEGER) {
154                         obj->expectation = omxExpectationFromIndex(expNumber, om->currentState);
155                         setFreeVarGroup(obj->expectation, obj->freeVarGroup);
156                         omxCompleteExpectation(obj->expectation);
157                 }
158         }
159         UNPROTECT(1);   /* slotValue */
160         
161         obj->initFun(obj);
162
163         if(obj->computeFun == NULL) error("Failed to initialize fit function %s", obj->fitType); 
164         
165         obj->matrix->isDirty = TRUE;
166         obj->initialized = TRUE;
167 }
168
169 void setFreeVarGroup(omxFitFunction *ff, FreeVarGroup *fvg)
170 {
171         (*ff->setVarGroup)(ff, fvg);
172 }
173
174 void omxFitFunctionPrint(omxFitFunction* off, const char* d) {
175         mxLog("(FitFunction, type %s)", off->fitType);
176         omxPrintMatrix(off->matrix, d);
177 }
178
179
180 /* Helper functions */
181 omxMatrix* omxNewMatrixFromSlot(SEXP rObj, omxState* currentState, const char* slotName) {
182         SEXP slotValue;
183         PROTECT(slotValue = GET_SLOT(rObj, install(slotName)));
184         omxMatrix* newMatrix = omxMatrixLookupFromState1(slotValue, currentState);
185         UNPROTECT(1);
186         return newMatrix;
187 }
188