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