Move freeVars stuff out of omxState
[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 <string>
52
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 struct omxConfidenceInterval omxConfidenceInterval;
61
62 #include "omxMatrix.h"
63 #include "omxAlgebra.h"
64 #include "omxExpectation.h"
65 #include "omxFitFunction.h"
66 #include "omxData.h"
67
68 #include <vector>
69
70 struct omxFreeVarLocation {
71         int matrix;
72         int row, col;
73 };
74
75 struct omxFreeVar {                     // Free Variables
76         double lbound, ubound;  // Bounds
77         std::vector<omxFreeVarLocation> locations;
78         int numDeps;            // number of algebra/matrix dependencies
79         int *deps;              // indices of algebra/matrix dependencies
80         const char* name;
81 };
82
83 struct omxConstraint {          // Free Variable Constraints
84         int size;
85         int opCode;
86         double* lbound;
87         double* ubound;
88         omxMatrix* result;
89 };
90
91 enum omxCheckpointType {
92         OMX_FILE_CHECKPOINT,
93         OMX_CONNECTION_CHECKPOINT
94 };
95 typedef enum omxCheckpointType omxCheckpointType;
96
97 struct omxCheckpoint {
98         omxCheckpointType type;
99         time_t time;
100         int numIterations;
101         time_t lastCheckpoint;  // FIXME: Cannot update at sub-second times.
102         FILE* file;                                             // TODO: Maybe make the connection piece a union instead.
103         SEXP connection;
104         unsigned short int saveHessian;
105 };
106
107 struct omxConfidenceInterval {          // For Confidence interval request
108         omxMatrix* matrix;                              // The matrix
109         int row, col;                                   // Location of element to calculate
110         double ubound;                                  // Fit-space upper boundary
111         double lbound;                                  // Fit-space lower boundary
112         double max;                                             // Value at upper bound
113         double min;                                             // Value at lower bound
114         int lCode;                                              // Optimizer code at lower bound
115         int uCode;                                              // Optimizer code at upper bound
116         unsigned short calcLower;               // Are we currently calculating lbound?
117 };
118
119 #define MAX_STRING_LEN 250
120
121 // omxGlobal is for state that is read-only during parallel sections.
122 struct omxGlobal {
123         int ciMaxIterations;
124         int numThreads;
125         int analyticGradients;
126         int numChildren;
127
128         int numIntervals;
129         omxConfidenceInterval* intervalList;
130
131         int numFreeParams;
132         omxFreeVar* freeVarList;
133 };
134 extern struct omxGlobal Global;
135
136 // omxState is for stuff that must be duplicated for thread safety.
137 struct omxState {
138         std::vector< omxMatrix* > matrixList;
139         std::vector< omxMatrix* > algebraList;
140         std::vector< omxExpectation* > expectationList;
141         std::vector< omxData* > dataList;
142         std::vector< class omxCompute* > computeList;
143         omxState** childList;                                                                                   // List of child states
144         omxState* parentState;                                                                                  // Parent State
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
151 /* Data members for use by Fit Function and Algebra Calculations */
152         long int computeCount;                                                                                  // How many times have things been evaluated so far?
153         long int currentRow;                                                                                    // If we're calculating row-by-row, what row are we on?
154
155         /* For Checkpointing */
156         int majorIteration;                                                                                             // Major iteration number
157         int minorIteration;                                                                                             // Minor iteration within major iteration
158         time_t startTime;                                                                                               // Time of first computation
159         time_t endTime;                                                                                                 // 'Cause we might as well report it
160         omxCheckpoint* checkpointList;                                                                  // List of checkpoints
161         char *chkptText1, *chkptText2;                                                                  // Placeholders for checkpointing text
162         int numCheckpoints;                                                                                             // Number of checkpoints
163
164         char statusMsg[MAX_STRING_LEN];
165 };
166
167 extern omxState* globalState;
168
169 /* Initialize and Destroy */
170         void omxInitState(omxState* state, omxState *parentState);
171         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList, omxMatrix** algebraList, omxData** dataList, omxMatrix* fitFunction);
172 void omxFreeChildStates(omxState *state);
173 void omxFreeState(omxState *state);
174         void omxDuplicateState(omxState *tgt, omxState* src); 
175                                                                         // Duplicates the current state object
176         void omxSetMajorIteration(omxState *state, int value);                          // Recursively set major iteration number
177         void omxSetMinorIteration(omxState *state, int value);                          // Recursively set minor iteration number
178
179         omxMatrix* omxLookupDuplicateElement(omxState* os, omxMatrix* element);
180
181         void omxResetStatus(omxState *state);    
182 inline bool isErrorRaised(omxState *state) { return state->statusMsg[0] != 0; }
183 void omxRaiseError(omxState *state, int errorCode, const char* errorMsg); // DEPRECATED
184 void omxRaiseErrorf(omxState *state, const char* errorMsg, ...);
185                                                                                                                                                 // TODO: Move RaiseError to omxOptimizer.
186
187 /* Advance a step */
188         void omxStateNextRow(omxState *state);                                                          // Advance Row
189         void omxStateNextEvaluation(omxState *state);                                           // Advance Evaluation count
190
191         void omxWriteCheckpointMessage(char *msg);
192         void omxSaveCheckpoint(double* x, double* f, int force);        // Save out checkpoints
193 void omxExamineFitOutput(omxState *state, omxMatrix *fitMatrix, int *mode);
194
195 void mxLog(const char* msg, ...);   // thread-safe
196 void mxLogBig(const std::string str);
197 std::string string_snprintf(const std::string fmt, ...);
198
199 #endif /* _OMXSTATE_H_ */
200
201