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