15 #ifdef BORNAGAIN_PYTHON
24 std::string error_description(
const std::string& title)
26 std::stringstream buf;
35 const std::string& functionName,
36 const std::string& path)
40 PyObject* pCompiledFn = Py_CompileString(script.c_str(),
"", Py_file_input);
42 throw std::runtime_error(error_description(
"Can't compile snippet"));
45 PyObject* pModule = PyImport_ExecCodeModule((
char*)
"test", pCompiledFn);
47 Py_DecRef(pCompiledFn);
48 throw std::runtime_error(error_description(
"Can't exec module"));
52 PyObject* pAddFn = PyObject_GetAttrString(pModule, functionName.c_str());
54 throw std::runtime_error(
"Can't locate compiled function");
56 PyObject* instance = PyObject_CallFunctionObjArgs(pAddFn, NULL);
60 Py_DecRef(pCompiledFn);
61 throw std::runtime_error(error_description(
"Can't call function"));
67 Py_DecRef(pCompiledFn);
70 swig_type_info* pTypeInfo = SWIG_TypeQuery(
"MultiLayer *");
72 const int res = SWIG_ConvertPtr(instance, &argp1, pTypeInfo, 0);
73 if (!SWIG_IsOK(res)) {
75 throw std::runtime_error(
"SWIG failed to extract a MultiLayer.");
79 std::unique_ptr<MultiLayer> result(multilayer->
clone());
87 const std::string& path)
91 PyObject* pCompiledFn = Py_CompileString(script.c_str(),
"", Py_file_input);
93 throw std::runtime_error(error_description(
"Can't compile snippet"));
96 PyObject* pModule = PyImport_ExecCodeModule((
char*)
"test", pCompiledFn);
98 Py_DecRef(pCompiledFn);
99 throw std::runtime_error(error_description(
"Can't exec module"));
102 PyObject* dict = PyModule_GetDict(pModule);
104 throw std::runtime_error(
"Can't get dictionary from module");
106 std::vector<std::string> result;
109 while (PyDict_Next(dict, &pos, &key, &value)) {
110 if (PyCallable_Check(value)) {
112 if (func_name.find(
"__") == std::string::npos)
113 result.push_back(func_name);
119 Py_DecRef(pCompiledFn);
Defines class MultiLayer.
Includes python header and takes care of warnings.
Defines PyImport namespace.
Defines PyUtils namespace.
Our sample model: a stack of layers one below the other.
MultiLayer * clone() const final
Returns a clone of this ISampleNode object.
std::vector< std::string > listOfFunctions(const std::string &script, const std::string &path="")
Returns list of functions defined in the script.
std::unique_ptr< MultiLayer > createFromPython(const std::string &script, const std::string &functionName, const std::string &path="")
Creates a multi layer by running python code in embedded interpreter.
std::string toString(PyObject *obj)
Converts PyObject into string, if possible, or throws exception.
std::string pythonStackTrace()
Returns string representing python stack trace.
void import_bornagain(const std::string &path="")
Imports BornAgain from given location. If path is empty, tries to rely on PYTHONPATH.