Corrections to state duplication.
[openmx:openmx.git] / src / omxState.c
1 /*
2  *  Copyright 2007-2009 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 "omxState.h"
28
29 /* Initialize and Destroy */
30         void omxInitState(omxState* state, omxState *parentState, int numThreads) {
31                 int i;
32                 state->numMats = 0;
33                 state->numAlgs = 0;
34                 state->numData = 0;
35                 state->numFreeParams = 0;
36                 state->numDynamic = 0;
37                 state->maxDynamic = 0;
38                 if (numThreads > 1) {
39                         state->numChildren = numThreads;
40                         state->childList = (omxState**) Calloc(numThreads, omxState*);
41                         for(i = 0; i < numThreads; i++) {
42                                 state->childList[i] = (omxState*) R_alloc(1, sizeof(omxState));
43                                 omxInitState(state->childList[i], state, 1);
44                         }
45                 } else {
46                 state->numChildren = 0;
47                         state->childList = NULL;
48                 }
49                 state->matrixList = NULL;
50                 state->algebraList = NULL;
51                 state->dynamicList = NULL;
52         state->parentState = parentState;
53         state->parentMatrix = NULL;
54         state->parentAlgebra = NULL;
55                 state->parentConList= NULL;
56                 state->dataList = NULL;
57                 state->objectiveMatrix = NULL;
58                 state->hessian = NULL;
59                 state->conList = NULL;
60                 state->freeVarList = NULL;
61                 state->optimizerState = NULL;
62                 state->optimalValues = NULL;
63                 state->optimum = 9999999999;
64
65                 state->majorIteration = 0;
66                 state->minorIteration = 0;
67                 state->startTime = 0;
68                 state->endTime = 0;
69                 state->numCheckpoints = 0;
70                 state->checkpointList = NULL;
71                 state->chkptText1 = NULL;
72                 state->chkptText2 = NULL;
73
74                 state->computeCount = -1;
75                 state->currentRow = -1;
76
77                 state->statusCode = 0;
78                 strncpy(state->statusMsg, "", 1);
79         }
80
81         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList,
82                                                 omxMatrix** algebraList, omxData** dataList, omxMatrix* objective) {
83                 error("NYI: Can't fill a state from outside yet. Besides, do you really need a single function to do this?");
84         }
85         
86         omxState* omxGetState(omxState* os, int stateNumber) {
87                 // TODO: Need to implement a smarter way to enumerate children
88                 if(stateNumber == 0) return os;
89                 if((stateNumber-1) < os->numChildren) {
90                         return(os->childList[stateNumber-1]);
91                 } else {
92                         // TODO: Account for unequal numbers of grandchild states
93                         int subState = (stateNumber - os->numChildren - 1);
94                         return omxGetState(os->childList[subState % os->numChildren], subState / os->numChildren);
95                 }
96         }
97
98         void omxUpdateState(omxState* tgt, omxState* src) {
99                 tgt->computeCount               = src->computeCount;
100                 tgt->currentRow                 = src->currentRow;
101                 tgt->optimalValues              = src->optimalValues;
102                 tgt->majorIteration     = src->majorIteration;
103                 tgt->minorIteration     = src->minorIteration;
104
105                 for(int i = 0; i < src->numMats; i++) {
106                         omxCopyMatrix(tgt->matrixList[i], src->matrixList[i]);
107                 }
108
109                 for(int i = 0; i < src->numAlgs; i++) {
110                         omxUpdateAlgebra(tgt->algebraList[i], src->algebraList[i]);
111                 }
112
113                 for(int i = 0; i < src->numDynamic; i++) {
114                         omxUpdateAlgebra(tgt->dynamicList[i], src->dynamicList[i]);
115                 }
116
117         }
118
119         void omxAddDynamicMatrix(omxState* state, omxMatrix* matrix) {
120                 if (state->dynamicList == NULL) {
121                         state->dynamicList = (omxMatrix**) malloc(16 * sizeof(omxMatrix*));
122                         state->maxDynamic = 16;
123                 }
124                 if (state->numDynamic == state->maxDynamic) {
125                         state->dynamicList = realloc(state->dynamicList, state->maxDynamic * 2 * sizeof(omxMatrix*));
126                         state->maxDynamic = state->maxDynamic * 2;
127                 }
128                 matrix->matrixNumber = state->numDynamic;
129                 state->dynamicList[state->numDynamic] = matrix;
130                 state->numDynamic = state->numDynamic + 1;              
131         }
132         
133         void omxDuplicateState(omxState* tgt, omxState* src, unsigned short fullCopy) {
134                 tgt->numMats                    = src->numMats;
135                 tgt->numAlgs                    = src->numAlgs;
136                 tgt->numData                    = src->numData;
137                 tgt->dataList                   = src->dataList;
138                 tgt->numChildren                = 0;
139                 
140                 // Duplicate matrices and algebras and build parentLists.
141                 tgt->parentState                = src;
142                 tgt->parentMatrix               = src->matrixList;
143                 tgt->parentAlgebra              = src->algebraList;
144                 tgt->matrixList                 = (omxMatrix**) R_alloc(tgt->numMats, sizeof(omxMatrix*));
145                 for(int j = 0; j < tgt->numMats; j++) {
146                         // TODO: Smarter inference for which matrices to duplicate
147                         tgt->matrixList[j] = omxDuplicateMatrix(src->matrixList[j], tgt, fullCopy);
148                 }
149                                 
150                 tgt->parentConList              = src->conList;
151                 tgt->numConstraints     = src->numConstraints;
152                 tgt->conList                    = (omxConstraint*) R_alloc(tgt->numConstraints, sizeof(omxConstraint));
153                 for(int j = 0; j < tgt->numConstraints; j++) {
154                         tgt->conList[j].size   = src->conList[j].size;
155                         tgt->conList[j].opCode = src->conList[j].opCode;
156                         tgt->conList[j].lbound = src->conList[j].lbound;
157                         tgt->conList[j].ubound = src->conList[j].ubound;
158                         tgt->conList[j].result = omxDuplicateMatrix(src->conList[j].result, tgt, fullCopy);
159                 }
160
161                 tgt->algebraList                = (omxMatrix**) R_alloc(tgt->numAlgs, sizeof(omxMatrix*));
162
163                 for(int j = 0; j < tgt->numAlgs; j++) {
164                         // TODO: Smarter inference for which algebras to duplicate
165                         tgt->algebraList[j] = omxDuplicateMatrix(src->algebraList[j], tgt, fullCopy);
166                 }
167
168                 for(int j = 0; j < tgt->numAlgs; j++) {
169                         omxDuplicateAlgebra(tgt->algebraList[j], src->algebraList[j], tgt, fullCopy);
170                 }
171
172                 
173                 tgt->childList                  = NULL;
174
175                 tgt->objectiveMatrix    = omxLookupDuplicateElement(tgt, src->objectiveMatrix);
176                 tgt->hessian                    = src->hessian;
177
178                 tgt->numFreeParams                      = src->numFreeParams;
179                 tgt->freeVarList                = (omxFreeVar*) R_alloc(tgt->numFreeParams, sizeof(omxFreeVar));
180                 for(int j = 0; j < tgt->numFreeParams; j++) {
181                         tgt->freeVarList[j].lbound                      = src->freeVarList[j].lbound;
182                         tgt->freeVarList[j].ubound                      = src->freeVarList[j].ubound;
183                         tgt->freeVarList[j].numLocations        = src->freeVarList[j].numLocations;
184                         
185                         int nLocs                                                       = tgt->freeVarList[j].numLocations;
186                         tgt->freeVarList[j].matrices            = (int*) R_alloc(nLocs, sizeof(int));
187                         tgt->freeVarList[j].row                         = (int*) R_alloc(nLocs, sizeof(int));
188                         tgt->freeVarList[j].col                         = (int*) R_alloc(nLocs, sizeof(int));
189
190                         for(int k = 0; k < nLocs; k++) {
191                                 int theMat                                              = src->freeVarList[j].matrices[k];
192                                 int theRow                                              = src->freeVarList[j].row[k];
193                                 int theCol                                              = src->freeVarList[j].col[k];
194
195                                 tgt->freeVarList[j].matrices[k] = theMat;
196                                 tgt->freeVarList[j].row[k]              = theRow;
197                                 tgt->freeVarList[j].col[k]              = theCol;
198                                                                 
199                                 tgt->freeVarList[j].name                = src->freeVarList[j].name;
200                         }
201                 }
202                 
203                 if (src->optimizerState) {
204                         tgt->optimizerState                                     = (omxOptimizerState*) R_alloc(1, sizeof(omxOptimizerState));
205                         tgt->optimizerState->currentParameter   = src->optimizerState->currentParameter;
206                         tgt->optimizerState->offset                             = src->optimizerState->offset;
207                         tgt->optimizerState->alpha                              = src->optimizerState->alpha;
208                 }
209                 
210                 tgt->optimalValues              = src->optimalValues;
211                 tgt->optimum                    = 9999999999;
212                                   
213                 tgt->majorIteration     = 0;
214                 tgt->minorIteration     = 0;
215                 tgt->startTime                  = src->startTime;
216                 tgt->endTime                    = 0;
217                 
218                 // TODO: adjust checkpointing based on parallelization method
219                 tgt->numCheckpoints     = 0;
220                 tgt->checkpointList     = NULL;
221                 tgt->chkptText1                 = NULL;
222                 tgt->chkptText2                 = NULL;
223                                   
224                 tgt->computeCount               = src->computeCount;
225                 tgt->currentRow                 = src->currentRow;
226
227                 tgt->statusCode                 = 0;
228                 strncpy(tgt->statusMsg, "", 1);
229         }
230
231     omxMatrix* omxLookupDuplicateElement(omxState* os, omxMatrix* element) {
232         if(os == NULL || element == NULL) return NULL;
233
234                 if (element->hasMatrixNumber) {
235                         int matrixNumber = element->matrixNumber;
236                         if (matrixNumber >= 0) {
237                                 return(os->algebraList[matrixNumber]);
238                         } else {
239                                 return(os->matrixList[-matrixNumber - 1]);
240                         }
241                 }
242
243         for(int i = 0; i < os->numConstraints; i++) {
244             if(os->parentConList[i].result == element) {
245                                 if(os->conList[i].result != NULL)   // Not sure of proper failure behavior here.
246                     return(os->conList[i].result);
247                 else
248                     omxRaiseError(os, -2, "Initialization Copy Error: Constraint required but not yet processed.");
249             }
250         }
251
252         return NULL;
253     }
254
255         void omxFreeState(omxState *state) {
256                 int k;
257
258                 if (state->numChildren > 0) {
259                         for(k = 0; k < state->numChildren; k++) {
260                                 omxFreeState(state->childList[k]);
261                         }
262                         Free(state->childList);
263                         state->childList = NULL;
264                         state->numChildren = 0;
265                 }
266
267                 if(OMX_DEBUG) { Rprintf("Freeing %d Algebras.\n", state->numAlgs);}
268                 for(k = 0; k < state->numAlgs; k++) {
269                         if(OMX_DEBUG) { Rprintf("Freeing Algebra %d at 0x%x.\n", k, state->algebraList[k]); }
270                         omxFreeAllMatrixData(state->algebraList[k]);
271                 }
272
273                 if(OMX_DEBUG) { Rprintf("Freeing %d Matrices.\n", state->numMats);}
274                 for(k = 0; k < state->numMats; k++) {
275                         if(OMX_DEBUG) { Rprintf("Freeing Matrix %d at 0x%x.\n", k, state->matrixList[k]); }
276                         omxFreeAllMatrixData(state->matrixList[k]);
277                 }
278
279                 if(OMX_DEBUG) { Rprintf("Freeing %d Data Sets.\n", state->numData);}
280                 for(k = 0; k < state->numData; k++) {
281                         if(OMX_DEBUG) { Rprintf("Freeing Data Set %d at 0x%x.\n", k, state->dataList[k]); }
282                         omxFreeData(state->dataList[k]);
283                 }
284
285         if(OMX_DEBUG) {Rprintf("Freeing %d Children.\n", state->numChildren);}
286         for(k = 0; k < state->numChildren; k++) {
287                         if(OMX_DEBUG) { Rprintf("Freeing Child State %d at 0x%x.\n", k, state->childList[k]); }
288                         omxFreeState(state->childList[k]);            
289         }
290
291                 if(OMX_DEBUG) { Rprintf("Freeing %d Checkpoints.\n", state->numCheckpoints);}
292                 for(k = 0; k < state->numCheckpoints; k++) {
293                         if(OMX_DEBUG) { Rprintf("Freeing Data Set %d at 0x%x.\n", k, state->checkpointList[k]); }
294                         omxCheckpoint oC = state->checkpointList[k];
295                         switch(oC.type) {
296                                 case OMX_FILE_CHECKPOINT:
297                                         fclose(oC.file);
298                                         break;
299                                 case OMX_SOCKET_CHECKPOINT:     // NYI :::DEBUG:::
300                                         // TODO: Close socket
301                                         break;
302                                 case OMX_CONNECTION_CHECKPOINT: // NYI :::DEBUG:::
303                                         // Do nothing: this should be handled by R upon return.
304                                         break;
305                         }
306                         if(state->chkptText1 != NULL) {
307                                 Free(state->chkptText1);
308                         }
309                         if(state->chkptText2 != NULL) {
310                                 Free(state->chkptText2);
311                         }
312                         // Checkpoint list itself is freed by R.
313                 }
314
315                 if(state->dynamicList != NULL) free(state->dynamicList);
316
317                 if(OMX_DEBUG) { Rprintf("State Freed.\n");}
318         }
319
320         void omxSaveState(omxState *os, double* freeVals, double minimum) {
321                 if(os->optimalValues == NULL) {
322                         os->optimalValues = (double*) R_alloc(os->numFreeParams, sizeof(double));
323                 }
324
325                 for(int i = 0; i < os->numFreeParams; i++) {
326                         os->optimalValues[i] = freeVals[i];
327                 }
328                 os->optimum = minimum;
329                 os->optimumStatus = os->statusCode;
330                 strncpy(os->optimumMsg, os->statusMsg, 250);
331         }
332
333         void omxRaiseError(omxState *state, int errorCode, char* errorMsg) {
334                 if(OMX_DEBUG && errorCode) { Rprintf("Error %d raised: %s", errorCode, errorMsg);}
335                 if(OMX_DEBUG && !errorCode) { Rprintf("Error status cleared."); }
336                 state->statusCode = errorCode;
337                 strncpy(state->statusMsg, errorMsg, 249);
338                 state->statusMsg[249] = '\0';
339                 if(state->computeCount <= 0 && errorCode < 0) {
340                         state->statusCode--;                    // Decrement status for init errors.
341                 }
342         }
343
344         void omxStateNextRow(omxState *state) {
345                 state->currentRow++;
346         };
347         void omxStateNextEvaluation(omxState *state) {
348                 state->currentRow = 0;
349                 state->computeCount++;
350         };
351
352         void omxSaveCheckpoint(omxState *os, double* x, double* f) {
353                 time_t now = time(NULL);
354                 int soFar = now - os->startTime;                // Translated into minutes
355                 int n;
356                 for(int i = 0; i < os->numCheckpoints; i++) {
357                         n = 0;
358                         omxCheckpoint* oC = &(os->checkpointList[i]);
359                         // Check based on time
360                         if(oC->time > 0 && (soFar - oC->lastCheckpoint) >= oC->time) {
361                                 oC->lastCheckpoint = soFar;
362                                 n = 1;
363                         }
364                         // Or iterations
365                         if(oC->numIterations > 0 && (os->majorIteration - oC->lastCheckpoint) >= oC->numIterations) {
366                                 oC->lastCheckpoint = os->majorIteration;
367                                 n = 1;
368                         }
369
370                         if(n) {         //In either case, save a checkpoint.
371                                 if(os->chkptText1 == NULL) {    // First one: set up output
372                                         // FIXME: Is it faster to allocate this on the stack?
373                                         os->chkptText1 = (char*) Calloc((24+15*os->numFreeParams), char);
374                                         os->chkptText2 = (char*) Calloc(1.0+15.0*os->numFreeParams*
375                                                                                                                 (os->numFreeParams + 1.0)/2.0, char);
376                                         if (oC->type == OMX_FILE_CHECKPOINT) {
377                                                 fprintf(oC->file, "iterations\ttimestamp\tobjective\t");
378                                                 for(int j = 0; j < os->numFreeParams; j++) {
379                                                         if(strcmp(os->freeVarList[j].name, CHAR(NA_STRING)) == 0) {
380                                                                 fprintf(oC->file, "%s", os->freeVarList[j].name);
381                                                         } else {
382                                                                 fprintf(oC->file, "\"%s\"", os->freeVarList[j].name);
383                                                         }
384                                                         if (j != os->numFreeParams - 1) fprintf(oC->file, "\t");
385                                                 }
386                                                 fprintf(oC->file, "\n");
387                                                 fflush(oC->file);
388                                         }
389                                 }
390                                 char tempstring[25];
391                                 sprintf(tempstring, "%d", os->majorIteration);
392
393                                 if(strncmp(os->chkptText1, tempstring, strlen(tempstring))) {   // Returns zero if they're the same.
394                                         struct tm * nowTime = localtime(&now);                                          // So this only happens if the text is out of date.
395                                         strftime(tempstring, 25, "%b %d %Y %I:%M:%S %p", nowTime);
396                                         sprintf(os->chkptText1, "%d \"%s\" %9.5f", os->majorIteration, tempstring, f[0]);
397                                         for(int j = 0; j < os->numFreeParams; j++) {
398                                                 sprintf(tempstring, " %9.5f", x[j]);
399                                                 strncat(os->chkptText1, tempstring, 14);
400                                         }
401
402                                         double* hessian = os->hessian;
403                                         if(hessian != NULL) {
404                                                 for(int j = 0; j < os->numFreeParams; j++) {
405                                                         for(int k = 0; k <= j; k++) {
406                                                                 sprintf(tempstring, " %9.5f", hessian[j]);
407                                                                 strncat(os->chkptText2, tempstring, 14);
408                                                         }
409                                                 }
410                                         }
411                                 }
412
413                                 if(oC->type == OMX_FILE_CHECKPOINT) {
414                                         fprintf(oC->file, "%s", os->chkptText1);
415                                         if(oC->saveHessian)
416                                                 fprintf(oC->file, "%s", os->chkptText2);
417                                         fprintf(oC->file, "\n");
418                                         fflush(oC->file);
419                                 } else if(oC->type == OMX_SOCKET_CHECKPOINT) {
420                                         n = write(oC->socket, os->chkptText1, strlen(os->chkptText1));
421                                         if(n != strlen(os->chkptText1)) warning("Error writing checkpoint.");
422                                         if(oC->saveHessian) {
423                                                 n = write(oC->socket, os->chkptText2, strlen(os->chkptText2));
424                                                 if(n != strlen(os->chkptText1)) warning("Error writing checkpoint.");
425                                         }
426                                         n = write(oC->socket, "\n", 1);
427                                         if(n != 1) warning("Error writing checkpoint.");
428                                 } else if(oC->type == OMX_CONNECTION_CHECKPOINT) {
429                                         warning("NYI: R_connections are not yet implemented.");
430                                         oC->numIterations = 0;
431                                         oC->time = 0;
432                                 }
433                         }
434                 }
435         }