v0.16.3
Loading...
Searching...
No Matches
SDFPython.cpp
Go to the documentation of this file.
1#include <MoFEM.hpp>
2#include <SDFPython.hpp>
3#include <boost/python.hpp>
4#include <boost/python/numpy.hpp>
5#include <cmath>
6#include <cstring>
7
8namespace MoFEM {
9namespace bp = boost::python;
10namespace np = boost::python::numpy;
11namespace {
12struct PythonLock {
13 PyGILState_STATE state = PyGILState_Ensure();
14 ~PythonLock() { PyGILState_Release(state); }
15};
16} // namespace
17
19 bp::dict globals;
20 std::string file;
21
22 MoFEMErrorCode evaluate(const char *name, int columns, double dt, double t,
24 const MatrixDouble &normals, int block,
25 MatrixDouble &values) const {
27 if (coordinates.size2() != 3 || normals.size2() != 3 ||
28 coordinates.size1() != normals.size1())
29 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
30 "SDF coordinates and normals must both have shape (N,3)");
31 PythonLock lock;
32 if (!globals.has_key(name) ||
33 !PyCallable_Check(bp::object(globals[name]).ptr()))
34 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
35 "Script %s has no callable %s", file.c_str(), name);
36 try {
37 const auto n = coordinates.size1();
38 std::vector<np::ndarray> args;
39 for (int d = 0; d != 6; ++d) {
40 auto a = np::empty(bp::make_tuple(n), np::dtype::get_builtin<double>());
41 auto *p = reinterpret_cast<double *>(a.get_data());
42 for (size_t i = 0; i != n; ++i)
43 p[i] = d < 3 ? coordinates(i, d) : normals(i, d - 3);
44 args.push_back(a);
45 }
46 bp::object result = globals[name](dt, t, args[0], args[1], args[2],
47 args[3], args[4], args[5], block);
48 auto a = np::from_object(result, np::dtype::get_builtin<double>());
49 if (a.get_nd() != (columns == 1 ? 1 : 2) ||
50 a.shape(0) != static_cast<Py_intptr_t>(n) ||
51 (columns != 1 && a.shape(1) != columns))
52 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
53 "Wrong result shape from %s in %s", name, file.c_str());
54 values.resize(n, columns, false);
55 for (size_t i = 0; i != n; ++i)
56 for (int d = 0; d != columns; ++d) {
57 double v;
58 std::memcpy(&v,
59 a.get_data() + i * a.strides(0) +
60 (columns == 1 ? 0 : d * a.strides(1)),
61 sizeof(v));
62 if (!std::isfinite(v))
63 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
64 "Non-finite result from %s in %s", name, file.c_str());
65 values(i, d) = v;
66 }
67 } catch (const bp::error_already_set &) {
68 PyErr_Print();
69 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
70 "Python %s failed in %s", name, file.c_str());
71 }
73 }
74};
75
76SDFPython::SDFPython() = default;
78 if (impl) {
79 PythonLock lock;
80 impl.reset();
81 }
82}
83
86 Py_Initialize();
87 PythonLock lock;
88 try {
89 bp::import("numpy");
90 np::initialize();
91 if (PyErr_Occurred())
92 bp::throw_error_already_set();
93 } catch (const bp::error_already_set &) {
94 PyErr_Print();
95 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
96 "Could not initialise NumPy");
97 }
99}
100
103 if (Py_IsInitialized() && Py_FinalizeEx() < 0)
104 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
105 "Python finalisation failed");
107}
108
109MoFEMErrorCode SDFPython::sdfInit(const std::string &file) {
111 if (!Py_IsInitialized())
112 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
113 "Initialise Python/NumPy before loading an SDF");
114 PythonLock lock;
115 try {
116 auto next = std::make_unique<Impl>();
117 next->file = file;
118 next->globals["__builtins__"] = bp::import("builtins");
119 next->globals["__file__"] = file;
120 next->globals["__name__"] = "mofem_sdf";
121 bp::exec_file(file.c_str(), next->globals, next->globals);
122 if (!next->globals.has_key("sdf") ||
123 !PyCallable_Check(bp::object(next->globals["sdf"]).ptr()))
124 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
125 "Script %s has no callable sdf", file.c_str());
126 impl = std::move(next);
127 } catch (const bp::error_already_set &) {
128 PyErr_Print();
129 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL,
130 "Could not load SDF script %s", file.c_str());
131 }
133}
134
137 if (!impl)
138 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL, "Load an SDF first");
139 PythonLock lock;
140 for (const auto *name : {"grad_sdf", "hess_sdf"})
141 if (!impl->globals.has_key(name) ||
142 !PyCallable_Check(bp::object(impl->globals[name]).ptr()))
143 SETERRQ(PETSC_COMM_SELF, MOFEM_DATA_INCONSISTENCY,
144 "Contact requires %s in %s", name, impl->file.c_str());
146}
147
149 const MatrixDouble &n, int block,
150 VectorDouble &values) const {
152 if (!impl)
153 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL, "Load an SDF first");
155 CHKERR impl->evaluate("sdf", 1, dt, t, x, n, block, result);
156 values.resize(result.size1(), false);
157 for (size_t i = 0; i != values.size(); ++i)
158 values[i] = result(i, 0);
160}
161
163 const MatrixDouble &x,
164 const MatrixDouble &n, int block,
165 MatrixDouble &values) const {
167 if (!impl)
168 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL, "Load an SDF first");
169 CHKERR impl->evaluate("grad_sdf", 3, dt, t, x, n, block, values);
171}
172
174 const MatrixDouble &x,
175 const MatrixDouble &n, int block,
176 MatrixDouble &values) const {
178 if (!impl)
179 SETERRQ(PETSC_COMM_SELF, MOFEM_OPERATION_UNSUCCESSFUL, "Load an SDF first");
180 CHKERR impl->evaluate("hess_sdf", 6, dt, t, x, n, block, values);
182}
183
184double SDFPython::value(const std::array<double, 3> &point, double dt, double t,
185 int block) const {
186 MatrixDouble x(1, 3), n(1, 3);
187 for (int d = 0; d != 3; ++d) {
188 x(0, d) = point[d];
189 n(0, d) = 0;
190 }
192 CHK_THROW_MESSAGE(evalSdf(dt, t, x, n, block, result),
193 "SDF evaluation failed");
194 return result[0];
195}
196} // namespace MoFEM
TetMeshData result
Vec t
Removal: the ring edge.
std::vector< std::array< double, 3 > > coordinates
PyGILState_STATE state
Definition SDFPython.cpp:13
Reusable vectorised Python signed-distance evaluator.
SmartPetscObj< Vec > values
std::string name
constexpr double a
#define CHK_THROW_MESSAGE(err, msg)
Check and throw MoFEM exception.
#define MoFEMFunctionBegin
First executable line of each MoFEM function, used for error handling. Final line of MoFEM functions ...
@ MOFEM_OPERATION_UNSUCCESSFUL
Definition definitions.h:34
@ MOFEM_DATA_INCONSISTENCY
Definition definitions.h:31
#define MoFEMFunctionReturn(a)
Last executable line of each PETSc function used for error handling. Replaces return()
#define CHKERR
Inline error check.
FTensor::Index< 'i', SPACE_DIM > i
double dt
const double v
phase velocity of light in medium (cm/ns)
PetscErrorCode MoFEMErrorCode
MoFEM/PETSc error code.
implementation of Data Operators for Forces and Sources
Definition Common.hpp:10
MoFEMErrorCode evaluate(const char *name, int columns, double dt, double t, const MatrixDouble &coordinates, const MatrixDouble &normals, int block, MatrixDouble &values) const
Definition SDFPython.cpp:22
MoFEMErrorCode requireDerivatives() const
static MoFEMErrorCode initialise()
Definition SDFPython.cpp:84
MoFEMErrorCode evalHessSdf(double dt, double t, const MatrixDouble &coordinates, const MatrixDouble &normals, int block, MatrixDouble &values) const
MoFEMErrorCode sdfInit(const std::string &file)
double value(const std::array< double, 3 > &point, double dt=0, double t=0, int block=0) const
MoFEMErrorCode evalSdf(double dt, double t, const MatrixDouble &coordinates, const MatrixDouble &normals, int block, VectorDouble &values) const
static MoFEMErrorCode finalise()
std::unique_ptr< Impl > impl
Definition SDFPython.hpp:44
MoFEMErrorCode evalGradSdf(double dt, double t, const MatrixDouble &coordinates, const MatrixDouble &normals, int block, MatrixDouble &values) const