Revert "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 numMats, numAlgs, numExpects, numData, numChildren;                 // Number of matrices, algebras, and data elements
135         omxMatrix** matrixList;                                                                                 // Model Matrices
136         omxMatrix** algebraList;                                                                                // Model Algebras
137         omxExpectation** expectationList;                                                       // Model Expectations
138         omxData** dataList;                                                                                             // Data Objects
139         omxState** childList;                                                                                   // List of child states
140         omxState* parentState;                                                                                  // Parent State
141         int* markMatrices;                                                                                              // An array of [0,1] values used by markFreeVarDependencies()
142
143                                                                     // TODO: Need a way to deal with unregistered matrices that have free vars
144         omxMatrix* fitMatrix;                                                                                   // Fit Function Algebra
145
146         /* May want to farm these out to the omxFitFunction object. */
147         int numConstraints;
148         int nclin, ncnln;                                               // Number of linear and nonlinear constraints
149         omxConstraint* conList;                                                                                 // List of constraints
150         int numIntervals;
151         int currentInterval;                                                                                    // The interval currently being calculated
152         omxConfidenceInterval* intervalList;                                                    // List of confidence intervals requested
153
154         int numFreeParams;
155         omxFreeVar* freeVarList;                                                                                // List of Free Variables and where they go.
156
157         /* Saved Optimum State */ // TODO: Rename saved optimum state
158         double* optimalValues;                                                                                  // Values of the free parameters at the optimum value
159         double optimum;                                                                                                 // Fit function value at last saved optimum
160         double* hessian;                                                                                                // Current hessian storage
161         int optimumStatus;                                                                                              // Optimizer status of last saved optimum (0=converged, 1=green, -1=error, >1=red)
162         char optimumMsg[MAX_STRING_LEN];                                                                                        // Status message of last saved optimum
163         omxOptimizerState* optimizerState;                                                              // Current optimum parameters for limit computation
164
165 /* Current Optimization State (optimizer-specific) */
166 //      void* optimizerInfo;                                                                                    // Optimizer specific storage
167
168 /* Data members for use by Fit Function and Algebra Calculations */
169         long int computeCount;                                                                                  // How many times have things been evaluated so far?
170         long int currentRow;                                                                                    // If we're calculating row-by-row, what row are we on?
171
172         /* For Checkpointing */
173         int majorIteration;                                                                                             // Major iteration number
174         int minorIteration;                                                                                             // Minor iteration within major iteration
175         time_t startTime;                                                                                               // Time of first computation
176         time_t endTime;                                                                                                 // 'Cause we might as well report it
177         omxCheckpoint* checkpointList;                                                                  // List of checkpoints
178         char *chkptText1, *chkptText2;                                                                  // Placeholders for checkpointing text
179         int numCheckpoints;                                                                                             // Number of checkpoints
180
181         int inform, iter;                                                                                                       // Status code, if appropriate
182         int statusCode;
183         char statusMsg[MAX_STRING_LEN];                                                                                 // Status/Error message to report
184         double saturatedModel;                                                                                  // Saturated model likelihood, where applicable
185         int analyticGradients;
186 };
187
188 /* Initialize and Destroy */
189         void omxInitState(omxState* state, omxState *parentState, int numChildren); // Constructor
190         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList, omxMatrix** algebraList, omxData** dataList, omxMatrix* fitFunction);
191         void omxFreeState(omxState *state);                                                                     // Destructor
192         void omxSaveState(omxState *os, double* freeVals, double minimum);      // Saves the current optimization values //TODO: Rename omxSaveState.
193         void omxUpdateState(omxState* tgt, omxState* src, int copyStatus);      // Updates the tgt state with the contents of src state
194         void omxPartialUpdateState(omxState* tgt, omxState* src, omxMatrix *tgtMatrix,
195                                omxMatrix *srcMatrix, int copyStatus);    // Updates the tgt state with the contents of src state ONLY for the specific matrix and its dependencies
196         void omxDuplicateState(omxState *tgt, omxState* src); 
197         int omxTotalThreadCount(omxState *state);
198                                                                         // Duplicates the current state object
199         omxState* omxGetState(omxState *os, int stateNum);                                      // Retrieve a child by number
200
201         void omxSetMajorIteration(omxState *state, int value);                          // Recursively set major iteration number
202         void omxSetMinorIteration(omxState *state, int value);                          // Recursively set minor iteration number
203
204         omxMatrix* omxLookupDuplicateElement(omxState* os, omxMatrix* element);
205         omxExpectation* omxLookupDuplicateExpectation(omxState* os, omxExpectation* ox);
206
207         void omxResetStatus(omxState *state);    
208         void omxRaiseError(omxState *state, int errorCode, char* errorMsg);     // old API
209 void omxRaiseErrorf(omxState *state, char* errorMsg, ...);   // new API
210                                                                                                                                                 // TODO: Move RaiseError to omxOptimizer.
211
212 /* Advance a step */
213         void omxStateNextRow(omxState *state);                                                          // Advance Row
214         void omxStateNextEvaluation(omxState *state);                                           // Advance Evaluation count
215
216         void omxWriteCheckpointMessage(omxState *os, char *msg);
217         void omxSaveCheckpoint(omxState* os, double* x, double* f, int force);  // Save out checkpoints
218 void omxExamineFitOutput(omxState *state, omxMatrix *fitMatrix, int *mode);
219
220 #endif /* _OMXSTATE_H_ */
221
222