Refrain from duplicating the model unless required by the fitfunction
[openmx:openmx.git] / src / omxState.c
1 /*
2  *  Copyright 2007-2013 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) {
31                 state->numMats = 0;
32                 state->numAlgs = 0;
33                 state->numExpects = 0;
34                 state->numConstraints = 0;
35                 state->numData = 0;
36                 state->numFreeParams = 0;
37                 state->numChildren = 0;
38                 state->childList = NULL;
39                 state->matrixList = NULL;
40                 state->algebraList = NULL;
41                 state->expectationList = NULL;
42                 state->parentState = parentState;
43                 state->dataList = NULL;
44                 state->fitMatrix = NULL;
45                 state->hessian = NULL;
46                 state->conList = NULL;
47                 state->freeVarList = NULL;
48                 state->optimizerState = NULL;
49                 state->optimalValues = NULL;
50                 state->optimum = 9999999999;
51
52                 state->majorIteration = 0;
53                 state->minorIteration = 0;
54                 state->startTime = 0;
55                 state->endTime = 0;
56                 state->numCheckpoints = 0;
57                 state->checkpointList = NULL;
58                 state->chkptText1 = NULL;
59                 state->chkptText2 = NULL;
60
61         state->currentInterval = -1;
62
63                 state->computeCount = -1;
64                 state->currentRow = -1;
65
66                 state->statusCode = 0;
67                 strncpy(state->statusMsg, "", 1);
68         }
69
70         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList,
71                                                 omxMatrix** algebraList, omxData** dataList, omxMatrix* fitFunction) {
72                 error("NYI: Can't fill a state from outside yet. Besides, do you really need a single function to do this?");
73         }
74         
75         omxState* omxGetState(omxState* os, int stateNumber) {
76                 // TODO: Need to implement a smarter way to enumerate children
77                 if(stateNumber == 0) return os;
78                 if((stateNumber-1) < os->numChildren) {
79                         return(os->childList[stateNumber-1]);
80                 } else {
81                         error("Not implemented");
82                         // TODO: Account for unequal numbers of grandchild states
83                         int subState = (stateNumber - os->numChildren - 1);
84                         return omxGetState(os->childList[subState % os->numChildren], subState / os->numChildren);
85                 }
86         }
87
88         void omxSetMajorIteration(omxState *state, int value) {
89                 state->majorIteration = value;
90                 for(int i = 0; i < state->numChildren; i++) {
91                         omxSetMajorIteration(state->childList[i], value);
92                 }
93         }
94
95         void omxSetMinorIteration(omxState *state, int value) {
96                 state->minorIteration = value;
97                 for(int i = 0; i < state->numChildren; i++) {
98                         omxSetMinorIteration(state->childList[i], value);
99                 }
100         }
101         
102         void omxDuplicateState(omxState* tgt, omxState* src) {
103                 tgt->numMats                    = src->numMats;
104                 tgt->numAlgs                    = src->numAlgs;
105                 tgt->numExpects                 = src->numExpects;
106                 tgt->numData                    = src->numData;
107                 tgt->dataList                   = src->dataList;
108                 tgt->numChildren                = 0;
109                 
110                 // Duplicate matrices and algebras and build parentLists.
111                 tgt->parentState                = src;
112                 tgt->matrixList                 = (omxMatrix**) R_alloc(tgt->numMats, sizeof(omxMatrix*));
113                 tgt->expectationList    = (omxExpectation**) R_alloc(tgt->numExpects, sizeof(omxExpectation*));
114                 tgt->algebraList                = (omxMatrix**) R_alloc(tgt->numAlgs, sizeof(omxMatrix*));
115                 tgt->markMatrices               = (int*) R_alloc(tgt->numMats + tgt->numAlgs, sizeof(int));
116
117                 memcpy(tgt->markMatrices, src->markMatrices, (tgt->numMats + tgt->numAlgs) * sizeof(int));
118                                 
119                 memset(tgt->matrixList, 0, sizeof(omxMatrix*) * tgt->numMats);
120                 memset(tgt->algebraList, 0, sizeof(omxMatrix*) * tgt->numAlgs);
121                 memset(tgt->expectationList, 0, sizeof(omxExpectation*) * tgt->numExpects);
122
123                 for(int j = 0; j < tgt->numMats; j++) {
124                         // TODO: Smarter inference for which matrices to duplicate
125                         tgt->matrixList[j] = omxDuplicateMatrix(src->matrixList[j], tgt);
126                 }
127
128                 tgt->numConstraints     = src->numConstraints;
129                 tgt->conList                    = (omxConstraint*) R_alloc(tgt->numConstraints, sizeof(omxConstraint));
130                 for(int j = 0; j < tgt->numConstraints; j++) {
131                         tgt->conList[j].size   = src->conList[j].size;
132                         tgt->conList[j].opCode = src->conList[j].opCode;
133                         tgt->conList[j].lbound = src->conList[j].lbound;
134                         tgt->conList[j].ubound = src->conList[j].ubound;
135                         tgt->conList[j].result = omxDuplicateMatrix(src->conList[j].result, tgt);
136                 }
137
138                 for(int j = 0; j < tgt->numAlgs; j++) {
139                         // TODO: Smarter inference for which algebras to duplicate
140                         tgt->algebraList[j] = omxDuplicateMatrix(src->algebraList[j], tgt);
141                 }
142
143                 for(int j = 0; j < tgt->numExpects; j++) {
144                         // TODO: Smarter inference for which expectations to duplicate
145                         tgt->expectationList[j] = omxDuplicateExpectation(src->expectationList[j], tgt);
146                 }
147
148                 for(int j = 0; j < tgt->numAlgs; j++) {
149                         omxDuplicateAlgebra(tgt->algebraList[j], src->algebraList[j], tgt);
150                 }
151
152                 for(int j = 0; j < tgt->numExpects; j++) {
153                         // TODO: Smarter inference for which expectations to duplicate
154                         omxCompleteExpectation(tgt->expectationList[j]);
155                 }
156
157                 tgt->childList                  = NULL;
158
159                 tgt->fitMatrix  = omxLookupDuplicateElement(tgt, src->fitMatrix);
160                 tgt->hessian                    = src->hessian;
161
162                 tgt->numFreeParams                      = src->numFreeParams;
163                 tgt->freeVarList                = (omxFreeVar*) R_alloc(tgt->numFreeParams, sizeof(omxFreeVar));
164                 for(int j = 0; j < tgt->numFreeParams; j++) {
165                         int nLocs                                                       = src->freeVarList[j].numLocations;
166                         int numDeps                                                     = src->freeVarList[j].numDeps;
167
168                         tgt->freeVarList[j].lbound                      = src->freeVarList[j].lbound;
169                         tgt->freeVarList[j].ubound                      = src->freeVarList[j].ubound;
170                         tgt->freeVarList[j].numLocations        = nLocs;
171                         tgt->freeVarList[j].numDeps                     = numDeps;
172                         
173                         tgt->freeVarList[j].matrices            = (int*) R_alloc(nLocs, sizeof(int));
174                         tgt->freeVarList[j].row                         = (int*) R_alloc(nLocs, sizeof(int));
175                         tgt->freeVarList[j].col                         = (int*) R_alloc(nLocs, sizeof(int));
176                         tgt->freeVarList[j].deps                        = (int*) R_alloc(numDeps, sizeof(int));
177
178                         for(int k = 0; k < nLocs; k++) {
179                                 int theMat                                              = src->freeVarList[j].matrices[k];
180                                 int theRow                                              = src->freeVarList[j].row[k];
181                                 int theCol                                              = src->freeVarList[j].col[k];
182
183                                 tgt->freeVarList[j].matrices[k] = theMat;
184                                 tgt->freeVarList[j].row[k]              = theRow;
185                                 tgt->freeVarList[j].col[k]              = theCol;
186                                                                 
187                                 tgt->freeVarList[j].name                = src->freeVarList[j].name;
188                         }
189
190                         for(int k = 0; k < numDeps; k++) {
191                                 tgt->freeVarList[j].deps[k] = src->freeVarList[j].deps[k];
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         omxExpectation* omxLookupDuplicateExpectation(omxState* os, omxExpectation* ox) {
251                 if(os == NULL || ox == NULL) return NULL;
252
253                 return(os->expectationList[ox->expNum]);
254         }
255
256         int omxCountLeafNodes(omxState *state) {
257                 int children = state->numChildren;
258                 if (children == 0) {
259                         return(1);
260                 } else {
261                         int sum = 0;
262                         for(int i = 0; i < children; i++) {
263                                 sum += omxCountLeafNodes(state->childList[i]);
264                         }
265                         return(sum);
266                 }
267         }
268
269         /* Traverse to the root of the state hierarchy,
270          * and then count the number of leaf nodes */
271         int omxTotalThreadCount(omxState *state) {
272
273                 while(state->parentState != NULL) {
274                         state = state->parentState;
275                 }
276         
277                 return(omxCountLeafNodes(state));
278         }
279
280         void omxFreeState(omxState *state) {
281                 int k;
282
283                 if (state->numChildren > 0) {
284                         for(k = 0; k < state->numChildren; k++) {
285                                 omxFreeState(state->childList[k]);
286                         }
287                         Free(state->childList);
288                         state->childList = NULL;
289                         state->numChildren = 0;
290                 }
291
292                 if(OMX_DEBUG) { Rprintf("Freeing %d Algebras.\n", state->numAlgs);}
293                 for(k = 0; k < state->numAlgs; k++) {
294                         if(OMX_DEBUG) { Rprintf("Freeing Algebra %d at 0x%x.\n", k, state->algebraList[k]); }
295                         omxFreeAllMatrixData(state->algebraList[k]);
296                 }
297
298                 if(OMX_DEBUG) { Rprintf("Freeing %d Matrices.\n", state->numMats);}
299                 for(k = 0; k < state->numMats; k++) {
300                         if(OMX_DEBUG) { Rprintf("Freeing Matrix %d at 0x%x.\n", k, state->matrixList[k]); }
301                         omxFreeAllMatrixData(state->matrixList[k]);
302                 }
303                 
304                 if(OMX_DEBUG) { Rprintf("Freeing %d Model Expectations.\n", state->numExpects);}
305                 for(k = 0; k < state->numExpects; k++) {
306                         if(OMX_DEBUG) { Rprintf("Freeing Expectation %d at 0x%x.\n", k, state->expectationList[k]); }
307                         omxFreeExpectationArgs(state->expectationList[k]);
308                 }
309
310                 if(OMX_DEBUG) { Rprintf("Freeing %d Constraints.\n", state->numConstraints);}
311                 for(k = 0; k < state->numConstraints; k++) {
312                         if(OMX_DEBUG) { Rprintf("Freeing Constraint %d at 0x%x.\n", k, state->conList[k]); }
313                         omxFreeAllMatrixData(state->conList[k].result);
314                 }
315
316                 if(OMX_DEBUG) { Rprintf("Freeing %d Data Sets.\n", state->numData);}
317                 for(k = 0; k < state->numData; k++) {
318                         if(OMX_DEBUG) { Rprintf("Freeing Data Set %d at 0x%x.\n", k, state->dataList[k]); }
319                         omxFreeData(state->dataList[k]);
320                 }
321
322         if(OMX_DEBUG) {Rprintf("Freeing %d Children.\n", state->numChildren);}
323         for(k = 0; k < state->numChildren; k++) {
324                         if(OMX_DEBUG) { Rprintf("Freeing Child State %d at 0x%x.\n", k, state->childList[k]); }
325                         omxFreeState(state->childList[k]);            
326         }
327
328                 if(OMX_DEBUG) { Rprintf("Freeing %d Checkpoints.\n", state->numCheckpoints);}
329                 for(k = 0; k < state->numCheckpoints; k++) {
330                         if(OMX_DEBUG) { Rprintf("Freeing Data Set %d at 0x%x.\n", k, state->checkpointList[k]); }
331                         omxCheckpoint oC = state->checkpointList[k];
332                         switch(oC.type) {
333                                 case OMX_FILE_CHECKPOINT:
334                                         fclose(oC.file);
335                                         break;
336                                 case OMX_SOCKET_CHECKPOINT:     // NYI :::DEBUG:::
337                                         // TODO: Close socket
338                                         break;
339                                 case OMX_CONNECTION_CHECKPOINT: // NYI :::DEBUG:::
340                                         // Do nothing: this should be handled by R upon return.
341                                         break;
342                         }
343                         if(state->chkptText1 != NULL) {
344                                 Free(state->chkptText1);
345                         }
346                         if(state->chkptText2 != NULL) {
347                                 Free(state->chkptText2);
348                         }
349                         // Checkpoint list itself is freed by R.
350                 }
351
352                 if(OMX_DEBUG) { Rprintf("State Freed.\n");}
353         }
354
355         void omxSaveState(omxState *os, double* freeVals, double minimum) {
356                 if(os->optimalValues == NULL) {
357                         os->optimalValues = (double*) R_alloc(os->numFreeParams, sizeof(double));
358                 }
359
360                 for(int i = 0; i < os->numFreeParams; i++) {
361                         os->optimalValues[i] = freeVals[i];
362                 }
363                 os->optimum = minimum;
364                 os->optimumStatus = os->statusCode;
365                 strncpy(os->optimumMsg, os->statusMsg, 250);
366         }
367
368         void omxResetStatus(omxState *state) {
369                 int numChildren = state->numChildren;
370                 state->statusCode = 0;
371                 state->statusMsg[0] = '\0';
372                 for(int i = 0; i < numChildren; i++) {
373                         omxResetStatus(state->childList[i]);
374                 }
375         }
376
377 void omxRaiseErrorf(omxState *state, char* errorMsg, ...)
378 {
379         va_list ap;
380         va_start(ap, errorMsg);
381         int fit = vsnprintf(state->statusMsg, MAX_STRING_LEN, errorMsg, ap);
382         va_end(ap);
383         if(OMX_DEBUG) {
384                 if (!(fit > -1 && fit < MAX_STRING_LEN)) {
385                         Rprintf("Error exceeded maximum length: %s\n", errorMsg);
386                 } else {
387                         Rprintf("Error raised: %s\n", state->statusMsg);
388                 }
389         }
390         state->statusCode = -1;  // this provides no additional information beyond errorMsg[0]!=0 TODO
391 }
392
393         void omxRaiseError(omxState *state, int errorCode, char* errorMsg) {
394                 if(OMX_DEBUG && errorCode) { Rprintf("Error %d raised: %s\n", errorCode, errorMsg);}
395                 if(OMX_DEBUG && !errorCode) { Rprintf("Error status cleared."); }
396                 state->statusCode = errorCode;
397                 strncpy(state->statusMsg, errorMsg, 249);
398                 state->statusMsg[249] = '\0';
399                 if(state->computeCount <= 0 && errorCode < 0) {
400                         state->statusCode--;                    // Decrement status for init errors.
401                 }
402         }
403
404         void omxStateNextRow(omxState *state) {
405                 state->currentRow++;
406         };
407
408         void omxStateNextEvaluation(omxState *state) {
409                 state->currentRow = -1;
410                 state->computeCount++;
411         };
412
413         void omxWriteCheckpointHeader(omxState *os, omxCheckpoint* oC) {
414                 // FIXME: Is it faster to allocate this on the stack?
415                 os->chkptText1 = (char*) Calloc((24 + 15 * os->numFreeParams), char);
416                 os->chkptText2 = (char*) Calloc(1.0 + 15.0 * os->numFreeParams*
417                         (os->numFreeParams + 1.0) / 2.0, char);
418                 if (oC->type == OMX_FILE_CHECKPOINT) {
419                         fprintf(oC->file, "iterations\ttimestamp\tobjective\t");
420                         for(int j = 0; j < os->numFreeParams; j++) {
421                                 if(strcmp(os->freeVarList[j].name, CHAR(NA_STRING)) == 0) {
422                                         fprintf(oC->file, "%s", os->freeVarList[j].name);
423                                 } else {
424                                         fprintf(oC->file, "\"%s\"", os->freeVarList[j].name);
425                                 }
426                                 if (j != os->numFreeParams - 1) fprintf(oC->file, "\t");
427                         }
428                         fprintf(oC->file, "\n");
429                         fflush(oC->file);
430                 }
431         }
432  
433         void omxWriteCheckpointMessage(omxState *os, char *msg) {
434                 for(int i = 0; i < os->numCheckpoints; i++) {
435                         omxCheckpoint* oC = &(os->checkpointList[i]);
436                         if(os->chkptText1 == NULL) {    // First one: set up output
437                                 omxWriteCheckpointHeader(os, oC);
438                         }
439                         if (oC->type == OMX_FILE_CHECKPOINT) {
440                                 fprintf(oC->file, "%d \"%s\" NA ", os->majorIteration, msg);
441                                 for(int j = 0; j < os->numFreeParams; j++) {
442                                         fprintf(oC->file, "NA ");
443                                 }
444                                 fprintf(oC->file, "\n");
445                         }
446                 }
447         }
448
449         void omxSaveCheckpoint(omxState *os, double* x, double* f, int force) {
450                 time_t now = time(NULL);
451                 int soFar = now - os->startTime;                // Translated into minutes
452                 int n;
453                 for(int i = 0; i < os->numCheckpoints; i++) {
454                         n = 0;
455                         omxCheckpoint* oC = &(os->checkpointList[i]);
456                         // Check based on time            
457                         if((oC->time > 0 && (soFar - oC->lastCheckpoint) >= oC->time) || force) {
458                                 oC->lastCheckpoint = soFar;
459                                 n = 1;
460                         }
461                         // Or iterations
462                         if((oC->numIterations > 0 && (os->majorIteration - oC->lastCheckpoint) >= oC->numIterations) || force) {
463                                 oC->lastCheckpoint = os->majorIteration;
464                                 n = 1;
465                         }
466
467                         if(n) {         //In either case, save a checkpoint.
468                                 if(os->chkptText1 == NULL) {    // First one: set up output
469                                         omxWriteCheckpointHeader(os, oC);
470                                 }
471                                 char tempstring[25];
472                                 sprintf(tempstring, "%d", os->majorIteration);
473
474                                 if(strncmp(os->chkptText1, tempstring, strlen(tempstring))) {   // Returns zero if they're the same.
475                                         struct tm * nowTime = localtime(&now);                                          // So this only happens if the text is out of date.
476                                         strftime(tempstring, 25, "%b %d %Y %I:%M:%S %p", nowTime);
477                                         sprintf(os->chkptText1, "%d \"%s\" %9.5f", os->majorIteration, tempstring, f[0]);
478                                         for(int j = 0; j < os->numFreeParams; j++) {
479                                                 sprintf(tempstring, " %9.5f", x[j]);
480                                                 strncat(os->chkptText1, tempstring, 14);
481                                         }
482
483                                         double* hessian = os->hessian;
484                                         if(hessian != NULL) {
485                                                 for(int j = 0; j < os->numFreeParams; j++) {
486                                                         for(int k = 0; k <= j; k++) {
487                                                                 sprintf(tempstring, " %9.5f", hessian[j]);
488                                                                 strncat(os->chkptText2, tempstring, 14);
489                                                         }
490                                                 }
491                                         }
492                                 }
493
494                                 if(oC->type == OMX_FILE_CHECKPOINT) {
495                                         fprintf(oC->file, "%s", os->chkptText1);
496                                         if(oC->saveHessian)
497                                                 fprintf(oC->file, "%s", os->chkptText2);
498                                         fprintf(oC->file, "\n");
499                                         fflush(oC->file);
500                                 } else if(oC->type == OMX_SOCKET_CHECKPOINT) {
501                                         n = write(oC->socket, os->chkptText1, strlen(os->chkptText1));
502                                         if(n != strlen(os->chkptText1)) warning("Error writing checkpoint.");
503                                         if(oC->saveHessian) {
504                                                 n = write(oC->socket, os->chkptText2, strlen(os->chkptText2));
505                                                 if(n != strlen(os->chkptText1)) warning("Error writing checkpoint.");
506                                         }
507                                         n = write(oC->socket, "\n", 1);
508                                         if(n != 1) warning("Error writing checkpoint.");
509                                 } else if(oC->type == OMX_CONNECTION_CHECKPOINT) {
510                                         warning("NYI: R_connections are not yet implemented.");
511                                         oC->numIterations = 0;
512                                         oC->time = 0;
513                                 }
514                         }
515                 }
516         }
517
518 void omxExamineFitOutput(omxState *state, omxMatrix *fitMatrix, int *mode)
519 {
520         if (!R_FINITE(fitMatrix->data[0])) {
521                 omxRaiseErrorf(state, "Fit function returned %g at iteration %d.%d",
522                                fitMatrix->data[0], state->majorIteration, state->minorIteration);
523                 *mode = -1;
524         }
525 }