Change how dirty matrices are indicated
[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, mgSetFreeVarGroup},
60 };
61
62 void omxFreeFitFunctionArgs(omxFitFunction *off) {
63         if(off==NULL) return;
64     
65         /* Completely destroy the fit function structures */
66         if(OMX_DEBUG) {mxLog("Freeing fit function object at 0x%x.", off);}
67         if(off->matrix != NULL) {
68                 if(off->destructFun != NULL) {
69                         if(OMX_DEBUG) {mxLog("Calling fit function destructor for 0x%x.", off);}
70                         off->destructFun(off);
71                 }
72                 off->matrix = NULL;
73         }
74 }
75
76 void omxFitFunctionCreateChildren(omxState *globalState)
77 {
78         if (Global->numThreads <= 1) return;
79
80         int numThreads = Global->numChildren = Global->numThreads;
81
82         globalState->childList = (omxState**) Calloc(numThreads, omxState*);
83
84         for(int ii = 0; ii < numThreads; ii++) {
85                 globalState->childList[ii] = new omxState;
86                 omxInitState(globalState->childList[ii]);
87                 omxDuplicateState(globalState->childList[ii], globalState);
88         }
89 }
90
91 void omxDuplicateFitMatrix(omxMatrix *tgt, const omxMatrix *src, omxState* newState) {
92
93         if(tgt == NULL || src == NULL) return;
94
95         omxFitFunction *ff = src->fitFunction;
96         if(ff == NULL) return;
97     
98         omxFillMatrixFromMxFitFunction(tgt, ff->fitType, src->matrixNumber);
99         setFreeVarGroup(tgt->fitFunction, src->fitFunction->freeVarGroup);
100         tgt->fitFunction->rObj = ff->rObj;
101         omxCompleteFitFunction(tgt);
102 }
103
104 void omxFitFunctionCompute(omxFitFunction *off, int want, FitContext *fc)
105 {
106         if (!off->initialized) error("FitFunction not initialized");
107
108         if(OMX_DEBUG_ALGEBRA) { 
109                 mxLog("FitFunction compute: 0x%0x (needed: %s).", off,
110                       (omxMatrixIsDirty(off->matrix)?"Yes":"No"));
111         }
112
113         off->computeFun(off, want, fc);
114
115         omxMarkClean(off->matrix);
116 }
117
118 void defaultAddOutput(omxFitFunction* oo, MxRList *out)
119 {}
120
121 void omxFillMatrixFromMxFitFunction(omxMatrix* om, const char *fitType, int matrixNumber)
122 {
123         omxFitFunction *obj = (omxFitFunction*) R_alloc(1, sizeof(omxFitFunction));
124         memset(obj, 0, sizeof(omxFitFunction));
125
126         /* Register FitFunction and Matrix with each other */
127         obj->matrix = om;
128         omxResizeMatrix(om, 1, 1, FALSE);                                       // FitFunction matrices MUST be 1x1.
129         om->fitFunction = obj;
130         om->hasMatrixNumber = TRUE;
131         om->matrixNumber = matrixNumber;
132         
133         for (size_t fx=0; fx < OMX_STATIC_ARRAY_SIZE(omxFitFunctionSymbolTable); fx++) {
134                 const omxFitFunctionTableEntry *entry = omxFitFunctionSymbolTable + fx;
135                 if(strcmp(fitType, entry->name) == 0) {
136                         obj->fitType = entry->name;
137                         obj->initFun = entry->initFun;
138
139                         // We need to set up the FreeVarGroup before calling initFun
140                         // because older fit functions expect to know the number of
141                         // free variables during initFun.
142                         obj->setVarGroup = entry->setVarGroup; // ugh!
143                         obj->addOutput = defaultAddOutput;
144                         break;
145                 }
146         }
147
148         if (obj->initFun == NULL) error("Fit function %s not implemented", fitType);
149 }
150
151 void omxCompleteFitFunction(omxMatrix *om)
152 {
153         omxFitFunction *obj = om->fitFunction;
154         if (obj->initialized) return;
155         SEXP rObj = obj->rObj;
156
157         SEXP slotValue;
158         PROTECT(slotValue = GET_SLOT(rObj, install("expectation")));
159         if (LENGTH(slotValue) == 1) {
160                 int expNumber = INTEGER(slotValue)[0];  
161                 if(expNumber != NA_INTEGER) {
162                         obj->expectation = omxExpectationFromIndex(expNumber, om->currentState);
163                         setFreeVarGroup(obj->expectation, obj->freeVarGroup);
164                         omxCompleteExpectation(obj->expectation);
165                 }
166         }
167         UNPROTECT(1);   /* slotValue */
168         
169         obj->initFun(obj);
170
171         if(obj->computeFun == NULL) error("Failed to initialize fit function %s", obj->fitType); 
172         
173         omxMarkDirty(obj->matrix);
174         obj->initialized = TRUE;
175 }
176
177 void setFreeVarGroup(omxFitFunction *ff, FreeVarGroup *fvg)
178 {
179         (*ff->setVarGroup)(ff, fvg);
180 }
181
182 void omxFitFunctionPrint(omxFitFunction* off, const char* d) {
183         mxLog("(FitFunction, type %s)", off->fitType);
184         omxPrintMatrix(off->matrix, d);
185 }
186
187
188 /* Helper functions */
189 omxMatrix* omxNewMatrixFromSlot(SEXP rObj, omxState* currentState, const char* slotName) {
190         SEXP slotValue;
191         PROTECT(slotValue = GET_SLOT(rObj, install(slotName)));
192         omxMatrix* newMatrix = omxMatrixLookupFromState1(slotValue, currentState);
193         UNPROTECT(1);
194         return newMatrix;
195 }
196