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