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