Changes necessary to get "Number of Cores" option to do anything (namely crash OpenMx)
[openmx:openmx.git] / src / omxState.h
1 /*
2  *  Copyright 2007-2009 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 "omxObjective.h"
67 #include "omxData.h"
68 //#include "omxOptimizer.h"                                                                                     // omxOptimizer objects coming soon
69
70 /* Structure definitions for object evaluation */  // Might be cleaner to give these their own files.
71 struct omxFreeVar {                     // Free Variables
72         double lbound, ubound;  // Bounds
73         int numLocations;
74         double** location;              // And where they go.
75         int* matrices;                  // Matrix numbers for dirtying.
76         int *row, *col;                 // Locations for copying.
77         const char* name;
78 };
79
80 struct omxConstraint {          // Free Variable Constraints
81         int size;
82         int opCode;
83         double* lbound;
84         double* ubound;
85         omxMatrix* result;
86 };
87
88 struct omxOptimizerState {                      // For hessian or confidence interval computation
89         int currentParameter;                   // Which parameter is being examined?
90         double offset;                                  // Current offset of optimization
91         short int alpha;                                // Parameter multiplier
92         // Objective should be:  (3.84 - (-2LL))^2 + alpha * parameter
93         // Alpha should generally be +1 to minimize parameter -1 to maximize
94 };
95
96 enum omxCheckpointType {
97         OMX_FILE_CHECKPOINT = 0,
98         OMX_SOCKET_CHECKPOINT = 1,
99         OMX_CONNECTION_CHECKPOINT = 2
100 };
101
102 struct omxCheckpoint {
103         omxCheckpointType type;
104         time_t time;
105         int numIterations;
106         unsigned long int lastCheckpoint;       // FIXME: Cannot update at sub-second times.
107         FILE* file;                                             // TODO: Maybe make the connection piece a union instead.
108         int socket;
109         SEXP connection;
110         unsigned short int saveHessian;
111 };
112
113 struct omxConfidenceInterval {          // For Confidence interval request
114         omxMatrix* matrix;                              // The matrix
115         int row, col;                                   // Location of element to calculate
116         double ubound;                                  // Objective-space upper boundary
117         double lbound;                                  // Objective-space lower boundary
118         double max;                                             // Value at upper bound
119         double min;                                             // Value at lower bound
120         int lCode;                                              // Optimizer code at lower bound
121         int uCode;                                              // Optimizer code at upper bound
122         unsigned short calcLower;               // Are we currently calculating lbound?
123 };
124
125 #define MAX_STRING_LEN 250
126
127 struct omxState {                                                                                                       // The Current State of Optimization
128
129 /* Model and Optimizer Pointers */
130
131 //      omxOptimizer* optimizer;                                                                                // Current Optimizer
132         int numMats, numAlgs, numData, numChildren;                                             // Number of matrices, algebras, and data elements
133         omxMatrix** matrixList;                                                                                 // Model Matrices
134         omxMatrix** algebraList;                                                                                // Model Algebras
135         omxData** dataList;                                                                                             // Data Objects
136     omxState** childList;                                           // List of child states
137     omxState* parentState;                                          // Parent State
138     omxMatrix** parentMatrix;                                       // Parent's Matrix List
139     omxMatrix** parentAlgebra;                                      // Parent's Algebra List
140         omxConstraint* parentConList;                                                                   // Parent's Constraint List
141                                                                     // TODO: Need a way to deal with unregistered matrices that have free vars
142         omxMatrix* objectiveMatrix;                                                                             // Objective Algebra
143
144         /* May want to farm these out to the omxObjective object. */
145         int numConstraints;
146         omxConstraint* conList;                                                                                 // List of constraints
147         int numIntervals;
148         int currentInterval;                                                                                    // The interval currently being calculated
149         omxConfidenceInterval* intervalList;                                                    // List of confidence intervals requested
150
151         int numFreeParams;
152         omxFreeVar* freeVarList;                                                                                // List of Free Variables and where they go.
153
154         /* Saved Optimum State */ // TODO: Rename saved optimum state
155         double* optimalValues;                                                                                  // Values of the free parameters at the optimum value
156         double optimum;                                                                                                 // Objective value at last saved optimum
157         double* hessian;                                                                                                // Current hessian storage
158         int optimumStatus;                                                                                              // Optimizer status of last saved optimum (0=converged, 1=green, -1=error, >1=red)
159         char optimumMsg[250];                                                                                   // Status message of last saved optimum
160         omxOptimizerState* optimizerState;                                                              // Current optimum parameters for limit computation
161
162 /* Current Optimization State (optimizer-specific) */
163 //      void* optimizerInfo;                                                                                    // Optimizer specific storage
164
165 /* Data members for use by Objective Function and Algebra Calculations */
166         long int computeCount;                                                                                  // How many times have things been evaluated so far?
167         long int currentRow;                                                                                    // If we're calculating row-by-row, what row are we on?
168
169         /* For Checkpointing */
170         int majorIteration;                                                                                             // Major iteration number
171         int minorIteration;                                                                                             // Minor iteration within major iteration
172         time_t startTime;                                                                                               // Time of first computation
173         time_t endTime;                                                                                                 // 'Cause we might as well report it
174         omxCheckpoint* checkpointList;                                                                  // List of checkpoints
175         char *chkptText1, *chkptText2;                                                                  // Placeholders for checkpointing text
176         int numCheckpoints;                                                                                             // Number of checkpoints
177
178         int statusCode;                                                                                                 // Status code, if appropriate
179         char statusMsg[250];                                                                                    // Status/Error message to report
180         double saturatedModel;                                                                                  // Saturated model likelihood, where applicable
181
182 };
183
184 /* Initialize and Destroy */
185         void omxInitState(omxState* state, int numChildren);                            // Constructor
186         void omxFillState(omxState* state, /*omxOptimizer *oo,*/ omxMatrix** matrixList, omxMatrix** algebraList, omxData** dataList, omxMatrix* objective);
187         void omxFreeState(omxState *oo);                                                                        // Destructor
188         void omxSaveState(omxState *os, double* freeVals, double minimum);      // Saves the current optimization values //TODO: Rename omxSaveState.
189     void omxDuplicateState(omxState *tgt, omxState* src, unsigned short fullCopy); 
190                                                                         // Duplicates the current state object
191     omxMatrix* omxLookupDuplicateElement(omxState* os, omxMatrix* element);
192     
193         void omxRaiseError(omxState *oo, int errorCode, char* errorMsg);        // Raise an Error
194                                                                                                                                                 // TODO: Move RaiseError to omxOptimizer.
195
196 /* Advance a step */
197         void omxStateNextRow(omxState *oo);                                                                     // Advance Row
198         void omxStateNextEvaluation(omxState *oo);                                                      // Advance Evaluation count
199
200         void omxSaveCheckpoint(omxState* os, double* x, double* f);                     // Save out checkpoints
201
202 #endif /* _OMXSTATE_H_ */
203
204