Enable R_NO_REMAP for a cleaner namespace
[openmx:openmx.git] / src / omxFitFunction.cpp
1 /*
2  *  Copyright 2007-2014 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                 Rf_warning("%s: setFreeVarGroup called with different group (%d vs %d)",
48                         ff->matrix->name, ff->freeVarGroup->id[0], fvg->id[0]);
49         }
50         ff->freeVarGroup = fvg;
51 }
52
53 static const omxFitFunctionTableEntry omxFitFunctionSymbolTable[] = {
54         {"MxFitFunctionAlgebra",                        &omxInitAlgebraFitFunction, defaultSetFreeVarGroup},
55         {"MxFitFunctionWLS",                            &omxInitWLSFitFunction, defaultSetFreeVarGroup},
56         {"MxFitFunctionRow",                            &omxInitRowFitFunction, defaultSetFreeVarGroup},
57         {"MxFitFunctionML",                             &omxInitMLFitFunction, defaultSetFreeVarGroup},
58         {"imxFitFunctionFIML", &omxInitFIMLFitFunction, defaultSetFreeVarGroup},
59         {"MxFitFunctionR",                                      &omxInitRFitFunction, defaultSetFreeVarGroup},
60         {"MxFitFunctionMultigroup", &initFitMultigroup, mgSetFreeVarGroup},
61 };
62
63 void omxFreeFitFunctionArgs(omxFitFunction *off) {
64         if(off==NULL) return;
65     
66         /* Completely destroy the fit function structures */
67         if(off->matrix != NULL) {
68                 if (off->destructFun) off->destructFun(off);
69                 off->matrix = NULL;
70         }
71 }
72
73 void omxFitFunctionCreateChildren(omxState *globalState)
74 {
75         if (Global->numThreads <= 1) return;
76
77         int numThreads = Global->numChildren = Global->numThreads;
78
79         globalState->childList = (omxState**) Calloc(numThreads, omxState*);
80
81         for(int ii = 0; ii < numThreads; ii++) {
82                 globalState->childList[ii] = new omxState;
83                 omxInitState(globalState->childList[ii]);
84                 omxDuplicateState(globalState->childList[ii], globalState);
85         }
86 }
87
88 void omxDuplicateFitMatrix(omxMatrix *tgt, const omxMatrix *src, omxState* newState) {
89
90         if(tgt == NULL || src == NULL) return;
91
92         omxFitFunction *ff = src->fitFunction;
93         if(ff == NULL) return;
94     
95         omxFillMatrixFromMxFitFunction(tgt, ff->fitType, src->matrixNumber);
96         setFreeVarGroup(tgt->fitFunction, src->fitFunction->freeVarGroup);
97         tgt->fitFunction->rObj = ff->rObj;
98         omxCompleteFitFunction(tgt);
99 }
100
101 void omxFitFunctionCompute(omxFitFunction *off, int want, FitContext *fc)
102 {
103         if (!off->initialized) Rf_error("FitFunction not initialized");
104
105         off->computeFun(off, want, fc);
106         if (fc) fc->wanted |= want;
107
108         omxMarkClean(off->matrix);
109 }
110
111 void defaultAddOutput(omxFitFunction* oo, MxRList *out)
112 {}
113
114 void omxFillMatrixFromMxFitFunction(omxMatrix* om, const char *fitType, int matrixNumber)
115 {
116         omxFitFunction *obj = (omxFitFunction*) R_alloc(1, sizeof(omxFitFunction));
117         memset(obj, 0, sizeof(omxFitFunction));
118
119         /* Register FitFunction and Matrix with each other */
120         obj->matrix = om;
121         omxResizeMatrix(om, 1, 1, FALSE);                                       // FitFunction matrices MUST be 1x1.
122         om->fitFunction = obj;
123         om->hasMatrixNumber = TRUE;
124         om->matrixNumber = matrixNumber;
125         
126         for (size_t fx=0; fx < OMX_STATIC_ARRAY_SIZE(omxFitFunctionSymbolTable); fx++) {
127                 const omxFitFunctionTableEntry *entry = omxFitFunctionSymbolTable + fx;
128                 if(strcmp(fitType, entry->name) == 0) {
129                         obj->fitType = entry->name;
130                         obj->initFun = entry->initFun;
131
132                         // We need to set up the FreeVarGroup before calling initFun
133                         // because older fit functions expect to know the number of
134                         // free variables during initFun.
135                         obj->setVarGroup = entry->setVarGroup; // ugh!
136                         obj->addOutput = defaultAddOutput;
137                         break;
138                 }
139         }
140
141         if (obj->initFun == NULL) Rf_error("Fit function %s not implemented", fitType);
142 }
143
144 void omxCompleteFitFunction(omxMatrix *om)
145 {
146         omxFitFunction *obj = om->fitFunction;
147         if (obj->initialized) return;
148         SEXP rObj = obj->rObj;
149
150         SEXP slotValue;
151         Rf_protect(slotValue = R_do_slot(rObj, Rf_install("expectation")));
152         if (LENGTH(slotValue) == 1) {
153                 int expNumber = INTEGER(slotValue)[0];  
154                 if(expNumber != NA_INTEGER) {
155                         obj->expectation = omxExpectationFromIndex(expNumber, om->currentState);
156                         setFreeVarGroup(obj->expectation, obj->freeVarGroup);
157                         omxCompleteExpectation(obj->expectation);
158                 }
159         }
160         Rf_unprotect(1);        /* slotValue */
161         
162         obj->initFun(obj);
163
164         if(obj->computeFun == NULL) Rf_error("Failed to initialize fit function %s", obj->fitType); 
165         
166         omxMarkDirty(obj->matrix);
167         obj->initialized = TRUE;
168 }
169
170 void setFreeVarGroup(omxFitFunction *ff, FreeVarGroup *fvg)
171 {
172         (*ff->setVarGroup)(ff, fvg);
173 }
174
175 void omxFitFunctionPrint(omxFitFunction* off, const char* d) {
176         mxLog("(FitFunction, type %s)", off->fitType);
177         omxPrintMatrix(off->matrix, d);
178 }
179
180
181 /* Helper functions */
182 omxMatrix* omxNewMatrixFromSlot(SEXP rObj, omxState* currentState, const char* slotName) {
183         SEXP slotValue;
184         Rf_protect(slotValue = R_do_slot(rObj, Rf_install(slotName)));
185         omxMatrix* newMatrix = omxMatrixLookupFromState1(slotValue, currentState);
186         Rf_unprotect(1);
187         return newMatrix;
188 }
189