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