@@ -29,6 +29,19 @@ PyObject *target_function(PyObject * /*self*/, PyObject *args)
2929 return PyFloat_FromDouble (r);
3030};
3131
32+ PyObject *jac_function (PyObject * /* self*/ , PyObject *args)
33+ {
34+ PyArrayObject *arr = (PyArrayObject *)PyTuple_GetItem (args, 0 );
35+
36+ uint size = PyArray_SIZE (arr);
37+ auto params = (double *)PyArray_DATA (arr);
38+ double values[size];
39+ gGradFunction ->Gradient (params, values);
40+ npy_intp dims[1 ] = {size};
41+ PyObject *py_array = PyArray_SimpleNewFromData (1 , dims, NPY_DOUBLE, values);
42+ return py_array;
43+ };
44+
3245// _______________________________________________________________________
3346ScipyMinimizer::ScipyMinimizer () : BasicMinimizer()
3447{
@@ -55,6 +68,7 @@ void ScipyMinimizer::PyInitialize()
5568 static PyObject *ParamsError;
5669 static PyMethodDef ParamsMethods[] = {
5770 {" target_function" , target_function, METH_VARARGS, " Target function to minimize." },
71+ {" jac_function" , jac_function, METH_VARARGS, " Jacobian function." },
5872 {NULL , NULL , 0 , NULL } /* Sentinel */
5973 };
6074
@@ -100,8 +114,9 @@ void ScipyMinimizer::PyInitialize()
100114 // Scipy initialization
101115 PyRunString (" from scipy.optimize import minimize" );
102116 fMinimize = PyDict_GetItemString (fLocalNS , " minimize" );
103- PyRunString (" from params import target_function" );
117+ PyRunString (" from params import target_function, jac_function " );
104118 fTarget = PyDict_GetItemString (fLocalNS , " target_function" );
119+ fJacobian = PyDict_GetItemString (fLocalNS , " jac_function" );
105120}
106121
107122// _______________________________________________________________________
@@ -130,7 +145,6 @@ bool ScipyMinimizer::Minimize()
130145 (gFunction ) = ObjFunction ();
131146 (gGradFunction ) = GradObjFunction ();
132147 auto method = fOptions .MinimizerAlgorithm ();
133-
134148 std::cout << " === Scipy Minimization" << std::endl;
135149 std::cout << " === Method: " << method << std::endl;
136150 std::cout << " === Initial value: (" ;
@@ -147,7 +161,7 @@ bool ScipyMinimizer::Minimize()
147161
148162 PyObject *pargs = PyTuple_New (0 );
149163
150- auto pyvalues = Py_BuildValue (" (OOOs )" , fTarget , py_array, pargs, method.c_str ());
164+ auto pyvalues = Py_BuildValue (" (OOOsO )" , fTarget , py_array, pargs, method.c_str (), fJacobian );
151165
152166 PyObject *result = PyObject_CallObject (fMinimize , pyvalues);
153167 Py_DECREF (pyvalues);
0 commit comments