15 #ifdef BORNAGAIN_PYTHON
27 std::stringstream buf;
36 const std::string& functionName,
37 const std::string& path)
41 PyObject* pCompiledFn = Py_CompileString(script.c_str(),
"", Py_file_input);
46 PyObject* pModule = PyImport_ExecCodeModule((
char*)
"test", pCompiledFn);
48 Py_DecRef(pCompiledFn);
53 PyObject* pAddFn = PyObject_GetAttrString(pModule, functionName.c_str());
55 throw std::runtime_error(
"Can't locate compiled function");
57 PyObject* instance = PyObject_CallFunctionObjArgs(pAddFn, NULL);
61 Py_DecRef(pCompiledFn);
68 Py_DecRef(pCompiledFn);
71 swig_type_info* pTypeInfo = SWIG_TypeQuery(
"MultiLayer *");
73 const int res = SWIG_ConvertPtr(instance, &argp1, pTypeInfo, 0);
74 if (!SWIG_IsOK(res)) {
76 throw std::runtime_error(
"SWIG failed to extract a MultiLayer.");
80 std::unique_ptr<MultiLayer> result(multilayer->
clone());
88 const std::string& path)
92 PyObject* pCompiledFn = Py_CompileString(script.c_str(),
"", Py_file_input);
97 PyObject* pModule = PyImport_ExecCodeModule((
char*)
"test", pCompiledFn);
99 Py_DecRef(pCompiledFn);
103 PyObject* dict = PyModule_GetDict(pModule);
105 throw std::runtime_error(
"Can't get dictionary from module");
107 std::vector<std::string> result;
110 while (PyDict_Next(dict, &pos, &key, &value)) {
111 if (PyCallable_Check(value)) {
113 if (func_name.find(
"__") == std::string::npos)
114 result.push_back(func_name);
120 Py_DecRef(pCompiledFn);
Defines class MultiLayer.
Defines PyEmbeddedUtils namespace.
Defines PyImport namespace.
Includes python header and takes care of warnings.
Our sample model: a stack of layers one below the other.
MultiLayer * clone() const final override
Returns a clone of multilayer with clones of all layers and interfaces between layers.
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.
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 error_description(const std::string &title)