PolyFEM
Loading...
Searching...
No Matches
ExpressionValue.cpp
Go to the documentation of this file.
1#include "ExpressionValue.hpp"
2
5
6#include <units/units.hpp>
7
8#include <igl/PI.h>
9
10#include <tinyexpr.h>
11#include <filesystem>
12#include <memory>
13#ifdef POLYFEM_WITH_PYTHON
14// pybind11 enables a debug-only reference counter when NDEBUG is not defined.
15// On MSVC that path can fail with C2480 because it uses a function-local
16// thread_local variable. Keep the workaround scoped to pybind11's headers.
17#if defined(_MSC_VER) && !defined(NDEBUG) && !defined(PYBIND11_HANDLE_REF_DEBUG)
18#define POLYFEM_RESTORE_NDEBUG_AFTER_PYBIND11
19#define NDEBUG
20#endif
21#include <pybind11/embed.h>
22#include <pybind11/pybind11.h>
23#include <pybind11/stl.h>
24#ifdef POLYFEM_RESTORE_NDEBUG_AFTER_PYBIND11
25#undef NDEBUG
26#undef POLYFEM_RESTORE_NDEBUG_AFTER_PYBIND11
27#endif
28#endif
29
30#include <iostream>
31
32namespace polyfem
33{
34 using namespace io;
35
36 namespace utils
37 {
39 {
40#ifdef POLYFEM_WITH_PYTHON
41 return Py_IsInitialized() && PyGILState_Check();
42#else
43 return false;
44#endif
45 }
46
47#ifdef POLYFEM_WITH_PYTHON
48 namespace py = pybind11;
49
50 namespace
51 {
52 class PythonInterpreter
53 {
54 public:
55 static PythonInterpreter &instance()
56 {
57 static PythonInterpreter interpreter;
58 return interpreter;
59 }
60
61 PythonInterpreter(const PythonInterpreter &) = delete;
62 PythonInterpreter &operator=(const PythonInterpreter &) = delete;
63
64 private:
65 PythonInterpreter()
66 {
67 if (!Py_IsInitialized())
68 {
69 // Keep the embedded interpreter alive for the process lifetime.
70 // Python-backed ExpressionValues may be destroyed during static
71 // teardown, and finalizing first makes their py::object cleanup unsafe.
72#ifdef POLYFEM_PYTHON_EXECUTABLE
73 PyConfig config;
74 PyConfig_InitPythonConfig(&config);
75
76 wchar_t *program_raw = Py_DecodeLocale(POLYFEM_PYTHON_EXECUTABLE, nullptr);
77 if (program_raw == nullptr)
78 {
79 PyConfig_Clear(&config);
80 log_and_throw_error("Failed to decode Python executable path.");
81 }
82
83 PyStatus status = PyConfig_SetString(&config, &config.program_name, program_raw);
84 PyMem_RawFree(program_raw);
85 if (PyStatus_Exception(status))
86 {
87 PyConfig_Clear(&config);
88 log_and_throw_error("Failed to configure embedded Python program_name.");
89 }
90
91 guard_ = new py::scoped_interpreter(&config);
92#else
93 guard_ = new py::scoped_interpreter();
94#endif
95 }
96 }
97
98 ~PythonInterpreter() = default;
99
100 py::scoped_interpreter *guard_ = nullptr;
101 };
102
103 void ensure_python_interpreter()
104 {
105 try
106 {
107 (void)PythonInterpreter::instance();
108 }
109 catch (const std::exception &e)
110 {
111 log_and_throw_error(fmt::format("Failed to initialize embedded Python: {}", e.what()));
112 }
113 }
114
115 std::shared_ptr<py::object> make_python_object_holder(py::object value)
116 {
117 return std::shared_ptr<py::object>(
118 new py::object(std::move(value)),
119 [](py::object *object) {
120 if (Py_IsInitialized())
121 {
122 py::gil_scoped_acquire gil;
123 delete object;
124 }
125 else
126 {
127 (void)object->release();
128 delete object;
129 }
130 });
131 }
132
133 py::object load_python_value_function(const std::string &path, const std::string &function_name)
134 {
135 ensure_python_interpreter();
136 py::gil_scoped_acquire gil;
137
138 py::module_ importlib_util = py::module_::import("importlib.util");
139 py::module_ pathlib = py::module_::import("pathlib");
140
141 py::object resolved_path = pathlib.attr("Path")(path).attr("resolve")();
142 std::string module_name = resolved_path.attr("stem").cast<std::string>();
143 std::string resolved_path_str = py::str(resolved_path).cast<std::string>();
144
145 py::object spec = importlib_util.attr("spec_from_file_location")(module_name, resolved_path_str);
146 if (spec.is_none())
147 log_and_throw_error(fmt::format("Unable to create Python module spec from '{}'", resolved_path_str));
148
149 py::object loader = spec.attr("loader");
150 if (loader.is_none())
151 log_and_throw_error(fmt::format("Python module '{}' has no loader", resolved_path_str));
152
153 py::object module = importlib_util.attr("module_from_spec")(spec);
154 loader.attr("exec_module")(module);
155
156 if (!py::hasattr(module, function_name.c_str()))
157 log_and_throw_error(fmt::format("Python expression file '{}' must define a function named '{}'", resolved_path_str, function_name));
158
159 py::object value = module.attr(function_name.c_str());
160 if (!PyCallable_Check(value.ptr()))
161 log_and_throw_error(fmt::format("Python attribute '{}' in '{}' is not callable", function_name, resolved_path_str));
162
163 return value;
164 }
165 } // namespace
166
167 void ExpressionValue::init_python(const std::string &path, const std::string &function_name)
168 {
169 clear();
170
171 py::object value = load_python_value_function(path, function_name);
172 auto callable = make_python_object_holder(std::move(value));
173
174 sfunc_ = [callable](double x, double y, double z, double t, int index) -> double {
175 py::gil_scoped_acquire gil;
176 py::object out = (*callable)(x, y, z, t, index);
177
178 try
179 {
180 return out.cast<double>();
181 }
182 catch (const py::cast_error &)
183 {
184 log_and_throw_error("Python expression must return a scalar convertible to double");
185 return 0;
186 }
187 };
188 }
189
190#endif
191
192 static double min(double a, double b) { return a < b ? a : b; }
193 static double max(double a, double b) { return a > b ? a : b; }
194 static double smoothstep(double a)
195 {
196 if (a < 0)
197 return 0;
198 else if (a > 1)
199 return 1;
200 else
201 return (3 * pow(a, 2)) - (2 * pow(a, 3));
202 }
203 static double half_smoothstep(double a)
204 {
205 double b = (a + 1.) / 2.;
206 return 2. * smoothstep(b) - 1.;
207 }
208 static double deg2rad(double d) { return d * igl::PI / 180.0; }
209 static double rotate_2D_x(double x, double y, double theta)
210 {
211 return x * cos(theta) - y * sin(theta);
212 }
213 static double rotate_2D_y(double x, double y, double theta)
214 {
215 return x * sin(theta) + y * cos(theta);
216 }
217 static double smooth_abs(double x, double k)
218 {
219 return tanh(k * x) * x;
220 }
221 static double iflargerthanzerothenelse(double check, double ttrue, double ffalse)
222 {
223 return check >= 0 ? ttrue : ffalse;
224 }
225 static double sign(double x)
226 {
227 return (0 < x) - (x < 0);
228 }
229 static double compare(double a, double b)
230 {
231 return a < b ? 1.0 : 0.0;
232 }
233
238
240 {
241 expr_ = "";
242 mat_.resize(0, 0);
243 mat_expr_ = {};
244 sfunc_ = nullptr;
245 tfunc_ = nullptr;
246 value_ = 0;
247 index_ = -1;
248 }
249
250 void ExpressionValue::init(const double val)
251 {
252 clear();
253
254 value_ = val;
255 }
256
257 void ExpressionValue::init(const Eigen::MatrixXd &val)
258 {
259 clear();
260
261 mat_ = val;
262 }
263
264 void ExpressionValue::init(const std::string &expr, const io::ResourceIO &resources)
265 {
266 clear();
267
268 if (expr.empty())
269 {
270 return;
271 }
272
273 try
274 {
275 if (resources.exists(expr) && !resources.is_group(expr))
276 {
277 mat_ = resources.read_matrix(expr);
278 return;
279 }
280 }
281 catch (const std::exception &)
282 {
283 }
284
285 expr_ = expr;
286
287 double x = 0, y = 0, z = 0, t = 0;
288
289 std::vector<te_variable> vars = {
290 {"x", &x, TE_VARIABLE},
291 {"y", &y, TE_VARIABLE},
292 {"z", &z, TE_VARIABLE},
293 {"t", &t, TE_VARIABLE},
294 {"min", (const void *)min, TE_FUNCTION2},
295 {"max", (const void *)max, TE_FUNCTION2},
296 {"smoothstep", (const void *)smoothstep, TE_FUNCTION1},
297 {"half_smoothstep", (const void *)half_smoothstep, TE_FUNCTION1},
298 {"deg2rad", (const void *)deg2rad, TE_FUNCTION1},
299 {"rotate_2D_x", (const void *)rotate_2D_x, TE_FUNCTION3},
300 {"rotate_2D_y", (const void *)rotate_2D_y, TE_FUNCTION3},
301 {"if", (const void *)iflargerthanzerothenelse, TE_FUNCTION3},
302 {"compare", (const void *)compare, TE_FUNCTION2},
303 {"smooth_abs", (const void *)smooth_abs, TE_FUNCTION2},
304 {"sign", (const void *)sign, TE_FUNCTION1},
305 };
306
307 int err;
308 te_expr *tmp = te_compile(expr.c_str(), vars.data(), vars.size(), &err);
309 if (!tmp)
310 {
311 logger().error("Unable to parse: {}", expr);
312 logger().error("Error near character {}.", err);
313 log_and_throw_error("Invalid expression '{}'.", expr);
314 }
315 te_free(tmp);
316 }
317
318 void ExpressionValue::init(const json &vals, const io::ResourceIO &resources)
319 {
320 clear();
321
322 if (vals.is_number())
323 {
324 init(vals.get<double>());
325 }
326 else if (vals.is_boolean())
327 {
328 init(vals.get<bool>() ? 1. : 0.);
329 }
330 else if (vals.is_array())
331 {
332 if (vals.empty() || vals[0].is_number())
333 {
334 mat_.resize(vals.size(), 1);
335
336 for (int i = 0; i < mat_.size(); ++i)
337 {
338 if (!vals[i].is_number())
339 log_and_throw_error("Expression arrays must contain either only numbers or only expressions.");
340 mat_(i) = vals[i].get<double>();
341 }
342 }
343 else
344 {
345 mat_expr_ = std::vector<ExpressionValue>(vals.size());
346
347 for (int i = 0; i < vals.size(); ++i)
348 {
349 mat_expr_[i].init(vals[i], resources);
350 if (unit_type_set_)
351 {
352 mat_expr_[i].unit_type_ = unit_type_;
353 mat_expr_[i].unit_type_set_ = true;
354 }
355 }
356 }
357
358 if (t_index_.size() > 0)
359 if (mat_.size() != t_index_.size() && mat_expr_.size() != t_index_.size())
360 logger().error("Specifying varying dirichlet over time, however 'time_reference' does not match dirichlet boundary conditions.");
361 }
362 else if (vals.is_object())
363 {
364 units::precise_unit unit;
365 if (vals.contains("unit"))
366 {
367 if (!vals["unit"].is_string())
368 log_and_throw_error("Expression object 'unit' must be a string.");
369
370 const std::string unit_str = vals["unit"].get<std::string>();
371 if (!unit_str.empty())
372 unit = units::unit_from_string(unit_str);
373 }
374
375 if (vals.contains("file_name"))
376 {
377#ifndef POLYFEM_WITH_PYTHON
379 "Python expression '{}' requested, but PolyFEM was built without Python support. "
380 "Reconfigure with -DPOLYFEM_WITH_PYTHON=ON to enable Python expressions.",
381 vals["file_name"].dump());
382#else
383 if (!vals["file_name"].is_string())
384 log_and_throw_error("Python expression 'file_name' must be a string.");
385 if (!vals.contains("function_name") || !vals["function_name"].is_string())
386 log_and_throw_error("Python expression '{}' must include a string 'function_name'.", vals["file_name"].get<std::string>());
387
388 const std::string path = resources.materialize(vals["file_name"].get<std::string>()).string();
389 const std::string function_name = vals["function_name"].get<std::string>();
390
391 init_python(path, function_name);
392 unit_ = unit;
393 return;
394#endif
395 }
396
397 if (!vals.contains("value"))
398 log_and_throw_error("Expression object must contain either 'value' or 'file_name'.");
399
400 init(vals["value"], resources);
401 unit_ = unit;
402 }
403 else
404 {
405 init(vals.get<std::string>(), resources);
406 }
407 }
408
409 void ExpressionValue::init(const std::function<double(double x, double y, double z)> &func)
410 {
411 clear();
412
413 sfunc_ = [func](double x, double y, double z, double t, int index) { return func(x, y, z); };
414 }
415
416 void ExpressionValue::init(const std::function<double(double x, double y, double z, double t)> &func)
417 {
418 clear();
419 sfunc_ = [func](double x, double y, double z, double t, int index) { return func(x, y, z, t); };
420 }
421
422 void ExpressionValue::init(const std::function<double(double x, double y, double z, double t, int index)> &func)
423 {
424 clear();
425 sfunc_ = func;
426 }
427
428 void ExpressionValue::init(const std::function<Eigen::MatrixXd(double x, double y, double z)> &func, const int coo)
429 {
430 clear();
431
432 tfunc_ = [func](double x, double y, double z, double t) { return func(x, y, z); };
433 tfunc_coo_ = coo;
434 }
435
436 void ExpressionValue::init(const std::function<Eigen::MatrixXd(double x, double y, double z, double t)> &func, const int coo)
437 {
438 clear();
439
440 tfunc_ = func;
441 tfunc_coo_ = coo;
442 }
443
445 {
446 if (t.is_array())
447 {
448 for (int i = 0; i < t.size(); ++i)
449 {
450 t_index_[std::round(t[i].get<double>() * 1000.) / 1000.] = i;
451 }
452
453 if (mat_.size() != t_index_.size() && mat_expr_.size() != t_index_.size())
454 logger().error("Specifying varying dirichlet over time, however 'time_reference' does not match dirichlet boundary conditions.");
455 }
456 }
457
458 double ExpressionValue::operator()(double x, double y, double z, double t, int index) const
459 {
460 double result;
461 if (expr_.empty())
462 {
463 if (t_index_.size() > 0)
464 {
465 t = std::round(t * 1000.) / 1000.;
466 if (t_index_.count(t) != 0)
467 {
468 if (mat_.size() > 0)
469 return mat_(t_index_.at(t));
470 else if (mat_expr_.size() > 0)
471 return mat_expr_[t_index_.at(t)](x, y, z, t, index);
472 }
473 else
474 {
475 logger().error("Cannot find dirichlet condition for time step {}.", t);
476 return 0;
477 }
478 }
479
480 if (mat_.size() > 0)
481 result = mat_(index_ >= 0 ? index_ : index);
482 else if (sfunc_)
483 result = sfunc_(x, y, z, t, index);
484 else if (tfunc_)
485 result = tfunc_(x, y, z, t)(tfunc_coo_);
486 else
487 result = value_;
488 }
489 else
490 {
491
492 std::vector<te_variable> vars = {
493 {"x", &x, TE_VARIABLE},
494 {"y", &y, TE_VARIABLE},
495 {"z", &z, TE_VARIABLE},
496 {"t", &t, TE_VARIABLE},
497 {"min", (const void *)min, TE_FUNCTION2},
498 {"max", (const void *)max, TE_FUNCTION2},
499 {"smoothstep", (const void *)smoothstep, TE_FUNCTION1},
500 {"half_smoothstep", (const void *)half_smoothstep, TE_FUNCTION1},
501 {"deg2rad", (const void *)deg2rad, TE_FUNCTION1},
502 {"rotate_2D_x", (const void *)rotate_2D_x, TE_FUNCTION3},
503 {"rotate_2D_y", (const void *)rotate_2D_y, TE_FUNCTION3},
504 {"if", (const void *)iflargerthanzerothenelse, TE_FUNCTION3},
505 {"compare", (const void *)compare, TE_FUNCTION2},
506 {"smooth_abs", (const void *)smooth_abs, TE_FUNCTION2},
507 {"sign", (const void *)sign, TE_FUNCTION1},
508 };
509
510 int err;
511 te_expr *tmp = te_compile(expr_.c_str(), vars.data(), vars.size(), &err);
512 if (!tmp)
513 {
514 logger().error("Unable to parse: {}", expr_);
515 logger().error("Error near character {}.", err);
516 log_and_throw_error("Invalid expression '{}'.", expr_);
517 }
518 result = te_eval(tmp);
519 te_free(tmp);
520 }
521
522 if (!unit_.base_units().empty())
523 {
524 if (!unit_.is_convertible(unit_type_))
525 log_and_throw_error(fmt::format("Cannot convert {} to {}", units::to_string(unit_), units::to_string(unit_type_)));
526
527 result = units::convert(result, unit_, unit_type_);
528 }
529
530 return result;
531 }
532 } // namespace utils
533} // namespace polyfem
double val
ElementAssemblyValues vals
int y
int z
int x
Read-only interface to a hierarchical collection of simulation resources.
virtual std::filesystem::path materialize(const std::string &path) const =0
virtual bool exists(const std::string &path) const =0
virtual Eigen::MatrixXd read_matrix(const std::string &path) const =0
virtual bool is_group(const std::string &path) const =0
std::vector< ExpressionValue > mat_expr_
std::function< double(double x, double y, double z, double t, int index)> sfunc_
std::function< Eigen::MatrixXd(double x, double y, double z, double t)> tfunc_
std::map< double, int > t_index_
double operator()(double x, double y, double z=0, double t=0, int index=-1) const
void init(const json &vals, const io::ResourceIO &resources)
bool python_gil_held()
Whether the caller holds Python's interpreter lock.
spdlog::logger & logger()
Retrieves the current logger.
Definition Logger.cpp:44
nlohmann::json json
Definition Common.hpp:9
void log_and_throw_error(const std::string &msg)
Definition Logger.cpp:73