6#include <units/units.hpp>
13#ifdef POLYFEM_WITH_PYTHON
17#if defined(_MSC_VER) && !defined(NDEBUG) && !defined(PYBIND11_HANDLE_REF_DEBUG)
18#define POLYFEM_RESTORE_NDEBUG_AFTER_PYBIND11
21#include <pybind11/embed.h>
22#include <pybind11/pybind11.h>
23#include <pybind11/stl.h>
24#ifdef POLYFEM_RESTORE_NDEBUG_AFTER_PYBIND11
26#undef POLYFEM_RESTORE_NDEBUG_AFTER_PYBIND11
40#ifdef POLYFEM_WITH_PYTHON
41 return Py_IsInitialized() && PyGILState_Check();
47#ifdef POLYFEM_WITH_PYTHON
48 namespace py = pybind11;
52 class PythonInterpreter
55 static PythonInterpreter &instance()
57 static PythonInterpreter interpreter;
61 PythonInterpreter(
const PythonInterpreter &) =
delete;
62 PythonInterpreter &operator=(
const PythonInterpreter &) =
delete;
67 if (!Py_IsInitialized())
72#ifdef POLYFEM_PYTHON_EXECUTABLE
74 PyConfig_InitPythonConfig(&config);
76 wchar_t *program_raw = Py_DecodeLocale(POLYFEM_PYTHON_EXECUTABLE,
nullptr);
77 if (program_raw ==
nullptr)
79 PyConfig_Clear(&config);
80 log_and_throw_error(
"Failed to decode Python executable path.");
83 PyStatus status = PyConfig_SetString(&config, &config.program_name, program_raw);
84 PyMem_RawFree(program_raw);
85 if (PyStatus_Exception(status))
87 PyConfig_Clear(&config);
91 guard_ =
new py::scoped_interpreter(&config);
93 guard_ =
new py::scoped_interpreter();
98 ~PythonInterpreter() =
default;
100 py::scoped_interpreter *guard_ =
nullptr;
103 void ensure_python_interpreter()
107 (void)PythonInterpreter::instance();
109 catch (
const std::exception &e)
115 std::shared_ptr<py::object> make_python_object_holder(py::object value)
117 return std::shared_ptr<py::object>(
118 new py::object(std::move(value)),
119 [](py::object *
object) {
120 if (Py_IsInitialized())
122 py::gil_scoped_acquire gil;
127 (void)object->release();
133 py::object load_python_value_function(
const std::string &path,
const std::string &function_name)
135 ensure_python_interpreter();
136 py::gil_scoped_acquire gil;
138 py::module_ importlib_util = py::module_::import(
"importlib.util");
139 py::module_ pathlib = py::module_::import(
"pathlib");
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>();
145 py::object spec = importlib_util.attr(
"spec_from_file_location")(module_name, resolved_path_str);
147 log_and_throw_error(fmt::format(
"Unable to create Python module spec from '{}'", resolved_path_str));
149 py::object loader = spec.attr(
"loader");
150 if (loader.is_none())
153 py::object
module = importlib_util.attr("module_from_spec")(spec);
154 loader.attr(
"exec_module")(module);
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));
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));
167 void ExpressionValue::init_python(
const std::string &path,
const std::string &function_name)
171 py::object value = load_python_value_function(path, function_name);
172 auto callable = make_python_object_holder(std::move(value));
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);
180 return out.cast<
double>();
182 catch (
const py::cast_error &)
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)
201 return (3 * pow(a, 2)) - (2 * pow(a, 3));
203 static double half_smoothstep(
double a)
205 double b = (a + 1.) / 2.;
206 return 2. * smoothstep(b) - 1.;
208 static double deg2rad(
double d) {
return d * igl::PI / 180.0; }
209 static double rotate_2D_x(
double x,
double y,
double theta)
211 return x * cos(theta) -
y * sin(theta);
213 static double rotate_2D_y(
double x,
double y,
double theta)
215 return x * sin(theta) +
y * cos(theta);
217 static double smooth_abs(
double x,
double k)
219 return tanh(k *
x) *
x;
221 static double iflargerthanzerothenelse(
double check,
double ttrue,
double ffalse)
223 return check >= 0 ? ttrue : ffalse;
225 static double sign(
double x)
227 return (0 <
x) - (
x < 0);
229 static double compare(
double a,
double b)
231 return a <
b ? 1.0 : 0.0;
281 catch (
const std::exception &)
287 double x = 0,
y = 0,
z = 0, t = 0;
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},
308 te_expr *tmp = te_compile(expr.c_str(), vars.data(), vars.size(), &err);
311 logger().error(
"Unable to parse: {}", expr);
312 logger().error(
"Error near character {}.", err);
322 if (
vals.is_number())
326 else if (
vals.is_boolean())
330 else if (
vals.is_array())
332 if (
vals.empty() ||
vals[0].is_number())
336 for (
int i = 0; i <
mat_.size(); ++i)
338 if (!
vals[i].is_number())
339 log_and_throw_error(
"Expression arrays must contain either only numbers or only expressions.");
347 for (
int i = 0; i <
vals.size(); ++i)
360 logger().error(
"Specifying varying dirichlet over time, however 'time_reference' does not match dirichlet boundary conditions.");
362 else if (
vals.is_object())
364 units::precise_unit unit;
365 if (
vals.contains(
"unit"))
367 if (!
vals[
"unit"].is_string())
370 const std::string unit_str =
vals[
"unit"].get<std::string>();
371 if (!unit_str.empty())
372 unit = units::unit_from_string(unit_str);
375 if (
vals.contains(
"file_name"))
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());
383 if (!
vals[
"file_name"].is_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>());
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>();
391 init_python(path, function_name);
397 if (!
vals.contains(
"value"))
405 init(
vals.get<std::string>(), resources);
413 sfunc_ = [func](
double x,
double y,
double z,
double t,
int index) {
return func(
x,
y,
z); };
419 sfunc_ = [func](
double x,
double y,
double z,
double t,
int index) {
return func(
x,
y,
z, t); };
432 tfunc_ = [func](
double x,
double y,
double z,
double t) {
return func(
x,
y,
z); };
448 for (
int i = 0; i < t.size(); ++i)
450 t_index_[std::round(t[i].get<double>() * 1000.) / 1000.] = i;
454 logger().error(
"Specifying varying dirichlet over time, however 'time_reference' does not match dirichlet boundary conditions.");
465 t = std::round(t * 1000.) / 1000.;
475 logger().error(
"Cannot find dirichlet condition for time step {}.", t);
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},
511 te_expr *tmp = te_compile(
expr_.c_str(), vars.data(), vars.size(), &err);
515 logger().error(
"Error near character {}.", err);
518 result = te_eval(tmp);
522 if (!
unit_.base_units().empty())
ElementAssemblyValues vals
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
void set_t(const json &t)
std::vector< ExpressionValue > mat_expr_
units::precise_unit unit_
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_
units::precise_unit unit_type_
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.
void log_and_throw_error(const std::string &msg)