|
| 1 | +#include <Python.h> // Needs to be included first to avoid redefinition of _POSIX_C_SOURCE |
| 2 | +#include <Math/ScipyMinimizer.h> |
| 3 | +#include <Fit/ParameterSettings.h> |
| 4 | +#include <Math/IFunction.h> |
| 5 | +#include <Math/FitMethodFunction.h> |
| 6 | +#include <TString.h> |
| 7 | +#include <iostream> |
| 8 | + |
| 9 | +#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION |
| 10 | +#include <numpy/arrayobject.h> |
| 11 | + |
| 12 | +using namespace ROOT; |
| 13 | +using namespace ROOT::Math; |
| 14 | +using namespace ROOT::Math::Experimental; |
| 15 | +using namespace ROOT::Fit; |
| 16 | + |
| 17 | + |
| 18 | +/// function wrapper for the function to be minimized |
| 19 | +const ROOT::Math::IMultiGenFunction *gFunction; |
| 20 | +/// function wrapper for the gradient of the function to be minimized |
| 21 | +const ROOT::Math::IMultiGradFunction *gGradFunction; |
| 22 | + |
| 23 | +PyObject * target_function(PyObject */*self*/, PyObject *args) |
| 24 | +{ |
| 25 | + PyArrayObject *arr = (PyArrayObject *)PyTuple_GetItem(args, 0); |
| 26 | + |
| 27 | + auto params = (double *)PyArray_DATA(arr); |
| 28 | + auto r = (*gFunction)(params); |
| 29 | + |
| 30 | + return PyFloat_FromDouble(r); |
| 31 | +}; |
| 32 | + |
| 33 | + |
| 34 | +//_______________________________________________________________________ |
| 35 | +ScipyMinimizer::ScipyMinimizer() : BasicMinimizer() |
| 36 | +{ |
| 37 | + fOptions.SetMinimizerType("Scipy"); |
| 38 | + fOptions.SetMinimizerAlgorithm("lbfgsb"); |
| 39 | + if (!PyIsInitialized()) { |
| 40 | + PyInitialize(); |
| 41 | + } |
| 42 | + |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +//_______________________________________________________________________ |
| 48 | +ScipyMinimizer::ScipyMinimizer(const char *type) |
| 49 | +{ |
| 50 | + fOptions.SetMinimizerType("Scipy"); |
| 51 | + fOptions.SetMinimizerAlgorithm(type); |
| 52 | + if (!PyIsInitialized()) { |
| 53 | + PyInitialize(); |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +//_______________________________________________________________________ |
| 58 | +void ScipyMinimizer::PyInitialize() |
| 59 | +{ |
| 60 | + static PyObject *ParamsError; |
| 61 | + static PyMethodDef ParamsMethods[] = { |
| 62 | + {"target_function", target_function, METH_VARARGS, |
| 63 | + "Target function to minimize."}, |
| 64 | + {NULL, NULL, 0, NULL} /* Sentinel */ |
| 65 | + }; |
| 66 | + |
| 67 | + static struct PyModuleDef paramsmodule = { |
| 68 | + PyModuleDef_HEAD_INIT, |
| 69 | + "params", /* name of module */ |
| 70 | + "ROOT Scipy parameters", /* module documentation, may be NULL */ |
| 71 | + -1, /* size of per-interpreter state of the module, |
| 72 | + or -1 if the module keeps state in global variables. */ |
| 73 | + ParamsMethods |
| 74 | + }; |
| 75 | + |
| 76 | + auto PyInit_params = [](void)->PyObject * |
| 77 | + { |
| 78 | + PyObject *m; |
| 79 | + |
| 80 | + m = PyModule_Create(¶msmodule); |
| 81 | + if (m == NULL) |
| 82 | + return NULL; |
| 83 | + |
| 84 | + ParamsError = PyErr_NewException("params.error", NULL, NULL); |
| 85 | + Py_XINCREF(ParamsError); |
| 86 | + if (PyModule_AddObject(m, "error", ParamsError) < 0) { |
| 87 | + Py_XDECREF(ParamsError); |
| 88 | + Py_CLEAR(ParamsError); |
| 89 | + Py_DECREF(m); |
| 90 | + return NULL; |
| 91 | + } |
| 92 | + |
| 93 | + return m; |
| 94 | + }; |
| 95 | + if (PyImport_AppendInittab("params", PyInit_params) == -1) { |
| 96 | + MATH_ERROR_MSG("ScipyMinimizer::Minimize", "could not extend in-built modules table"); |
| 97 | + exit(1); |
| 98 | + } |
| 99 | + |
| 100 | + bool pyIsInitialized = PyIsInitialized(); |
| 101 | + if (!pyIsInitialized) { |
| 102 | + Py_Initialize(); // Python initialization |
| 103 | + } |
| 104 | + fLocalNS = PyDict_New(); |
| 105 | + fGlobalNS = PyDict_New(); |
| 106 | + |
| 107 | + if (!pyIsInitialized) { |
| 108 | + _import_array(); // Numpy initialization |
| 109 | + } |
| 110 | + //Scipy initialization |
| 111 | + PyRunString("from scipy.optimize import minimize"); |
| 112 | + fMinimize = PyDict_GetItemString(fLocalNS, "minimize"); |
| 113 | + PyRunString("from params import target_function"); |
| 114 | + fTarget = PyDict_GetItemString(fLocalNS, "target_function"); |
| 115 | +} |
| 116 | + |
| 117 | +//_______________________________________________________________________ |
| 118 | +// Finalize Python interpreter |
| 119 | +void ScipyMinimizer::PyFinalize() |
| 120 | +{ |
| 121 | + if (fMinimize) Py_DECREF(fMinimize); |
| 122 | + Py_Finalize(); |
| 123 | +} |
| 124 | + |
| 125 | +//_______________________________________________________________________ |
| 126 | +int ScipyMinimizer::PyIsInitialized() |
| 127 | +{ |
| 128 | + if (!Py_IsInitialized()) return kFALSE; |
| 129 | + return kTRUE; |
| 130 | +} |
| 131 | + |
| 132 | +//_______________________________________________________________________ |
| 133 | +ScipyMinimizer::~ScipyMinimizer() |
| 134 | +{ |
| 135 | +} |
| 136 | + |
| 137 | +//_______________________________________________________________________ |
| 138 | +bool ScipyMinimizer::Minimize() |
| 139 | +{ |
| 140 | + (gFunction)= ObjFunction(); |
| 141 | + (gGradFunction) = GradObjFunction(); |
| 142 | + auto method = fOptions.MinimizerAlgorithm(); |
| 143 | + |
| 144 | + std::cout<<"=== Scipy Minimization"<<std::endl; |
| 145 | + std::cout<<"=== Method: "<<method<<std::endl; |
| 146 | + std::cout<<"=== Initial value: ("; |
| 147 | + for(uint i=0;i<NDim();i++ ) |
| 148 | + { |
| 149 | + std::cout<<X()[i]; |
| 150 | + if(i<NDim()-1) |
| 151 | + std::cout<<","; |
| 152 | + } |
| 153 | + std::cout<<")"<<std::endl; |
| 154 | + |
| 155 | + double *values = const_cast<double*>(X()); |
| 156 | + npy_intp dims[1] = { NDim()}; |
| 157 | + PyObject *py_array= PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, values); |
| 158 | + |
| 159 | + PyObject *pargs=PyTuple_New(0); |
| 160 | + |
| 161 | + auto pyvalues = Py_BuildValue("(OOOs)",fTarget,py_array,pargs,method.c_str()); |
| 162 | + |
| 163 | + PyObject *result = PyObject_CallObject(fMinimize,pyvalues); |
| 164 | + Py_DECREF(pyvalues); |
| 165 | + Py_DECREF(py_array); |
| 166 | + |
| 167 | + |
| 168 | + //if the minimization works |
| 169 | + PyObject *pstatus = PyObject_GetAttrString(result,"status"); |
| 170 | + bool status = PyBool_Check(pstatus ); |
| 171 | + Py_DECREF(pstatus); |
| 172 | + |
| 173 | + //the x values for the minimum |
| 174 | + PyArrayObject *pyx = (PyArrayObject *)PyObject_GetAttrString(result,"x"); |
| 175 | + const double *x =(const double *)PyArray_DATA(pyx); |
| 176 | + Py_DECREF(pyx); |
| 177 | + |
| 178 | + SetFinalValues(x); |
| 179 | + auto obj_value = (*gFunction)(x); |
| 180 | + SetMinValue(obj_value); |
| 181 | + |
| 182 | + return status; |
| 183 | +} |
| 184 | + |
| 185 | +//_______________________________________________________________________ |
| 186 | +void ScipyMinimizer::PyRunString(TString code, TString errorMessage, int start) { |
| 187 | + auto fPyReturn = PyRun_String(code, start, fGlobalNS, fLocalNS); |
| 188 | + if (!fPyReturn) { |
| 189 | + auto msg = errorMessage + Form(" \ncode = \"%s\"",code.Data()); |
| 190 | + MATH_ERROR_MSG("ScipyMinimizer::PyRunString", msg.Data() ); |
| 191 | + PyErr_Print(); |
| 192 | + exit(1); |
| 193 | + } |
| 194 | +} |
0 commit comments