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