SimiLie
Loading...
Searching...
No Matches
nonlinear_magnetostatics.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 similie_generate_cpp_hamiltonian import (
9 HamiltonianDefinition,
10 SymbolicFunctionDefinition,
11)
12from sympy import Function, simplify, symbols
13
14INTERPOLATED_BH_CURVE_HEADER = """\
15template <std::size_t MaxSamples>
16struct InterpolatedNonlinearBHCurve
17{
18 static constexpr std::size_t MAX_SAMPLES = MaxSamples;
19
20 std::size_t m_num_samples = 0;
21 std::array<double, MAX_SAMPLES> m_b {};
22 std::array<double, MAX_SAMPLES> m_h {};
23 std::array<double, MAX_SAMPLES> m_q {};
24 std::array<double, MAX_SAMPLES> m_nu {};
25 std::array<double, MAX_SAMPLES> m_energy {};
26 std::array<double, MAX_SAMPLES - 1> m_dnu_dq {};
27
28 template <std::size_t NumSamples>
29 explicit InterpolatedNonlinearBHCurve(
30 std::array<double, NumSamples> const& magnetic_induction_samples,
31 std::array<double, NumSamples> const& magnetic_field_samples,
32 std::size_t num_samples = NumSamples)
33 : m_num_samples(num_samples)
34 {
35 static_assert(NumSamples <= MAX_SAMPLES);
36 if (m_num_samples < 2 || m_num_samples > NumSamples) {
37 throw std::runtime_error("invalid nonlinear B-H curve sample count");
38 }
39
40 for (std::size_t i = 0; i < m_num_samples; ++i) {
41 m_b[i] = magnetic_induction_samples[i];
42 m_h[i] = magnetic_field_samples[i];
43 m_q[i] = m_b[i] * m_b[i];
44 }
45
46 m_nu[0] = m_h[1] / m_b[1];
47 for (std::size_t i = 1; i < m_num_samples; ++i) {
48 m_nu[i] = m_h[i] / m_b[i];
49 }
50 for (std::size_t i = 0; i + 1 < m_num_samples; ++i) {
51 m_dnu_dq[i] = (m_nu[i + 1] - m_nu[i]) / (m_q[i + 1] - m_q[i]);
52 }
53 m_energy[0] = 0.0;
54 for (std::size_t i = 0; i + 1 < m_num_samples; ++i) {
55 double const delta_q = m_q[i + 1] - m_q[i];
56 m_energy[i + 1] = m_energy[i] + 0.5 * m_nu[i] * delta_q
57 + 0.25 * m_dnu_dq[i] * delta_q * delta_q;
58 }
59 }
60
61 [[nodiscard]] KOKKOS_FUNCTION std::size_t bracket_q(double q_value) const
62 {
63 if (q_value <= m_q[0]) {
64 return 0;
65 }
66 for (std::size_t i = 0; i + 1 < m_num_samples; ++i) {
67 if (q_value <= m_q[i + 1]) {
68 return i;
69 }
70 }
71 return m_num_samples - 2;
72 }
73
74 [[nodiscard]] KOKKOS_FUNCTION std::size_t bracket_h(double h_value) const
75 {
76 if (h_value <= m_h[0]) {
77 return 0;
78 }
79 for (std::size_t i = 0; i + 1 < m_num_samples; ++i) {
80 if (h_value <= m_h[i + 1]) {
81 return i;
82 }
83 }
84 return m_num_samples - 2;
85 }
86
87 [[nodiscard]] KOKKOS_FUNCTION double nu_from_q(double q_value) const
88 {
89 std::size_t const interval = bracket_q(q_value);
90 return m_nu[interval] + m_dnu_dq[interval] * (q_value - m_q[interval]);
91 }
92
93 [[nodiscard]] KOKKOS_FUNCTION double dnu_dq(double q_value) const
94 {
95 return m_dnu_dq[bracket_q(q_value)];
96 }
97
98 [[nodiscard]] KOKKOS_FUNCTION double h_from_b(double b_value) const
99 {
100 return nu_from_q(b_value * b_value) * b_value;
101 }
102
103 [[nodiscard]] KOKKOS_FUNCTION double dh_db_from_b(double b_value) const
104 {
105 double const q = b_value * b_value;
106 return nu_from_q(q) + 2.0 * q * dnu_dq(q);
107 }
108
109 [[nodiscard]] KOKKOS_FUNCTION double h_over_b_from_b(double b_value) const
110 {
111 return nu_from_q(b_value * b_value);
112 }
113
114 [[nodiscard]] KOKKOS_FUNCTION double d_h_over_b_db_from_b(double b_value) const
115 {
116 return 2.0 * b_value * dnu_dq(b_value * b_value);
117 }
118
119 [[nodiscard]] KOKKOS_FUNCTION double d2_h_over_b_db2_from_b(double b_value) const
120 {
121 return 2.0 * dnu_dq(b_value * b_value);
122 }
123
124 [[nodiscard]] KOKKOS_FUNCTION double h_over_b_from_q(double q_value) const
125 {
126 return nu_from_q(q_value);
127 }
128
129 [[nodiscard]] KOKKOS_FUNCTION double d_h_over_b_dq_from_q(double q_value) const
130 {
131 return dnu_dq(q_value);
132 }
133
134 [[nodiscard]] KOKKOS_FUNCTION double d2_h_over_b_dq2_from_q(double) const
135 {
136 return 0.0;
137 }
138
139 [[nodiscard]] KOKKOS_FUNCTION double magnetic_energy_from_q(double q_value) const
140 {
141 std::size_t const interval = bracket_q(q_value);
142 double const delta_q = q_value - m_q[interval];
143 return m_energy[interval] + 0.5 * m_nu[interval] * delta_q
144 + 0.25 * m_dnu_dq[interval] * delta_q * delta_q;
145 }
146
147 [[nodiscard]] KOKKOS_FUNCTION double b_from_h(double h_value) const
148 {
149 if (h_value <= m_h[0]) {
150 return m_b[0];
151 }
152 std::size_t const interval = bracket_h(h_value);
153 double lower = m_b[interval];
154 double upper = m_b[interval + 1];
155 // Extend the bracket for the extrapolated final polynomial segment.
156 for (unsigned int i = 0; i < 64 && h_from_b(upper) < h_value; ++i) {
157 upper *= 2.0;
158 }
159 // Inverting H(B) requires solving a cubic on each nu(B^2) segment.
160 for (unsigned int i = 0; i < 64; ++i) {
161 double const middle = lower + 0.5 * (upper - lower);
162 if (h_from_b(middle) < h_value) {
163 lower = middle;
164 } else {
165 upper = middle;
166 }
167 }
168 return lower + 0.5 * (upper - lower);
169 }
170
171 [[nodiscard]] KOKKOS_FUNCTION double db_dh(double h_value) const
172 {
173 return 1.0 / dh_db_from_b(b_from_h(h_value));
174 }
175
176};
177"""
178
179
180CONSTITUTIVE_LAW_HEADER = """\
181struct NonlinearMagneticState
182{
183 sil::exterior::Form<std::array<double, 3>> value {};
184};
185
186template <class BHCurve>
187class NonlinearMagneticInductionToMagneticField
188{
189 BHCurve m_bh_curve;
190
191 [[nodiscard]] KOKKOS_FUNCTION std::array<double, 9> jacobian_from_magnetic_induction(
192 std::span<double const, 3> magnetic_induction) const
193 {
194 double const q = magnetic_induction[0] * magnetic_induction[0]
195 + magnetic_induction[1] * magnetic_induction[1]
196 + magnetic_induction[2] * magnetic_induction[2];
197 double const b_norm = std::sqrt(q);
198 if (b_norm == 0.0) {
199 double const dh_db = m_bh_curve.dh_db_from_b(0.0);
200 return {
201 dh_db,
202 0.0,
203 0.0,
204 0.0,
205 dh_db,
206 0.0,
207 0.0,
208 0.0,
209 dh_db,
210 };
211 }
212 double const h_norm = m_bh_curve.h_from_b(b_norm);
213 double const dh_db = m_bh_curve.dh_db_from_b(b_norm);
214 double const scale = h_norm / b_norm;
215 double const radial_scale = (dh_db - scale) / q;
216 std::array<double, 9> jacobian {};
217 for (std::size_t row = 0; row < 3; ++row) {
218 for (std::size_t column = 0; column < 3; ++column) {
219 jacobian[3 * row + column]
220 = (row == column ? scale : 0.0)
221 + radial_scale * magnetic_induction[row] * magnetic_induction[column];
222 }
223 }
224 return jacobian;
225 }
226
227 [[nodiscard]] KOKKOS_FUNCTION static std::array<double, 9> inverse_matrix3x3(
228 std::array<double, 9> const& matrix)
229 {
230 double const a00 = matrix[0];
231 double const a01 = matrix[1];
232 double const a02 = matrix[2];
233 double const a10 = matrix[3];
234 double const a11 = matrix[4];
235 double const a12 = matrix[5];
236 double const a20 = matrix[6];
237 double const a21 = matrix[7];
238 double const a22 = matrix[8];
239
240 double const c00 = a11 * a22 - a12 * a21;
241 double const c01 = a02 * a21 - a01 * a22;
242 double const c02 = a01 * a12 - a02 * a11;
243 double const c10 = a12 * a20 - a10 * a22;
244 double const c11 = a00 * a22 - a02 * a20;
245 double const c12 = a02 * a10 - a00 * a12;
246 double const c20 = a10 * a21 - a11 * a20;
247 double const c21 = a01 * a20 - a00 * a21;
248 double const c22 = a00 * a11 - a01 * a10;
249
250 double const determinant = a00 * c00 + a01 * c10 + a02 * c20;
251 return {
252 c00 / determinant,
253 c01 / determinant,
254 c02 / determinant,
255 c10 / determinant,
256 c11 / determinant,
257 c12 / determinant,
258 c20 / determinant,
259 c21 / determinant,
260 c22 / determinant,
261 };
262 }
263
264public:
265 static constexpr std::size_t N = 3;
266 using State = NonlinearMagneticState;
267
268 explicit NonlinearMagneticInductionToMagneticField(BHCurve bh_curve) : m_bh_curve(bh_curve) {}
269
270 template <class Elem>
271 [[nodiscard]] KOKKOS_FUNCTION sil::exterior::Form<std::array<double, N>> operator()(State const& state, Elem const& elem) const
272 {
273 static_cast<void>(elem);
274 sil::exterior::Form<std::array<double, N>> const& magnetic_induction = state.value;
275 double const q = magnetic_induction[0] * magnetic_induction[0]
276 + magnetic_induction[1] * magnetic_induction[1]
277 + magnetic_induction[2] * magnetic_induction[2];
278 double const b_norm = std::sqrt(q);
279 if (b_norm == 0.0) {
280 return {0.0, 0.0, 0.0};
281 }
282 double const scale = m_bh_curve.h_from_b(b_norm) / b_norm;
283 return {
284 scale * magnetic_induction[0],
285 scale * magnetic_induction[1],
286 scale * magnetic_induction[2],
287 };
288 }
289
290 template <class Elem>
291 [[nodiscard]] KOKKOS_FUNCTION std::array<double, N * N> value(State const& state, Elem const& elem) const
292 {
293 return jacobian(state, elem);
294 }
295
296 template <class Elem>
297 [[nodiscard]] KOKKOS_FUNCTION sil::exterior::Form<std::array<double, N>> inverse(State const& state, Elem const& elem) const
298 {
299 static_cast<void>(elem);
300 sil::exterior::Form<std::array<double, N>> const& magnetic_field = state.value;
301 double const h_norm = std::sqrt(
302 magnetic_field[0] * magnetic_field[0] + magnetic_field[1] * magnetic_field[1] + magnetic_field[2] * magnetic_field[2]);
303 if (h_norm == 0.0) {
304 return {0.0, 0.0, 0.0};
305 }
306 double const b_norm = m_bh_curve.b_from_h(h_norm);
307 double const scale = b_norm / h_norm;
308 return {scale * magnetic_field[0], scale * magnetic_field[1], scale * magnetic_field[2]};
309 }
310
311 template <class Elem>
312 [[nodiscard]] KOKKOS_FUNCTION std::array<double, N * N> inverse_value(State const& state, Elem const& elem) const
313 {
314 State const inverse_state {inverse(state, elem)};
315 return inverse_matrix3x3(jacobian(inverse_state, elem));
316 }
317
318 template <class Elem>
319 [[nodiscard]] KOKKOS_FUNCTION std::array<double, N * N> jacobian(State const& state, Elem const& elem) const
320 {
321 static_cast<void>(elem);
322 return jacobian_from_magnetic_induction(state.value);
323 }
324};
325
326static_assert(similie::physics::ConstitutiveLawConcept<
327 NonlinearMagneticInductionToMagneticField<InterpolatedNonlinearBHCurve<2>>,
328 similie::physics::detail::ElementConcept>);
329"""
330
331
333 @staticmethod
334 def __call__() -> HamiltonianDefinition:
335 a = symbols("A0:3")
336 b = symbols("B0:3")
337 j = symbols("j0:3")
338 magnetic_energy = Function("magnetic_energy")
339 q = sum(component**2 for component in b)
340 hamiltonian = simplify(magnetic_energy(q)) - sum(a[i] * j[i] for i in range(3))
341
342 return HamiltonianDefinition(
343 namespace="similie::physics::magnetostatics",
344 struct_name="NonlinearMagnetostaticsHamiltonian",
345 parameters=["bh_curve"],
346 hamiltonian=hamiltonian,
347 variables=[a, b, j],
348 template_parameters=["class BHCurve"],
349 parameter_types={"bh_curve": "BHCurve"},
350 symbolic_functions={
351 "magnetic_energy": SymbolicFunctionDefinition(
352 value_expression="m_bh_curve.magnetic_energy_from_q({argument})",
353 derivative_expressions={
354 1: "0.5 * m_bh_curve.h_over_b_from_q({argument})",
355 2: "0.5 * m_bh_curve.d_h_over_b_dq_from_q({argument})",
356 },
357 )
358 },
359 namespace_preamble=INTERPOLATED_BH_CURVE_HEADER,
360 namespace_epilogue=CONSTITUTIVE_LAW_HEADER,
361 )