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