SimiLie
Loading...
Searching...
No Matches
generate_cpp_constitutive_law.py
1#!/usr/bin/env python3
2# SPDX-FileCopyrightText: 2026 Baptiste Legouix
3# SPDX-License-Identifier: AGPL-3.0-or-later
4# AI-GENERATED
5
6from __future__ import annotations
7
8from dataclasses import dataclass
9from pathlib import Path
10
11from sympy import diff, solve, symbols
12from sympy.printing.codeprinter import cxxcode
13
14
15@dataclass(frozen=True)
17 namespace: str
18 class_name: str
19 parameters: list[str]
20 variables: list[str]
21 output_variable: str
22 constitutive_law: object
23
24
25def _replace_symbols(expression: str, replacements: dict[str, str]) -> str:
26 for source, target in replacements.items():
27 expression = expression.replace(source, target)
28 return expression
29
30
32 output_path: Path,
33 namespace: str,
34 class_name: str,
35 parameters: list[tuple[str, str, bool]],
36 variables: list[str],
37 output_variable: str,
38 constitutive_law,
39) -> None:
40 output_path.parent.mkdir(parents=True, exist_ok=True)
41
42 parameter_replacements = {
43 constructor_name: member_name for member_name, constructor_name, _ in parameters
44 }
45 constitutive_law_symbols = {
46 str(symbol): symbol
47 for symbol in constitutive_law.free_symbols
48 if str(symbol) not in parameter_replacements
49 }
50 if not variables:
51 raise ValueError("Constitutive law must define at least one variable")
52 if any(name not in constitutive_law_symbols for name in variables):
53 raise ValueError("Constitutive law variables must match symbolic variables")
54
55 state_variable_name = variables[-1]
56 state_variable_symbol = constitutive_law_symbols[state_variable_name]
57 output_symbol = symbols(output_variable)
58 inverse_solution = solve(
59 output_symbol - constitutive_law, state_variable_symbol, dict=True
60 )
61 if not inverse_solution:
62 raise ValueError("Unable to invert constitutive law")
63 inverse_expression = inverse_solution[0][state_variable_symbol]
64 forward_value_expression = diff(constitutive_law, state_variable_symbol)
65 inverse_value_expression = diff(inverse_expression, output_symbol)
66
67 parameter_members = "\n".join(
68 f" {'const ' if is_const else ''}double {member_name};"
69 for member_name, _, is_const in parameters
70 )
71 constructor_signature = ",\n ".join(
72 f"double {constructor_name}_" for _, constructor_name, _ in parameters
73 )
74 constructor_initializers = ", ".join(
75 f"{member_name}({constructor_name}_)"
76 for member_name, constructor_name, _ in parameters
77 )
78 context_members = "\n".join(
79 f" double {name} = 0.0;" for name in variables[:-1]
80 )
81
82 def render(expression, inverse: bool = False) -> str:
83 argument_symbols = {
84 constitutive_law_symbols[name]: symbols(f"__state_{i}")
85 for i, name in enumerate(variables)
86 }
87 argument_replacements = {
88 f"__state_{i}": f"state.{name}" for i, name in enumerate(variables[:-1])
89 }
90 argument_replacements[f"__state_{len(variables) - 1}"] = "state.value[0]"
91 if inverse:
92 argument_symbols[output_symbol] = symbols("__output")
93 argument_replacements["__output"] = "state.value[0]"
94 return _replace_symbols(
96 cxxcode(expression.xreplace(argument_symbols)), parameter_replacements
97 ),
98 argument_replacements,
99 )
100
101 output_path.write_text(
102 f"""\
103// SPDX-FileCopyrightText: 2026 Baptiste Legouix
104// SPDX-License-Identifier: AGPL-3.0-or-later
105// AI-GENERATED
106
107#pragma once
108
109#include <array>
110#include <cmath>
111#include <cstddef>
112#include <Kokkos_Core.hpp>
113#include <similie/exterior/form.hpp>
114#include <similie/physics/concepts.hpp>
115
116namespace {namespace} {{
117
118class {class_name}
119{{
120{parameter_members}
121
122public:
123 static constexpr std::size_t N = 1;
124 struct State
125 {{
126 sil::exterior::Form<std::array<double, N>> value {{}};
127{context_members}
128 }};
129
130 KOKKOS_FUNCTION constexpr explicit {class_name}(
131 {constructor_signature})
132 : {constructor_initializers}
133 {{
134 }}
135
136 template <class Elem>
137 [[nodiscard]] KOKKOS_FUNCTION constexpr std::array<double, N * N> value(State const& state, Elem const& elem) const
138 {{
139 static_cast<void>(elem);
140 return {{{render(forward_value_expression)}}};
141 }}
142
143 template <class Elem>
144 [[nodiscard]] KOKKOS_FUNCTION constexpr std::array<double, N * N> jacobian(State const& state, Elem const& elem) const
145 {{
146 return value(state, elem);
147 }}
148
149 template <class Elem>
150 [[nodiscard]] KOKKOS_FUNCTION constexpr sil::exterior::Form<std::array<double, N>> operator()(State const& state, Elem const& elem) const
151 {{
152 static_cast<void>(elem);
153 return {{{render(constitutive_law)}}};
154 }}
155
156 template <class Elem>
157 [[nodiscard]] KOKKOS_FUNCTION constexpr std::array<double, N * N> inverse_value(State const& state, Elem const& elem) const
158 {{
159 static_cast<void>(elem);
160 return {{{render(inverse_value_expression, True)}}};
161 }}
162
163 template <class Elem>
164 [[nodiscard]] KOKKOS_FUNCTION constexpr sil::exterior::Form<std::array<double, N>> inverse(State const& state, Elem const& elem) const
165 {{
166 static_cast<void>(elem);
167 return {{{render(inverse_expression, True)}}};
168 }}
169}};
170
171static_assert(similie::physics::ConstitutiveLawConcept<{class_name}, similie::physics::detail::ElementConcept>);
172
173}} // namespace {namespace}
174"""
175 )
176
177
179 functor_class, output_path: Path, *args, **kwargs
180) -> None:
181 definition = functor_class.__call__(*args, **kwargs)
182 parameter_tuples = [(f"m_{name}", name, True) for name in definition.parameters]
184 output_path=output_path,
185 namespace=definition.namespace,
186 class_name=definition.class_name,
187 parameters=parameter_tuples,
188 variables=definition.variables,
189 output_variable=definition.output_variable,
190 constitutive_law=definition.constitutive_law,
191 )
str _replace_symbols(str expression, dict[str, str] replacements)
None write_cpp_constitutive_law_header(Path output_path, str namespace, str class_name, list[tuple[str, str, bool]] parameters, list[str] variables, str output_variable, constitutive_law)