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