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