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