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