Revert "Store expectationList in std::vector"
[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->numExpects = 0;
33                 state->numConstraints = 0;
34                 state->numFreeParams = 0;
35                 state->numChildren = 0;
36                 state->childList = NULL;
37                 state->expectationList = NULL;
38                 state->parentState = parentState;
39                 state->fitMatrix = NULL;
40                 state->hessian = NULL;
41                 state->conList = NULL;
42                 state->freeVarList = NULL;
43                 state->optimalValues = NULL;
44                 state->optimum = 9999999999;
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->currentInterval = -1;
56
57                 state->computeCount = -1;
58                 state->currentRow = -1;
59
60                 state->statusCode = 0;
61                 strncpy(state->statusMsg, "", 1);
62         }
63
64         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList,
65                                                 omxMatrix** algebraList, omxData** dataList, omxMatrix* fitFunction) {
66                 error("NYI: Can't fill a state from outside yet. Besides, do you really need a single function to do this?");
67         }
68         
69         omxState* omxGetState(omxState* os, int stateNumber) {
70                 // TODO: Need to implement a smarter way to enumerate children
71                 if(stateNumber == 0) return os;
72                 if((stateNumber-1) < os->numChildren) {
73                         return(os->childList[stateNumber-1]);
74                 } else {
75                         error("Not implemented");
76                         // TODO: Account for unequal numbers of grandchild states
77                         int subState = (stateNumber - os->numChildren - 1);
78                         return omxGetState(os->childList[subState % os->numChildren], subState / os->numChildren);
79                 }
80         }
81
82         void omxSetMajorIteration(omxState *state, int value) {
83                 state->majorIteration = value;
84                 for(int i = 0; i < state->numChildren; i++) {
85                         omxSetMajorIteration(state->childList[i], value);
86                 }
87         }
88
89         void omxSetMinorIteration(omxState *state, int value) {
90                 state->minorIteration = value;
91                 for(int i = 0; i < state->numChildren; i++) {
92                         omxSetMinorIteration(state->childList[i], value);
93                 }
94         }
95         
96         void omxDuplicateState(omxState* tgt, omxState* src) {
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->markMatrices               = src->markMatrices; // TODO, unused in children?
105                                 
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(size_t j = 0; j < tgt->algebraList.size(); j++) {
124                         // TODO: Smarter inference for which algebras to duplicate
125                         tgt->algebraList.push_back(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(size_t j = 0; j < tgt->algebraList.size(); 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->fitMatrix  = omxLookupDuplicateElement(tgt, src->fitMatrix);
145                 tgt->hessian                    = src->hessian;
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         int omxCountLeafNodes(omxState *state) {
221                 int children = state->numChildren;
222                 if (children == 0) {
223                         return(1);
224                 } else {
225                         int sum = 0;
226                         for(int i = 0; i < children; i++) {
227                                 sum += omxCountLeafNodes(state->childList[i]);
228                         }
229                         return(sum);
230                 }
231         }
232
233         /* Traverse to the root of the state hierarchy,
234          * and then count the number of leaf nodes */
235         int omxTotalThreadCount(omxState *state) {
236
237                 while(state->parentState != NULL) {
238                         state = state->parentState;
239                 }
240         
241                 return(omxCountLeafNodes(state));
242         }
243
244         void omxFreeState(omxState *state) {
245                 int k;
246
247                 if (state->numChildren > 0) {
248                         for(k = 0; k < state->numChildren; k++) {
249                                 // Data are not modified and not copied. The same memory
250                                 // is shared across all instances of state. We only need
251                                 // to free the data once, so let the parent do it.
252                                 state->childList[k]->dataList.clear();
253
254                                 omxFreeState(state->childList[k]);
255                         }
256                         Free(state->childList);
257                         state->childList = NULL;
258                         state->numChildren = 0;
259                 }
260
261                 for(size_t ax = 0; ax < state->algebraList.size(); ax++) {
262                         if(OMX_DEBUG) { Rprintf("Freeing Algebra %d at 0x%x.\n", ax, state->algebraList[ax]); }
263                         omxFreeAllMatrixData(state->algebraList[ax]);
264                 }
265
266                 if(OMX_DEBUG) { Rprintf("Freeing %d Matrices.\n", state->matrixList.size());}
267                 for(size_t mk = 0; mk < state->matrixList.size(); mk++) {
268                         if(OMX_DEBUG) { Rprintf("Freeing Matrix %d at 0x%x.\n", mk, state->matrixList[mk]); }
269                         omxFreeAllMatrixData(state->matrixList[mk]);
270                 }
271                 
272                 if(OMX_DEBUG) { Rprintf("Freeing %d Model Expectations.\n", state->numExpects);}
273                 for(k = 0; k < state->numExpects; k++) {
274                         if(OMX_DEBUG) { Rprintf("Freeing Expectation %d at 0x%x.\n", k, state->expectationList[k]); }
275                         omxFreeExpectationArgs(state->expectationList[k]);
276                 }
277
278                 if(OMX_DEBUG) { Rprintf("Freeing %d Constraints.\n", state->numConstraints);}
279                 for(k = 0; k < state->numConstraints; k++) {
280                         if(OMX_DEBUG) { Rprintf("Freeing Constraint %d at 0x%x.\n", k, state->conList[k]); }
281                         omxFreeAllMatrixData(state->conList[k].result);
282                 }
283
284                 if(OMX_DEBUG) { Rprintf("Freeing %d Data Sets.\n", state->dataList.size());}
285                 for(size_t dx = 0; dx < state->dataList.size(); dx++) {
286                         if(OMX_DEBUG) { Rprintf("Freeing Data Set %d at 0x%x.\n", dx, state->dataList[dx]); }
287                         omxFreeData(state->dataList[dx]);
288                 }
289
290                 delete [] state->freeVarList;
291
292         if(OMX_DEBUG) {Rprintf("Freeing %d Children.\n", state->numChildren);}
293         for(k = 0; k < state->numChildren; k++) {
294                         if(OMX_DEBUG) { Rprintf("Freeing Child State %d at 0x%x.\n", k, state->childList[k]); }
295                         omxFreeState(state->childList[k]);            
296         }
297
298                 if(OMX_DEBUG) { Rprintf("Freeing %d Checkpoints.\n", state->numCheckpoints);}
299                 for(k = 0; k < state->numCheckpoints; k++) {
300                         if(OMX_DEBUG) { Rprintf("Freeing Data Set %d at 0x%x.\n", k, state->checkpointList[k]); }
301                         omxCheckpoint oC = state->checkpointList[k];
302                         switch(oC.type) {
303                                 case OMX_FILE_CHECKPOINT:
304                                         fclose(oC.file);
305                                         break;
306                                 case OMX_CONNECTION_CHECKPOINT: // NYI :::DEBUG:::
307                                         // Do nothing: this should be handled by R upon return.
308                                         break;
309                         }
310                         if(state->chkptText1 != NULL) {
311                                 Free(state->chkptText1);
312                         }
313                         if(state->chkptText2 != NULL) {
314                                 Free(state->chkptText2);
315                         }
316                         // Checkpoint list itself is freed by R.
317                 }
318
319                 delete state;
320
321                 if(OMX_DEBUG) { Rprintf("State Freed.\n");}
322         }
323
324         void omxSaveState(omxState *os, double* freeVals, double minimum) {
325                 if(os->optimalValues == NULL) {
326                         os->optimalValues = (double*) R_alloc(os->numFreeParams, sizeof(double));
327                 }
328
329                 for(int i = 0; i < os->numFreeParams; i++) {
330                         os->optimalValues[i] = freeVals[i];
331                 }
332                 os->optimum = minimum;
333                 os->optimumStatus = os->statusCode;
334                 strncpy(os->optimumMsg, os->statusMsg, 250);
335         }
336
337         void omxResetStatus(omxState *state) {
338                 int numChildren = state->numChildren;
339                 state->statusCode = 0;
340                 state->statusMsg[0] = '\0';
341                 for(int i = 0; i < numChildren; i++) {
342                         omxResetStatus(state->childList[i]);
343                 }
344         }
345
346 void omxRaiseErrorf(omxState *state, const char* errorMsg, ...)
347 {
348         va_list ap;
349         va_start(ap, errorMsg);
350         int fit = vsnprintf(state->statusMsg, MAX_STRING_LEN, errorMsg, ap);
351         va_end(ap);
352         if(OMX_DEBUG) {
353                 if (!(fit > -1 && fit < MAX_STRING_LEN)) {
354                         Rprintf("Error exceeded maximum length: %s\n", errorMsg);
355                 } else {
356                         Rprintf("Error raised: %s\n", state->statusMsg);
357                 }
358         }
359         state->statusCode = -1;  // this provides no additional information beyond errorMsg[0]!=0 TODO
360 }
361
362         void omxRaiseError(omxState *state, int errorCode, const char* errorMsg) {
363                 if(OMX_DEBUG && errorCode) { Rprintf("Error %d raised: %s\n", errorCode, errorMsg);}
364                 if(OMX_DEBUG && !errorCode) { Rprintf("Error status cleared."); }
365                 state->statusCode = errorCode;
366                 strncpy(state->statusMsg, errorMsg, 249);
367                 state->statusMsg[249] = '\0';
368                 if(state->computeCount <= 0 && errorCode < 0) {
369                         state->statusCode--;                    // Decrement status for init errors.
370                 }
371         }
372
373         void omxStateNextRow(omxState *state) {
374                 state->currentRow++;
375         };
376
377         void omxStateNextEvaluation(omxState *state) {
378                 state->currentRow = -1;
379                 state->computeCount++;
380         };
381
382         void omxWriteCheckpointHeader(omxState *os, omxCheckpoint* oC) {
383                 // FIXME: Is it faster to allocate this on the stack?
384                 os->chkptText1 = (char*) Calloc((24 + 15 * os->numFreeParams), char);
385                 os->chkptText2 = (char*) Calloc(1.0 + 15.0 * os->numFreeParams*
386                         (os->numFreeParams + 1.0) / 2.0, char);
387                 if (oC->type == OMX_FILE_CHECKPOINT) {
388                         fprintf(oC->file, "iterations\ttimestamp\tobjective\t");
389                         for(int j = 0; j < os->numFreeParams; j++) {
390                                 if(strcmp(os->freeVarList[j].name, CHAR(NA_STRING)) == 0) {
391                                         fprintf(oC->file, "%s", os->freeVarList[j].name);
392                                 } else {
393                                         fprintf(oC->file, "\"%s\"", os->freeVarList[j].name);
394                                 }
395                                 if (j != os->numFreeParams - 1) fprintf(oC->file, "\t");
396                         }
397                         fprintf(oC->file, "\n");
398                         fflush(oC->file);
399                 }
400         }
401  
402         void omxWriteCheckpointMessage(omxState *os, char *msg) {
403                 for(int i = 0; i < os->numCheckpoints; i++) {
404                         omxCheckpoint* oC = &(os->checkpointList[i]);
405                         if(os->chkptText1 == NULL) {    // First one: set up output
406                                 omxWriteCheckpointHeader(os, oC);
407                         }
408                         if (oC->type == OMX_FILE_CHECKPOINT) {
409                                 fprintf(oC->file, "%d \"%s\" NA ", os->majorIteration, msg);
410                                 for(int j = 0; j < os->numFreeParams; j++) {
411                                         fprintf(oC->file, "NA ");
412                                 }
413                                 fprintf(oC->file, "\n");
414                         }
415                 }
416         }
417
418         void omxSaveCheckpoint(omxState *os, double* x, double* f, int force) {
419                 time_t now = time(NULL);
420                 int soFar = now - os->startTime;                // Translated into minutes
421                 int n;
422                 for(int i = 0; i < os->numCheckpoints; i++) {
423                         n = 0;
424                         omxCheckpoint* oC = &(os->checkpointList[i]);
425                         // Check based on time            
426                         if((oC->time > 0 && (soFar - oC->lastCheckpoint) >= oC->time) || force) {
427                                 oC->lastCheckpoint = soFar;
428                                 n = 1;
429                         }
430                         // Or iterations
431                         if((oC->numIterations > 0 && (os->majorIteration - oC->lastCheckpoint) >= oC->numIterations) || force) {
432                                 oC->lastCheckpoint = os->majorIteration;
433                                 n = 1;
434                         }
435
436                         if(n) {         //In either case, save a checkpoint.
437                                 if(os->chkptText1 == NULL) {    // First one: set up output
438                                         omxWriteCheckpointHeader(os, oC);
439                                 }
440                                 char tempstring[25];
441                                 sprintf(tempstring, "%d", os->majorIteration);
442
443                                 if(strncmp(os->chkptText1, tempstring, strlen(tempstring))) {   // Returns zero if they're the same.
444                                         struct tm * nowTime = localtime(&now);                                          // So this only happens if the text is out of date.
445                                         strftime(tempstring, 25, "%b %d %Y %I:%M:%S %p", nowTime);
446                                         sprintf(os->chkptText1, "%d \"%s\" %9.5f", os->majorIteration, tempstring, f[0]);
447                                         for(int j = 0; j < os->numFreeParams; j++) {
448                                                 sprintf(tempstring, " %9.5f", x[j]);
449                                                 strncat(os->chkptText1, tempstring, 14);
450                                         }
451
452                                         double* hessian = os->hessian;
453                                         if(hessian != NULL) {
454                                                 for(int j = 0; j < os->numFreeParams; j++) {
455                                                         for(int k = 0; k <= j; k++) {
456                                                                 sprintf(tempstring, " %9.5f", hessian[j]);
457                                                                 strncat(os->chkptText2, tempstring, 14);
458                                                         }
459                                                 }
460                                         }
461                                 }
462
463                                 if(oC->type == OMX_FILE_CHECKPOINT) {
464                                         fprintf(oC->file, "%s", os->chkptText1);
465                                         if(oC->saveHessian)
466                                                 fprintf(oC->file, "%s", os->chkptText2);
467                                         fprintf(oC->file, "\n");
468                                         fflush(oC->file);
469                                 } else if(oC->type == OMX_CONNECTION_CHECKPOINT) {
470                                         warning("NYI: R_connections are not yet implemented.");
471                                         oC->numIterations = 0;
472                                         oC->time = 0;
473                                 }
474                         }
475                 }
476         }
477
478 void omxExamineFitOutput(omxState *state, omxMatrix *fitMatrix, int *mode)
479 {
480         if (!R_FINITE(fitMatrix->data[0])) {
481                 omxRaiseErrorf(state, "Fit function returned %g at iteration %d.%d",
482                                fitMatrix->data[0], state->majorIteration, state->minorIteration);
483                 *mode = -1;
484         }
485 }