With checkpoint=TRUE, always write to the checkpoint
[openmx:openmx.git] / src / omxState.h
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.h
20 *
21 *  Created: Timothy R. Brick    Date: 2009-05-23
22 *
23 *       Contains header information for the omxState structure
24 *   omxStates keep the current optimization state.
25 *
26 **********************************************************/
27
28 #ifndef _OMXSTATE_H_
29 #define _OMXSTATE_H_
30
31 #include "R.h"
32 #include <Rinternals.h>
33 #include <Rdefines.h>
34 #include <R_ext/Rdynload.h>
35 #include <R_ext/BLAS.h>
36 #include <R_ext/Lapack.h>
37 #include <sys/types.h>
38
39 #ifdef WIN32
40
41 #include <winsock.h>
42
43 #else
44
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <netdb.h>
48
49 #endif
50
51 #include <time.h>
52 #include <unistd.h>
53 #include "omxDefines.h"
54
55 /* Forward declarations for later includes */
56 typedef struct omxState omxState;
57 typedef struct omxFreeVar omxFreeVar;
58 typedef struct omxConstraint omxConstraint;
59 typedef struct omxCheckpoint omxCheckpoint;
60 typedef enum omxCheckpointType omxCheckpointType;
61 typedef struct omxOptimizerState omxOptimizerState;
62 typedef struct omxConfidenceInterval omxConfidenceInterval;
63
64 #include "omxMatrix.h"
65 #include "omxAlgebra.h"
66 #include "omxObjective.h"
67 #include "omxData.h"
68 //#include "omxOptimizer.h"                                                                                     // omxOptimizer objects coming soon
69
70 /* Structure definitions for object evaluation */  // Might be cleaner to give these their own files.
71 struct omxFreeVar {                     // Free Variables
72         double lbound, ubound;  // Bounds
73         int numLocations;
74         int* matrices;                  // Matrix numbers.
75         int *row, *col;                 // Locations for copying.
76         const char* name;
77 };
78
79 struct omxConstraint {          // Free Variable Constraints
80         int size;
81         int opCode;
82         double* lbound;
83         double* ubound;
84         omxMatrix* result;
85 };
86
87 struct omxOptimizerState {                      // For hessian or confidence interval computation
88         int currentParameter;                   // Which parameter is being examined?
89         double offset;                                  // Current offset of optimization
90         short int alpha;                                // Parameter multiplier
91         // Objective should be:  (3.84 - (-2LL))^2 + alpha * parameter
92         // Alpha should generally be +1 to minimize parameter -1 to maximize
93 };
94
95 enum omxCheckpointType {
96         OMX_FILE_CHECKPOINT = 0,
97         OMX_SOCKET_CHECKPOINT = 1,
98         OMX_CONNECTION_CHECKPOINT = 2
99 };
100
101 struct omxCheckpoint {
102         omxCheckpointType type;
103         time_t time;
104         int numIterations;
105         unsigned long int lastCheckpoint;       // FIXME: Cannot update at sub-second times.
106         FILE* file;                                             // TODO: Maybe make the connection piece a union instead.
107         int socket;
108         SEXP connection;
109         unsigned short int saveHessian;
110 };
111
112 struct omxConfidenceInterval {          // For Confidence interval request
113         omxMatrix* matrix;                              // The matrix
114         int row, col;                                   // Location of element to calculate
115         double ubound;                                  // Objective-space upper boundary
116         double lbound;                                  // Objective-space lower boundary
117         double max;                                             // Value at upper bound
118         double min;                                             // Value at lower bound
119         int lCode;                                              // Optimizer code at lower bound
120         int uCode;                                              // Optimizer code at upper bound
121         unsigned short calcLower;               // Are we currently calculating lbound?
122 };
123
124 #define MAX_STRING_LEN 250
125
126 struct omxState {                                                                                                       // The Current State of Optimization
127
128 /* Model and Optimizer Pointers */
129
130 //      omxOptimizer* optimizer;                                                                                // Current Optimizer
131         int numMats, numAlgs, numData, numChildren;                                             // Number of matrices, algebras, and data elements
132         omxMatrix** matrixList;                                                                                 // Model Matrices
133         omxMatrix** algebraList;                                                                                // Model Algebras
134         omxData** dataList;                                                                                             // Data Objects
135         omxState** childList;                                                                                   // List of child states
136         omxState* parentState;                                                                                  // Parent State
137
138                                                                     // TODO: Need a way to deal with unregistered matrices that have free vars
139         omxMatrix* objectiveMatrix;                                                                             // Objective Algebra
140
141         /* May want to farm these out to the omxObjective object. */
142         int numConstraints;
143         omxConstraint* conList;                                                                                 // List of constraints
144         int numIntervals;
145         int currentInterval;                                                                                    // The interval currently being calculated
146         omxConfidenceInterval* intervalList;                                                    // List of confidence intervals requested
147
148         int numFreeParams;
149         omxFreeVar* freeVarList;                                                                                // List of Free Variables and where they go.
150
151         /* Saved Optimum State */ // TODO: Rename saved optimum state
152         double* optimalValues;                                                                                  // Values of the free parameters at the optimum value
153         double optimum;                                                                                                 // Objective value at last saved optimum
154         double* hessian;                                                                                                // Current hessian storage
155         int optimumStatus;                                                                                              // Optimizer status of last saved optimum (0=converged, 1=green, -1=error, >1=red)
156         char optimumMsg[250];                                                                                   // Status message of last saved optimum
157         omxOptimizerState* optimizerState;                                                              // Current optimum parameters for limit computation
158
159 /* Current Optimization State (optimizer-specific) */
160 //      void* optimizerInfo;                                                                                    // Optimizer specific storage
161
162 /* Data members for use by Objective Function and Algebra Calculations */
163         long int computeCount;                                                                                  // How many times have things been evaluated so far?
164         long int currentRow;                                                                                    // If we're calculating row-by-row, what row are we on?
165
166         /* For Checkpointing */
167         int majorIteration;                                                                                             // Major iteration number
168         int minorIteration;                                                                                             // Minor iteration within major iteration
169         time_t startTime;                                                                                               // Time of first computation
170         time_t endTime;                                                                                                 // 'Cause we might as well report it
171         omxCheckpoint* checkpointList;                                                                  // List of checkpoints
172         char *chkptText1, *chkptText2;                                                                  // Placeholders for checkpointing text
173         int numCheckpoints;                                                                                             // Number of checkpoints
174
175         int statusCode;                                                                                                 // Status code, if appropriate
176         char statusMsg[250];                                                                                    // Status/Error message to report
177         double saturatedModel;                                                                                  // Saturated model likelihood, where applicable
178         int analyticGradients;
179 };
180
181 /* Initialize and Destroy */
182         void omxInitState(omxState* state, omxState *parentState, int numChildren); // Constructor
183         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList, omxMatrix** algebraList, omxData** dataList, omxMatrix* objective);
184         void omxFreeState(omxState *state);                                                                     // Destructor
185         void omxSaveState(omxState *os, double* freeVals, double minimum);      // Saves the current optimization values //TODO: Rename omxSaveState.
186         void omxUpdateState(omxState* tgt, omxState* src, int copyStatus);      // Updates the tgt state with the contents of src state
187         void omxDuplicateState(omxState *tgt, omxState* src); 
188         int omxTotalThreadCount(omxState *state);
189                                                                         // Duplicates the current state object
190         omxState* omxGetState(omxState *os, int stateNum);                                      // Retrieve a child by number
191
192         void omxSetMajorIteration(omxState *state, int value);                          // Recursively set major iteration number
193         void omxSetMinorIteration(omxState *state, int value);                          // Recursively set minor iteration number
194
195         omxMatrix* omxLookupDuplicateElement(omxState* os, omxMatrix* element);
196     
197         void omxRaiseError(omxState *state, int errorCode, char* errorMsg);     // Raise an Error
198                                                                                                                                                 // TODO: Move RaiseError to omxOptimizer.
199
200 /* Advance a step */
201         void omxStateNextRow(omxState *state);                                                          // Advance Row
202         void omxStateNextEvaluation(omxState *state);                                           // Advance Evaluation count
203
204         void omxSaveCheckpoint(omxState* os, double* x, double* f, int force);  // Save out checkpoints
205
206 #endif /* _OMXSTATE_H_ */
207
208