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