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