Partial check-in of checkpointing code.
[openmx:openmx.git] / src / omxState.h
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.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 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <time.h>
41 #include <netdb.h>
42 #include <unistd.h>
43 #include "omxDefines.h"
44
45 /* Forward declarations for later includes */
46 typedef struct omxState omxState;
47 typedef struct omxFreeVar omxFreeVar;
48 typedef struct omxConstraint omxConstraint;
49 typedef struct omxCheckpoint omxCheckpoint;
50 typedef enum omxCheckpointType omxCheckpointType;
51 typedef struct omxOptimizerState omxOptimizerState;
52 typedef struct omxConfidenceInterval omxConfidenceInterval;
53
54 #include "omxMatrix.h"
55 #include "omxAlgebra.h"
56 #include "omxObjective.h"
57 #include "omxData.h"
58 //#include "omxOptimizer.h"                                                                                     // omxOptimizer objects coming soon
59
60 /* Structure definitions for object evaluation */  // Might be cleaner to give these their own files.
61 struct omxFreeVar {                     // Free Variables
62         double lbound, ubound;  // Bounds
63         int numLocations;
64         double** location;              // And where they go.
65         int* matrices;                  // Matrix numbers for dirtying.
66 };
67
68 struct omxConstraint {          // Free Variable Constraints
69         int size;
70         int opCode;
71         double* lbound;
72         double* ubound;
73         omxMatrix* result;
74 };
75
76 struct omxOptimizerState {                      // For hessian or confidence interval computation
77         int currentParameter;                   // Which parameter is being examined?
78         double offset;                                  // Current offset of optimization
79         short int alpha;                                // Parameter multiplier
80         // Objective should be:  (3.84 - (-2LL))^2 + alpha * parameter
81         // Alpha should generally be +1 to minimize parameter -1 to maximize
82 };
83
84 enum omxCheckpointType {
85         OMX_FILE_CHECKPOINT = 0,
86         OMX_SOCKET_CHECKPOINT = 1,
87         OMX_CONNECTION_CHECKPOINT = 2
88 };
89
90 struct omxCheckpoint {
91         omxCheckpointType type;
92         time_t time;
93         int numIterations;
94         double lastCheckpoint;
95         FILE* file;                                     // TODO: Maybe make the connection piece a union instead.
96         int socket;
97         SEXP connection;
98         unsigned short int saveHessian;
99 };
100
101 struct omxConfidenceInterval {          // For Confidence interval request
102         omxMatrix* matrix;                              // The matrix
103         int row, col;                                   // Location of element to calculate
104         double ubound;                                  // Objective-space upper boundary
105         double lbound;                                  // Objective-space lower boundary
106         double max;                                             // Value at upper bound
107         double min;                                             // Value at lower bound
108         int lCode;                                              // Optimizer code at lower bound
109         int uCode;                                              // Optimizer code at upper bound
110         unsigned short calcLower;               // Are we currently calculating lbound?
111 };
112
113 #define MAX_STRING_LEN 250
114
115 struct omxState {                                                                                                       // The Current State of Optimization
116
117 /* Model and Optimizer Pointers */
118
119 //      omxOptimizer* optimizer;                                                                                // Current Optimizer
120         int numMats, numAlgs, numData;                                                                  // Number of matrices, algebras, and data elements
121         omxMatrix** matrixList;                                                                                 // Model Matrices
122         omxMatrix** algebraList;                                                                                // Model Algebras
123         omxData** dataList;                                                                                             // Data Objects
124         omxMatrix* objectiveMatrix;                                                                             // Objective Algebra
125
126         /* May want to farm these out to the omxObjective object. */
127         int numConstraints;
128         omxConstraint* conList;                                                                                 // List of constraints
129         int numIntervals;
130         int currentInterval;                                                                                    // The interval currently being calculated
131         omxConfidenceInterval* intervalList;                                                    // List of confidence intervals requested
132
133         int numFreeParams;
134         omxFreeVar* freeVarList;                                                                                // List of Free Variables and where they go.
135         
136         /* Saved Optimum State */ // TODO: Rename saved optimum state
137         double* optimalValues;                                                                                  // Values of the free parameters at the optimum value
138         double optimum;                                                                                                 // Objective value at last saved optimum
139         double* hessian;                                                                                                // Current hessian storage
140         int optimumStatus;                                                                                              // Optimizer status of last saved optimum (0=converged, 1=green, -1=error, >1=red)
141         char optimumMsg[250];                                                                                   // Status message of last saved optimum
142         omxOptimizerState* optimizerState;                                                              // Current optimum parameters for limit computation
143
144 /* Current Optimization State (optimizer-specific) */
145 //      void* optimizerInfo;                                                                                    // Optimizer specific storage
146
147 /* Data members for use by Objective Function and Algebra Calculations */
148         long int computeCount;                                                                                  // How many times have things been evaluated so far?
149         long int currentRow;                                                                                    // If we're calculating row-by-row, what row are we on?
150         
151         /* For Checkpointing */
152         int majorIteration;                                                                                             // Major iteration number
153         int minorIteration;                                                                                             // Minor iteration within major iteration
154         time_t startTime;                                                                                               // Time of first computation
155         time_t endTime;                                                                                                 // 'Cause we might as well report it
156         omxCheckpoint* checkpointList;                                                                          // List of checkpoints
157         char *chkptText1, *chkptText2;                                                                  // Placeholders for checkpointing text
158         int numCheckpoints;                                                                                             // Number of checkpoints
159         
160         int statusCode;                                                                                                 // Status code, if appropriate
161         char statusMsg[250];                                                                                    // Status/Error message to report
162         double saturatedModel;                                                                                  // Saturated model likelihood, where applicable
163
164 };
165
166 /* Initialize and Destroy */
167         void omxInitState(omxState* state);                                                                     // Null Constructor
168         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList, omxMatrix** algebraList, omxData** dataList, omxMatrix* objective); 
169         void omxFreeState(omxState *oo);                                                                        // Destructor
170         void omxSaveState(omxState *os, double* freeVals, double minimum);      // Saves the current optimization values //TODO: Rename omxSaveState.
171         
172         void omxRaiseError(omxState *oo, int errorCode, char* errorMsg);        // Raise an Error 
173                                                                                                                                                 // TODO: Move RaiseError to omxOptimizer.
174         
175 /* Advance a step */
176         void omxStateNextRow(omxState *oo);                                                                     // Advance Row
177         void omxStateNextEvaluation(omxState *oo);                                                      // Advance Evaluation count
178         
179         void omxSaveCheckpoint(omxState* os, double* x);                                        // Save out checkpoints
180         
181 #endif /* _OMXSTATE_H_ */
182
183