I don't know if this is the correct forum but,
I am doing some Python Embedding from:
https://docs.python.org/3.6/extending/em...-embedding
I cannot figure out how to pass the keyword rosen from the C/Python API in the nelderMead function argument correctly.
I have tried hard-coding PyUnicode_DecodeFSDefault but it outputs a string into the Python when rosen itself is a type class
from scipy.
from scipy.optimize import minimize, rosen, rosen_der
def nelderMead(func):
x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
res = minimize(func, x0, method='Nelder-Mead', tol=1e-6)
print(res.x)
please advise
.
jibarra Wrote:I cannot figure out how to pass the keyword rosen from the C/Python API in the nelderMead function argument correctly.
I don't understand what you want to do. Do you want to call function nelderMead? with which argument? from C, from python? Why can't you do it? Can you post your code?
I want to call the nelderMead Python function from C, and pass in the keyword rosen that I've imported from from scipy.optimize import minimize, rosen, rosen_der from C into the nelderMead function. The problem is whenever is pass in a string or PyObject, python reads it as a type string but rosen is a type class. So the rosen parameter does not get invoked as a class but as a string.
C Code below:
//https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html
#include</usr/include/python3.6m/Python.h>
int main(){
PyObject *pName,*pFunc, *pValue, *pModule, *pOpt;
Py_Initialize();
//Access file in local folder where C file is stored
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
//Convert String to PyObject
pName = PyUnicode_DecodeFSDefault("Rosenbrock_Function");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if(pModule){
pFunc = PyObject_GetAttrString(pModule,"nelderMead");
Py_DECREF(pModule);
}
pOpt = PyUnicode_DecodeFSDefault("rosen");
pValue = PyObject_CallFunctionObjArgs(pFunc,pOpt,NULL);
Py_FinalizeEx();
return 0;
}
You need to retrieve the 'rosen' attribute from the module as well. Here is a code that works for me (in python 3.5)
#include</usr/include/python3.5m/Python.h>
int main(){
PyObject *pFunc, *pValue, *pModule, *pOpt;
Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
if(pModule = PyImport_ImportModule("Rosenbrock_Function")){
if(pFunc = PyObject_GetAttrString(pModule,"nelderMead")){
if(pOpt = PyObject_GetAttrString(pModule, "rosen")){
pValue = PyObject_CallFunctionObjArgs(pFunc,pOpt,NULL);
Py_DECREF(pOpt);
Py_XDECREF(pValue);
}
Py_DECREF(pFunc);
}
Py_DECREF(pModule);
}
Py_Finalize();
return 0;
}
Don't use PyUnicode_DecodeFSDefault unless you're dealing with filesystem paths.