omxComputeEstimateHessian reorg 8/11
[openmx:openmx.git] / src / omxState.h
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.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 #else
42
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <netdb.h>
46
47 #endif
48
49 #include <time.h>
50 #include <unistd.h>
51 #include "omxDefines.h"
52
53 /* Forward declarations for later includes */
54 typedef struct omxState omxState;
55 typedef struct omxFreeVar omxFreeVar;
56 typedef struct omxConstraint omxConstraint;
57 typedef struct omxCheckpoint omxCheckpoint;
58 typedef struct omxConfidenceInterval omxConfidenceInterval;
59
60 #include "omxMatrix.h"
61 #include "omxAlgebra.h"
62 #include "omxExpectation.h"
63 #include "omxFitFunction.h"
64 #include "omxData.h"
65 //#include "omxOptimizer.h"                                                                                     // omxOptimizer objects coming soon
66
67 #include <vector>
68
69 struct omxFreeVarLocation {
70         int matrix;
71         int row, col;
72 };
73
74 struct omxFreeVar {                     // Free Variables
75         double lbound, ubound;  // Bounds
76         std::vector<omxFreeVarLocation> locations;
77         int numDeps;            // number of algebra/matrix dependencies
78         int *deps;              // indices of algebra/matrix dependencies
79         const char* name;
80 };
81
82 struct omxConstraint {          // Free Variable Constraints
83         int size;
84         int opCode;
85         double* lbound;
86         double* ubound;
87         omxMatrix* result;
88 };
89
90 enum omxCheckpointType {
91         OMX_FILE_CHECKPOINT,
92         OMX_CONNECTION_CHECKPOINT
93 };
94 typedef enum omxCheckpointType omxCheckpointType;
95
96 struct omxCheckpoint {
97         omxCheckpointType type;
98         time_t time;
99         int numIterations;
100         time_t lastCheckpoint;  // FIXME: Cannot update at sub-second times.
101         FILE* file;                                             // TODO: Maybe make the connection piece a union instead.
102         SEXP connection;
103         unsigned short int saveHessian;
104 };
105
106 struct omxConfidenceInterval {          // For Confidence interval request
107         omxMatrix* matrix;                              // The matrix
108         int row, col;                                   // Location of element to calculate
109         double ubound;                                  // Fit-space upper boundary
110         double lbound;                                  // Fit-space lower boundary
111         double max;                                             // Value at upper bound
112         double min;                                             // Value at lower bound
113         int lCode;                                              // Optimizer code at lower bound
114         int uCode;                                              // Optimizer code at upper bound
115         unsigned short calcLower;               // Are we currently calculating lbound?
116 };
117
118 #define MAX_STRING_LEN 250
119
120 struct omxState {
121         int numHessians;
122         int calculateStdErrors;
123
124         int numThreads;
125         int numAlgs, numExpects, numChildren;
126         std::vector< omxMatrix* > matrixList;
127         omxMatrix** algebraList;                                                                                // Model Algebras
128         omxExpectation** expectationList;                                                       // Model Expectations
129         std::vector< omxData* > dataList;
130         omxState** childList;                                                                                   // List of child states
131         omxState* parentState;                                                                                  // Parent State
132         std::vector<int> markMatrices;
133
134                                                                     // TODO: Need a way to deal with unregistered matrices that have free vars
135         omxMatrix* fitMatrix;                                                                                   // Fit Function Algebra
136
137         /* May want to farm these out to the omxFitFunction object. */
138         int numConstraints;
139         int nclin, ncnln;                                               // Number of linear and nonlinear constraints
140         omxConstraint* conList;                                                                                 // List of constraints
141         int numIntervals;
142         int currentInterval;                                                                                    // The interval currently being calculated
143         omxConfidenceInterval* intervalList;                                                    // List of confidence intervals requested
144
145         int numFreeParams;
146         omxFreeVar* freeVarList;                                                                                // List of Free Variables and where they go.
147
148         /* Saved Optimum State */ // TODO: Rename saved optimum state
149         double* optimalValues;                                                                                  // Values of the free parameters at the optimum value
150         double optimum;                                                                                                 // Fit function value at last saved optimum
151
152 /* Data members for use by Fit Function and Algebra Calculations */
153         long int computeCount;                                                                                  // How many times have things been evaluated so far?
154         long int currentRow;                                                                                    // If we're calculating row-by-row, what row are we on?
155
156         /* For Checkpointing */
157         int majorIteration;                                                                                             // Major iteration number
158         int minorIteration;                                                                                             // Minor iteration within major iteration
159         time_t startTime;                                                                                               // Time of first computation
160         time_t endTime;                                                                                                 // 'Cause we might as well report it
161         omxCheckpoint* checkpointList;                                                                  // List of checkpoints
162         char *chkptText1, *chkptText2;                                                                  // Placeholders for checkpointing text
163         int numCheckpoints;                                                                                             // Number of checkpoints
164
165         int inform, iter;                                                                                                       // Status code, if appropriate
166         int statusCode;
167         char statusMsg[MAX_STRING_LEN];                                                                                 // Status/Error message to report
168         int analyticGradients;
169 };
170
171 /* Initialize and Destroy */
172         void omxInitState(omxState* state, omxState *parentState);
173         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList, omxMatrix** algebraList, omxData** dataList, omxMatrix* fitFunction);
174         void omxFreeState(omxState *state);                                                                     // Destructor
175         void omxSaveState(omxState *os, double* freeVals, double minimum);      // Saves the current optimization values //TODO: Rename omxSaveState.
176         void omxUpdateState(omxState* tgt, omxState* src, int copyStatus);      // Updates the tgt state with the contents of src state
177         void omxPartialUpdateState(omxState* tgt, omxState* src, omxMatrix *tgtMatrix,
178                                omxMatrix *srcMatrix, int copyStatus);    // Updates the tgt state with the contents of src state ONLY for the specific matrix and its dependencies
179         void omxDuplicateState(omxState *tgt, omxState* src); 
180                                                                         // Duplicates the current state object
181         omxState* omxGetState(omxState *os, int stateNum);                                      // Retrieve a child by number
182
183         void omxSetMajorIteration(omxState *state, int value);                          // Recursively set major iteration number
184         void omxSetMinorIteration(omxState *state, int value);                          // Recursively set minor iteration number
185
186         omxMatrix* omxLookupDuplicateElement(omxState* os, omxMatrix* element);
187         omxExpectation* omxLookupDuplicateExpectation(omxState* os, omxExpectation* ox);
188
189         void omxResetStatus(omxState *state);    
190 void omxRaiseError(omxState *state, int errorCode, const char* errorMsg);
191 void omxRaiseErrorf(omxState *state, const char* errorMsg, ...);
192                                                                                                                                                 // TODO: Move RaiseError to omxOptimizer.
193
194 /* Advance a step */
195         void omxStateNextRow(omxState *state);                                                          // Advance Row
196         void omxStateNextEvaluation(omxState *state);                                           // Advance Evaluation count
197
198         void omxWriteCheckpointMessage(omxState *os, char *msg);
199         void omxSaveCheckpoint(omxState* os, double* x, double* f, int force);  // Save out checkpoints
200 void omxExamineFitOutput(omxState *state, omxMatrix *fitMatrix, int *mode);
201
202 #endif /* _OMXSTATE_H_ */
203
204