Deadcode
[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         omxState* omxGetState(omxState* os, int stateNumber) {
67                 // TODO: Need to implement a smarter way to enumerate children
68                 if(stateNumber == 0) return os;
69                 if((stateNumber-1) < os->numChildren) {
70                         return(os->childList[stateNumber-1]);
71                 } else {
72                         error("Not implemented");
73                         // TODO: Account for unequal numbers of grandchild states
74                         int subState = (stateNumber - os->numChildren - 1);
75                         return omxGetState(os->childList[subState % os->numChildren], subState / os->numChildren);
76                 }
77         }
78
79         void omxSetMajorIteration(omxState *state, int value) {
80                 state->majorIteration = value;
81                 for(int i = 0; i < state->numChildren; i++) {
82                         omxSetMajorIteration(state->childList[i], value);
83                 }
84         }
85
86         void omxSetMinorIteration(omxState *state, int value) {
87                 state->minorIteration = value;
88                 for(int i = 0; i < state->numChildren; i++) {
89                         omxSetMinorIteration(state->childList[i], value);
90                 }
91         }
92         
93         void omxDuplicateState(omxState* tgt, omxState* src) {
94                 tgt->numAlgs                    = src->numAlgs;
95                 tgt->numExpects                 = src->numExpects;
96                 tgt->dataList                   = src->dataList;
97                 tgt->numChildren                = 0;
98                 
99                 // Duplicate matrices and algebras and build parentLists.
100                 tgt->parentState                = src;
101                 tgt->expectationList    = (omxExpectation**) R_alloc(tgt->numExpects, sizeof(omxExpectation*));
102                 tgt->algebraList                = (omxMatrix**) R_alloc(tgt->numAlgs, sizeof(omxMatrix*));
103                 tgt->markMatrices               = src->markMatrices; // TODO, unused in children?
104                                 
105                 memset(tgt->algebraList, 0, sizeof(omxMatrix*) * tgt->numAlgs);
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(int j = 0; j < tgt->numAlgs; j++) {
124                         // TODO: Smarter inference for which algebras to duplicate
125                         tgt->algebraList[j] = 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(int j = 0; j < tgt->numAlgs; 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         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                 os->optimumStatus = os->statusCode;
311                 strncpy(os->optimumMsg, os->statusMsg, 250);
312         }
313
314         void omxResetStatus(omxState *state) {
315                 int numChildren = state->numChildren;
316                 state->statusCode = 0;
317                 state->statusMsg[0] = '\0';
318                 for(int i = 0; i < numChildren; i++) {
319                         omxResetStatus(state->childList[i]);
320                 }
321         }
322
323 void omxRaiseErrorf(omxState *state, const char* errorMsg, ...)
324 {
325         va_list ap;
326         va_start(ap, errorMsg);
327         int fit = vsnprintf(state->statusMsg, MAX_STRING_LEN, errorMsg, ap);
328         va_end(ap);
329         if(OMX_DEBUG) {
330                 if (!(fit > -1 && fit < MAX_STRING_LEN)) {
331                         Rprintf("Error exceeded maximum length: %s\n", errorMsg);
332                 } else {
333                         Rprintf("Error raised: %s\n", state->statusMsg);
334                 }
335         }
336         state->statusCode = -1;  // this provides no additional information beyond errorMsg[0]!=0 TODO
337 }
338
339         void omxRaiseError(omxState *state, int errorCode, const char* errorMsg) {
340                 if(OMX_DEBUG && errorCode) { Rprintf("Error %d raised: %s\n", errorCode, errorMsg);}
341                 if(OMX_DEBUG && !errorCode) { Rprintf("Error status cleared."); }
342                 state->statusCode = errorCode;
343                 strncpy(state->statusMsg, errorMsg, 249);
344                 state->statusMsg[249] = '\0';
345                 if(state->computeCount <= 0 && errorCode < 0) {
346                         state->statusCode--;                    // Decrement status for init errors.
347                 }
348         }
349
350         void omxStateNextRow(omxState *state) {
351                 state->currentRow++;
352         };
353
354         void omxStateNextEvaluation(omxState *state) {
355                 state->currentRow = -1;
356                 state->computeCount++;
357         };
358
359         void omxWriteCheckpointHeader(omxState *os, omxCheckpoint* oC) {
360                 // FIXME: Is it faster to allocate this on the stack?
361                 os->chkptText1 = (char*) Calloc((24 + 15 * os->numFreeParams), char);
362                 os->chkptText2 = (char*) Calloc(1.0 + 15.0 * os->numFreeParams*
363                         (os->numFreeParams + 1.0) / 2.0, char);
364                 if (oC->type == OMX_FILE_CHECKPOINT) {
365                         fprintf(oC->file, "iterations\ttimestamp\tobjective\t");
366                         for(int j = 0; j < os->numFreeParams; j++) {
367                                 if(strcmp(os->freeVarList[j].name, CHAR(NA_STRING)) == 0) {
368                                         fprintf(oC->file, "%s", os->freeVarList[j].name);
369                                 } else {
370                                         fprintf(oC->file, "\"%s\"", os->freeVarList[j].name);
371                                 }
372                                 if (j != os->numFreeParams - 1) fprintf(oC->file, "\t");
373                         }
374                         fprintf(oC->file, "\n");
375                         fflush(oC->file);
376                 }
377         }
378  
379         void omxWriteCheckpointMessage(omxState *os, char *msg) {
380                 for(int i = 0; i < os->numCheckpoints; i++) {
381                         omxCheckpoint* oC = &(os->checkpointList[i]);
382                         if(os->chkptText1 == NULL) {    // First one: set up output
383                                 omxWriteCheckpointHeader(os, oC);
384                         }
385                         if (oC->type == OMX_FILE_CHECKPOINT) {
386                                 fprintf(oC->file, "%d \"%s\" NA ", os->majorIteration, msg);
387                                 for(int j = 0; j < os->numFreeParams; j++) {
388                                         fprintf(oC->file, "NA ");
389                                 }
390                                 fprintf(oC->file, "\n");
391                         }
392                 }
393         }
394
395         void omxSaveCheckpoint(omxState *os, double* x, double* f, int force) {
396                 time_t now = time(NULL);
397                 int soFar = now - os->startTime;                // Translated into minutes
398                 int n;
399                 for(int i = 0; i < os->numCheckpoints; i++) {
400                         n = 0;
401                         omxCheckpoint* oC = &(os->checkpointList[i]);
402                         // Check based on time            
403                         if((oC->time > 0 && (soFar - oC->lastCheckpoint) >= oC->time) || force) {
404                                 oC->lastCheckpoint = soFar;
405                                 n = 1;
406                         }
407                         // Or iterations
408                         if((oC->numIterations > 0 && (os->majorIteration - oC->lastCheckpoint) >= oC->numIterations) || force) {
409                                 oC->lastCheckpoint = os->majorIteration;
410                                 n = 1;
411                         }
412
413                         if(n) {         //In either case, save a checkpoint.
414                                 if(os->chkptText1 == NULL) {    // First one: set up output
415                                         omxWriteCheckpointHeader(os, oC);
416                                 }
417                                 char tempstring[25];
418                                 sprintf(tempstring, "%d", os->majorIteration);
419
420                                 if(strncmp(os->chkptText1, tempstring, strlen(tempstring))) {   // Returns zero if they're the same.
421                                         struct tm * nowTime = localtime(&now);                                          // So this only happens if the text is out of date.
422                                         strftime(tempstring, 25, "%b %d %Y %I:%M:%S %p", nowTime);
423                                         sprintf(os->chkptText1, "%d \"%s\" %9.5f", os->majorIteration, tempstring, f[0]);
424                                         for(int j = 0; j < os->numFreeParams; j++) {
425                                                 sprintf(tempstring, " %9.5f", x[j]);
426                                                 strncat(os->chkptText1, tempstring, 14);
427                                         }
428
429                                         double* hessian = os->hessian;
430                                         if(hessian != NULL) {
431                                                 for(int j = 0; j < os->numFreeParams; j++) {
432                                                         for(int k = 0; k <= j; k++) {
433                                                                 sprintf(tempstring, " %9.5f", hessian[j]);
434                                                                 strncat(os->chkptText2, tempstring, 14);
435                                                         }
436                                                 }
437                                         }
438                                 }
439
440                                 if(oC->type == OMX_FILE_CHECKPOINT) {
441                                         fprintf(oC->file, "%s", os->chkptText1);
442                                         if(oC->saveHessian)
443                                                 fprintf(oC->file, "%s", os->chkptText2);
444                                         fprintf(oC->file, "\n");
445                                         fflush(oC->file);
446                                 } else if(oC->type == OMX_CONNECTION_CHECKPOINT) {
447                                         warning("NYI: R_connections are not yet implemented.");
448                                         oC->numIterations = 0;
449                                         oC->time = 0;
450                                 }
451                         }
452                 }
453         }
454
455 void omxExamineFitOutput(omxState *state, omxMatrix *fitMatrix, int *mode)
456 {
457         if (!R_FINITE(fitMatrix->data[0])) {
458                 omxRaiseErrorf(state, "Fit function returned %g at iteration %d.%d",
459                                fitMatrix->data[0], state->majorIteration, state->minorIteration);
460                 *mode = -1;
461         }
462 }