SimiLie
Loading...
Searching...
No Matches
navier_stokes_fourier.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
6"""Explicit Navier-Stokes-Fourier evolution and symbolic thermodynamic closures.
7
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.
11"""
12
13from __future__ import annotations
14
15import argparse
16import re
17import shutil
18import subprocess
19from dataclasses import dataclass
20from pathlib import Path
21
22from sympy import Matrix, Rational, Symbol, diff, simplify, symbols, sympify
23from sympy.printing.codeprinter import cxxcode
24
25
26def _cpp(expression, replacements=None):
27 expression = sympify(expression)
28 return cxxcode(expression.xreplace(replacements or {}), standard="c++17")
29
30
31def _identifier(name):
32 if not re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", name):
33 raise ValueError(f"Invalid C++ identifier: {name}")
34
35
36def _write_header(output, text):
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)
42
43
44@dataclass(frozen=True)
46 """Caller-supplied caloric closure, with no particular equation of state.
47
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.
52 """
53
54 density: Symbol
55 specific_internal_energy: Symbol
56 pressure: object
57 temperature: object
58 parameters: tuple[Symbol, ...] = ()
59
60 def __post_init__(self):
61 if self.density == self.specific_internal_energy:
62 raise ValueError("Thermodynamic state variables must be distinct")
63 declared = {self.density, self.specific_internal_energy, *self.parametersparameters}
64 if len(declared) != 2 + len(self.parametersparameters):
65 raise ValueError(
66 "Thermodynamic parameters must be distinct from state variables"
67 )
68 for expression in (self.pressure, self.temperature):
69 if sympify(expression).free_symbols - declared:
70 raise ValueError("Undeclared symbols in thermodynamic relation")
71
72 def derivatives(self):
73 rho, energy = self.density, self.specific_internal_energy
74 p, temperature = sympify(self.pressure), sympify(self.temperature)
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")
81 return {
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
89 ),
90 "sound_speed_squared": simplify(p_rho + p * p_e / rho**2),
91 }
92
94 """Exactness residual for ds=de/T-p drho/(T rho^2).
95
96 Zero is required for thermodynamic consistency. It is exposed rather
97 than forcing SymPy to decide identities for every user-defined function.
98 """
99 rho, energy = self.density, self.specific_internal_energy
100 return simplify(
101 diff(1 / self.temperature, rho)
102 - diff(-self.pressure / (self.temperature * rho**2), energy)
103 )
104
105 def temperature_gradient(self, density_gradient, energy_gradient):
106 derivatives = self.derivatives()
107 return (
108 Matrix(density_gradient) * derivatives["temperature_density_derivative"]
109 + Matrix(energy_gradient) * derivatives["temperature_energy_derivative"]
110 )
111
112 def generate_cpp(self, output_path, namespace, class_name):
113 """Generate a local, device-callable closure with analytic derivatives."""
114 _identifier(class_name)
115 for name in namespace.split("::"):
116 _identifier(name)
117 for parameter in self.parametersparameters:
118 _identifier(str(parameter))
119 replacements = {
120 self.density: Symbol("density"),
121 self.specific_internal_energy: Symbol("specific_internal_energy"),
122 }
123 methods = {
124 "pressure": self.pressure,
125 "temperature": self.temperature,
126 **self.derivatives(),
127 }
128 if any(
129 str(parameter) in {"density", "specific_internal_energy", *methods}
130 for parameter in self.parametersparameters
131 ):
132 raise ValueError(
133 "Thermodynamic parameter collides with a generated C++ method or argument"
134 )
135 members = "\n".join(f" double const {p};" for p in self.parametersparameters)
136 arguments = ", ".join(f"double {p}_" for p in self.parametersparameters)
137 initializers = ", ".join(f"{p}({p}_)" for p in self.parametersparameters)
138 constructor = f" KOKKOS_FUNCTION explicit {class_name}({arguments})"
139 if initializers:
140 constructor += f" : {initializers}"
141 constructor += " {}"
142 functions = []
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})"
149 functions.append(
150 f" KOKKOS_FUNCTION {result_type} {name}(Scalar const& density, Scalar const& specific_internal_energy) const\n"
151 f" {{ return {code}; }}"
152 )
153 functions = "\n".join(functions)
154 output = Path(output_path)
155 output.parent.mkdir(parents=True, exist_ok=True)
157 output,
158 f"""// SPDX-FileCopyrightText: 2026 Baptiste Legouix
159// SPDX-License-Identifier: AGPL-3.0-or-later
160// AI-GENERATED
161// Generated from caller-supplied SymPy thermodynamics. Do not edit.
162#pragma once
163#include <cmath>
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.
170 */
171class {class_name} {{
172public:
173 using Scalar = sil::exterior::Form<double>;
174{members}
175{constructor}
176{functions}
177}};
178}} // namespace {namespace}
179""",
180 )
181
182
184 """Symbolic mass, momentum, total-energy fluxes and explicit time rates.
185
186 Newtonian stress uses Stokes' zero bulk-viscosity assumption in 3D;
187 Fourier conductivity is mu*cp/Pr. No thermodynamic law is fixed here.
188 """
189
190 def __init__(self):
191 self.density = Symbol("rho", positive=True)
192 self.momentum = Matrix(symbols("m0:3"))
193 self.total_energy = Symbol("rho_E")
194 self.velocity = self.momentum / self.density
196 self.total_energy - self.momentum.dot(self.momentum) / (2 * self.density)
197 ) / self.density
198 self.viscosity, self.prandtl, self.cp, self.pressure = symbols("mu Pr cp p")
199 self.velocity_gradient = Matrix(3, 3, lambda a, b: Symbol(f"g{a}{b}"))
200 self.temperature_gradient = Matrix(symbols("dT0:3"))
201 self.stress = self.viscosity * (
203 + self.velocity_gradient.T
204 - Rational(2, 3) * self.velocity_gradient.trace() * Matrix.eye(3)
205 )
206 self.heat_flux = (
207 -self.viscosity * self.cp / self.prandtl * self.temperature_gradient
208 )
209 self.flux_divergence = Matrix(
210 symbols("div_mass div_m0 div_m1 div_m2 div_energy")
211 )
213
214 def fluxes(self, thermodynamics=None, stress=None, heat_flux=None):
215 p, cp = self.pressure, self.cp
216 if thermodynamics is not None:
217 replacement = {
218 thermodynamics.density: self.density,
219 thermodynamics.specific_internal_energy: self.specific_internal_energy,
220 }
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] = (
232 self.momentum[axis] * self.velocity[normal]
233 + (p if axis == normal else 0)
234 - tau[axis, normal]
235 )
236 flux[4, normal] = (
237 (self.total_energy + p) * self.velocity[normal]
238 - sum(tau[axis, normal] * self.velocity[axis] for axis in range(3))
239 + q[normal]
240 )
241 return flux
242
243 def generate_cpp(self, output_path):
244 """Generate generic C++ physics, templated on caller thermodynamics."""
245 replacements = {
246 self.density: Symbol("state.density"),
247 self.total_energy: Symbol("state.total_energy"),
248 self.viscosity: Symbol("viscosity"),
249 self.pressure: Symbol("primitive.pressure"),
250 **{m: Symbol(f"state.momentum[{a}]") for a, m in enumerate(self.momentum)},
251 **{
252 self.velocity_gradient[a, b]: Symbol(f"gradient[{a}][{b}]")
253 for a in range(3)
254 for b in range(3)
255 },
256 }
257 stress_code = "\n".join(
258 f" result[{a}][{b}] = {_cpp(self.stress[a, b], replacements)};"
259 for a in range(3)
260 for b in range(3)
261 )
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)
265 flux_code = []
266 for normal in range(3):
267 flux_code.append(f" if (normal == {normal}) {{")
268 flux_code.append(
269 f" result.mass = {_cpp(fluxes[0, normal], replacements)};"
270 )
271 for a in range(3):
272 flux_code.append(
273 f" result.momentum[{a}] = {_cpp(fluxes[a + 1, normal], replacements)};"
274 )
275 flux_code.append(
276 f" result.total_energy = {_cpp(fluxes[4, normal], replacements)};"
277 )
278 flux_code.append(" }")
279 energy_code = _cpp(self.specific_internal_energy, replacements)
280 output = Path(output_path)
281 output.parent.mkdir(parents=True, exist_ok=True)
283 output,
284 _CPP_HEADER.format(
285 energy=energy_code, stress=stress_code, flux="\n".join(flux_code)
286 ),
287 )
288
289
290_CPP_HEADER = """// SPDX-FileCopyrightText: 2026 Baptiste Legouix
291// SPDX-License-Identifier: AGPL-3.0-or-later
292// AI-GENERATED
293// Generated by fluid/navier_stokes_fourier.py. Do not edit.
294#pragma once
295#include <array>
296#include <cmath>
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.
308 */
309template<class Thermodynamics>
310class NavierStokesFourier {{
311public:
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)
324 {{
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>);
328 }}
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
334 {{
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;
338 return result;
339 }}
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
350 {{
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];
356 return result;
357 }}
358 KOKKOS_FUNCTION VelocityGradient stress(VelocityGradient const& gradient) const
359 {{
360 VelocityGradient result{{}};
361{stress}
362 return result;
363 }}
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
366 {{
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];
370 return result;
371 }}
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,
374 int normal) const
375 {{
376 VelocityGradient const tau=stress(velocity_gradient);
377 sil::exterior::Form<std::array<double,3>> const q=heat_flux(state,temperature_gradient);
378 Flux result{{}};
379{flux}
380 return result;
381 }}
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.
385 */
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
389 {{
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];
405 }}
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]);
409 return result;
410 }}
411 KOKKOS_FUNCTION State operator()(Flux const& divergence) const
412 {{
413 return {{Scalar(-divergence.mass),{{-divergence.momentum[0],-divergence.momentum[1],-divergence.momentum[2]}},Scalar(-divergence.total_energy)}};
414 }}
415}};
416}} // namespace similie::physics::fluid
417"""
418
419if __name__ == "__main__":
420 parser = argparse.ArgumentParser(description=__doc__)
421 parser.add_argument("--output", required=True, type=Path)
422 NavierStokesFourier().generate_cpp(parser.parse_args().output)
fluxes(self, thermodynamics=None, stress=None, heat_flux=None)
temperature_gradient(self, density_gradient, energy_gradient)
generate_cpp(self, output_path, namespace, class_name)
_cpp(expression, replacements=None)