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