Remove fitMatrix from omxState
[openmx:openmx.git] / src / omxState.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 *  omxState.cc
20 *
21 *  Created: Timothy R. Brick    Date: 2009-06-05
22 *
23 *       omxStates carry the current optimization state
24 *
25 **********************************************************/
26
27 #include <stdarg.h>
28 #include "omxState.h"
29
30 /* Initialize and Destroy */
31         void omxInitState(omxState* state, omxState *parentState) {
32                 state->numHessians = 0;
33                 state->calculateStdErrors = FALSE;
34                 state->numAlgs = 0;
35                 state->numExpects = 0;
36                 state->numConstraints = 0;
37                 state->numFreeParams = 0;
38                 state->numChildren = 0;
39                 state->childList = NULL;
40                 state->algebraList = NULL;
41                 state->expectationList = NULL;
42                 state->parentState = parentState;
43                 state->conList = NULL;
44                 state->freeVarList = NULL;
45                 state->optimalValues = NULL;
46                 state->optimum = 9999999999;
47
48                 state->majorIteration = 0;
49                 state->minorIteration = 0;
50                 state->startTime = 0;
51                 state->endTime = 0;
52                 state->numCheckpoints = 0;
53                 state->checkpointList = NULL;
54                 state->chkptText1 = NULL;
55                 state->chkptText2 = NULL;
56
57         state->currentInterval = -1;
58
59                 state->computeCount = -1;
60                 state->currentRow = -1;
61
62                 state->statusCode = 0;
63                 strncpy(state->statusMsg, "", 1);
64         }
65
66         omxState* omxGetState(omxState* os, int stateNumber) {
67                 // TODO: Need to implement a smarter way to enumerate children
68                 if(stateNumber == 0) return os;
69                 if((stateNumber-1) < os->numChildren) {
70                         return(os->childList[stateNumber-1]);
71                 } else {
72                         error("Not implemented");
73                         // TODO: Account for unequal numbers of grandchild states
74                         int subState = (stateNumber - os->numChildren - 1);
75                         return omxGetState(os->childList[subState % os->numChildren], subState / os->numChildren);
76                 }
77         }
78
79         void omxSetMajorIteration(omxState *state, int value) {
80                 state->majorIteration = value;
81                 for(int i = 0; i < state->numChildren; i++) {
82                         omxSetMajorIteration(state->childList[i], value);
83                 }
84         }
85
86         void omxSetMinorIteration(omxState *state, int value) {
87                 state->minorIteration = value;
88                 for(int i = 0; i < state->numChildren; i++) {
89                         omxSetMinorIteration(state->childList[i], value);
90                 }
91         }
92         
93         void omxDuplicateState(omxState* tgt, omxState* src) {
94                 tgt->numAlgs                    = src->numAlgs;
95                 tgt->numExpects                 = src->numExpects;
96                 tgt->dataList                   = src->dataList;
97                 tgt->numChildren                = 0;
98                 
99                 // Duplicate matrices and algebras and build parentLists.
100                 tgt->parentState                = src;
101                 tgt->expectationList    = (omxExpectation**) R_alloc(tgt->numExpects, sizeof(omxExpectation*));
102                 tgt->algebraList                = (omxMatrix**) R_alloc(tgt->numAlgs, sizeof(omxMatrix*));
103                 tgt->markMatrices               = src->markMatrices; // TODO, unused in children?
104                                 
105                 memset(tgt->algebraList, 0, sizeof(omxMatrix*) * tgt->numAlgs);
106                 memset(tgt->expectationList, 0, sizeof(omxExpectation*) * tgt->numExpects);
107
108                 for(size_t mx = 0; mx < src->matrixList.size(); mx++) {
109                         // TODO: Smarter inference for which matrices to duplicate
110                         tgt->matrixList.push_back(omxDuplicateMatrix(src->matrixList[mx], tgt));
111                 }
112
113                 tgt->numConstraints     = src->numConstraints;
114                 tgt->conList                    = (omxConstraint*) R_alloc(tgt->numConstraints, sizeof(omxConstraint));
115                 for(int j = 0; j < tgt->numConstraints; j++) {
116                         tgt->conList[j].size   = src->conList[j].size;
117                         tgt->conList[j].opCode = src->conList[j].opCode;
118                         tgt->conList[j].lbound = src->conList[j].lbound;
119                         tgt->conList[j].ubound = src->conList[j].ubound;
120                         tgt->conList[j].result = omxDuplicateMatrix(src->conList[j].result, tgt);
121                 }
122
123                 for(int j = 0; j < tgt->numAlgs; j++) {
124                         // TODO: Smarter inference for which algebras to duplicate
125                         tgt->algebraList[j] = omxDuplicateMatrix(src->algebraList[j], tgt);
126                 }
127
128                 for(int j = 0; j < tgt->numExpects; j++) {
129                         // TODO: Smarter inference for which expectations to duplicate
130                         tgt->expectationList[j] = omxDuplicateExpectation(src->expectationList[j], tgt);
131                 }
132
133                 for(int j = 0; j < tgt->numAlgs; j++) {
134                         omxDuplicateAlgebra(tgt->algebraList[j], src->algebraList[j], tgt);
135                 }
136
137                 for(int j = 0; j < tgt->numExpects; j++) {
138                         // TODO: Smarter inference for which expectations to duplicate
139                         omxCompleteExpectation(tgt->expectationList[j]);
140                 }
141
142                 tgt->childList                  = NULL;
143
144                 tgt->numFreeParams                      = src->numFreeParams;
145                 tgt->freeVarList                = new omxFreeVar[tgt->numFreeParams];
146                 for(int j = 0; j < tgt->numFreeParams; j++) {
147                         int numDeps                                                     = src->freeVarList[j].numDeps;
148
149                         tgt->freeVarList[j].lbound                      = src->freeVarList[j].lbound;
150                         tgt->freeVarList[j].ubound                      = src->freeVarList[j].ubound;
151                         tgt->freeVarList[j].locations                   = src->freeVarList[j].locations;
152                         tgt->freeVarList[j].numDeps                     = numDeps;
153                         
154                         tgt->freeVarList[j].deps                        = (int*) R_alloc(numDeps, sizeof(int));
155
156                         tgt->freeVarList[j].name                = src->freeVarList[j].name;
157
158                         for(int k = 0; k < numDeps; k++) {
159                                 tgt->freeVarList[j].deps[k] = src->freeVarList[j].deps[k];
160                         }
161                 }
162                 
163                 tgt->optimalValues              = src->optimalValues;
164                 tgt->optimum                    = 9999999999;
165                                   
166                 tgt->majorIteration     = 0;
167                 tgt->minorIteration     = 0;
168                 tgt->startTime                  = src->startTime;
169                 tgt->endTime                    = 0;
170                 
171                 // TODO: adjust checkpointing based on parallelization method
172                 tgt->numCheckpoints     = 0;
173                 tgt->checkpointList     = NULL;
174                 tgt->chkptText1                 = NULL;
175                 tgt->chkptText2                 = NULL;
176                                   
177                 tgt->computeCount               = src->computeCount;
178                 tgt->currentRow                 = src->currentRow;
179
180                 tgt->statusCode                 = 0;
181                 strncpy(tgt->statusMsg, "", 1);
182         }
183
184         omxMatrix* omxLookupDuplicateElement(omxState* os, omxMatrix* element) {
185                 if(os == NULL || element == NULL) return NULL;
186
187                 if (element->hasMatrixNumber) {
188                         int matrixNumber = element->matrixNumber;
189                         if (matrixNumber >= 0) {
190                                 return(os->algebraList[matrixNumber]);
191                         } else {
192                                 return(os->matrixList[-matrixNumber - 1]);
193                         }
194                 }
195
196                 omxConstraint* parentConList = os->parentState->conList;
197
198                 for(int i = 0; i < os->numConstraints; i++) {
199                         if(parentConList[i].result == element) {
200                                 if(os->conList[i].result != NULL) {   // Not sure of proper failure behavior here.
201                 return(os->conList[i].result);
202                                 } else {
203                     omxRaiseError(os, -2, "Initialization Copy Error: Constraint required but not yet processed.");
204             }
205                         }
206                 }
207
208                 return NULL;
209         }
210         
211         omxExpectation* omxLookupDuplicateExpectation(omxState* os, omxExpectation* ox) {
212                 if(os == NULL || ox == NULL) return NULL;
213
214                 return(os->expectationList[ox->expNum]);
215         }
216
217         void omxFreeState(omxState *state) {
218                 int k;
219
220                 if (state->numChildren > 0) {
221                         for(k = 0; k < state->numChildren; k++) {
222                                 // Data are not modified and not copied. The same memory
223                                 // is shared across all instances of state. We only need
224                                 // to free the data once, so let the parent do it.
225                                 state->childList[k]->dataList.clear();
226
227                                 omxFreeState(state->childList[k]);
228                         }
229                         Free(state->childList);
230                         state->childList = NULL;
231                         state->numChildren = 0;
232                 }
233
234                 if(OMX_DEBUG) { Rprintf("Freeing %d Algebras.\n", state->numAlgs);}
235                 for(k = 0; k < state->numAlgs; k++) {
236                         if(OMX_DEBUG) { Rprintf("Freeing Algebra %d at 0x%x.\n", k, state->algebraList[k]); }
237                         omxFreeAllMatrixData(state->algebraList[k]);
238                 }
239
240                 if(OMX_DEBUG) { Rprintf("Freeing %d Matrices.\n", state->matrixList.size());}
241                 for(size_t mk = 0; mk < state->matrixList.size(); mk++) {
242                         if(OMX_DEBUG) { Rprintf("Freeing Matrix %d at 0x%x.\n", mk, state->matrixList[mk]); }
243                         omxFreeAllMatrixData(state->matrixList[mk]);
244                 }
245                 
246                 if(OMX_DEBUG) { Rprintf("Freeing %d Model Expectations.\n", state->numExpects);}
247                 for(k = 0; k < state->numExpects; k++) {
248                         if(OMX_DEBUG) { Rprintf("Freeing Expectation %d at 0x%x.\n", k, state->expectationList[k]); }
249                         omxFreeExpectationArgs(state->expectationList[k]);
250                 }
251
252                 if(OMX_DEBUG) { Rprintf("Freeing %d Constraints.\n", state->numConstraints);}
253                 for(k = 0; k < state->numConstraints; k++) {
254                         if(OMX_DEBUG) { Rprintf("Freeing Constraint %d at 0x%x.\n", k, state->conList[k]); }
255                         omxFreeAllMatrixData(state->conList[k].result);
256                 }
257
258                 if(OMX_DEBUG) { Rprintf("Freeing %d Data Sets.\n", state->dataList.size());}
259                 for(size_t dx = 0; dx < state->dataList.size(); dx++) {
260                         if(OMX_DEBUG) { Rprintf("Freeing Data Set %d at 0x%x.\n", dx, state->dataList[dx]); }
261                         omxFreeData(state->dataList[dx]);
262                 }
263
264                 delete [] state->freeVarList;
265
266         if(OMX_DEBUG) {Rprintf("Freeing %d Children.\n", state->numChildren);}
267         for(k = 0; k < state->numChildren; k++) {
268                         if(OMX_DEBUG) { Rprintf("Freeing Child State %d at 0x%x.\n", k, state->childList[k]); }
269                         omxFreeState(state->childList[k]);            
270         }
271
272                 if(OMX_DEBUG) { Rprintf("Freeing %d Checkpoints.\n", state->numCheckpoints);}
273                 for(k = 0; k < state->numCheckpoints; k++) {
274                         if(OMX_DEBUG) { Rprintf("Freeing Data Set %d at 0x%x.\n", k, state->checkpointList[k]); }
275                         omxCheckpoint oC = state->checkpointList[k];
276                         switch(oC.type) {
277                                 case OMX_FILE_CHECKPOINT:
278                                         fclose(oC.file);
279                                         break;
280                                 case OMX_CONNECTION_CHECKPOINT: // NYI :::DEBUG:::
281                                         // Do nothing: this should be handled by R upon return.
282                                         break;
283                         }
284                         if(state->chkptText1 != NULL) {
285                                 Free(state->chkptText1);
286                         }
287                         if(state->chkptText2 != NULL) {
288                                 Free(state->chkptText2);
289                         }
290                         // Checkpoint list itself is freed by R.
291                 }
292
293                 delete state;
294
295                 if(OMX_DEBUG) { Rprintf("State Freed.\n");}
296         }
297
298         void omxSaveState(omxState *os, double* freeVals, double minimum) {
299                 if(os->optimalValues == NULL) {
300                         os->optimalValues = (double*) R_alloc(os->numFreeParams, sizeof(double));
301                 }
302
303                 for(int i = 0; i < os->numFreeParams; i++) {
304                         os->optimalValues[i] = freeVals[i];
305                 }
306                 os->optimum = minimum;
307         }
308
309         void omxResetStatus(omxState *state) {
310                 int numChildren = state->numChildren;
311                 state->statusCode = 0;
312                 state->statusMsg[0] = '\0';
313                 for(int i = 0; i < numChildren; i++) {
314                         omxResetStatus(state->childList[i]);
315                 }
316         }
317
318 void omxRaiseErrorf(omxState *state, const char* errorMsg, ...)
319 {
320         va_list ap;
321         va_start(ap, errorMsg);
322         int fit = vsnprintf(state->statusMsg, MAX_STRING_LEN, errorMsg, ap);
323         va_end(ap);
324         if(OMX_DEBUG) {
325                 if (!(fit > -1 && fit < MAX_STRING_LEN)) {
326                         Rprintf("Error exceeded maximum length: %s\n", errorMsg);
327                 } else {
328                         Rprintf("Error raised: %s\n", state->statusMsg);
329                 }
330         }
331         state->statusCode = -1;  // this provides no additional information beyond errorMsg[0]!=0 TODO
332 }
333
334         void omxRaiseError(omxState *state, int errorCode, const char* errorMsg) {
335                 if(OMX_DEBUG && errorCode) { Rprintf("Error %d raised: %s\n", errorCode, errorMsg);}
336                 if(OMX_DEBUG && !errorCode) { Rprintf("Error status cleared."); }
337                 state->statusCode = errorCode;
338                 strncpy(state->statusMsg, errorMsg, 249);
339                 state->statusMsg[249] = '\0';
340                 if(state->computeCount <= 0 && errorCode < 0) {
341                         state->statusCode--;                    // Decrement status for init errors.
342                 }
343         }
344
345         void omxStateNextRow(omxState *state) {
346                 state->currentRow++;
347         };
348
349         void omxStateNextEvaluation(omxState *state) {
350                 state->currentRow = -1;
351                 state->computeCount++;
352         };
353
354         void omxWriteCheckpointHeader(omxState *os, omxCheckpoint* oC) {
355                 // FIXME: Is it faster to allocate this on the stack?
356                 os->chkptText1 = (char*) Calloc((24 + 15 * os->numFreeParams), char);
357                 os->chkptText2 = (char*) Calloc(1.0 + 15.0 * os->numFreeParams*
358                         (os->numFreeParams + 1.0) / 2.0, char);
359                 if (oC->type == OMX_FILE_CHECKPOINT) {
360                         fprintf(oC->file, "iterations\ttimestamp\tobjective\t");
361                         for(int j = 0; j < os->numFreeParams; j++) {
362                                 if(strcmp(os->freeVarList[j].name, CHAR(NA_STRING)) == 0) {
363                                         fprintf(oC->file, "%s", os->freeVarList[j].name);
364                                 } else {
365                                         fprintf(oC->file, "\"%s\"", os->freeVarList[j].name);
366                                 }
367                                 if (j != os->numFreeParams - 1) fprintf(oC->file, "\t");
368                         }
369                         fprintf(oC->file, "\n");
370                         fflush(oC->file);
371                 }
372         }
373  
374         void omxWriteCheckpointMessage(omxState *os, char *msg) {
375                 for(int i = 0; i < os->numCheckpoints; i++) {
376                         omxCheckpoint* oC = &(os->checkpointList[i]);
377                         if(os->chkptText1 == NULL) {    // First one: set up output
378                                 omxWriteCheckpointHeader(os, oC);
379                         }
380                         if (oC->type == OMX_FILE_CHECKPOINT) {
381                                 fprintf(oC->file, "%d \"%s\" NA ", os->majorIteration, msg);
382                                 for(int j = 0; j < os->numFreeParams; j++) {
383                                         fprintf(oC->file, "NA ");
384                                 }
385                                 fprintf(oC->file, "\n");
386                         }
387                 }
388         }
389
390         void omxSaveCheckpoint(omxState *os, double* x, double* f, int force) {
391                 time_t now = time(NULL);
392                 int soFar = now - os->startTime;                // Translated into minutes
393                 int n;
394                 for(int i = 0; i < os->numCheckpoints; i++) {
395                         n = 0;
396                         omxCheckpoint* oC = &(os->checkpointList[i]);
397                         // Check based on time            
398                         if((oC->time > 0 && (soFar - oC->lastCheckpoint) >= oC->time) || force) {
399                                 oC->lastCheckpoint = soFar;
400                                 n = 1;
401                         }
402                         // Or iterations
403                         if((oC->numIterations > 0 && (os->majorIteration - oC->lastCheckpoint) >= oC->numIterations) || force) {
404                                 oC->lastCheckpoint = os->majorIteration;
405                                 n = 1;
406                         }
407
408                         if(n) {         //In either case, save a checkpoint.
409                                 if(os->chkptText1 == NULL) {    // First one: set up output
410                                         omxWriteCheckpointHeader(os, oC);
411                                 }
412                                 char tempstring[25];
413                                 sprintf(tempstring, "%d", os->majorIteration);
414
415                                 if(strncmp(os->chkptText1, tempstring, strlen(tempstring))) {   // Returns zero if they're the same.
416                                         struct tm * nowTime = localtime(&now);                                          // So this only happens if the text is out of date.
417                                         strftime(tempstring, 25, "%b %d %Y %I:%M:%S %p", nowTime);
418                                         sprintf(os->chkptText1, "%d \"%s\" %9.5f", os->majorIteration, tempstring, f[0]);
419                                         for(int j = 0; j < os->numFreeParams; j++) {
420                                                 sprintf(tempstring, " %9.5f", x[j]);
421                                                 strncat(os->chkptText1, tempstring, 14);
422                                         }
423                                 }
424
425                                 if(oC->type == OMX_FILE_CHECKPOINT) {
426                                         fprintf(oC->file, "%s", os->chkptText1);
427                                         if(oC->saveHessian)
428                                                 fprintf(oC->file, "%s", os->chkptText2);
429                                         fprintf(oC->file, "\n");
430                                         fflush(oC->file);
431                                 } else if(oC->type == OMX_CONNECTION_CHECKPOINT) {
432                                         warning("NYI: R_connections are not yet implemented.");
433                                         oC->numIterations = 0;
434                                         oC->time = 0;
435                                 }
436                         }
437                 }
438         }
439
440 void omxExamineFitOutput(omxState *state, omxMatrix *fitMatrix, int *mode)
441 {
442         if (!R_FINITE(fitMatrix->data[0])) {
443                 omxRaiseErrorf(state, "Fit function returned %g at iteration %d.%d",
444                                fitMatrix->data[0], state->majorIteration, state->minorIteration);
445                 *mode = -1;
446         }
447 }