15 #ifdef BORNAGAIN_PYTHON
25 std::string error_description(
const std::string& title)
27 std::stringstream buf;
36 const std::string& functionName,
37 const std::string& path)
39 PyEmbeddedUtils::import_bornagain(path);
41 PyObject* pCompiledFn = Py_CompileString(script.c_str(),
"", Py_file_input);
43 throw std::runtime_error(error_description(
"Can't compile snippet"));
46 PyObject* pModule = PyImport_ExecCodeModule((
char*)
"test", pCompiledFn);
48 Py_DecRef(pCompiledFn);
49 throw std::runtime_error(error_description(
"Can't exec module"));
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);
62 throw std::runtime_error(error_description(
"Can't call function"));
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)
90 PyEmbeddedUtils::import_bornagain(path);
92 PyObject* pCompiledFn = Py_CompileString(script.c_str(),
"", Py_file_input);
94 throw std::runtime_error(error_description(
"Can't compile snippet"));
97 PyObject* pModule = PyImport_ExecCodeModule((
char*)
"test", pCompiledFn);
99 Py_DecRef(pCompiledFn);
100 throw std::runtime_error(error_description(
"Can't exec module"));
103 PyObject* dict = PyModule_GetDict(pModule);
105 throw std::runtime_error(
"Can't get dictionary from module");
107 std::vector<std::string> result;
108 PyObject *key, *value;
110 while (PyDict_Next(dict, &pos, &key, &value)) {
111 if (PyCallable_Check(value)) {
112 std::string func_name = PyEmbeddedUtils::toString(key);
113 if (func_name.find(
"__") == std::string::npos)
114 result.push_back(func_name);
120 Py_DecRef(pCompiledFn);
Defines class MultiLayer.
Defines PyEmbeddedUtils namespace.
std::string pythonStackTrace()
Returns string representing python stack trace.
Defines PyImport namespace.
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.
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.