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