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