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