Skip to content
Open
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ The user-visible changes of canoP, by version (see `CONTRIBUTING.md` for the ver

## Unreleased

- New model `porousflow`: compressible flow in a porous medium of variable porosity, port of the model
PorousFluid of canoP 2.x (branch 38-correct-diffusion-flux-discretization-SEL). All-regime flux on
the superficial velocity with the Darcy-Forchheimer drag in the interface velocity and three low Mach
corrections; Darcy-Forchheimer drag as a relaxation solved exactly after the time step, or as a
source at each stage as in canoP 2.x; gravity, viscous and thermal fluxes; initial and boundary
conditions of a porous block in a channel, Beavers-Joseph, a porous backward facing step, a porous
plug and a porous cylinder; four examples. Its hyperbolic flux and sources match canoP 2.x to
1e-14 on porous shock tubes; its diffusion fluxes use the compact gradients of canoP. A Riemann
solver may take the cell size `h` (`riemann(qL, qR, uL, uR, p, h, dim, GL, GR)`), a relaxation the
time step `dt` (`relaxation(w, qn, p, dt, dim)`: relaxation of finite rate).

- canoP studio with VS Code Remote-SSH, where code-server is not allowed: the user guide describes the
installation, the canoP icon and Claude Code (proxy of the Claude API); `open_studio` of the MCP
bridge recognises a Remote-SSH window and points to the canoP icon or the Ports panel of VS Code
Expand Down
4 changes: 3 additions & 1 deletion Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ and compiled for the CPU or the GPU at run time.
- **twophase5eq**: five-equation model of two phases in mechanical equilibrium
([Padioleau 2021](https://theses.hal.science/tel-03130146));
- **twophase7eq**: seven-equation Baer-Nunziato model with pressure and velocity relaxations
([Chen 2019](https://www.theses.fr/2019AIXM0380)).
([Chen 2019](https://www.theses.fr/2019AIXM0380));
- **porousflow**: compressible flow in a porous medium of variable porosity, with the
Darcy-Forchheimer drag of a Kozeny-Carman permeability.

HLL, HLLC and all-regime fluxes with non-conservative products, MUSCL reconstruction with scalar
limiters, forward Euler or SSP Runge-Kutta 2, viscous and thermal fluxes, gravity, block-based AMR
Expand Down
4 changes: 3 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ Models:
- **twophase5eq**: five-equation homogeneous model of two phases in mechanical equilibrium
([Padioleau 2021](https://theses.hal.science/tel-03130146));
- **twophase7eq**: seven-equation Baer-Nunziato model with pressure and velocity relaxations
([Chen 2019](https://www.theses.fr/2019AIXM0380)).
([Chen 2019](https://www.theses.fr/2019AIXM0380));
- **porousflow**: compressible flow in a porous medium of variable porosity, with the
Darcy-Forchheimer drag of a Kozeny-Carman permeability.

Numerics: HLL, HLLC and all-regime fluxes with non-conservative products, MUSCL reconstruction with
scalar limiters, forward Euler or SSP Runge-Kutta 2, viscous and thermal fluxes, gravity, block-based
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ build in `_build`, a Cuda build for an A100 in `_build_cuda_ampere80`, so that s
keeps both builds.

**Dimension** chooses the executable, `canoP_2d` or `canoP_3d`; a build compiles the one chosen. The
model (`onephase`, `twophase5eq`, `twophase7eq`) is not chosen here but in the input file
model (`onephase`, `twophase5eq`, `twophase7eq`, `porousflow`) is not chosen here but in the input file
(`simulation.model`): the physics is written in Python and compiled at run time, so a new model,
initial condition or flux needs no new build of canoP.

Expand Down
19 changes: 18 additions & 1 deletion docs/user-guide/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

# Models

The three models share the finite volume solver of canoP; each one is a directory of `physics/`. The
The four models share the finite volume solver of canoP; each one is a directory of `physics/`. The
{doc}`../physics-guide/reference` gives, for each model, its variables, its parameters and every value
of its options with the parameters it reads.

Expand Down Expand Up @@ -40,6 +40,23 @@ Seven-equation Baer-Nunziato model: each phase has its velocity, pressure and en
`velocity_relaxation`, `pressure_velocity_relaxation`);
- viscous and thermal fluxes, gravity.

## porousflow

Compressible flow of a fluid in a porous medium of porosity `eps(x)`, fixed in time: the equations of
onephase for the fluid in the pores, weighted by the porosity, with the pressure term `eps grad P` as
a non-conservative product, and the Darcy-Forchheimer drag of the Kozeny-Carman permeability
`k = eps^3 / ((1 - eps)^2 rp_2C)`. Port of the model PorousFluid of canoP 2.x.

- conservative variables: mass, energy and momentum per unit volume of the medium `em`, `emE`,
`emV_x`, `emV_y` (`emV_z`), porosity `eps`;
- flux: all-regime on the superficial velocity `eps V`, with the Darcy-Forchheimer drag in the
interface velocity (`darcy_correction_enabled`) and low Mach corrections;
- Darcy-Forchheimer drag: relaxation `darcy`, solved exactly after the time step (first order in
time where it acts, exact for any stiffness), or source `darcy`, at each stage as in canoP 2.x;
- source gravity; viscous and thermal fluxes times the porosity;
- examples: a porous block in a channel, the Beavers-Joseph flow over a porous layer, a backward
facing step whose step is porous, and a shock tube into a porous medium.

## Common numerics

- MUSCL reconstruction of the primitive variables with the limiters minmod, maxmod, mc, smart,
Expand Down
34 changes: 25 additions & 9 deletions physics/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,16 @@ def option_path(model, category, name):
return os.path.join(MODELS_DIR, model, category, name + ".py")


def function_arguments(path, name):
"""Return the names of the arguments of the function name of a file, [] when it is not defined."""
with open(path, encoding="utf-8") as f:
text = f.read()
for node in ast.parse(text, filename=path).body:
if isinstance(node, ast.FunctionDef) and node.name == name:
return [a.arg for a in node.args.args]
return []


# =============================================================================
# Views
# =============================================================================
Expand Down Expand Up @@ -584,11 +594,14 @@ def _kernels(self, initial, boundary):
k: ["bp%d: BCParameters_%s = bc_parameters_%s(bpar)" % (k, n, n),
"kind = wall_kind_bc_%s(face, x, y, z, h, bp%d, dim)" % (n, k)]
for k, n in enumerate(o["boundary_conditions"])}) + ["return kind"])
# The size h of the cells is given to the Riemann solvers that take it (argument h)
def riemann_call(n):
h = "h, " if "h" in function_arguments(option_path(m, "hyperbolic_fluxes", n), "riemann") else ""
return "riemann_hyp_%s(qL, qR, uL, uR, p, %sdim, GL, GR)" % (n, h)
riemann = _function(
"riemann(hyperbolic: int, qL: Prim, qR: Prim, uL: Cons, uR: Cons, p: Params, dim: int, GL: Cons, "
"GR: Cons) -> None",
_switch("hyperbolic", {k + 1: ["riemann_hyp_%s(qL, qR, uL, uR, p, dim, GL, GR)" % n]
for k, n in enumerate(o["hyperbolic_fluxes"])}))
"riemann(hyperbolic: int, qL: Prim, qR: Prim, uL: Cons, uR: Cons, p: Params, h: float, dim: int, "
"GL: Cons, GR: Cons) -> None",
_switch("hyperbolic", {k + 1: [riemann_call(n)] for k, n in enumerate(o["hyperbolic_fluxes"])}))
diffusion_flux = _function(
"diffusion_flux(diffusion: int, p: Params, %s, dim: int, F: Cons) -> None" % _GRADIENTS,
_switch("diffusion", {k + 1: ["diffusion_flux_diff_%s(p, %s, dim, F)" % (n, _GRADIENT_NAMES)]
Expand All @@ -607,11 +620,14 @@ def _kernels(self, initial, boundary):
sources = _function(
"sources(source: int, w: Cons, q: Prim, p: Params, dt: float, dim: int) -> None",
_switch("source", {k + 1: ["source_src_%s(w, q, p, dt, dim)" % n] for k, n in enumerate(o["sources"])}))
# The time step is given to the relaxations that take it (argument dt): finite rate relaxations
def relaxation_call(n):
dt = "dt, " if "dt" in function_arguments(option_path(m, "relaxations", n), "relaxation") else ""
return "relaxation_relax_%s(w, qn, p, %sdim)" % (n, dt)
relaxations = _function(
"relaxations(relaxation: int, w: Cons, p: Params, dim: int) -> None",
"relaxations(relaxation: int, w: Cons, p: Params, dt: float, dim: int) -> None",
["qn: Prim = cons_to_prim(w, p, dim)"]
+ _switch("relaxation", {k + 1: ["relaxation_relax_%s(w, qn, p, dim)" % n]
for k, n in enumerate(o["relaxations"])}))
+ _switch("relaxation", {k + 1: [relaxation_call(n)] for k, n in enumerate(o["relaxations"])}))
indicator = _function(
"indicator(criterion: int, Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, "
"ib: int, dim: int) -> float",
Expand Down Expand Up @@ -731,10 +747,10 @@ def sources(self, Uin, Uout, num_owned, dt):
ncells=self.ncells, dim=self.dim, dt=dt, source=self.source)

def relaxations(self, Uold, Unew, num_owned, dt):
"""Apply the instantaneous relaxation to Unew in the owned octants, after the time step."""
"""Apply the relaxation to Unew in the owned octants, after the time step dt."""
if self.relaxation != 0 and num_owned > 0:
run(num_owned * self.ncells, self.K["relaxations_kernel"], Unew=view(Unew), par=self.par,
ncells=self.ncells, dim=self.dim, relaxation=self.relaxation)
ncells=self.ncells, dim=self.dim, dt=dt, relaxation=self.relaxation)

def refine_flags(self, Ug, Qg, flags, num_owned, level_min, level_max):
"""Compute the refinement flags of the owned octants: -1 coarsen, 0 keep, 1 refine.
Expand Down
8 changes: 4 additions & 4 deletions physics/loops.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,14 +155,14 @@ def sources_kernel(i: int, Uin: pk.View3D[pk.double], Uout: pk.View3D[pk.double]

@pk.workunit
def relaxations_kernel(i: int, Unew: pk.View3D[pk.double], par: pk.View1D[pk.double], ncells: int, dim: int,
relaxation: int) -> None:
"""Apply the instantaneous relaxation to the cell i of Unew, after the time step."""
dt: float, relaxation: int) -> None:
"""Apply the relaxation to the cell i of Unew, after the time step dt."""
iOct: int = i // ncells
ic: int = i % ncells
mp: ModelParameters = model_parameters(par)
p: Params = make_params(mp)
w: Cons = load_cons(Unew, iOct, ic, dim)
relaxations(relaxation, w, p, dim)
relaxations(relaxation, w, p, dt, dim)
store_cons(Unew, iOct, ic, dim, w)


Expand Down Expand Up @@ -402,7 +402,7 @@ def fluxes_kernel(i: int, Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], Sx
rotate_cons(uR, dr)
GL: Cons = zero_cons()
GR: Cons = zero_cons()
riemann(hyperbolic, qL, qR, uL, uR, p, dim, GL, GR)
riemann(hyperbolic, qL, qR, uL, uR, p, h, dim, GL, GR)

if diffusion != 0:
# State and gradients rotated: components, then directions (g0 along the normal)
Expand Down
13 changes: 7 additions & 6 deletions physics/onephase/hyperbolic_fluxes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@

A hyperbolic flux file defines:

- ``riemann(qL, qR, uL, uR, p, dim, GL, GR)``: adds to ``GL`` and ``GR`` (zero at the call) the
numerical flux of a face seen by its left and right cells. The states are rotated so that the
normal of the face is x: ``qL`` and ``qR`` are the reconstructed primitive face states (with the
wall treatment at the faces of the domain), ``uL`` and ``uR`` the conservative states of the two
cells, loaded only for a model with non-conservative products (``variables`` of ``__init__.py``).
A conservative model fills ``GL`` only.
- ``riemann(qL, qR, uL, uR, p, dim, GL, GR)``, or ``riemann(qL, qR, uL, uR, p, h, dim, GL, GR)``
when it needs the size ``h`` of the cells of the face: adds to ``GL`` and ``GR`` (zero at the
call) the numerical flux of a face seen by its left and right cells. The states are rotated so
that the normal of the face is x: ``qL`` and ``qR`` are the reconstructed primitive face states
(with the wall treatment at the faces of the domain), ``uL`` and ``uR`` the conservative states of
the two cells, loaded only for a model with non-conservative products (``variables`` of
``__init__.py``). A conservative model fills ``GL`` only.

The kernel rotates the fluxes back and multiplies them by ``dt / h``. The stable time step of the
hyperbolic fluxes is ``hyperbolic_inv_dt`` of ``model.py``.
Expand Down
13 changes: 9 additions & 4 deletions physics/onephase/relaxations/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# SPDX-FileCopyrightText: 2025 canoP authors
#
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Instantaneous relaxations: one file per value of ``physics.relaxation`` (or ``none``).
"""Relaxations: one file per value of ``physics.relaxation`` (or ``none``).

A relaxation file defines:
A relaxation file defines one of:

- ``relaxation(w, qn, p, dim)``: replaces the conservative state ``w`` of a cell by its projection
on the equilibrium, ``qn`` being the primitive state of ``w``. It applies once per time step,
after the time integration.
on the equilibrium (instantaneous relaxation), ``qn`` being the primitive state of ``w``;
- ``relaxation(w, qn, p, dt, dim)``: integrates over the time step ``dt`` a relaxation of finite
rate (a stiff source of the cell, solved exactly).

It applies once per time step, after the time integration: a relaxation of finite rate is split
from the other terms, at first order in time where it acts (the other terms keep the order of
``simulation.time_order``).
"""
105 changes: 105 additions & 0 deletions physics/porousflow/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# SPDX-FileCopyrightText: 2026 canoP authors
#
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Model porousflow: compressible flow of a fluid in a porous medium of porosity eps(x).

Equations, for the porosity eps (fixed in time), the density m, the velocity V (intrinsic: that of
the fluid in the pores), the pressure P, the specific total energy E and the gravity g::

d_t (eps m) + div(eps m V) = 0
d_t (eps m V) + div(eps m V V - eps tau) + eps grad P = eps m g + D
d_t (eps m E) + div(eps (m E + P) V - eps tau V + eps Q) = eps m g.V
d_t eps = 0

with the viscous stress tau and the heat flux ``Q = -kappa grad T`` of the diffusion fluxes. The
pressure term ``eps grad P`` is a non-conservative product: the left and right fluxes of a face
differ (``hyperbolic_fluxes/allregime.py``). ``D`` is the Darcy-Forchheimer drag of the porous
medium, with the Kozeny-Carman permeability (``relaxations/darcy.py``, solved exactly after the time
step, or ``sources/darcy.py``, at each stage as in canoP 2.x)::

k(eps) = eps^3 / ((1 - eps)^2 rp_2C) (infinite for eps = 1: no drag)
D = -eps^2 mu V / k - eps^3 m C_F |V| V / sqrt(k), C_F = 1.75 eps / sqrt(150 eps^5)

The equation of state is a stiffened gas with covolume and reference energy (Noble-Abel stiffened
gas, ``model.py``), as for the model onephase; with ``eps = 1`` everywhere the model is the onephase
model.

Variables, in the order of the arrays of canoP (names of the outputs and checkpoints, the vectors
with the components ``_x``, ``_y``, ``_z``), d being the dimension::

conservative 0 em, 1 emE, 2..1+d emV, 2+d eps (em = eps m, emE = eps m E, emV = eps m V)
primitive 0 m, 1 P, 2 T, 3..2+d V, 3+d eps

Parameters (section ``[param]``):

- ``eosFluid.gamma``, ``eosFluid.q``, ``eosFluid.b``, ``eosFluid.pinf``, ``eosFluid.Cv``: equation
of state (adiabatic index, reference energy, covolume, stiffening pressure, heat capacity at
constant volume);
- ``eosFluid.mu``, ``eosFluid.eta``: dynamic viscosity and second viscosity coefficient
(``diffusion_fluxes/viscosity.py``; ``mu`` also in the Darcy drag);
- ``eosFluid.kappa``: thermal conductivity (``diffusion_fluxes/conductivity.py``);
- ``eosFluid.rp_2C``: coefficient of the Kozeny-Carman permeability, ``rp_2C = C / rp^2`` for the
pore radius rp and the Kozeny constant C (0: infinite permeability, no drag);
- ``gravity_x``, ``gravity_y``, ``gravity_z``: gravity (``sources/gravity.py``, ``sources/darcy.py``);
- ``K``: coefficient of the acoustic impedance of the all-regime flux
(``hyperbolic_fluxes/allregime.py``);
- ``lowmach_correction_enabled``: 1: low Mach correction of the all-regime flux;
- ``lowmach_correction_scheme``: the low Mach correction with the Darcy correction: 1 all-regime,
2 entropy satisfying (Chalons et al. 2014), 3 semi-discrete acoustic entropy satisfying;
- ``darcy_correction_enabled``: 1: Darcy-Forchheimer drag in the interface velocity of the
all-regime flux;
- ``eosFluid.qp``: read but not used.

Port of the model PorousFluid of canoP 2.x (branch 38-correct-diffusion-flux-discretization-SEL).

The option files of the model are in the directories ``initial_conditions``,
``boundary_conditions``, ``refine_conditions``, ``hyperbolic_fluxes``, ``diffusion_fluxes``,
``sources`` and ``relaxations``, one file per value of the option of the input file. They import
``model.py`` and may call its functions and their own.
"""
from physics.common import AXES, get_int, get_real


def variables(dim):
"""Return the variables of the model.

``conservative`` and ``primitive``: the variables in the order of the arrays of canoP, also the
names of the outputs and checkpoints; ``derived``: the derived output fields (``derived_field``
of ``model.py``); ``nonconservative``: whether the left and right fluxes of a face differ
(non-conservative products).
"""
axes = AXES[:dim]
return {"conservative": ["em", "emE"] + ["emV_" + a for a in axes] + ["eps"],
"primitive": ["m", "P", "T"] + ["V_" + a for a in axes] + ["eps"],
"derived": [],
"nonconservative": True}


def params(dim):
"""Return the parameters of the model, ``{name: value}``.

The kernels read them through the class ``ModelParameters`` (``make_params`` of ``model.py``).
"""
res = {}

res["eos_gamma"] = get_real("param", "eosFluid.gamma", 1.666)
res["eos_q"] = get_real("param", "eosFluid.q", 0.0)
res["eos_b"] = get_real("param", "eosFluid.b", 0.0)
res["eos_pinf"] = get_real("param", "eosFluid.pinf", 0.0)
res["eos_Cv"] = get_real("param", "eosFluid.Cv", 1.0)
res["eos_mu"] = get_real("param", "eosFluid.mu", 0.0)
res["eos_eta"] = get_real("param", "eosFluid.eta", 0.0)
res["eos_kappa"] = get_real("param", "eosFluid.kappa", 0.0)
res["eos_rp_2C"] = get_real("param", "eosFluid.rp_2C", 0.0)
get_real("param", "eosFluid.qp", 0.0)

res["gravity_x"] = get_real("param", "gravity_x", 0.0)
res["gravity_y"] = get_real("param", "gravity_y", 0.0)
res["gravity_z"] = get_real("param", "gravity_z", 0.0)

res["lowmach"] = get_int("param", "lowmach_correction_enabled", 0)
res["lowmach_scheme"] = get_int("param", "lowmach_correction_scheme", 1)
res["darcy_correction"] = get_int("param", "darcy_correction_enabled", 0)
res["K"] = get_real("param", "K", 1.1)

return res
Loading
Loading