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