6"""Explicit Navier-Stokes-Fourier evolution and symbolic thermodynamic closures.
8Independent thermodynamic coordinates are density rho and specific internal
9energy e. A caller supplies p(rho,e) and T(rho,e), not a Hamiltonian. SymPy
10computes local thermodynamic derivatives; exterior supplies spatial derivatives.
13from __future__
import annotations
19from dataclasses
import dataclass
20from pathlib
import Path
22from sympy
import Matrix, Rational, Symbol, diff, simplify, symbols, sympify
23from sympy.printing.codeprinter
import cxxcode
26def _cpp(expression, replacements=None):
27 expression = sympify(expression)
28 return cxxcode(expression.xreplace(replacements
or {}), standard=
"c++17")
32 if not re.fullmatch(
r"[A-Za-z_][A-Za-z_0-9]*", name):
33 raise ValueError(f
"Invalid C++ identifier: {name}")
37 output.parent.mkdir(parents=
True, exist_ok=
True)
38 output.write_text(text)
39 formatter = shutil.which(
"clang-format")
40 if formatter
is not None:
41 subprocess.run([formatter,
"-i", str(output)], check=
True)
44@dataclass(frozen=True)
46 """Caller-supplied caloric closure, with no particular equation of state.
48 cv=1/T_e. cp=(dh/dT)_p is evaluated as a ratio of Jacobians in (rho,e),
49 with h=e+p/rho. c^2=p_rho+p*p_e/rho^2 follows from de=p/rho^2 drho
50 along an isentrope. The closure must describe one smooth phase with an
51 invertible local (p,T) map, positive heat capacities and sound speed.
55 specific_internal_energy: Symbol
58 parameters: tuple[Symbol, ...] = ()
61 if self.
density == self.specific_internal_energy:
62 raise ValueError(
"Thermodynamic state variables must be distinct")
66 "Thermodynamic parameters must be distinct from state variables"
69 if sympify(expression).free_symbols - declared:
70 raise ValueError(
"Undeclared symbols in thermodynamic relation")
73 rho, energy = self.
density, self.specific_internal_energy
75 p_rho, p_e = diff(p, rho), diff(p, energy)
76 t_rho, t_e = diff(temperature, rho), diff(temperature, energy)
77 enthalpy = energy + p / rho
78 jacobian = simplify(t_e * p_rho - t_rho * p_e)
79 if simplify(t_e) == 0
or jacobian == 0:
80 raise ValueError(
"Degenerate thermodynamic closure: cv or cp is undefined")
82 "pressure_density_derivative": p_rho,
83 "pressure_energy_derivative": p_e,
84 "temperature_density_derivative": t_rho,
85 "temperature_energy_derivative": t_e,
86 "heat_capacity_at_constant_volume": simplify(1 / t_e),
87 "heat_capacity_at_constant_pressure": simplify(
88 (diff(enthalpy, energy) * p_rho - diff(enthalpy, rho) * p_e) / jacobian
90 "sound_speed_squared": simplify(p_rho + p * p_e / rho**2),
94 """Exactness residual for ds=de/T-p drho/(T rho^2).
96 Zero is required for thermodynamic consistency. It is exposed rather
97 than forcing SymPy to decide identities for every user-defined function.
99 rho, energy = self.
density, self.specific_internal_energy
108 Matrix(density_gradient) * derivatives[
"temperature_density_derivative"]
109 + Matrix(energy_gradient) * derivatives[
"temperature_energy_derivative"]
113 """Generate a local, device-callable closure with analytic derivatives."""
115 for name
in namespace.split(
"::"):
120 self.
density: Symbol(
"density"),
121 self.specific_internal_energy: Symbol(
"specific_internal_energy"),
129 str(parameter)
in {
"density",
"specific_internal_energy", *methods}
133 "Thermodynamic parameter collides with a generated C++ method or argument"
138 constructor = f
" KOKKOS_FUNCTION explicit {class_name}({arguments})"
140 constructor += f
" : {initializers}"
143 for name, expression
in methods.items():
144 code =
_cpp(expression, replacements)
145 result_type =
"double"
146 if name
in {
"pressure",
"temperature",
"sound_speed_squared"}:
147 result_type =
"Scalar"
148 code = f
"Scalar({code})"
150 f
" KOKKOS_FUNCTION {result_type} {name}(Scalar const& density, Scalar const& specific_internal_energy) const\n"
151 f
" {{ return {code}; }}"
153 functions =
"\n".join(functions)
154 output = Path(output_path)
155 output.parent.mkdir(parents=
True, exist_ok=
True)
158 f
"""// SPDX-FileCopyrightText: 2026 Baptiste Legouix
159// SPDX-License-Identifier: AGPL-3.0-or-later
161// Generated from caller-supplied SymPy thermodynamics. Do not edit.
164#include <similie/exterior/form.hpp>
165#include <Kokkos_Core.hpp>
166namespace {namespace} {{
167/** Thermodynamics in (rho,e), including analytic cv, cp, and isentropic c^2.
168 * cp is a Jacobian ratio at fixed pressure; no ideal-gas identity is assumed.
169 * \\important This operator and documentation is fully AI-generated.
173 using Scalar = sil::exterior::Form<double>;
178}} // namespace {namespace}
184 """Symbolic mass, momentum, total-energy fluxes and explicit time rates.
186 Newtonian stress uses Stokes' zero bulk-viscosity assumption in 3D;
187 Fourier conductivity is mu*cp/Pr. No thermodynamic law is fixed here.
210 symbols(
"div_mass div_m0 div_m1 div_m2 div_energy")
214 def fluxes(self, thermodynamics=None, stress=None, heat_flux=None):
216 if thermodynamics
is not None:
218 thermodynamics.density: self.
density,
221 p = sympify(thermodynamics.pressure).xreplace(replacement)
222 cp = thermodynamics.derivatives()[
223 "heat_capacity_at_constant_pressure"
224 ].xreplace(replacement)
225 tau = self.
stress if stress
is None else stress
226 q = self.
heat_flux.subs(self.
cp, cp)
if heat_flux
is None else heat_flux
227 flux = Matrix.zeros(5, 3)
228 for normal
in range(3):
229 flux[0, normal] = self.
momentum[normal]
230 for axis
in range(3):
231 flux[axis + 1, normal] = (
233 + (p
if axis == normal
else 0)
238 - sum(tau[axis, normal] * self.
velocity[axis]
for axis
in range(3))
244 """Generate generic C++ physics, templated on caller thermodynamics."""
246 self.
density: Symbol(
"state.density"),
249 self.
pressure: Symbol(
"primitive.pressure"),
250 **{m: Symbol(f
"state.momentum[{a}]")
for a, m
in enumerate(self.
momentum)},
257 stress_code =
"\n".join(
258 f
" result[{a}][{b}] = {_cpp(self.stress[a, b], replacements)};"
262 tau = Matrix(3, 3,
lambda a, b: Symbol(f
"tau[{a}][{b}]"))
263 q = Matrix([Symbol(f
"q[{a}]")
for a
in range(3)])
264 fluxes = self.
fluxes(stress=tau, heat_flux=q)
266 for normal
in range(3):
267 flux_code.append(f
" if (normal == {normal}) {{")
269 f
" result.mass = {_cpp(fluxes[0, normal], replacements)};"
273 f
" result.momentum[{a}] = {_cpp(fluxes[a + 1, normal], replacements)};"
276 f
" result.total_energy = {_cpp(fluxes[4, normal], replacements)};"
278 flux_code.append(
" }")
280 output = Path(output_path)
281 output.parent.mkdir(parents=
True, exist_ok=
True)
285 energy=energy_code, stress=stress_code, flux=
"\n".join(flux_code)
290_CPP_HEADER =
"""// SPDX-FileCopyrightText: 2026 Baptiste Legouix
291// SPDX-License-Identifier: AGPL-3.0-or-later
293// Generated by fluid/navier_stokes_fourier.py. Do not edit.
297#include <similie/exterior/form.hpp>
298#include <Kokkos_Core.hpp>
299#include <similie/exterior/form.hpp>
300#include <similie/physics/concepts.hpp>
301namespace similie::physics::fluid {{
302/** Explicit mass, momentum, and energy conservation with Newtonian/Fourier fluxes.
303 * dt rho=-div(rho u), dt(rho u)=-div(rho u tensor u+p I-tau),
304 * dt(rho E)=-div((rho E+p)u-tau.u+q), q=-mu cp/Pr grad T.
305 * Thermodynamics supplies p(rho,e), T(rho,e), cv, cp and isentropic c^2.
306 * Spatial derivatives are supplied by exterior; no optimizer or Hamiltonian.
307 * \\important This operator and documentation is fully AI-generated.
309template<class Thermodynamics>
310class NavierStokesFourier {{
312 using Scalar = sil::exterior::Form<double>;
313 static constexpr std::size_t N = 5;
314 static constexpr bool IS_LINEAR = false;
315 struct State {{ Scalar density; sil::exterior::Form<std::array<double,3>> momentum; Scalar total_energy; }};
316 struct PrimitiveVariables {{ Scalar density; sil::exterior::Form<std::array<double,3>> velocity; Scalar pressure; Scalar temperature; }};
317 struct Flux {{ Scalar mass; sil::exterior::Form<std::array<double,3>> momentum; Scalar total_energy; }};
318 using VelocityGradient=std::array<std::array<double,3>,3>;
319 Thermodynamics const thermodynamics;
320 double const prandtl, viscosity;
321 KOKKOS_FUNCTION explicit NavierStokesFourier(Thermodynamics closure, double prandtl_number,
322 double dynamic_viscosity)
323 : thermodynamics(closure), prandtl(prandtl_number), viscosity(dynamic_viscosity)
325 // Check the complete type; a class-scope self-check recursively enters
326 // PhysicsConcept when this model is first used as a constrained argument.
327 static_assert(PhysicsConcept<NavierStokesFourier>);
329 KOKKOS_FUNCTION Scalar specific_internal_energy(State const& state) const
330 {{ return Scalar({energy}); }}
331 KOKKOS_FUNCTION Scalar pressure(State const& state) const
332 {{ return Scalar(thermodynamics.pressure(state.density,specific_internal_energy(state))); }}
333 KOKKOS_FUNCTION PrimitiveVariables primitives(State const& state) const
335 Scalar const e=specific_internal_energy(state);
336 PrimitiveVariables result{{state.density,{{}},Scalar(thermodynamics.pressure(state.density,e)),Scalar(thermodynamics.temperature(state.density,e))}};
337 for(int a=0;a<3;++a) result.velocity[a]=state.momentum[a]/state.density;
340 KOKKOS_FUNCTION double heat_capacity_at_constant_volume(State const& state) const
341 {{ return thermodynamics.heat_capacity_at_constant_volume(state.density,specific_internal_energy(state)); }}
342 KOKKOS_FUNCTION double heat_capacity_at_constant_pressure(State const& state) const
343 {{ return thermodynamics.heat_capacity_at_constant_pressure(state.density,specific_internal_energy(state)); }}
344 KOKKOS_FUNCTION Scalar sound_speed_squared(State const& state) const
345 {{ return Scalar(thermodynamics.sound_speed_squared(state.density,specific_internal_energy(state))); }}
346 KOKKOS_FUNCTION double conductivity(State const& state) const
347 {{ return viscosity*heat_capacity_at_constant_pressure(state)/prandtl; }}
348 KOKKOS_FUNCTION sil::exterior::Form<std::array<double,3>> temperature_gradient(State const& state,
349 sil::exterior::Form<std::array<double,3>> const& density_gradient, sil::exterior::Form<std::array<double,3>> const& energy_gradient) const
351 Scalar const e=specific_internal_energy(state);
352 double const dr=thermodynamics.temperature_density_derivative(state.density,e);
353 double const de=thermodynamics.temperature_energy_derivative(state.density,e);
354 sil::exterior::Form<std::array<double,3>> result{{}};
355 for(int a=0;a<3;++a) result[a]=dr*density_gradient[a]+de*energy_gradient[a];
358 KOKKOS_FUNCTION VelocityGradient stress(VelocityGradient const& gradient) const
360 VelocityGradient result{{}};
364 KOKKOS_FUNCTION sil::exterior::Form<std::array<double,3>> heat_flux(State const& state,
365 sil::exterior::Form<std::array<double,3>> const& temperature_gradient) const
367 double const kappa=conductivity(state);
368 sil::exterior::Form<std::array<double,3>> result{{}};
369 for(int a=0;a<3;++a) result[a]=-kappa*temperature_gradient[a];
372 KOKKOS_FUNCTION Flux flux(State const& state, PrimitiveVariables const& primitive,
373 VelocityGradient const& velocity_gradient, sil::exterior::Form<std::array<double,3>> const& temperature_gradient,
376 VelocityGradient const tau=stress(velocity_gradient);
377 sil::exterior::Form<std::array<double,3>> const q=heat_flux(state,temperature_gradient);
382 /** Symmetric two-point kinetic-energy-preserving transport.
383 * Face gradients come from reduction/reconstruction of exterior derivatives.
384 * This centered flux is consistent but does not enforce positivity.
386 KOKKOS_FUNCTION Flux two_point_flux(State const& left, State const& right,
387 VelocityGradient const& face_velocity_gradient,
388 sil::exterior::Form<std::array<double,3>> const& face_temperature_gradient, int normal) const
390 KOKKOS_ASSERT(normal>=0 && normal<3);
391 PrimitiveVariables const l=primitives(left), r=primitives(right);
392 double const mass=0.25*(l.density+r.density)*(l.velocity[normal]+r.velocity[normal]);
393 double const pressure=0.5*(l.pressure+r.pressure);
394 double const internal=0.5*(specific_internal_energy(left)+specific_internal_energy(right));
395 double kinetic=0, work=0;
396 VelocityGradient const tau=stress(face_velocity_gradient);
397 sil::exterior::Form<std::array<double,3>> const ql=heat_flux(left,face_temperature_gradient),
398 qr=heat_flux(right,face_temperature_gradient);
399 Flux result{{Scalar(mass),{{}},Scalar(0)}};
400 for(int a=0;a<3;++a) {{
401 kinetic+=0.5*l.velocity[a]*r.velocity[a];
402 work+=tau[a][normal]*0.5*(l.velocity[a]+r.velocity[a]);
403 result.momentum[a]=mass*0.5*(l.velocity[a]+r.velocity[a])
404 +(a==normal?pressure:0)-tau[a][normal];
406 result.total_energy=mass*(internal+kinetic)
407 +0.5*pressure*(l.velocity[normal]+r.velocity[normal])-work
408 +0.5*(ql[normal]+qr[normal]);
411 KOKKOS_FUNCTION State operator()(Flux const& divergence) const
413 return {{Scalar(-divergence.mass),{{-divergence.momentum[0],-divergence.momentum[1],-divergence.momentum[2]}},Scalar(-divergence.total_energy)}};
416}} // namespace similie::physics::fluid
419if __name__ ==
"__main__":
420 parser = argparse.ArgumentParser(description=__doc__)
421 parser.add_argument(
"--output", required=
True, type=Path)
tuple specific_internal_energy
generate_cpp(self, output_path)
fluxes(self, thermodynamics=None, stress=None, heat_flux=None)
temperature_gradient(self, density_gradient, energy_gradient)
integrability_residual(self)
generate_cpp(self, output_path, namespace, class_name)
_cpp(expression, replacements=None)
_write_header(output, text)