omxComputeEstimateHessian reorg 2/11
[openmx:openmx.git] / src / npsolWrap.cpp
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 #include <stdio.h>
18 #include <sys/types.h>
19 #include <errno.h>
20
21 #include <R.h>
22 #include <Rinternals.h>
23 #include <Rdefines.h>
24 #include <R_ext/Rdynload.h>
25 #include <R_ext/BLAS.h>
26 #include <R_ext/Lapack.h>
27
28 #include "omxDefines.h"
29 #include "types.h"
30 #include "npsolWrap.h"
31 #include "omxOpenmpWrap.h"
32 #include "omxState.h"
33 #include "omxGlobalState.h"
34 #include "omxMatrix.h"
35 #include "omxAlgebra.h"
36 #include "omxFitFunction.h"
37 #include "omxExpectation.h"
38 #include "omxNPSOLSpecific.h"
39 #include "omxImportFrontendState.h"
40 #include "omxExportBackendState.h"
41 #include "omxOptimizer.h"
42 #include "omxHessianCalculation.h"
43
44 omp_lock_t GlobalRLock;
45
46 static R_CallMethodDef callMethods[] = {
47         {"omxBackend", (DL_FUNC) omxBackend, 12},
48         {"omxCallAlgebra", (DL_FUNC) omxCallAlgebra, 3},
49         {"findIdenticalRowsData", (DL_FUNC) findIdenticalRowsData, 5},
50         {NULL, NULL, 0}
51 };
52
53 #ifdef  __cplusplus
54 extern "C" {
55 #endif
56
57 void R_init_OpenMx(DllInfo *info) {
58         R_registerRoutines(info, NULL, callMethods, NULL, NULL);
59
60         omx_omp_init_lock(&GlobalRLock);
61
62         // There is no code that will change behavior whether openmp
63         // is set for nested or not. I'm just keeping this in case it
64         // makes a difference with older versions of openmp. 2012-12-24 JNP
65 #if defined(_OPENMP) && _OPENMP <= 200505
66         omp_set_nested(0);
67 #endif
68 }
69
70 void R_unload_OpenMx(DllInfo *info) {
71         omx_omp_destroy_lock(&GlobalRLock);
72 }
73
74 #ifdef  __cplusplus
75 }
76 #endif
77
78 void string_to_try_error( const std::string& str )
79 {
80         error("%s", str.c_str());
81 }
82
83 void exception_to_try_error( const std::exception& ex )
84 {
85         string_to_try_error(ex.what());
86 }
87
88 SEXP asR(MxRList *out)
89 {
90        SEXP names, ans;
91        int len = out->size();
92        PROTECT(names = allocVector(STRSXP, len));
93        PROTECT(ans = allocVector(VECSXP, len));
94        for (int lx=0; lx < len; ++lx) {
95                SET_STRING_ELT(names, lx, (*out)[lx].first);
96                SET_VECTOR_ELT(ans,   lx, (*out)[lx].second);
97        }
98        namesgets(ans, names);
99        return ans;
100 }
101
102 /* Main functions */
103 SEXP omxCallAlgebra2(SEXP matList, SEXP algNum, SEXP options) {
104
105         omxManageProtectInsanity protectManager;
106
107         if(OMX_DEBUG) { Rprintf("-----------------------------------------------------------------------\n");}
108         if(OMX_DEBUG) { Rprintf("Explicit call to algebra %d.\n", INTEGER(algNum));}
109
110         int j,k,l;
111         omxMatrix* algebra;
112         int algebraNum = INTEGER(algNum)[0];
113         SEXP ans, nextMat;
114         char output[250];
115         int errOut = 0;
116
117         /* Create new omxState for current state storage and initialize it. */
118         
119         globalState = new omxState;
120         omxInitState(globalState, NULL);
121         if(OMX_DEBUG) { Rprintf("Created state object at 0x%x.\n", globalState);}
122
123         /* Retrieve All Matrices From the MatList */
124
125         if(OMX_DEBUG) { Rprintf("Processing %d matrix(ces).\n", length(matList));}
126
127         omxMatrix *args[length(matList)];
128         for(k = 0; k < length(matList); k++) {
129                 PROTECT(nextMat = VECTOR_ELT(matList, k));      // This is the matrix + populations
130                 args[k] = omxNewMatrixFromRPrimitive(nextMat, globalState, 1, - k - 1);
131                 globalState->matrixList.push_back(args[k]);
132                 if(OMX_DEBUG) {
133                         Rprintf("Matrix initialized at 0x%0xd = (%d x %d).\n",
134                                 globalState->matrixList[k], globalState->matrixList[k]->rows, globalState->matrixList[k]->cols);
135                 }
136         }
137
138         algebra = omxNewAlgebraFromOperatorAndArgs(algebraNum, args, length(matList), globalState);
139
140         if(algebra==NULL) {
141                 error(globalState->statusMsg);
142         }
143
144         if(OMX_DEBUG) {Rprintf("Completed Algebras and Matrices.  Beginning Initial Compute.\n");}
145         omxStateNextEvaluation(globalState);
146
147         omxRecompute(algebra);
148
149         PROTECT(ans = allocMatrix(REALSXP, algebra->rows, algebra->cols));
150         for(l = 0; l < algebra->rows; l++)
151                 for(j = 0; j < algebra->cols; j++)
152                         REAL(ans)[j * algebra->rows + l] =
153                                 omxMatrixElement(algebra, l, j);
154
155         if(OMX_DEBUG) { Rprintf("All Algebras complete.\n"); }
156
157         if(globalState->statusCode != 0) {
158                 errOut = globalState->statusCode;
159                 strncpy(output, globalState->statusMsg, 250);
160         }
161
162         omxFreeAllMatrixData(algebra);
163         omxFreeState(globalState);
164
165         if(errOut != 0) {
166                 error(output);
167         }
168
169         return ans;
170 }
171
172 SEXP omxCallAlgebra(SEXP matList, SEXP algNum, SEXP options)
173 {
174         try {
175                 return omxCallAlgebra2(matList, algNum, options);
176         } catch( std::exception& __ex__ ) {
177                 exception_to_try_error( __ex__ );
178         } catch(...) {
179                 string_to_try_error( "c++ exception (unknown reason)" );
180         }
181 }
182
183 SEXP omxBackend2(SEXP fitfunction, SEXP startVals, SEXP constraints,
184         SEXP matList, SEXP varList, SEXP algList, SEXP expectList,
185         SEXP data, SEXP intervalList, SEXP checkpointList, SEXP options, SEXP state) {
186
187         /* Helpful variables */
188
189         SEXP nextLoc;
190
191         int ciMaxIterations = 5;
192         int disableOptimizer = 0;
193         int numThreads = 1;
194         int analyticGradients = 0;
195
196         /* Sanity Check and Parse Inputs */
197         /* TODO: Need to find a way to account for nullness in these.  For now, all checking is done on the front-end. */
198 //      if(!isVector(startVals)) error ("startVals must be a vector");
199 //      if(!isVector(matList)) error ("matList must be a list");
200 //      if(!isVector(algList)) error ("algList must be a list");
201
202         omxManageProtectInsanity protectManager;
203
204         /* Create new omxState for current state storage and initialize it. */
205         globalState = new omxState;
206         omxInitState(globalState, NULL);
207
208         /*      Set NPSOL options */
209         omxSetNPSOLOpts(options, &globalState->numHessians, &globalState->calculateStdErrors, 
210                 &ciMaxIterations, &disableOptimizer, &numThreads, 
211                 &analyticGradients, length(startVals));
212
213         globalState->numThreads = numThreads;
214         globalState->numFreeParams = length(startVals);
215         globalState->analyticGradients = analyticGradients;
216         if(OMX_DEBUG) { Rprintf("Created state object at 0x%x.\n", globalState);}
217
218         /* Retrieve Data Objects */
219         omxProcessMxDataEntities(data);
220         if (globalState->statusMsg[0]) error(globalState->statusMsg);
221     
222         /* Retrieve All Matrices From the MatList */
223         omxProcessMxMatrixEntities(matList);
224         if (globalState->statusMsg[0]) error(globalState->statusMsg);
225
226         globalState->numAlgs = length(algList);
227         
228         if (length(startVals) != length(varList)) error("varList and startVals must be the same length");
229
230         /* Process Free Var List */
231         omxProcessFreeVarList(varList);
232         if (globalState->statusMsg[0]) error(globalState->statusMsg);
233
234         omxProcessMxExpectationEntities(expectList);
235         if (globalState->statusMsg[0]) error(globalState->statusMsg);
236
237         omxProcessMxAlgebraEntities(algList);
238         if (globalState->statusMsg[0]) error(globalState->statusMsg);
239
240         omxCompleteMxExpectationEntities();
241         if (globalState->statusMsg[0]) error(globalState->statusMsg);
242
243         omxProcessMxFitFunction(algList);
244         if (globalState->statusMsg[0]) error(globalState->statusMsg);
245
246         // This is the chance to check for matrix
247         // conformability, etc.  Any errors encountered should
248         // be reported using R's error() function, not
249         // omxRaiseErrorf.
250
251         omxInitialMatrixAlgebraCompute();
252         omxResetStatus(globalState);
253
254         if(!isNull(fitfunction)) {
255                 if(OMX_DEBUG) { Rprintf("Processing fit function.\n"); }
256                 globalState->fitMatrix = omxMatrixLookupFromState1(fitfunction, globalState);
257         }
258         if (globalState->statusMsg[0]) error(globalState->statusMsg);
259         
260         // TODO: Make calculateHessians an option instead.
261
262         /* Process Matrix and Algebra Population Function */
263         /*
264           Each matrix is a list containing a matrix and the other matrices/algebras that are
265           populated into it at each iteration.  The first element is already processed, above.
266           The rest of the list will be processed here.
267         */
268         for(int j = 0; j < length(matList); j++) {
269                 PROTECT(nextLoc = VECTOR_ELT(matList, j));              // This is the matrix + populations
270                 omxProcessMatrixPopulationList(globalState->matrixList[j], nextLoc);
271         }
272
273         /* Processing Constraints */
274         omxProcessConstraints(constraints);
275
276         /* Process Confidence Interval List */
277         omxProcessConfidenceIntervals(intervalList);
278
279         /* Process Checkpoint List */
280         omxProcessCheckpointOptions(checkpointList);
281
282         // Probably, this is always the same for all children and
283         // doesn't need to be copied to child states.
284         cacheFreeVarDependencies(globalState);
285
286         omxFitFunctionCreateChildren(globalState, numThreads);
287
288         int n = globalState->numFreeParams;
289
290         SEXP minimum, estimate, gradient, hessian;
291         PROTECT(minimum = NEW_NUMERIC(1));
292         PROTECT(estimate = allocVector(REALSXP, n));
293         PROTECT(gradient = allocVector(REALSXP, n));
294         PROTECT(hessian = allocMatrix(REALSXP, n, n));
295
296         if (n>0) { memcpy(REAL(estimate), REAL(startVals), sizeof(double)*n); }
297         
298         omxInvokeNPSOL(globalState->fitMatrix, REAL(minimum), REAL(estimate),
299                        REAL(gradient), REAL(hessian), disableOptimizer);
300
301         SEXP code, status, statusMsg, iterations;
302         SEXP evaluations, algebras, matrices, expectations;
303         SEXP intervals, intervalCodes;
304
305         PROTECT(code = NEW_NUMERIC(1));
306         PROTECT(status = allocVector(VECSXP, 3));
307         PROTECT(iterations = NEW_NUMERIC(1));
308         PROTECT(evaluations = NEW_NUMERIC(2));
309         PROTECT(matrices = NEW_LIST(globalState->matrixList.size()));
310         PROTECT(algebras = NEW_LIST(globalState->numAlgs));
311         PROTECT(expectations = NEW_LIST(globalState->numExpects));
312
313         PROTECT(intervals = allocMatrix(REALSXP, globalState->numIntervals, 2)); // for optimizer
314         PROTECT(intervalCodes = allocMatrix(INTSXP, globalState->numIntervals, 2)); // for optimizer
315
316         omxSaveState(globalState, REAL(estimate), REAL(minimum)[0]);
317
318         REAL(code)[0] = globalState->inform;
319         REAL(iterations)[0] = globalState->iter;
320         REAL(evaluations)[0] = globalState->computeCount;
321
322         /* Fill Status code. */
323         SET_VECTOR_ELT(status, 0, code);
324         PROTECT(code = NEW_NUMERIC(1));
325         REAL(code)[0] = globalState->statusCode;
326         SET_VECTOR_ELT(status, 1, code);
327         PROTECT(statusMsg = allocVector(STRSXP, 1));
328         SET_STRING_ELT(statusMsg, 0, mkChar(globalState->statusMsg));
329         SET_VECTOR_ELT(status, 2, statusMsg);
330
331         MxRList result;
332
333         if (globalState->numHessians && globalState->fitMatrix != NULL && globalState->optimumStatus >= 0 &&
334             globalState->numConstraints == 0) {
335                 omxComputeEstimateHessian *eh = new omxComputeEstimateHessian();
336                 eh->compute();
337                 eh->reportResults(&result);
338         }
339
340         /* Likelihood-based Confidence Interval Calculation */
341         if(globalState->numIntervals) {
342                 omxNPSOLConfidenceIntervals(globalState->fitMatrix, REAL(minimum), REAL(estimate),
343                                             REAL(gradient), REAL(hessian), ciMaxIterations);
344         }  
345
346         // What if fitfunction has its own repopulateFun? TODO
347         handleFreeVarListHelper(globalState, globalState->optimalValues, n);
348
349         omxFinalAlgebraCalculation(globalState, matrices, algebras, expectations); 
350
351         omxPopulateFitFunction(globalState, &result);
352
353         if(globalState->numIntervals) { // Populate CIs
354                 omxPopulateConfidenceIntervals(globalState, intervals, intervalCodes);
355         }
356         
357         REAL(evaluations)[1] = globalState->computeCount;
358
359         result.push_back(std::make_pair(mkChar("minimum"), minimum));
360         result.push_back(std::make_pair(mkChar("estimate"), estimate));
361         result.push_back(std::make_pair(mkChar("gradient"), gradient));
362         result.push_back(std::make_pair(mkChar("hessianCholesky"), hessian));
363         result.push_back(std::make_pair(mkChar("status"), status));
364         result.push_back(std::make_pair(mkChar("iterations"), iterations));
365         result.push_back(std::make_pair(mkChar("evaluations"), evaluations));
366         result.push_back(std::make_pair(mkChar("matrices"), matrices));
367         result.push_back(std::make_pair(mkChar("algebras"), algebras));
368         result.push_back(std::make_pair(mkChar("expectations"), expectations));
369         result.push_back(std::make_pair(mkChar("confidenceIntervals"), intervals));
370         result.push_back(std::make_pair(mkChar("confidenceIntervalCodes"), intervalCodes));
371
372         /* Free data memory */
373         omxFreeState(globalState);
374
375         return asR(&result);
376
377 }
378
379 SEXP omxBackend(SEXP fitfunction, SEXP startVals, SEXP constraints,
380         SEXP matList, SEXP varList, SEXP algList, SEXP expectList,
381         SEXP data, SEXP intervalList, SEXP checkpointList, SEXP options, SEXP state)
382 {
383         try {
384                 return omxBackend2(fitfunction, startVals, constraints,
385                                    matList, varList, algList, expectList,
386                                    data, intervalList, checkpointList, options, state);
387         } catch( std::exception& __ex__ ) {
388                 exception_to_try_error( __ex__ );
389         } catch(...) {
390                 string_to_try_error( "c++ exception (unknown reason)" );
391         }
392 }
393