Refrain from duplicating the model unless required by the fitfunction
[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 #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 "omxExpectation.h"
67 #include "omxFitFunction.h"
68 #include "omxData.h"
69 //#include "omxOptimizer.h"                                                                                     // omxOptimizer objects coming soon
70
71 /* Structure definitions for object evaluation */  // Might be cleaner to give these their own files.
72 struct omxFreeVar {                     // Free Variables
73         double lbound, ubound;  // Bounds
74         int numLocations;
75         int* matrices;                  // Matrix numbers.
76         int *row, *col;                 // Locations for copying.
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 struct omxOptimizerState {                      // For hessian or confidence interval computation
91         int currentParameter;                   // Which parameter is being examined?
92         double offset;                                  // Current offset of optimization
93         short int alpha;                                // Parameter multiplier
94         // NormalFit should be:  (Limit - (-2LL))^2 + alpha * parameter
95         // Alpha should generally be +1 to minimize parameter -1 to maximize
96 };
97
98 enum omxCheckpointType {
99         OMX_FILE_CHECKPOINT = 0,
100         OMX_SOCKET_CHECKPOINT = 1,
101         OMX_CONNECTION_CHECKPOINT = 2
102 };
103
104 struct omxCheckpoint {
105         omxCheckpointType type;
106         time_t time;
107         int numIterations;
108         unsigned long int lastCheckpoint;       // FIXME: Cannot update at sub-second times.
109         FILE* file;                                             // TODO: Maybe make the connection piece a union instead.
110         int socket;
111         SEXP connection;
112         unsigned short int saveHessian;
113 };
114
115 struct omxConfidenceInterval {          // For Confidence interval request
116         omxMatrix* matrix;                              // The matrix
117         int row, col;                                   // Location of element to calculate
118         double ubound;                                  // Fit-space upper boundary
119         double lbound;                                  // Fit-space lower boundary
120         double max;                                             // Value at upper bound
121         double min;                                             // Value at lower bound
122         int lCode;                                              // Optimizer code at lower bound
123         int uCode;                                              // Optimizer code at upper bound
124         unsigned short calcLower;               // Are we currently calculating lbound?
125 };
126
127 #define MAX_STRING_LEN 250
128
129 struct omxState {                                                                                                       // The Current State of Optimization
130
131 /* Model and Optimizer Pointers */
132
133 //      omxOptimizer* optimizer;                                                                                // Current Optimizer
134         int numThreads;
135         int numMats, numAlgs, numExpects, numData, numChildren;                 // Number of matrices, algebras, and data elements
136         omxMatrix** matrixList;                                                                                 // Model Matrices
137         omxMatrix** algebraList;                                                                                // Model Algebras
138         omxExpectation** expectationList;                                                       // Model Expectations
139         omxData** dataList;                                                                                             // Data Objects
140         omxState** childList;                                                                                   // List of child states
141         omxState* parentState;                                                                                  // Parent State
142         int* markMatrices;                                                                                              // An array of [0,1] values used by markFreeVarDependencies()
143
144                                                                     // TODO: Need a way to deal with unregistered matrices that have free vars
145         omxMatrix* fitMatrix;                                                                                   // Fit Function Algebra
146
147         /* May want to farm these out to the omxFitFunction object. */
148         int numConstraints;
149         int nclin, ncnln;                                               // Number of linear and nonlinear constraints
150         omxConstraint* conList;                                                                                 // List of constraints
151         int numIntervals;
152         int currentInterval;                                                                                    // The interval currently being calculated
153         omxConfidenceInterval* intervalList;                                                    // List of confidence intervals requested
154
155         int numFreeParams;
156         omxFreeVar* freeVarList;                                                                                // List of Free Variables and where they go.
157
158         /* Saved Optimum State */ // TODO: Rename saved optimum state
159         double* optimalValues;                                                                                  // Values of the free parameters at the optimum value
160         double optimum;                                                                                                 // Fit function value at last saved optimum
161         double* hessian;                                                                                                // Current hessian storage
162         int optimumStatus;                                                                                              // Optimizer status of last saved optimum (0=converged, 1=green, -1=error, >1=red)
163         char optimumMsg[MAX_STRING_LEN];                                                                                        // Status message of last saved optimum
164         omxOptimizerState* optimizerState;                                                              // Current optimum parameters for limit computation
165
166 /* Current Optimization State (optimizer-specific) */
167 //      void* optimizerInfo;                                                                                    // Optimizer specific storage
168
169 /* Data members for use by Fit Function and Algebra Calculations */
170         long int computeCount;                                                                                  // How many times have things been evaluated so far?
171         long int currentRow;                                                                                    // If we're calculating row-by-row, what row are we on?
172
173         /* For Checkpointing */
174         int majorIteration;                                                                                             // Major iteration number
175         int minorIteration;                                                                                             // Minor iteration within major iteration
176         time_t startTime;                                                                                               // Time of first computation
177         time_t endTime;                                                                                                 // 'Cause we might as well report it
178         omxCheckpoint* checkpointList;                                                                  // List of checkpoints
179         char *chkptText1, *chkptText2;                                                                  // Placeholders for checkpointing text
180         int numCheckpoints;                                                                                             // Number of checkpoints
181
182         int inform, iter;                                                                                                       // Status code, if appropriate
183         int statusCode;
184         char statusMsg[MAX_STRING_LEN];                                                                                 // Status/Error message to report
185         double saturatedModel;                                                                                  // Saturated model likelihood, where applicable
186         int analyticGradients;
187 };
188
189 /* Initialize and Destroy */
190         void omxInitState(omxState* state, omxState *parentState);
191         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList, omxMatrix** algebraList, omxData** dataList, omxMatrix* fitFunction);
192         void omxFreeState(omxState *state);                                                                     // Destructor
193         void omxSaveState(omxState *os, double* freeVals, double minimum);      // Saves the current optimization values //TODO: Rename omxSaveState.
194         void omxUpdateState(omxState* tgt, omxState* src, int copyStatus);      // Updates the tgt state with the contents of src state
195         void omxPartialUpdateState(omxState* tgt, omxState* src, omxMatrix *tgtMatrix,
196                                omxMatrix *srcMatrix, int copyStatus);    // Updates the tgt state with the contents of src state ONLY for the specific matrix and its dependencies
197         void omxDuplicateState(omxState *tgt, omxState* src); 
198         int omxTotalThreadCount(omxState *state);
199                                                                         // Duplicates the current state object
200         omxState* omxGetState(omxState *os, int stateNum);                                      // Retrieve a child by number
201
202         void omxSetMajorIteration(omxState *state, int value);                          // Recursively set major iteration number
203         void omxSetMinorIteration(omxState *state, int value);                          // Recursively set minor iteration number
204
205         omxMatrix* omxLookupDuplicateElement(omxState* os, omxMatrix* element);
206         omxExpectation* omxLookupDuplicateExpectation(omxState* os, omxExpectation* ox);
207
208         void omxResetStatus(omxState *state);    
209         void omxRaiseError(omxState *state, int errorCode, char* errorMsg);     // old API
210 void omxRaiseErrorf(omxState *state, char* errorMsg, ...);   // new API
211                                                                                                                                                 // TODO: Move RaiseError to omxOptimizer.
212
213 /* Advance a step */
214         void omxStateNextRow(omxState *state);                                                          // Advance Row
215         void omxStateNextEvaluation(omxState *state);                                           // Advance Evaluation count
216
217         void omxWriteCheckpointMessage(omxState *os, char *msg);
218         void omxSaveCheckpoint(omxState* os, double* x, double* f, int force);  // Save out checkpoints
219 void omxExamineFitOutput(omxState *state, omxMatrix *fitMatrix, int *mode);
220
221 #endif /* _OMXSTATE_H_ */
222
223