Store matrixList as a 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         int errOut = 0;                 // Error state: Clear
174
175         SEXP nextLoc;
176
177         int n;
178         int calculateStdErrors = FALSE;
179         int numHessians = 0;
180         int ciMaxIterations = 5;
181         int disableOptimizer = 0;
182         int numThreads = 1;
183         int analyticGradients = 0;
184
185         /* Sanity Check and Parse Inputs */
186         /* TODO: Need to find a way to account for nullness in these.  For now, all checking is done on the front-end. */
187 //      if(!isVector(startVals)) error ("startVals must be a vector");
188 //      if(!isVector(matList)) error ("matList must be a list");
189 //      if(!isVector(algList)) error ("algList must be a list");
190
191         omxManageProtectInsanity protectManager;
192
193         /*      Set NPSOL options */
194         omxSetNPSOLOpts(options, &numHessians, &calculateStdErrors, 
195                 &ciMaxIterations, &disableOptimizer, &numThreads, 
196                 &analyticGradients, length(startVals));
197
198         /* Create new omxState for current state storage and initialize it. */
199         globalState = new omxState;
200         omxInitState(globalState, NULL);
201         globalState->numThreads = numThreads;
202         globalState->numFreeParams = length(startVals);
203         globalState->analyticGradients = analyticGradients;
204         if(OMX_DEBUG) { Rprintf("Created state object at 0x%x.\n", globalState);}
205
206         /* Retrieve Data Objects */
207         if(!errOut) errOut = omxProcessMxDataEntities(data);
208     
209         /* Retrieve All Matrices From the MatList */
210         if(!errOut) omxProcessMxMatrixEntities(matList);
211
212         globalState->numAlgs = length(algList);
213         
214         if (length(startVals) != length(varList)) error("varList and startVals must be the same length");
215
216         /* Process Free Var List */
217         omxProcessFreeVarList(varList);
218
219         if(!errOut) {
220                 omxProcessMxExpectationEntities(expectList);
221                 omxProcessMxAlgebraEntities(algList);
222                 errOut = globalState->statusMsg[0];
223         }
224
225         /* Complete Expectations */
226         if(!errOut) {
227                 omxCompleteMxExpectationEntities();
228
229                 // This is the chance to check for matrix
230                 // conformability, etc.  Any errors encountered should
231                 // be reported using R's error() function, not
232                 // omxRaiseErrorf.
233
234                 omxInitialMatrixAlgebraCompute();
235                 omxResetStatus(globalState);
236         }
237
238         if(!errOut && !isNull(fitfunction)) {
239                 if(OMX_DEBUG) { Rprintf("Processing fit function.\n"); }
240                 globalState->fitMatrix = omxMatrixLookupFromState1(fitfunction, globalState);
241                 errOut = globalState->statusMsg[0];
242         }
243         
244         // TODO: Make calculateHessians an option instead.
245
246         if(errOut) error(globalState->statusMsg);
247
248         /* Process Matrix and Algebra Population Function */
249         /*
250           Each matrix is a list containing a matrix and the other matrices/algebras that are
251           populated into it at each iteration.  The first element is already processed, above.
252           The rest of the list will be processed here.
253         */
254         for(int j = 0; j < length(matList); j++) {
255                 PROTECT(nextLoc = VECTOR_ELT(matList, j));              // This is the matrix + populations
256                 omxProcessMatrixPopulationList(globalState->matrixList[j], nextLoc);
257         }
258
259         /* Processing Constraints */
260         omxProcessConstraints(constraints);
261
262         /* Process Confidence Interval List */
263         omxProcessConfidenceIntervals(intervalList);
264
265         /* Process Checkpoint List */
266         omxProcessCheckpointOptions(checkpointList);
267
268         // Probably, this is always the same for all children and
269         // doesn't need to be copied to child states.
270         cacheFreeVarDependencies(globalState);
271
272         omxFitFunctionCreateChildren(globalState, numThreads);
273
274         n = globalState->numFreeParams;
275
276         SEXP minimum, estimate, gradient, hessian;
277         PROTECT(minimum = NEW_NUMERIC(1));
278         PROTECT(estimate = allocVector(REALSXP, n));
279         PROTECT(gradient = allocVector(REALSXP, n));
280         PROTECT(hessian = allocMatrix(REALSXP, n, n));
281
282         if (n>0) { memcpy(REAL(estimate), REAL(startVals), sizeof(double)*n); }
283         
284         omxInvokeNPSOL(REAL(minimum), REAL(estimate), REAL(gradient), REAL(hessian), disableOptimizer);
285
286         SEXP code, status, statusMsg, iterations;
287         SEXP evaluations, ans=NULL, names=NULL, algebras, matrices, expectations, optimizer;
288         SEXP intervals, NAmat, intervalCodes, calculatedHessian, stdErrors;
289
290         int numReturns = 14;
291
292         PROTECT(code = NEW_NUMERIC(1));
293         PROTECT(status = allocVector(VECSXP, 3));
294         PROTECT(iterations = NEW_NUMERIC(1));
295         PROTECT(evaluations = NEW_NUMERIC(2));
296         PROTECT(matrices = NEW_LIST(globalState->matrixList.size()));
297         PROTECT(algebras = NEW_LIST(globalState->numAlgs));
298         PROTECT(expectations = NEW_LIST(globalState->numExpects));
299
300         PROTECT(optimizer = allocVector(VECSXP, 2));
301         PROTECT(calculatedHessian = allocMatrix(REALSXP, n, n));
302         PROTECT(stdErrors = allocMatrix(REALSXP, n, 1)); // for optimizer
303         PROTECT(names = allocVector(STRSXP, 2)); // for optimizer
304         PROTECT(intervals = allocMatrix(REALSXP, globalState->numIntervals, 2)); // for optimizer
305         PROTECT(intervalCodes = allocMatrix(INTSXP, globalState->numIntervals, 2)); // for optimizer
306         PROTECT(NAmat = allocMatrix(REALSXP, 1, 1)); // In case of missingness
307         REAL(NAmat)[0] = R_NaReal;
308
309         omxSaveState(globalState, REAL(estimate), REAL(minimum)[0]);
310
311         /* Fill in details from the optimizer */
312         SET_VECTOR_ELT(optimizer, 0, gradient);
313         SET_VECTOR_ELT(optimizer, 1, hessian);
314
315         SET_STRING_ELT(names, 0, mkChar("minimum"));
316         SET_STRING_ELT(names, 1, mkChar("estimate"));
317         namesgets(optimizer, names);
318
319         REAL(code)[0] = globalState->inform;
320         REAL(iterations)[0] = globalState->iter;
321         REAL(evaluations)[0] = globalState->computeCount;
322
323         /* Fill Status code. */
324         SET_VECTOR_ELT(status, 0, code);
325         PROTECT(code = NEW_NUMERIC(1));
326         REAL(code)[0] = globalState->statusCode;
327         SET_VECTOR_ELT(status, 1, code);
328         PROTECT(statusMsg = allocVector(STRSXP, 1));
329         SET_STRING_ELT(statusMsg, 0, mkChar(globalState->statusMsg));
330         SET_VECTOR_ELT(status, 2, statusMsg);
331
332         if(numHessians && globalState->fitMatrix != NULL && globalState->optimumStatus >= 0) {          // No hessians or standard errors if the optimum is invalid
333                 if(globalState->numConstraints == 0) {
334                         if(OMX_DEBUG) { Rprintf("Calculating Hessian for Fit Function.\n");}
335                         int gotHessians = omxEstimateHessian(numHessians, .0001, 4, globalState);
336                         if(gotHessians) {
337                                 if(calculateStdErrors) {
338                                         for(int j = 0; j < numHessians; j++) {          //TODO: Fix Hessian calculation to allow more if requested
339                                                 if(OMX_DEBUG) { Rprintf("Calculating Standard Errors for Fit Function.\n");}
340                                                 omxFitFunction* oo = globalState->fitMatrix->fitFunction;
341                                                 if(oo->getStandardErrorFun != NULL) {
342                                                         oo->getStandardErrorFun(oo);
343                                                 } else {
344                                                         omxCalculateStdErrorFromHessian(2.0, oo);
345                                                 }
346                                         }
347                                 }
348                         } else {
349                                 numHessians = 0;
350                         }
351                 } else {
352                         numHessians = 0;
353                 }
354         } else {
355                 numHessians = 0;
356         }
357
358         /* Likelihood-based Confidence Interval Calculation */
359         if(globalState->numIntervals) {
360                 omxNPSOLConfidenceIntervals(REAL(minimum), REAL(estimate), REAL(gradient), REAL(hessian), ciMaxIterations);
361         }  
362
363         handleFreeVarList(globalState, globalState->optimalValues, n);  // Restore to optima for final compute
364         if(!errOut) omxFinalAlgebraCalculation(globalState, matrices, algebras, expectations); 
365
366         omxPopulateFitFunction(globalState, numReturns, &ans, &names);
367
368         if(numHessians) {
369                 omxPopulateHessians(numHessians, globalState->fitMatrix, 
370                         calculatedHessian, stdErrors, calculateStdErrors, n);
371         }
372
373         if(globalState->numIntervals) { // Populate CIs
374                 omxPopulateConfidenceIntervals(globalState, intervals, intervalCodes);
375         }
376         
377         REAL(evaluations)[1] = globalState->computeCount;
378
379         int nextEl = 0;
380
381         SET_STRING_ELT(names, nextEl++, mkChar("minimum"));
382         SET_STRING_ELT(names, nextEl++, mkChar("estimate"));
383         SET_STRING_ELT(names, nextEl++, mkChar("gradient"));
384         SET_STRING_ELT(names, nextEl++, mkChar("hessianCholesky"));
385         SET_STRING_ELT(names, nextEl++, mkChar("status"));
386         SET_STRING_ELT(names, nextEl++, mkChar("iterations"));
387         SET_STRING_ELT(names, nextEl++, mkChar("evaluations"));
388         SET_STRING_ELT(names, nextEl++, mkChar("matrices"));
389         SET_STRING_ELT(names, nextEl++, mkChar("algebras"));
390         SET_STRING_ELT(names, nextEl++, mkChar("expectations"));
391         SET_STRING_ELT(names, nextEl++, mkChar("confidenceIntervals"));
392         SET_STRING_ELT(names, nextEl++, mkChar("confidenceIntervalCodes"));
393         SET_STRING_ELT(names, nextEl++, mkChar("calculatedHessian"));
394         SET_STRING_ELT(names, nextEl++, mkChar("standardErrors"));
395
396         nextEl = 0;
397
398         SET_VECTOR_ELT(ans, nextEl++, minimum);
399         SET_VECTOR_ELT(ans, nextEl++, estimate);
400         SET_VECTOR_ELT(ans, nextEl++, gradient);
401         SET_VECTOR_ELT(ans, nextEl++, hessian);
402         SET_VECTOR_ELT(ans, nextEl++, status);
403         SET_VECTOR_ELT(ans, nextEl++, iterations);
404         SET_VECTOR_ELT(ans, nextEl++, evaluations);
405         SET_VECTOR_ELT(ans, nextEl++, matrices);
406         SET_VECTOR_ELT(ans, nextEl++, algebras);
407         SET_VECTOR_ELT(ans, nextEl++, expectations);
408         SET_VECTOR_ELT(ans, nextEl++, intervals);
409         SET_VECTOR_ELT(ans, nextEl++, intervalCodes);
410         if(numHessians == 0) {
411                 SET_VECTOR_ELT(ans, nextEl++, NAmat);
412         } else {
413                 SET_VECTOR_ELT(ans, nextEl++, calculatedHessian);
414         }
415         if(!calculateStdErrors) {
416                 SET_VECTOR_ELT(ans, nextEl++, NAmat);
417         } else {
418                 SET_VECTOR_ELT(ans, nextEl++, stdErrors);
419         }
420         namesgets(ans, names);
421
422         if(OMX_VERBOSE) {
423                 Rprintf("Inform Value: %d\n", globalState->optimumStatus);
424                 Rprintf("--------------------------\n");
425         }
426
427         /* Free data memory */
428         omxFreeState(globalState);
429
430         if(OMX_DEBUG) {Rprintf("All vectors freed.\n");}
431
432         return(ans);
433
434 }
435
436 SEXP omxBackend(SEXP fitfunction, SEXP startVals, SEXP constraints,
437         SEXP matList, SEXP varList, SEXP algList, SEXP expectList,
438         SEXP data, SEXP intervalList, SEXP checkpointList, SEXP options, SEXP state)
439 {
440         try {
441                 return omxBackend2(fitfunction, startVals, constraints,
442                                    matList, varList, algList, expectList,
443                                    data, intervalList, checkpointList, options, state);
444         } catch( std::exception& __ex__ ) {
445                 exception_to_try_error( __ex__ );
446         } catch(...) {
447                 string_to_try_error( "c++ exception (unknown reason)" );
448         }
449 }
450