diff --git a/CHANGELOG.md b/CHANGELOG.md index eaee7cb..913a436 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Readme.md b/Readme.md index 42dbd44..76c1b3d 100644 --- a/Readme.md +++ b/Readme.md @@ -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 diff --git a/docs/index.md b/docs/index.md index 6ae1e09..ad01800 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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 diff --git a/docs/tutorial/build.md b/docs/tutorial/build.md index 61aec8e..d56fd81 100644 --- a/docs/tutorial/build.md +++ b/docs/tutorial/build.md @@ -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. diff --git a/docs/user-guide/models.md b/docs/user-guide/models.md index e8ead47..487f8e4 100644 --- a/docs/user-guide/models.md +++ b/docs/user-guide/models.md @@ -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. @@ -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, diff --git a/physics/common.py b/physics/common.py index b196ba1..9328183 100644 --- a/physics/common.py +++ b/physics/common.py @@ -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 # ============================================================================= @@ -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)] @@ -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", @@ -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. diff --git a/physics/loops.py b/physics/loops.py index cd8bfcd..d9f8ad9 100644 --- a/physics/loops.py +++ b/physics/loops.py @@ -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) @@ -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) diff --git a/physics/onephase/hyperbolic_fluxes/__init__.py b/physics/onephase/hyperbolic_fluxes/__init__.py index 6769574..649c810 100644 --- a/physics/onephase/hyperbolic_fluxes/__init__.py +++ b/physics/onephase/hyperbolic_fluxes/__init__.py @@ -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``. diff --git a/physics/onephase/relaxations/__init__.py b/physics/onephase/relaxations/__init__.py index fe3353d..4064f11 100644 --- a/physics/onephase/relaxations/__init__.py +++ b/physics/onephase/relaxations/__init__.py @@ -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``). """ diff --git a/physics/porousflow/__init__.py b/physics/porousflow/__init__.py new file mode 100644 index 0000000..1875353 --- /dev/null +++ b/physics/porousflow/__init__.py @@ -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 diff --git a/physics/porousflow/boundary_conditions/__init__.py b/physics/porousflow/boundary_conditions/__init__.py new file mode 100644 index 0000000..4761ece --- /dev/null +++ b/physics/porousflow/boundary_conditions/__init__.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Boundary conditions: one file per value of ``physics.boundary_condition``. + +The faces of the domain are numbered ``face = 2 d + s`` for the direction ``d`` (0 x, 1 y, 2 z) and +the side ``s`` (0 lower, 1 upper): 0 xmin, 1 xmax, 2 ymin, 3 ymax, 4 zmin, 5 zmax. A boundary +condition file defines: + +- ``params(dim)``: the parameters of the option, a dictionary ``{name: value}`` read from the input + file. The kernels read them as ``bp.`` (class ``BCParameters``); the names must not depend + on the input file. +- ``ghost_state(face, xout, xa, ya, za, h, uadj, umirror, bp, p, dim) -> Cons``: the conservative + state of a cell of an octant outside the domain, across ``face``. ``xout`` is the x coordinate of + the outside cell; ``(xa, ya, za)`` and ``h`` are the centre and size of the inside cell adjacent + to the face and ``uadj`` its state; ``umirror`` is the state of the inside cell mirrored through + the face. +- ``wall_kind(face, x, y, z, h, bp, dim) -> int``: the treatment of the face of the domain next to + the inside cell of centre ``(x, y, z)`` and size ``h``. It applies to the face states of the + hyperbolic flux (``wall_face_state`` of ``model.py``) and to the gradients of the diffusion flux + (``wall_gradient``): 0 none (the ghost cells act as inner cells), 1 reflective wall, 2 no-slip + wall, 3 outflow, 4 imposed state (the state of the ghost cell), 5 imposed pressure (the + reconstructed face state of the ghost cell). +""" diff --git a/physics/porousflow/boundary_conditions/backward_facing_step.py b/physics/porousflow/boundary_conditions/backward_facing_step.py new file mode 100644 index 0000000..760bf2b --- /dev/null +++ b/physics/porousflow/boundary_conditions/backward_facing_step.py @@ -0,0 +1,71 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""backward_facing_step: inflow above the step at xmin, imposed pressure at xmax, no-slip walls. + +On the face xmin, above ``y_step`` the ghost cells hold the inflow state (m0, P0, porosity 1) with the +velocity ``U_m`` (``inflow = 0``) or the parabolic profile ``6 U_m (y - y_step) (y_top - y) / +(y_top - y_step)^2`` of mean U_m (``inflow = 1``) (imposed state, wall kind 4); below it is a slip +wall (wall kind 1). On the face xmax the ghost cells take the state of the adjacent inside cell with +the pressure P0 (imposed pressure, wall kind 5). The other faces are no-slip walls (wall kind 2). +Parameters (section ``[backward_facing_step]``, read also by the initial condition +backward_facing_step): + +- ``m0``, ``P0``: density and pressure of the inflow, pressure of the outlet; +- ``U_m``: mean velocity of the inflow; +- ``inflow``: 1 parabolic profile, 0 uniform; +- ``y_step``, ``y_top``: heights of the step and of the channel. +""" +import pykokkos as pk + +from physics.common import get_int, get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("backward_facing_step", "m0", 1.0) + res["P0"] = get_real("backward_facing_step", "P0", 100.0) + res["U_m"] = get_real("backward_facing_step", "U_m", 1.0) + res["inflow"] = get_int("backward_facing_step", "inflow", 1) + res["y_step"] = get_real("backward_facing_step", "y_step", 1.0) + res["y_top"] = get_real("backward_facing_step", "y_top", 2.0) + + return res + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + u: Cons = umirror + if face == 0: + if ya >= bp.y_step: + vx: float = bp.U_m + if bp.inflow == 1: + hs: float = bp.y_top - bp.y_step + vx = 6 * bp.U_m * (ya - bp.y_step) * (bp.y_top - ya) / (hs * hs) + q: Prim = Prim(bp.m0, bp.P0, 0.0, vx, 0.0, 0.0, 1.0) + u = prim_to_cons(q, p, dim) + else: + reverse_momenta(u, 0, dim) + elif face == 1: + q2: Prim = cons_to_prim(uadj, p, dim) + q2.P = bp.P0 + u = prim_to_cons(q2, p, dim) + else: + reverse_momenta(u, -1, dim) + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + kind: int = 2 + if face == 0: + kind = 1 + if y >= bp.y_step: + kind = 4 + elif face == 1: + kind = 5 + return kind diff --git a/physics/porousflow/boundary_conditions/beavers_joseph.py b/physics/porousflow/boundary_conditions/beavers_joseph.py new file mode 100644 index 0000000..b22310e --- /dev/null +++ b/physics/porousflow/boundary_conditions/beavers_joseph.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""beavers_joseph: no-slip walls, imposed pressure P0 + gradP x on the x faces (inlet, outlet). + +On the faces normal to y and z, the ghost cells mirror the inside cells with every velocity reversed +(no-slip wall, wall kind 2). On the x faces, the ghost cells take the state of the adjacent inside +cell, porosity included, with the pressure P0 + gradP x at their centre (imposed pressure, wall +kind 5), as the boundary condition poiseuille. Parameters (section ``[beavers_joseph]``, read also +by the initial condition beavers_joseph): + +- ``P0``: pressure at x = 0; +- ``gradP``: pressure gradient along x. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["P0"] = get_real("beavers_joseph", "P0", 1.000008) + res["gradP"] = get_real("beavers_joseph", "gradP", -1E-6) + + return res + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + u: Cons = umirror + if face >= 2: + reverse_momenta(u, -1, dim) + else: + q2: Prim = cons_to_prim(uadj, p, dim) + q2.P = bp.P0 + bp.gradP * xout + u = prim_to_cons(q2, p, dim) + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + kind: int = 2 + if face < 2: + kind = 5 + return kind diff --git a/physics/porousflow/boundary_conditions/dirichlet.py b/physics/porousflow/boundary_conditions/dirichlet.py new file mode 100644 index 0000000..17c9e75 --- /dev/null +++ b/physics/porousflow/boundary_conditions/dirichlet.py @@ -0,0 +1,98 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""dirichlet: imposed state on each face of the domain. + +The ghost cells hold the imposed state of their face, which is also the face state of the hyperbolic +flux (wall kind 4). Parameters (section ``[dirichlet]``), for each face f from 0 to 5 (0 xmin, +1 xmax, 2 ymin, 3 ymax, 4 zmin, 5 zmax): + +- ``face.m``, ``face.P``: density and pressure; +- ``face.Vx``, ``face.Vy``, ``face.Vz`` (3D): velocity; +- ``face.eps``: porosity. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["face0_m"] = get_real("dirichlet", "face0.m", 1.0) + res["face0_P"] = get_real("dirichlet", "face0.P", 1.0) + res["face0_Vx"] = get_real("dirichlet", "face0.Vx", 0.0) + res["face0_Vy"] = get_real("dirichlet", "face0.Vy", 0.0) + res["face0_Vz"] = get_real("dirichlet", "face0.Vz", 0.0) if dim == 3 else 0.0 + res["face0_eps"] = get_real("dirichlet", "face0.eps", 1.0) + + res["face1_m"] = get_real("dirichlet", "face1.m", 1.0) + res["face1_P"] = get_real("dirichlet", "face1.P", 1.0) + res["face1_Vx"] = get_real("dirichlet", "face1.Vx", 0.0) + res["face1_Vy"] = get_real("dirichlet", "face1.Vy", 0.0) + res["face1_Vz"] = get_real("dirichlet", "face1.Vz", 0.0) if dim == 3 else 0.0 + res["face1_eps"] = get_real("dirichlet", "face1.eps", 1.0) + + res["face2_m"] = get_real("dirichlet", "face2.m", 1.0) + res["face2_P"] = get_real("dirichlet", "face2.P", 1.0) + res["face2_Vx"] = get_real("dirichlet", "face2.Vx", 0.0) + res["face2_Vy"] = get_real("dirichlet", "face2.Vy", 0.0) + res["face2_Vz"] = get_real("dirichlet", "face2.Vz", 0.0) if dim == 3 else 0.0 + res["face2_eps"] = get_real("dirichlet", "face2.eps", 1.0) + + res["face3_m"] = get_real("dirichlet", "face3.m", 1.0) + res["face3_P"] = get_real("dirichlet", "face3.P", 1.0) + res["face3_Vx"] = get_real("dirichlet", "face3.Vx", 0.0) + res["face3_Vy"] = get_real("dirichlet", "face3.Vy", 0.0) + res["face3_Vz"] = get_real("dirichlet", "face3.Vz", 0.0) if dim == 3 else 0.0 + res["face3_eps"] = get_real("dirichlet", "face3.eps", 1.0) + + res["face4_m"] = get_real("dirichlet", "face4.m", 1.0) + res["face4_P"] = get_real("dirichlet", "face4.P", 1.0) + res["face4_Vx"] = get_real("dirichlet", "face4.Vx", 0.0) + res["face4_Vy"] = get_real("dirichlet", "face4.Vy", 0.0) + res["face4_Vz"] = get_real("dirichlet", "face4.Vz", 0.0) if dim == 3 else 0.0 + res["face4_eps"] = get_real("dirichlet", "face4.eps", 1.0) + + res["face5_m"] = get_real("dirichlet", "face5.m", 1.0) + res["face5_P"] = get_real("dirichlet", "face5.P", 1.0) + res["face5_Vx"] = get_real("dirichlet", "face5.Vx", 0.0) + res["face5_Vy"] = get_real("dirichlet", "face5.Vy", 0.0) + res["face5_Vz"] = get_real("dirichlet", "face5.Vz", 0.0) if dim == 3 else 0.0 + res["face5_eps"] = get_real("dirichlet", "face5.eps", 1.0) + + return res + + +@pk.function +def dirichlet_state(bp: BCParameters, face: int, dim: int) -> Prim: + """Return the imposed primitive state of the face.""" + q: Prim = zero_prim() + if face == 0: + q = Prim(bp.face0_m, bp.face0_P, 0.0, bp.face0_Vx, bp.face0_Vy, bp.face0_Vz, bp.face0_eps) + elif face == 1: + q = Prim(bp.face1_m, bp.face1_P, 0.0, bp.face1_Vx, bp.face1_Vy, bp.face1_Vz, bp.face1_eps) + elif face == 2: + q = Prim(bp.face2_m, bp.face2_P, 0.0, bp.face2_Vx, bp.face2_Vy, bp.face2_Vz, bp.face2_eps) + elif face == 3: + q = Prim(bp.face3_m, bp.face3_P, 0.0, bp.face3_Vx, bp.face3_Vy, bp.face3_Vz, bp.face3_eps) + elif face == 4: + q = Prim(bp.face4_m, bp.face4_P, 0.0, bp.face4_Vx, bp.face4_Vy, bp.face4_Vz, bp.face4_eps) + elif face == 5: + q = Prim(bp.face5_m, bp.face5_P, 0.0, bp.face5_Vx, bp.face5_Vy, bp.face5_Vz, bp.face5_eps) + return q + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + q: Prim = dirichlet_state(bp, face, dim) + u: Cons = prim_to_cons(q, p, dim) + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + return 4 diff --git a/physics/porousflow/boundary_conditions/flow_around_cylinder.py b/physics/porousflow/boundary_conditions/flow_around_cylinder.py new file mode 100644 index 0000000..06d0ff0 --- /dev/null +++ b/physics/porousflow/boundary_conditions/flow_around_cylinder.py @@ -0,0 +1,55 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""flow_around_cylinder: uniform inflow at xmin, imposed pressure at xmax, slip walls elsewhere. + +The ghost cells of the face xmin hold the inflow state (m0, P0, velocity (U_m, 0, 0), porosity 1; +imposed state, wall kind 4). On the face xmax they take the state of the adjacent inside cell with +the pressure P0 (imposed pressure, wall kind 5). The other faces are slip walls (wall kind 1). +Parameters (section ``[flow_around_cylinder]``, read also by the initial condition +flow_around_cylinder): + +- ``m0``, ``P0``: density and pressure of the inflow, pressure of the outlet; +- ``U_m``: velocity of the inflow. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("flow_around_cylinder", "m0", 1.0) + res["P0"] = get_real("flow_around_cylinder", "P0", 100.0) + res["U_m"] = get_real("flow_around_cylinder", "U_m", 1.0) + + return res + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + u: Cons = umirror + if face == 0: + q: Prim = Prim(bp.m0, bp.P0, 0.0, bp.U_m, 0.0, 0.0, 1.0) + u = prim_to_cons(q, p, dim) + elif face == 1: + q2: Prim = cons_to_prim(uadj, p, dim) + q2.P = bp.P0 + u = prim_to_cons(q2, p, dim) + else: + reverse_momenta(u, face // 2, dim) + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + kind: int = 1 + if face == 0: + kind = 4 + elif face == 1: + kind = 5 + return kind diff --git a/physics/porousflow/boundary_conditions/neuman.py b/physics/porousflow/boundary_conditions/neuman.py new file mode 100644 index 0000000..bc552b2 --- /dev/null +++ b/physics/porousflow/boundary_conditions/neuman.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""neuman: outflow on every face of the domain. + +The ghost cells copy the adjacent inside cell (zero normal gradient), and the face states of the +hyperbolic flux use the outflow treatment (wall kind 3). +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """No parameters.""" + return {} + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + u: Cons = uadj + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + return 3 diff --git a/physics/porousflow/boundary_conditions/noslip.py b/physics/porousflow/boundary_conditions/noslip.py new file mode 100644 index 0000000..6ea5b18 --- /dev/null +++ b/physics/porousflow/boundary_conditions/noslip.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""noslip: no-slip walls on every face of the domain. + +The ghost cells mirror the inside cells with every velocity component reversed (wall kind 2). +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """No parameters.""" + return {} + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + u: Cons = umirror + reverse_momenta(u, -1, dim) + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + return 2 diff --git a/physics/porousflow/boundary_conditions/plug_flow.py b/physics/porousflow/boundary_conditions/plug_flow.py new file mode 100644 index 0000000..0e700b4 --- /dev/null +++ b/physics/porousflow/boundary_conditions/plug_flow.py @@ -0,0 +1,59 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""plug_flow: inflow at xmin, outflow at xmax, slip walls on the other faces (porous plug in a channel). + +Plug flow of Betchen, Straatman and Thompson (Numer. Heat Transfer A 49, 2006). The ghost cells of +the face xmin hold the inflow state: the density m0 and the velocity (Vx_in, 0, 0), with the +pressure and the porosity of the adjacent inside cell (imposed state, wall kind 4). The face xmax +is an outflow (wall kind 3) and the other faces are slip walls (wall kind 1). Parameters (section +``[plug_flow]``, read also by the initial condition plug_flow): + +- ``m0``: density of the inflow; +- ``Vx_in``: velocity of the inflow. + +canoP 2.x took the pressure of the inflow from a state mixing the inflow and the inside cell; it +is here that of the inside cell. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("plug_flow", "m0", 101325.0 / (287.0 * 300.0)) + res["Vx_in"] = get_real("plug_flow", "Vx_in", 1.5) + + return res + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + u: Cons = umirror + if face == 0: + q: Prim = cons_to_prim(uadj, p, dim) + q.m = bp.m0 + q.vx = bp.Vx_in + q.vy = 0.0 + q.vz = 0.0 + u = prim_to_cons(q, p, dim) + elif face == 1: + u = uadj + else: + reverse_momenta(u, face // 2, dim) + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + kind: int = 1 + if face == 0: + kind = 4 + elif face == 1: + kind = 3 + return kind diff --git a/physics/porousflow/boundary_conditions/poiseuille.py b/physics/porousflow/boundary_conditions/poiseuille.py new file mode 100644 index 0000000..875f20a --- /dev/null +++ b/physics/porousflow/boundary_conditions/poiseuille.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""poiseuille: no-slip walls, imposed pressure P0 + gradP x at the inlet and the outlet (x faces). + +On the faces normal to y and z, the ghost cells mirror the inside cells with every velocity reversed +(no-slip wall, wall kind 2). On the x faces, the ghost cells take the state of the adjacent inside +cell, porosity included, with the pressure P0 + gradP x at their centre (imposed pressure, wall +kind 5). Parameters (section ``[poiseuille]``, read also by the initial condition poiseuille): + +- ``P0``: pressure at x = 0; +- ``gradP``: pressure gradient along x. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["P0"] = get_real("poiseuille", "P0", 1.0) + res["gradP"] = get_real("poiseuille", "gradP", -1E-5) + + return res + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + u: Cons = umirror + if face >= 2: + reverse_momenta(u, -1, dim) + else: + q2: Prim = cons_to_prim(uadj, p, dim) + q2.P = bp.P0 + bp.gradP * xout + u = prim_to_cons(q2, p, dim) + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + kind: int = 2 + if face < 2: + kind = 5 + return kind diff --git a/physics/porousflow/boundary_conditions/reflective.py b/physics/porousflow/boundary_conditions/reflective.py new file mode 100644 index 0000000..d670597 --- /dev/null +++ b/physics/porousflow/boundary_conditions/reflective.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""reflective: slip walls on every face of the domain. + +The ghost cells mirror the inside cells with the normal velocity reversed (wall kind 1). +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """No parameters.""" + return {} + + +@pk.function +def ghost_state(face: int, xout: float, xa: float, ya: float, za: float, h: float, uadj: Cons, umirror: Cons, + bp: BCParameters, p: Params, dim: int) -> Cons: + u: Cons = umirror + reverse_momenta(u, face // 2, dim) + return u + + +@pk.function +def wall_kind(face: int, x: float, y: float, z: float, h: float, bp: BCParameters, dim: int) -> int: + return 1 diff --git a/physics/porousflow/diffusion_fluxes/__init__.py b/physics/porousflow/diffusion_fluxes/__init__.py new file mode 100644 index 0000000..7587f19 --- /dev/null +++ b/physics/porousflow/diffusion_fluxes/__init__.py @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Diffusion fluxes: one file per value of ``physics.diffusion_flux`` (or ``none``). + +A diffusion flux file defines: + +- ``diffusion_flux(p, q, g0, g1, g2, dim, F)``: adds to ``F`` the diffusion flux of a face along its + normal. The states are rotated so that the normal of the face is x: ``q`` is the primitive state + at the face (mean of the two cells, porosity included), ``g0``, ``g1``, ``g2`` the unlimited + gradients of the primitive variables at the face along x, y, z (``g0`` the difference of the two + cells over ``h``, ``g1`` and ``g2`` the mean of their centred differences). The kernel adds the + flux to the left and right hyperbolic fluxes. +- ``inv_dt(q, p, h, dim) -> float``: the inverse of the stable time step of the diffusion for a cell + of primitive state ``q`` and size ``h``. + +The fluxes of the porous medium are those of the fluid times the porosity of the face, ``q.eps``. +The time step is ``simulation.cfl`` divided by the max over the cells of the inverse time steps of +the hyperbolic and diffusion fluxes. +""" diff --git a/physics/porousflow/diffusion_fluxes/conductivity.py b/physics/porousflow/diffusion_fluxes/conductivity.py new file mode 100644 index 0000000..712af1f --- /dev/null +++ b/physics/porousflow/diffusion_fluxes/conductivity.py @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""conductivity: heat flux of the fluid in the pores, ``-eps kappa grad T``. + +``kappa`` is the thermal conductivity ``param.eosFluid.kappa``, ``eps`` the porosity of the face (mean +of the two cells). Inverse stable time step: ``kappa / (m Cv h^2)``. +""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +@pk.function +def diffusion_flux(p: Params, q: Prim, g0: Prim, g1: Prim, g2: Prim, dim: int, F: Cons) -> None: + eos: Eos = p.eos + F.emE -= eos.kappa * g0.T * q.eps + + +@pk.function +def inv_dt(q: Prim, p: Params, h: float, dim: int) -> float: + eos: Eos = p.eos + return eos.kappa / (q.m * eos.Cv * h * h) diff --git a/physics/porousflow/diffusion_fluxes/viscosity.py b/physics/porousflow/diffusion_fluxes/viscosity.py new file mode 100644 index 0000000..2bcc5ea --- /dev/null +++ b/physics/porousflow/diffusion_fluxes/viscosity.py @@ -0,0 +1,53 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""viscosity: Newtonian viscous stress of the fluid in the pores, ``eps tau``. + +The stress is ``tau = mu (grad V + grad V^T) + eta div(V) I``, with the dynamic viscosity +``param.eosFluid.mu`` and the second viscosity coefficient ``param.eosFluid.eta``, times the porosity +of the face (mean of the two cells). Inverse stable time step: ``mu / (m h^2)``. + +Difference with canoP 2.x: in 3D the whole stress is multiplied by the porosity (canoP 2.x leaves +out the terms in z). +""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +@pk.function +def grad_v(g0: Prim, g1: Prim, g2: Prim, dvel: int, ddir: int) -> float: + """Return the derivative of the velocity component dvel along the direction ddir.""" + if ddir == 0: + return vel(g0, dvel) + if ddir == 1: + return vel(g1, dvel) + return vel(g2, dvel) + + +@pk.function +def viscous_flux(mu: float, eta: float, q: Prim, g0: Prim, g1: Prim, g2: Prim, dim: int, F: Cons) -> None: + """Add to F the Newtonian viscous flux along x, times the porosity of the face.""" + div: float = 0 + for d in range(dim): + div += grad_v(g0, g1, g2, d, d) + # tau_xx = 2 mu du/dx + eta div(V), tau_xd = mu (du/dd + dvd/dx), times eps + tau: List[float] = [0.0, 0.0, 0.0] + tau[0] = (2. * mu * grad_v(g0, g1, g2, 0, 0) + eta * div) * q.eps + for d in range(1, dim): + tau[d] = mu * (grad_v(g0, g1, g2, 0, d) + grad_v(g0, g1, g2, d, 0)) * q.eps + for d in range(dim): + set_mom(F, d, mom(F, d) - tau[d]) + F.emE -= tau[d] * vel(q, d) + + +@pk.function +def diffusion_flux(p: Params, q: Prim, g0: Prim, g1: Prim, g2: Prim, dim: int, F: Cons) -> None: + eos: Eos = p.eos + viscous_flux(eos.mu, eos.eta, q, g0, g1, g2, dim, F) + + +@pk.function +def inv_dt(q: Prim, p: Params, h: float, dim: int) -> float: + eos: Eos = p.eos + return eos.mu / (q.m * h * h) diff --git a/physics/porousflow/hyperbolic_fluxes/__init__.py b/physics/porousflow/hyperbolic_fluxes/__init__.py new file mode 100644 index 0000000..dde39ec --- /dev/null +++ b/physics/porousflow/hyperbolic_fluxes/__init__.py @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Hyperbolic fluxes: one file per value of ``physics.hyperbolic_flux`` (or ``none``). + +A hyperbolic flux file defines: + +- ``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. The model has a non-conservative product (``eps grad P``): ``GL`` and ``GR`` + differ. + +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``. +""" diff --git a/physics/porousflow/hyperbolic_fluxes/allregime.py b/physics/porousflow/hyperbolic_fluxes/allregime.py new file mode 100644 index 0000000..9a8ff80 --- /dev/null +++ b/physics/porousflow/hyperbolic_fluxes/allregime.py @@ -0,0 +1,127 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""allregime: all-regime flux of the porous medium, with optional Darcy and low Mach corrections. + +Acoustic solver on the superficial velocity ``v = eps u`` of the face states, with the impedance +``a = K max(mL cL / epsL, mR cR / epsR)`` of the face (``param.K``):: + + v* = (vL + vR) / 2 - (PR - PL) / (2 a) + P* = (PL + PR) / 2 - theta a (vR - vL) / 2 + +With ``param.darcy_correction_enabled``, the interface velocity holds the Darcy-Forchheimer drag +over the cell size h, with the face means of the porosity, of the density, of the speed ``|V|`` and +of ``mu / k`` (Kozeny-Carman permeability k, ``param.eosFluid.mu``, ``param.eosFluid.rp_2C``):: + + v* = a (vL + vR - (PR - PL) / a) / (2 a + (mu / k) h + beta) + beta = eps h C_F(eps) |V| m sqrt(1 / k) + +The low Mach correction (``param.lowmach_correction_enabled``) is +``theta = min(|v*| / max(cL, cR), 1)``, else ``theta = 1``; with the Darcy correction, +``param.lowmach_correction_scheme`` chooses it: 1 that one, 2 the entropy satisfying correction of +Chalons et al. 2014, 3 a semi-discrete acoustic entropy satisfying correction (as in canoP 2.x). + +The advected quantities ``m``, ``m V``, ``m E`` are taken from the upwind face state and carried +by v*, so the fluxes are those of ``eps m``, ``eps m V`` and ``eps m E``. The pressure term of the +momentum is the non-conservative product ``eps grad P``: each cell takes ``P*`` times its own +porosity (``uL.eps``, ``uR.eps``), so a fluid at rest at uniform pressure stays at rest across a +jump of porosity. The flux of the porosity is zero. + +Differences with canoP 2.x: the speed ``|V|`` of the Darcy correction has its three components in 3D +(two in canoP 2.x), and ``mu / k`` is computed from ``1 / k`` (no division by zero for ``eps = 1`` +or ``mu = 0``). +""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +@pk.function +def lowmach_theta(scheme: int, vstar: float, vl: float, vr: float, pl: float, pr: float, rl: float, rr: float, + epsl: float, epsr: float, al: float, ar: float, aface: float, gamma: float) -> float: + """Return the low Mach correction theta of the Darcy-corrected flux (param.lowmach_correction_scheme).""" + theta: float = 1. + if scheme == 2: + # Entropy satisfying correction (Chalons et al. 2014) + tau_l: float = epsl * epsl / rl + tau_ls: float = tau_l + (1.0 / aface) * (vstar - vl) + p_inter_l: float = pl * pk.pow(tau_l / tau_ls, gamma) + tau_r: float = epsr * epsr / rr + tau_rs: float = tau_r + (1.0 / aface) * (vstar - vr) + p_inter_r: float = pr * pk.pow(tau_r / tau_rs, gamma) + pistar_base: float = 0.5 * (p_inter_l + p_inter_r) - 0.5 * (vr - vl) * aface + gradu: float = vr - vl + alpha_l: float = pk.fabs((pistar_base - p_inter_l) / gradu) * 2.0 / aface + alpha_r: float = pk.fabs((pistar_base - p_inter_r) / gradu) * 2.0 / aface + theta = pk.fmax(0.0, pk.fmin(1.0, 1 - pk.fmin(alpha_l, alpha_r))) + elif scheme == 3: + # Semi-discrete acoustic entropy satisfying correction + du: float = (vr - vl) + 1.0e-14 + dp: float = (pr - pl) / aface + theta_m: float = 0.0 + if du / (du - dp) > 0.0: + theta_m = dp / du + theta_p: float = 0.0 + if du / (du + dp) > 0.0: + theta_p = -dp / du + theta = pk.fmax(pk.fmin(pk.fmax(theta_m, theta_p), 1.), pk.fabs(vstar) / pk.fmax(al / rl, ar / rr)) + else: + theta = pk.fmin(pk.fabs(vstar) / pk.fmax(al / rl, ar / rr), 1.) + return theta + + +@pk.function +def riemann(qL: Prim, qR: Prim, uL: Cons, uR: Cons, p: Params, h: float, dim: int, GL: Cons, GR: Cons) -> None: + """Riemann solver of the face: the fluxes seen by the left (GL) and right (GR) cells.""" + eos: Eos = p.eos + rl: float = qL.m + pl: float = qL.P + vl: float = qL.vx * qL.eps + epsl: float = qL.eps + al: float = rl * eos_soundspeed(rl, pl, eos) + rr: float = qR.m + pr: float = qR.P + vr: float = qR.vx * qR.eps + epsr: float = qR.eps + ar: float = rr * eos_soundspeed(rr, pr, eos) + aface: float = p.K * pk.fmax(al / epsl, ar / epsr) + + vstar: float = 0.0 + theta: float = 1. + if p.darcy_correction != 0: + # Darcy-Forchheimer drag in the interface velocity + ikl: float = inv_permeability(epsl, eos) + ikr: float = inv_permeability(epsr, eos) + mu_k_face: float = 0.5 * (eos.mu * ikl + eos.mu * ikr) + eps_face: float = 0.5 * (epsl + epsr) + cf_face: float = forchheimer(eps_face) + inv_k_face: float = pk.sqrt(0.5 * (ikl + ikr)) + rho_face: float = 0.5 * (rl + rr) + uface: float = 0.5 * (speed(qL, dim) + speed(qR, dim)) + beta: float = eps_face * h * cf_face * uface * rho_face * inv_k_face + vstar = (aface / (2.0 * aface + mu_k_face * h + beta)) * ((vl + vr) - (pr - pl) / aface) + if p.lowmach != 0: + theta = lowmach_theta(p.lowmach_scheme, vstar, vl, vr, pl, pr, rl, rr, epsl, epsr, al, ar, aface, + eos.gamma) + else: + vstar = 0.5 * (vl + vr) - 0.5 * (pr - pl) / aface + if p.lowmach != 0: + theta = pk.fmin(pk.fabs(vstar) / pk.fmax(al / rl, ar / rr), 1.) + pstar: float = 0.5 * (pl + pr) - 0.5 * (vr - vl) * aface * theta + + # Upwind state, advected by the superficial velocity v* + qu: Prim = qR + if vstar > 0: + qu = qL + ru: float = qu.m + Eu: float = total_energy(qu, eos, dim) + GL.em += ru * vstar + GR.em += ru * vstar + for d in range(dim): + set_mom(GL, d, mom(GL, d) + ru * vel(qu, d) * vstar) + set_mom(GR, d, mom(GR, d) + ru * vel(qu, d) * vstar) + # Non-conservative product eps grad P: the porosity of each cell + GL.emx += pstar * uL.eps + GR.emx += pstar * uR.eps + GL.emE += Eu * vstar + pstar * vstar + GR.emE += Eu * vstar + pstar * vstar diff --git a/physics/porousflow/initial_conditions/__init__.py b/physics/porousflow/initial_conditions/__init__.py new file mode 100644 index 0000000..b577774 --- /dev/null +++ b/physics/porousflow/initial_conditions/__init__.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Initial conditions: one file per value of ``physics.initial_condition``. + +An initial condition file defines: + +- ``params(dim)``: the parameters of the option, a dictionary ``{name: value}`` read from the input + file. The kernels read them as ``ip.`` (class ``ICParameters``); the names must not depend + on the input file. +- ``initial_state(x, y, z, ip, domain, dim) -> Prim``: the primitive state at the cell centre + ``(x, y, z)`` (``z = 0`` in 2D). ``domain`` holds the lower corner (``domain[0:3]``) and the + lengths (``domain[3:6]``) of the domain. The kernel converts the state to conservative variables + with ``prim_to_cons`` of ``model.py``. +""" diff --git a/physics/porousflow/initial_conditions/backward_facing_step.py b/physics/porousflow/initial_conditions/backward_facing_step.py new file mode 100644 index 0000000..3bb6044 --- /dev/null +++ b/physics/porousflow/initial_conditions/backward_facing_step.py @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""backward_facing_step: fluid at rest in a channel whose step is a porous block. + +The porosity is eps0 in the rectangle of centre (x_c, y_c) and sides Lx, Ly, and 1 outside, with +smooth transitions of widths 0.01 Lx and 0.04 Ly:: + + eps = 1 - (1 - eps0) tx ty, tx = (1 + tanh((Lx / 2 - |x - x_c|) / (0.01 Lx))) / 2 + ty = (1 + tanh((Ly / 2 - |y - y_c|) / (0.04 Ly))) / 2 + +The density is m0 and the pressure P0; the boundary condition backward_facing_step brings the +inflow above the step. Parameters (section ``[backward_facing_step]``): + +- ``m0``, ``P0``: density and pressure; +- ``x_c``, ``y_c``: centre of the porous block; +- ``Lx``, ``Ly``: sides of the block; +- ``eps0``: porosity of the block. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("backward_facing_step", "m0", 1.0) + res["P0"] = get_real("backward_facing_step", "P0", 100.0) + res["x_c"] = get_real("backward_facing_step", "x_c", 2.0) + res["y_c"] = get_real("backward_facing_step", "y_c", 0.5) + res["Lx"] = get_real("backward_facing_step", "Lx", 4.0) + res["Ly"] = get_real("backward_facing_step", "Ly", 1.0) + res["eps0"] = get_real("backward_facing_step", "eps0", 0.4) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + tx: float = 0.5 * (1.0 + pk.tanh((ip.Lx / 2.0 - pk.fabs(x - ip.x_c)) / (0.01 * ip.Lx))) + ty: float = 0.5 * (1.0 + pk.tanh((ip.Ly / 2.0 - pk.fabs(y - ip.y_c)) / (0.01 * ip.Ly * 4.0))) + t: float = tx * ty + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + q.eps = 1.0 * (1.0 - t) + ip.eps0 * t + q.m = ip.m0 + q.P = ip.P0 + return q diff --git a/physics/porousflow/initial_conditions/beavers_joseph.py b/physics/porousflow/initial_conditions/beavers_joseph.py new file mode 100644 index 0000000..7a2484e --- /dev/null +++ b/physics/porousflow/initial_conditions/beavers_joseph.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""beavers_joseph: fluid at rest over a porous layer, pressure P0 + gradP x (Beavers and Joseph 1967). + +The porosity is eps0 in the layer y < y0 and 1 above, with a smooth transition of width about +1 / tau:: + + eps = eps0 (1 - t) + t, t = (1 + tanh(tau (y - y0))) / 2 + +The boundary condition beavers_joseph imposes the same pressure on the x faces. Parameters (section +``[beavers_joseph]``): + +- ``m0``: density; +- ``P0``: pressure at x = 0; +- ``gradP``: pressure gradient along x; +- ``y0``: top of the porous layer; +- ``eps0``: porosity of the layer; +- ``tau``: steepness of the transition. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("beavers_joseph", "m0", 0.2) + res["P0"] = get_real("beavers_joseph", "P0", 1.000008) + res["gradP"] = get_real("beavers_joseph", "gradP", -1E-6) + res["y0"] = get_real("beavers_joseph", "y0", 0.5) + res["eps0"] = get_real("beavers_joseph", "eps0", 0.7) + res["tau"] = get_real("beavers_joseph", "tau", 50.0) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + t: float = 0.5 * (1.0 + pk.tanh(ip.tau * (y - ip.y0))) + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + q.eps = ip.eps0 * (1.0 - t) + 1.0 * t + q.m = ip.m0 + q.P = ip.P0 + ip.gradP * x + return q diff --git a/physics/porousflow/initial_conditions/blast.py b/physics/porousflow/initial_conditions/blast.py new file mode 100644 index 0000000..06ad037 --- /dev/null +++ b/physics/porousflow/initial_conditions/blast.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""blast: sphere of state (m_in, P_in) in a fluid (m_out, P_out), at rest, in a medium of porosity eps. + +Parameters (section ``[blast]``): + +- ``x_c``, ``y_c``, ``z_c``: centre of the sphere; +- ``radius``: radius of the sphere; +- ``m_in``, ``P_in``: density and pressure inside the sphere; +- ``m_out``, ``P_out``: density and pressure outside; +- ``eps``: porosity (uniform). +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["x_c"] = get_real("blast", "x_c", 0.5) + res["y_c"] = get_real("blast", "y_c", 0.5) + res["z_c"] = get_real("blast", "z_c", 0.5) + + res["radius"] = get_real("blast", "radius", 0.25) + + res["m_in"] = get_real("blast", "m_in", 1.0) + res["m_out"] = get_real("blast", "m_out", 1.2) + + res["P_in"] = get_real("blast", "P_in", 10.0) + res["P_out"] = get_real("blast", "P_out", 1.0) + + res["eps"] = get_real("blast", "eps", 1.0) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ip.eps) + if dist2(x, y, z, ip.x_c, ip.y_c, ip.z_c, dim) < ip.radius * ip.radius: + q.m = ip.m_in + q.P = ip.P_in + else: + q.m = ip.m_out + q.P = ip.P_out + + return q diff --git a/physics/porousflow/initial_conditions/conduction.py b/physics/porousflow/initial_conditions/conduction.py new file mode 100644 index 0000000..e7d68d9 --- /dev/null +++ b/physics/porousflow/initial_conditions/conduction.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""conduction: Gaussian bump of density and pressure on a uniform fluid at rest. + +``m = m_out + m_c G`` and ``P = P_out + P_c G`` with ``G = exp(-r^2 / radius^2)``, ``r`` the +distance to the centre. Porosity 1 (no porous medium). +Parameters (section ``[conduction]``): + +- ``x_c``, ``y_c``, ``z_c``: centre of the bump; +- ``radius``: width of the bump; +- ``m_c``, ``P_c``: amplitudes of the density and of the pressure; +- ``m_out``, ``P_out``: density and pressure of the uniform fluid. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["x_c"] = get_real("conduction", "x_c", 0.5) + res["y_c"] = get_real("conduction", "y_c", 0.5) + res["z_c"] = get_real("conduction", "z_c", 0.5) + + res["radius"] = get_real("conduction", "radius", 0.1) + + res["m_c"] = get_real("conduction", "m_c", 1.0) + res["m_out"] = get_real("conduction", "m_out", 1.0) + + res["P_c"] = get_real("conduction", "P_c", 100.0) + res["P_out"] = get_real("conduction", "P_out", 1.0) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + g: float = pk.exp(-dist2(x, y, z, ip.x_c, ip.y_c, ip.z_c, dim) / (ip.radius * ip.radius)) + q.m = ip.m_out + ip.m_c * g + q.P = ip.P_out + ip.P_c * g + return q diff --git a/physics/porousflow/initial_conditions/flow_around_cylinder.py b/physics/porousflow/initial_conditions/flow_around_cylinder.py new file mode 100644 index 0000000..422adce --- /dev/null +++ b/physics/porousflow/initial_conditions/flow_around_cylinder.py @@ -0,0 +1,50 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""flow_around_cylinder: fluid at rest around a porous cylinder (axis along z). + +The porosity is eps0 in the disc of centre (x_c, y_c) and radius R, and 1 outside, with a smooth +transition of width 0.1 R:: + + eps = 1 - (1 - eps0) t, t = (1 + tanh((R - r) / (0.1 R))) / 2 + +with r the distance to the axis. The density is m0 and the pressure P0; the boundary condition +flow_around_cylinder brings the inflow. Parameters (section ``[flow_around_cylinder]``): + +- ``m0``, ``P0``: density and pressure; +- ``x_c``, ``y_c``: centre of the cylinder; +- ``radius``: radius R of the cylinder; +- ``eps0``: porosity of the cylinder. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("flow_around_cylinder", "m0", 1.0) + res["P0"] = get_real("flow_around_cylinder", "P0", 100.0) + res["x_c"] = get_real("flow_around_cylinder", "x_c", 0.5) + res["y_c"] = get_real("flow_around_cylinder", "y_c", 0.5) + res["radius"] = get_real("flow_around_cylinder", "radius", 0.1) + res["eps0"] = get_real("flow_around_cylinder", "eps0", 0.4) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + dx: float = pk.fabs(x - ip.x_c) + dy: float = pk.fabs(y - ip.y_c) + r: float = pk.sqrt(dx * dx + dy * dy) + t: float = 0.5 * (1.0 + pk.tanh((ip.radius - r) / (0.1 * ip.radius))) + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + q.eps = 1.0 * (1.0 - t) + ip.eps0 * t + q.m = ip.m0 + q.P = ip.P0 + return q diff --git a/physics/porousflow/initial_conditions/gresho.py b/physics/porousflow/initial_conditions/gresho.py new file mode 100644 index 0000000..13a313e --- /dev/null +++ b/physics/porousflow/initial_conditions/gresho.py @@ -0,0 +1,66 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""gresho: Gresho vortex of uniform density. + +Azimuthal velocity ``5 r`` for ``r < 0.2``, ``2 - 5 r`` for ``0.2 <= r < 0.4`` and 0 beyond, ``r`` +the distance to the axis of the vortex, with the pressure that balances it on top of the background +pressure ``P0 = m / mach^2``. Porosity 1 (no porous medium). Parameters (section ``[gresho]``): + +- ``x_c``, ``y_c``: centre of the vortex (axis along z); +- ``m``: density; +- ``mach``: Mach number, which sets the background pressure. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["x_c"] = get_real("gresho", "x_c", 0.5) + res["y_c"] = get_real("gresho", "y_c", 0.5) + + res["m"] = get_real("gresho", "m", 1.0) + res["mach"] = get_real("gresho", "mach", 0.01) + + return res + + +@pk.function +def gresho_utheta(r: float) -> float: + """Return the azimuthal velocity of the Gresho vortex at the distance r.""" + if r < 0.2: + return 5. * r + if r < 0.4: + return 2. - 5. * r + return 0. + + +@pk.function +def gresho_pressure(r: float, P0: float) -> float: + """Return the pressure of the Gresho vortex at the distance r, for the background pressure P0.""" + if r < 0.2: + return P0 + 5. * 5. * r * r / 2. + if r < 0.4: + return P0 + 5. * 5. * r * r / 2. + 4. * (1. - 5. * r + pk.log(5. * r)) + return P0 - 2. + pk.log(4. * 4.) + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + dxv: float = x - ip.x_c + dyv: float = y - ip.y_c + r: float = pk.sqrt(dxv * dxv + dyv * dyv) + theta: float = pk.atan2(dyv, dxv) + utheta: float = gresho_utheta(r) + q.m = ip.m + q.P = gresho_pressure(r, ip.m / (ip.mach * ip.mach)) + q.vx = -utheta * pk.sin(theta) + q.vy = utheta * pk.cos(theta) + return q diff --git a/physics/porousflow/initial_conditions/plug_flow.py b/physics/porousflow/initial_conditions/plug_flow.py new file mode 100644 index 0000000..fff0e09 --- /dev/null +++ b/physics/porousflow/initial_conditions/plug_flow.py @@ -0,0 +1,49 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""plug_flow: fluid at rest in a channel with a porous plug (Betchen, Straatman and Thompson 2006). + +The porosity is 1 for x < x_1 and x > x_2, eps0 in the plug between, with smooth transitions of +width about 2 / tau:: + + eps = (t1 + t2) + eps0 (1 - t1 - t2), t1 = (1 + tanh(tau (x_1 - x) / 2)) / 2, + t2 = (1 + tanh(tau (x - x_2) / 2)) / 2 + +The density is m0 and the pressure P0; the boundary condition plug_flow brings the inflow. +Parameters (section ``[plug_flow]``): + +- ``m0``, ``P0``: density and pressure; +- ``x_1``, ``x_2``: ends of the plug; +- ``eps0``: porosity of the plug; +- ``tau``: steepness of the transitions. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("plug_flow", "m0", 101325.0 / (287.0 * 300.0)) + res["P0"] = get_real("plug_flow", "P0", 101325.0) + res["x_1"] = get_real("plug_flow", "x_1", 3.0) + res["x_2"] = get_real("plug_flow", "x_2", 5.0) + res["eps0"] = get_real("plug_flow", "eps0", 0.7) + res["tau"] = get_real("plug_flow", "tau", 50.0) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + t1: float = 0.5 * (1.0 + pk.tanh(ip.tau * 0.5 * (ip.x_1 - x))) + t2: float = 0.5 * (1.0 + pk.tanh(ip.tau * 0.5 * (x - ip.x_2))) + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + q.eps = 1.0 * (t1 + t2) + ip.eps0 * (1 - t1 - t2) + q.m = ip.m0 + q.P = ip.P0 + return q diff --git a/physics/porousflow/initial_conditions/poiseuille.py b/physics/porousflow/initial_conditions/poiseuille.py new file mode 100644 index 0000000..c6e9baf --- /dev/null +++ b/physics/porousflow/initial_conditions/poiseuille.py @@ -0,0 +1,52 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""poiseuille: fluid at rest in a channel with a porous block, pressure P0 + gradP x. + +The porosity is 1 outside the block x_1 < x < x_2 and eps0 inside, with smooth transitions of width +about 2 / tau:: + + eps = 1 - (1 - eps0) t1 t2, t1 = (1 + tanh(tau (x - x_1) / 2)) / 2, + t2 = (1 + tanh(tau (x_2 - x) / 2)) / 2 + +The boundary condition poiseuille imposes the same pressure on the x faces. Parameters (section +``[poiseuille]``): + +- ``m0``: density; +- ``P0``: pressure at x = 0; +- ``gradP``: pressure gradient along x; +- ``x_1``, ``x_2``: ends of the porous block; +- ``eps0``: porosity of the block; +- ``tau``: steepness of the transitions. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["m0"] = get_real("poiseuille", "m0", 0.2) + res["P0"] = get_real("poiseuille", "P0", 1.0) + res["gradP"] = get_real("poiseuille", "gradP", -1E-5) + res["x_1"] = get_real("poiseuille", "x_1", 3.0) + res["x_2"] = get_real("poiseuille", "x_2", 5.0) + res["eps0"] = get_real("poiseuille", "eps0", 0.7) + res["tau"] = get_real("poiseuille", "tau", 50.0) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + t1: float = 0.5 * (1.0 + pk.tanh(ip.tau * 0.5 * (x - ip.x_1))) + t2: float = 0.5 * (1.0 + pk.tanh(ip.tau * 0.5 * (ip.x_2 - x))) + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + q.eps = 1.0 * (1.0 - t1 * t2) + ip.eps0 * t1 * t2 + q.m = ip.m0 + q.P = ip.P0 + ip.gradP * x + return q diff --git a/physics/porousflow/initial_conditions/rayleigh_taylor.py b/physics/porousflow/initial_conditions/rayleigh_taylor.py new file mode 100644 index 0000000..f0296b0 --- /dev/null +++ b/physics/porousflow/initial_conditions/rayleigh_taylor.py @@ -0,0 +1,68 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""rayleigh_taylor: heavy fluid above a light fluid in hydrostatic equilibrium, interface perturbed. + +The interface is the plane x = x0 and the gravity is along x: the light fluid (m_down) is below the +interface, the heavy fluid (m_up) above. The pressure is hydrostatic, ``P0 + m gravity_x (x - x0)``, +and the perturbation is a velocity along x:: + + V_x = amplitude cos(2 pi mode y / L_y) cos(2 pi mode z / L_z) exp(-(x - x0)^2 / (2 width^2)) + +with ``L_y``, ``L_z`` the lengths of the domain (the z factor is 1 in 2D). Porosity 1 (no porous +medium). Parameters (section ``[rayleigh_taylor]``): + +- ``m_down``, ``m_up``: densities below and above the interface; +- ``x0``: position of the interface; +- ``P0``: pressure at the interface; +- ``amplitude``, ``perturb_mode``, ``perturb_width``: amplitude, mode and width of the perturbation; +- ``param.gravity_x``: the gravity of the model, read here for the hydrostatic pressure; +- ``randomEnabled``: 1 (random perturbation) is not available; +- ``rand_seed``: read but not used. +""" +import math + +import pykokkos as pk + +from physics.common import get_int, get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + if get_int("rayleigh_taylor", "randomEnabled", 0): + raise ValueError("rayleigh_taylor.randomEnabled = 1 is not available with pykokkos") + get_int("rayleigh_taylor", "rand_seed", 12) + + res["m_down"] = get_real("rayleigh_taylor", "m_down", 1.0) + res["m_up"] = get_real("rayleigh_taylor", "m_up", 2.0) + + res["gravity_x"] = get_real("param", "gravity_x", -0.1) + + res["x0"] = get_real("rayleigh_taylor", "x0", 1.5) + res["P0"] = get_real("rayleigh_taylor", "P0", 1.0) + res["amplitude"] = get_real("rayleigh_taylor", "amplitude", 0.01) + res["mode"] = float(get_int("rayleigh_taylor", "perturb_mode", 1)) + res["width"] = get_real("rayleigh_taylor", "perturb_width", 0.05) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + if x < ip.x0: + q.m = ip.m_down + else: + q.m = ip.m_up + zz: float = 0.0 + if dim == 3: + zz = z + q.vx = (ip.amplitude * pk.cos(ip.mode * 2 * math.pi * y / domain[4]) + * pk.cos(ip.mode * 2 * math.pi * zz / domain[5]) + * pk.exp(-(x - ip.x0) * (x - ip.x0) / 2 / ip.width / ip.width)) + q.P = ip.P0 + q.m * ip.gravity_x * (x - ip.x0) + return q diff --git a/physics/porousflow/initial_conditions/riemann_problem.py b/physics/porousflow/initial_conditions/riemann_problem.py new file mode 100644 index 0000000..765befd --- /dev/null +++ b/physics/porousflow/initial_conditions/riemann_problem.py @@ -0,0 +1,63 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""riemann_problem: two uniform states separated by the plane x = x0, with a jump of porosity. + +Parameters (section ``[riemann_problem]``): + +- ``x0``: position of the discontinuity; +- ``m_left``, ``P_left``, ``Vx_left``, ``Vy_left``, ``Vz_left`` (3D), ``eps_left``: density, pressure, + velocity and porosity for x < x0; +- ``m_right``, ``P_right``, ``Vx_right``, ``Vy_right``, ``Vz_right`` (3D), ``eps_right``: the same for + x >= x0. +""" +import pykokkos as pk + +from physics.common import get_real # noqa: F401 # pylint: disable=unused-import +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + + res["x0"] = get_real("riemann_problem", "x0", 0.5) + + res["m_left"] = get_real("riemann_problem", "m_left", 1.0) + res["P_left"] = get_real("riemann_problem", "P_left", 0.4) + res["Vx_left"] = get_real("riemann_problem", "Vx_left", -2.0) + res["Vy_left"] = get_real("riemann_problem", "Vy_left", 0.0) + res["Vz_left"] = get_real("riemann_problem", "Vz_left", 0.0) if dim == 3 else 0.0 + res["eps_left"] = get_real("riemann_problem", "eps_left", 1.0) + + res["m_right"] = get_real("riemann_problem", "m_right", 1.0) + res["P_right"] = get_real("riemann_problem", "P_right", 0.4) + res["Vx_right"] = get_real("riemann_problem", "Vx_right", 2.0) + res["Vy_right"] = get_real("riemann_problem", "Vy_right", 0.0) + res["Vz_right"] = get_real("riemann_problem", "Vz_right", 0.0) if dim == 3 else 0.0 + res["eps_right"] = get_real("riemann_problem", "eps_right", 1.0) + + return res + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0) + if x >= ip.x0: + q.m = ip.m_right + q.P = ip.P_right + q.vx = ip.Vx_right + q.vy = ip.Vy_right + if dim == 3: + q.vz = ip.Vz_right + q.eps = ip.eps_right + else: + q.m = ip.m_left + q.P = ip.P_left + q.vx = ip.Vx_left + q.vy = ip.Vy_left + if dim == 3: + q.vz = ip.Vz_left + q.eps = ip.eps_left + return q diff --git a/physics/porousflow/model.py b/physics/porousflow/model.py new file mode 100644 index 0000000..c33cd1b --- /dev/null +++ b/physics/porousflow/model.py @@ -0,0 +1,498 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Kernel functions of the porousflow model: states, equation of state, conversions, face states. + +This file is compiled into every kernel of the model (``loops.py``), with the option files of the +categories the kernel uses; the option files import it and call its functions. + +States (classes ``Prim`` and ``Cons``) and their arrays ``[octant][variable][cell]``, d being the +dimension:: + + conservative 0 em, 1 emE, 2..1+d emV, 2+d eps (per unit volume of the medium) + primitive 0 m, 1 P, 2 T, 3..2+d V, 3+d eps (of the fluid in the pores) + +The conservative variables are those of the fluid per unit volume of the porous medium: +``em = eps m``, ``emE = eps m E``, ``emV = eps m V``. The porosity ``eps`` is constant in time; its +flux is zero. + +Equation of state: stiffened gas with covolume b and reference energy q (Noble-Abel stiffened gas), +with the specific internal energy e:: + + P = (gamma - 1) (e - q) / (1/m - b) - gamma pinf + T = (e - q - (1/m - b) pinf) / Cv + c^2 = gamma (P + pinf) / (m^2 (1/m - b)) + +Permeability of the medium (Kozeny-Carman): ``k(eps) = eps^3 / ((1 - eps)^2 rp_2C)``, computed as its +inverse ``inv_permeability`` (0 for ``eps = 1`` or ``rp_2C = 0``: no drag). + +``Params`` (built by ``make_params``) holds the parameters of the model, from the named parameters +``ModelParameters`` (``params`` of ``__init__.py``). +""" +import pykokkos as pk + + +# ============================================================================= +# States, parameters and equation of state +# ============================================================================= +# Equation of state and transport coefficients of the fluid, permeability of the medium +@pk.classtype +class Eos: + def __init__(self, gamma: float, q: float, b: float, pinf: float, Cv: float, mu: float, eta: float, kappa: float, + rp_2C: float): + self.gamma: float = gamma + self.q: float = q + self.b: float = b + self.pinf: float = pinf + self.Cv: float = Cv + self.mu: float = mu + self.eta: float = eta + self.kappa: float = kappa + self.rp_2C: float = rp_2C + + +# Primitive state of the fluid in the pores: density, pressure, temperature, velocity; porosity +@pk.classtype +class Prim: + def __init__(self, m: float, P: float, T: float, vx: float, vy: float, vz: float, eps: float): + self.m: float = m + self.P: float = P + self.T: float = T + self.vx: float = vx + self.vy: float = vy + self.vz: float = vz + self.eps: float = eps + + +# Conservative state per unit volume of the medium: eps m, eps m E, eps m V; porosity +@pk.classtype +class Cons: + def __init__(self, em: float, emE: float, emx: float, emy: float, emz: float, eps: float): + self.em: float = em + self.emE: float = emE + self.emx: float = emx + self.emy: float = emy + self.emz: float = emz + self.eps: float = eps + + +# Parameters of the model, built by make_params +@pk.classtype +class Params: + def __init__(self, eos: Eos, gravity_x: float, gravity_y: float, gravity_z: float, K: float, lowmach: int, + lowmach_scheme: int, darcy_correction: int): + self.eos: Eos = eos + self.gravity_x: float = gravity_x + self.gravity_y: float = gravity_y + self.gravity_z: float = gravity_z + self.K: float = K + self.lowmach: int = lowmach + self.lowmach_scheme: int = lowmach_scheme + self.darcy_correction: int = darcy_correction + + +@pk.function +def make_params(m: ModelParameters) -> Params: + """Return the parameters of the model from the named parameters (params of __init__.py).""" + eos: Eos = Eos(m.eos_gamma, m.eos_q, m.eos_b, m.eos_pinf, m.eos_Cv, m.eos_mu, m.eos_eta, m.eos_kappa, m.eos_rp_2C) + return Params(eos, m.gravity_x, m.gravity_y, m.gravity_z, m.K, m.lowmach, m.lowmach_scheme, m.darcy_correction) + + +@pk.function +def gravity(p: Params, d: int) -> float: + """Return the component d of the gravity.""" + if d == 0: + return p.gravity_x + if d == 1: + return p.gravity_y + return p.gravity_z + + +@pk.function +def zero_prim() -> Prim: + """Return a primitive state with every variable zero.""" + return Prim(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + + +@pk.function +def zero_cons() -> Cons: + """Return a conservative state with every variable zero.""" + return Cons(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + + +@pk.function +def eos_pressure(rho: float, eint: float, eos: Eos) -> float: + """Return the pressure from the density and the specific internal energy.""" + return (eos.gamma - 1.0) * (eint - eos.q) / (1.0 / rho - eos.b) - eos.gamma * eos.pinf + + +@pk.function +def eos_temperature(rho: float, eint: float, eos: Eos) -> float: + """Return the temperature from the density and the specific internal energy.""" + return ((eint - eos.q) - (1.0 / rho - eos.b) * eos.pinf) / eos.Cv + + +@pk.function +def eos_soundspeed(rho: float, p: float, eos: Eos) -> float: + """Return the sound speed from the density and the pressure.""" + return pk.sqrt(eos.gamma / (rho * rho) * (p + eos.pinf) / (1.0 / rho - eos.b)) + + +@pk.function +def eos_eint(rho: float, p: float, eos: Eos) -> float: + """Return the specific internal energy from the density and the pressure.""" + return (p + eos.gamma * eos.pinf) / (eos.gamma - 1.0) * (1.0 / rho - eos.b) + eos.q + + +@pk.function +def inv_permeability(eps: float, eos: Eos) -> float: + """Return the inverse of the Kozeny-Carman permeability, ``(1 - eps)^2 rp_2C / eps^3``.""" + return (1.0 - eps) * (1.0 - eps) * eos.rp_2C / (eps * eps * eps) + + +@pk.function +def forchheimer(eps: float) -> float: + """Return the Forchheimer coefficient ``C_F = 1.75 eps / sqrt(150 eps^5)``.""" + return 1.75 * eps / pk.sqrt(150.0 * eps * eps * eps * eps * eps) + + +@pk.function +def vel(q: Prim, d: int) -> float: + """Return the velocity component d.""" + if d == 0: + return q.vx + if d == 1: + return q.vy + return q.vz + + +@pk.function +def set_vel(q: Prim, d: int, v: float) -> None: + """Set the velocity component d.""" + if d == 0: + q.vx = v + elif d == 1: + q.vy = v + else: + q.vz = v + + +@pk.function +def mom(u: Cons, d: int) -> float: + """Return the momentum component d (eps m V_d).""" + if d == 0: + return u.emx + if d == 1: + return u.emy + return u.emz + + +@pk.function +def set_mom(u: Cons, d: int, v: float) -> None: + """Set the momentum component d (eps m V_d).""" + if d == 0: + u.emx = v + elif d == 1: + u.emy = v + else: + u.emz = v + + +@pk.function +def speed(q: Prim, dim: int) -> float: + """Return the norm of the velocity.""" + v2: float = 0.0 + for d in range(dim): + v2 += vel(q, d) * vel(q, d) + return pk.sqrt(v2) + + +@pk.function +def cons_to_prim(w: Cons, p: Params, dim: int) -> Prim: + """Return the primitive state of the conservative state w.""" + r: Prim = Prim(w.em / w.eps, 0.0, 0.0, 0.0, 0.0, 0.0, w.eps) + ekin: float = 0.0 + for d in range(dim): + v: float = mom(w, d) / w.em + set_vel(r, d, v) + ekin += v * v + ekin *= 0.5 + eint: float = w.emE / w.em - ekin + r.P = eos_pressure(r.m, eint, p.eos) + r.T = eos_temperature(r.m, eint, p.eos) + return r + + +@pk.function +def prim_to_cons(q: Prim, p: Params, dim: int) -> Cons: + """Return the conservative state of the primitive state q.""" + w: Cons = Cons(q.m * q.eps, 0.0, 0.0, 0.0, 0.0, q.eps) + ekin: float = 0.0 + for d in range(dim): + set_mom(w, d, vel(q, d) * q.m * q.eps) + ekin += 0.5 * vel(q, d) * vel(q, d) + eint: float = eos_eint(q.m, q.P, p.eos) + w.emE = q.m * (eint + ekin) * q.eps + return w + + +@pk.function +def total_energy(q: Prim, eos: Eos, dim: int) -> float: + """Return the total energy per unit volume of the fluid (m E, not multiplied by eps) of q.""" + ekin: float = 0.0 + for d in range(dim): + ekin += 0.5 * q.m * vel(q, d) * vel(q, d) + return q.m * eos_eint(q.m, q.P, eos) + ekin + + +# ============================================================================= +# Arrays +# ============================================================================= +@pk.function +def load_cons(A: pk.View3D[pk.double], iOct: int, ic: int, dim: int) -> Cons: + """Return the conservative state of the cell ic of the octant iOct of the array A.""" + emz: float = 0.0 + if dim == 3: + emz = A[iOct][4][ic] + return Cons(A[iOct][0][ic], A[iOct][1][ic], A[iOct][2][ic], A[iOct][3][ic], emz, A[iOct][2 + dim][ic]) + + +@pk.function +def store_cons(A: pk.View3D[pk.double], iOct: int, ic: int, dim: int, u: Cons) -> None: + """Store the conservative state u in the cell ic of the octant iOct of the array A.""" + A[iOct][0][ic] = u.em + A[iOct][1][ic] = u.emE + A[iOct][2][ic] = u.emx + A[iOct][3][ic] = u.emy + if dim == 3: + A[iOct][4][ic] = u.emz + A[iOct][2 + dim][ic] = u.eps + + +@pk.function +def load_prim(A: pk.View3D[pk.double], iOct: int, ic: int, dim: int) -> Prim: + """Return the primitive state of the cell ic of the octant iOct of the array A.""" + vz: float = 0.0 + if dim == 3: + vz = A[iOct][5][ic] + return Prim(A[iOct][0][ic], A[iOct][1][ic], A[iOct][2][ic], A[iOct][3][ic], A[iOct][4][ic], vz, + A[iOct][3 + dim][ic]) + + +@pk.function +def store_prim(A: pk.View3D[pk.double], iOct: int, ic: int, dim: int, q: Prim) -> None: + """Store the primitive state q in the cell ic of the octant iOct of the array A.""" + A[iOct][0][ic] = q.m + A[iOct][1][ic] = q.P + A[iOct][2][ic] = q.T + A[iOct][3][ic] = q.vx + A[iOct][4][ic] = q.vy + if dim == 3: + A[iOct][5][ic] = q.vz + A[iOct][3 + dim][ic] = q.eps + + +# ============================================================================= +# Time step +# ============================================================================= +@pk.function +def hyperbolic_inv_dt(q: Prim, p: Params, h: float, dim: int) -> float: + """Return the inverse stable time step of the hyperbolic fluxes, ``sum_d (c + |V_d|) / h``.""" + eos: Eos = p.eos + c: float = eos_soundspeed(q.m, q.P, eos) + V: float = 0.0 + for d in range(dim): + V += c + pk.fabs(vel(q, d)) + return V / h + + +# ============================================================================= +# Geometry of the problems +# ============================================================================= +@pk.function +def dist2(x: float, y: float, z: float, xc: float, yc: float, zc: float, dim: int) -> float: + """Return the squared distance from (x, y, z) to the point (xc, yc, zc), z ignored in 2D.""" + d2: float = 0.0 + d2 += (x - xc) * (x - xc) + d2 += (y - yc) * (y - yc) + if dim == 3: + d2 += (z - zc) * (z - zc) + return d2 + + +# ============================================================================= +# Reconstruction of the face states (MUSCL), rotations +# ============================================================================= +@pk.function +def rotate_prim(q: Prim, d: int) -> None: + """Swap the velocity components x and d: the direction d becomes x, and back.""" + tmp: float = q.vx + if d == 1: + q.vx = q.vy + q.vy = tmp + elif d == 2: + q.vx = q.vz + q.vz = tmp + + +@pk.function +def rotate_cons(u: Cons, d: int) -> None: + """Swap the momentum components x and d: the direction d becomes x, and back.""" + tmp: float = u.emx + if d == 1: + u.emx = u.emy + u.emy = tmp + elif d == 2: + u.emx = u.emz + u.emz = tmp + + +@pk.function +def add_slope(q: Prim, S: pk.View3D[pk.double], iOct: int, ics: int, s: int, dim: int) -> None: + """Add s/2 times the slope of the cell ics to q (MUSCL reconstruction).""" + q.m += 0.5 * s * S[iOct][0][ics] + q.P += 0.5 * s * S[iOct][1][ics] + q.T += 0.5 * s * S[iOct][2][ics] + q.vx += 0.5 * s * S[iOct][3][ics] + q.vy += 0.5 * s * S[iOct][4][ics] + if dim == 3: + q.vz += 0.5 * s * S[iOct][5][ics] + q.eps += 0.5 * s * S[iOct][3 + dim][ics] + + +@pk.function +def combine_prim(a: Prim, wa: float, b: Prim, wb: float, dim: int) -> Prim: + """Return wa a + wb b, variable by variable (state and gradients at a face for the diffusion).""" + q: Prim = zero_prim() + q.m = wa * a.m + wb * b.m + q.P = wa * a.P + wb * b.P + q.T = wa * a.T + wb * b.T + for d in range(dim): + set_vel(q, d, wa * vel(a, d) + wb * vel(b, d)) + q.eps = wa * a.eps + wb * b.eps + return q + + +@pk.function +def face_state(Qg: pk.View3D[pk.double], S: pk.View3D[pk.double], iOct: int, c0: int, c1: int, c2: int, s: int, + so2: int, bx: int, dim: int) -> Prim: + """Return the state of the cell (c0, c1, c2) at its face of side s (+1 upper, -1 lower). + + MUSCL reconstruction: the state of the cell, plus half its slope at second order (so2 == 2). + """ + q: Prim = load_prim(Qg, iOct, cell_index(c0, c1, c2, bx + 4, 2, dim), dim) + if so2 == 2: + add_slope(q, S, iOct, cell_index(c0, c1, c2, bx + 2, 1, dim), s, dim) + return q + + +# ============================================================================= +# Walls: face states at the faces of the domain. Kinds of treatment (wall_kind of the boundary +# condition): 1 reflective, 2 no-slip, 3 outflow, 4 imposed state (the state of the ghost cell), +# 5 imposed pressure (the reconstructed face state of the ghost cell) +# ============================================================================= +@pk.function +def reverse_momenta(u: Cons, d: int, dim: int) -> None: + """Reverse the momentum component d, or every component when d < 0.""" + for k in range(dim): + if d < 0 or k == d: + set_mom(u, k, -mom(u, k)) + + +@pk.function +def reverse_velocities(q: Prim, d: int, noslip: int, dim: int) -> None: + """Reverse the velocity component d, or every component when noslip == 1.""" + for k in range(dim): + if noslip == 1 or k == d: + set_vel(q, k, -vel(q, k)) + + +@pk.function +def wall_face_state(kind: int, d: int, qin: Prim, qghost: Prim, qface: Prim, dim: int) -> Prim: + """Return the ghost face state at a face of the domain of normal d, for the kind of wall. + + qin is the face state of the inside cell, qghost the state of the ghost cell and qface the + reconstructed face state of the ghost cell. Kinds 1 to 3 take qin, with the normal velocity (1) + or every velocity (2) reversed, or unchanged (3); kind 4 takes qghost; the other kinds keep + qface. The porosity of the face state is that of the state taken. + """ + q: Prim = qface + if kind == 1 or kind == 2 or kind == 3: + # Reflective, no-slip, outflow: the inside face state, velocities reversed for the walls + q = qin + if kind != 3: + noslip: int = 0 + if kind == 2: + noslip = 1 + reverse_velocities(q, d, noslip, dim) + elif kind == 4: + q = qghost + # Kind 5: the reconstructed face state of the ghost cell; the ghost cells hold the imposed + # pressure at their centres, so the face gets the imposed pressure of the face + return q + + +@pk.function +def wall_gradient(kind: int, d: int, gin: Prim, dim: int) -> Prim: + """Return the difference of the ghost cell along a direction tangential to a face of normal d. + + It is the mirror image of that of the inside cell gin: gin with the normal velocity (kind 1) or + every velocity (kind 2) reversed, and zero for an imposed state (kind 4). + """ + g: Prim = gin + if kind == 4: + g = zero_prim() + elif kind == 1 or kind == 2: + noslip: int = 0 + if kind == 2: + noslip = 1 + reverse_velocities(g, d, noslip, dim) + return g + + +# ============================================================================= +# Fluxes of a face, derived output fields +# ============================================================================= +@pk.function +def derived_field(k: int, u: Cons, q: Prim, p: Params, dim: int) -> float: + """Return the derived output field k (variables of __init__.py); this model has none.""" + return 0.0 + + +@pk.function +def add_cons(F: Cons, D: Cons) -> None: + """Add the flux D to the flux F.""" + F.em += D.em + F.emE += D.emE + F.emx += D.emx + F.emy += D.emy + F.emz += D.emz + F.eps += D.eps + + +@pk.function +def store_flux(A: pk.View3D[pk.double], iOct: int, f: int, dim: int, F: Cons, dtdx: float) -> None: + """Store the flux F times dtdx = dt / h in the face f of the octant iOct of the array A.""" + A[iOct][0][f] = F.em * dtdx + A[iOct][1][f] = F.emE * dtdx + A[iOct][2][f] = F.emx * dtdx + A[iOct][3][f] = F.emy * dtdx + if dim == 3: + A[iOct][4][f] = F.emz * dtdx + A[iOct][2 + dim][f] = F.eps * dtdx + + +# ============================================================================= +# Refinement: relative jump of a scalar +# ============================================================================= +@pk.function +def scalar_gradient(qi: float, qj: float) -> float: + """Return the relative jump of a scalar between two neighbour cells, in [0, 1]. + + The jump is 0 when both values are below 0.001 in absolute value. + """ + mx: float = pk.fmax(pk.fabs(qi), pk.fabs(qj)) + if mx < 0.001: + return 0.0 + mx = pk.fabs(qi - qj) / mx + return pk.fmax(pk.fmin(mx, 1.0), 0.0) diff --git a/physics/porousflow/refine_conditions/P_gradient.py b/physics/porousflow/refine_conditions/P_gradient.py new file mode 100644 index 0000000..1d3537e --- /dev/null +++ b/physics/porousflow/refine_conditions/P_gradient.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""P_gradient: relative jump of the pressure P.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = True + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + return scalar_gradient(Qg[iOct][1][ia], Qg[iOct][1][ib]) diff --git a/physics/porousflow/refine_conditions/T_gradient.py b/physics/porousflow/refine_conditions/T_gradient.py new file mode 100644 index 0000000..ed752be --- /dev/null +++ b/physics/porousflow/refine_conditions/T_gradient.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""T_gradient: relative jump of the temperature T.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = True + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + return scalar_gradient(Qg[iOct][2][ia], Qg[iOct][2][ib]) diff --git a/physics/porousflow/refine_conditions/V_gradient.py b/physics/porousflow/refine_conditions/V_gradient.py new file mode 100644 index 0000000..fc2c4c9 --- /dev/null +++ b/physics/porousflow/refine_conditions/V_gradient.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""V_gradient: relative jump of the velocity V, max over the components.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = True + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + v: float = 0.0 + for d in range(dim): + v = pk.fmax(v, scalar_gradient(Qg[iOct][3 + d][ia], Qg[iOct][3 + d][ib])) + return v diff --git a/physics/porousflow/refine_conditions/__init__.py b/physics/porousflow/refine_conditions/__init__.py new file mode 100644 index 0000000..d924de2 --- /dev/null +++ b/physics/porousflow/refine_conditions/__init__.py @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Refinement criteria: one file per value of ``physics.refine_condition``. + +A refinement criterion file defines: + +- ``NEEDS_PRIMITIVE``: True when ``indicator`` reads the primitive variables ``Qg``; canoP computes + them before the refinement only in that case (True when the file does not define it). +- ``indicator(Ug, Qg, iOct, ia, ib, dim) -> float``: the refinement indicator between the cell + ``ia`` of the octant ``iOct`` and its neighbour ``ib``, indices in the ghosted blocks (``bx + 4`` + cells per side) of the conservative variables ``Ug`` and of the primitive variables ``Qg``. + ``scalar_gradient`` of ``model.py`` gives the relative jump of a scalar, in [0, 1]. + +An octant is refined when the indicator of one of its cells with one of its neighbours exceeds +``amr.epsilon_refine``, and coarsened when none reaches ``amr.epsilon_coarsen``, within the levels +allowed by the AMR settings. +""" diff --git a/physics/porousflow/refine_conditions/any_gradient.py b/physics/porousflow/refine_conditions/any_gradient.py new file mode 100644 index 0000000..4f1ebda --- /dev/null +++ b/physics/porousflow/refine_conditions/any_gradient.py @@ -0,0 +1,21 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""any_gradient: max of the criteria emV_gradient, emE_gradient, em_gradient and eps_gradient.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = False + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + v: float = 0.0 + for d in range(dim): + v = pk.fmax(v, scalar_gradient(Ug[iOct][2 + d][ia], Ug[iOct][2 + d][ib])) + v = pk.fmax(v, scalar_gradient(Ug[iOct][1][ia], Ug[iOct][1][ib])) + v = pk.fmax(v, scalar_gradient(Ug[iOct][0][ia], Ug[iOct][0][ib])) + return pk.fmax(v, scalar_gradient(Ug[iOct][2 + dim][ia], Ug[iOct][2 + dim][ib])) diff --git a/physics/porousflow/refine_conditions/emE_gradient.py b/physics/porousflow/refine_conditions/emE_gradient.py new file mode 100644 index 0000000..aa293f2 --- /dev/null +++ b/physics/porousflow/refine_conditions/emE_gradient.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""emE_gradient: relative jump of the energy per unit volume emE = eps m E.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = False + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + return scalar_gradient(Ug[iOct][1][ia], Ug[iOct][1][ib]) diff --git a/physics/porousflow/refine_conditions/emV_gradient.py b/physics/porousflow/refine_conditions/emV_gradient.py new file mode 100644 index 0000000..94afeec --- /dev/null +++ b/physics/porousflow/refine_conditions/emV_gradient.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""emV_gradient: relative jump of the momentum per unit volume emV = eps m V, max over the components.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = False + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + v: float = 0.0 + for d in range(dim): + v = pk.fmax(v, scalar_gradient(Ug[iOct][2 + d][ia], Ug[iOct][2 + d][ib])) + return v diff --git a/physics/porousflow/refine_conditions/em_gradient.py b/physics/porousflow/refine_conditions/em_gradient.py new file mode 100644 index 0000000..81bf3f7 --- /dev/null +++ b/physics/porousflow/refine_conditions/em_gradient.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""em_gradient: relative jump of the mass per unit volume em = eps m.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = False + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + return scalar_gradient(Ug[iOct][0][ia], Ug[iOct][0][ib]) diff --git a/physics/porousflow/refine_conditions/eps_gradient.py b/physics/porousflow/refine_conditions/eps_gradient.py new file mode 100644 index 0000000..f2ba7c4 --- /dev/null +++ b/physics/porousflow/refine_conditions/eps_gradient.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""eps_gradient: relative jump of the porosity eps.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = False + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + return scalar_gradient(Ug[iOct][2 + dim][ia], Ug[iOct][2 + dim][ib]) diff --git a/physics/porousflow/refine_conditions/m_gradient.py b/physics/porousflow/refine_conditions/m_gradient.py new file mode 100644 index 0000000..3ac2460 --- /dev/null +++ b/physics/porousflow/refine_conditions/m_gradient.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""m_gradient: relative jump of the density m of the fluid.""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + +#: True when the indicator reads the primitive variables Qg. +NEEDS_PRIMITIVE = True + + +@pk.function +def indicator(Ug: pk.View3D[pk.double], Qg: pk.View3D[pk.double], iOct: int, ia: int, ib: int, + dim: int) -> float: + return scalar_gradient(Qg[iOct][0][ia], Qg[iOct][0][ib]) diff --git a/physics/porousflow/relaxations/__init__.py b/physics/porousflow/relaxations/__init__.py new file mode 100644 index 0000000..b0e6bb7 --- /dev/null +++ b/physics/porousflow/relaxations/__init__.py @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Relaxations: one file per value of ``physics.relaxation`` (or ``none``). + +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 (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``). + +The model has ``darcy``, the Darcy-Forchheimer drag (``darcy.py``). +""" diff --git a/physics/porousflow/relaxations/darcy.py b/physics/porousflow/relaxations/darcy.py new file mode 100644 index 0000000..bae1834 --- /dev/null +++ b/physics/porousflow/relaxations/darcy.py @@ -0,0 +1,40 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""darcy: Darcy-Forchheimer drag of the porous medium, solved exactly after the time step. + +The drag ``D = -eps^2 mu V / k - eps^3 m C_F |V| V / sqrt(k)`` of the medium of permeability +``k = eps^3 / ((1 - eps)^2 rp_2C)`` (``param.eosFluid.mu``, ``param.eosFluid.rp_2C``) only changes +the momentum: the density m, the porosity and the direction of V stay, and the speed ``s = |V|`` +follows ``ds/dt = -a s - b s^2``, with ``a = eps mu / (k m)`` and ``b = eps^2 C_F / sqrt(k)`` +(``C_F = 1.75 eps / sqrt(150 eps^5)``). Its exact solution over the time step is:: + + V <- V exp(-a dt) / (1 + b |V| (1 - exp(-a dt)) / a) + +The relaxation is split from the fluxes and sources (first order in time where the drag acts, the +order of ``simulation.time_order`` elsewhere), and exact for any stiffness: a velocity is damped by +``exp(-a dt)``, where the source ``darcy`` integrated at each stage of the Runge-Kutta 2 damps it by +``(1 + exp(-2 a dt)) / 2``. The energy is unchanged: the kinetic energy lost heats the fluid. No drag +where ``eps = 1`` (infinite permeability). Use the source ``gravity`` for the gravity. +""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +@pk.function +def relaxation(w: Cons, qn: Prim, p: Params, dt: float, dim: int) -> None: + """Damp the momentum of w by the exact solution of the Darcy-Forchheimer drag over dt.""" + eos: Eos = p.eos + ik: float = inv_permeability(qn.eps, eos) + a: float = qn.eps * eos.mu * ik / qn.m + b: float = qn.eps * qn.eps * forchheimer(qn.eps) * pk.sqrt(ik) + x: float = a * dt + e: float = pk.exp(-x) + # (1 - exp(-a dt)) / a, by its series for a small a dt (no cancellation, a = 0 included) + f: float = dt * (1.0 - x * (0.5 - x * (1.0 / 6.0 - x / 24.0))) + if x > 1.0e-3: + f = (1.0 - e) / a + factor: float = e / (1.0 + b * speed(qn, dim) * f) + for d in range(dim): + set_mom(w, d, mom(w, d) * factor) diff --git a/physics/porousflow/sources/__init__.py b/physics/porousflow/sources/__init__.py new file mode 100644 index 0000000..1ee0892 --- /dev/null +++ b/physics/porousflow/sources/__init__.py @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Rate sources: one file per value of ``physics.source`` (or ``none``). + +A source file defines: + +- ``source(w, q, p, dt, dim)``: adds ``dt S(q)`` to the conservative state ``w`` of a cell, ``q`` + being the primitive state at the beginning of the stage. It applies at each stage of the time + integration, after the update by the fluxes. +""" diff --git a/physics/porousflow/sources/darcy.py b/physics/porousflow/sources/darcy.py new file mode 100644 index 0000000..04d6d86 --- /dev/null +++ b/physics/porousflow/sources/darcy.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""darcy: Darcy-Forchheimer drag of the porous medium, after the gravity. + +The gravity (``param.gravity_x``, ``param.gravity_y``, ``param.gravity_z``, zero by default) +adds ``eps m g`` to the momentum and ``eps m g.V`` to the energy, as the source ``gravity``. Then +the drag ``D = -eps^2 mu V / k - eps^3 m C_F |V| V / sqrt(k)`` of the medium of permeability +``k = eps^3 / ((1 - eps)^2 rp_2C)`` (``param.eosFluid.mu``, ``param.eosFluid.rp_2C``) is +integrated exactly over the time step with the coefficients frozen:: + + eps m V <- eps m V exp(-dt (eps mu / (k m) + eps^2 C_F |V| / sqrt(k))) + +with ``C_F = 1.75 eps / sqrt(150 eps^5)``, the speed ``|V|`` of the state at the beginning of the +stage and the density m of the state after the fluxes and the gravity. The energy is unchanged: +the kinetic energy lost heats the fluid. No drag where ``eps = 1`` (infinite permeability). + +As in canoP 2.x. With ``simulation.time_order = 2`` the drag is then of first order in time, and a +stiff drag damps a velocity by ``(1 + exp(-2 a dt)) / 2`` per step instead of ``exp(-a dt)``: the +relaxation ``darcy`` (exact solution after the time step) is preferable. +""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +@pk.function +def source(w: Cons, q: Prim, p: Params, dt: float, dim: int) -> None: + # Gravity + for d in range(dim): + set_mom(w, d, mom(w, d) + gravity(p, d) * q.m * dt * q.eps) + for d in range(dim): + w.emE += gravity(p, d) * q.m * vel(q, d) * dt * q.eps + # Darcy-Forchheimer drag, with the density of the updated state + eos: Eos = p.eos + qn: Prim = cons_to_prim(w, p, dim) + ik: float = inv_permeability(q.eps, eos) + cf: float = forchheimer(q.eps) + decay: float = pk.exp(-dt * eos.mu * ik * q.eps / qn.m - dt * cf * q.eps * q.eps * speed(q, dim) * pk.sqrt(ik)) + for d in range(dim): + set_mom(w, d, mom(w, d) * decay) diff --git a/physics/porousflow/sources/gravity.py b/physics/porousflow/sources/gravity.py new file mode 100644 index 0000000..fe1c5d9 --- /dev/null +++ b/physics/porousflow/sources/gravity.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""gravity: source ``eps m g`` of the momentum and ``eps m g.V`` of the energy. + +The gravity ``g`` is ``param.gravity_x``, ``param.gravity_y``, ``param.gravity_z`` (parameters of +the model). +""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +@pk.function +def source(w: Cons, q: Prim, p: Params, dt: float, dim: int) -> None: + for d in range(dim): + set_mom(w, d, mom(w, d) + gravity(p, d) * q.m * dt * q.eps) + for d in range(dim): + w.emE += gravity(p, d) * q.m * vel(q, d) * dt * q.eps diff --git a/physics/twophase5eq/hyperbolic_fluxes/__init__.py b/physics/twophase5eq/hyperbolic_fluxes/__init__.py index 6769574..649c810 100644 --- a/physics/twophase5eq/hyperbolic_fluxes/__init__.py +++ b/physics/twophase5eq/hyperbolic_fluxes/__init__.py @@ -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``. diff --git a/physics/twophase5eq/relaxations/__init__.py b/physics/twophase5eq/relaxations/__init__.py index fe3353d..4064f11 100644 --- a/physics/twophase5eq/relaxations/__init__.py +++ b/physics/twophase5eq/relaxations/__init__.py @@ -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``). """ diff --git a/physics/twophase7eq/hyperbolic_fluxes/__init__.py b/physics/twophase7eq/hyperbolic_fluxes/__init__.py index 6769574..649c810 100644 --- a/physics/twophase7eq/hyperbolic_fluxes/__init__.py +++ b/physics/twophase7eq/hyperbolic_fluxes/__init__.py @@ -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``. diff --git a/physics/twophase7eq/relaxations/__init__.py b/physics/twophase7eq/relaxations/__init__.py index fe3353d..4064f11 100644 --- a/physics/twophase7eq/relaxations/__init__.py +++ b/physics/twophase7eq/relaxations/__init__.py @@ -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``). """ diff --git a/settings/settings_porousflow_backward_facing_step.ini b/settings/settings_porousflow_backward_facing_step.ini new file mode 100644 index 0000000..85369cc --- /dev/null +++ b/settings/settings_porousflow_backward_facing_step.ini @@ -0,0 +1,87 @@ +[simulation] +; model: a directory of physics/ +model = porousflow +; final time +tmax = 300. +; CFL number +cfl = 0.125 +; order in space: 1, or 2 (MUSCL reconstruction) +space_order = 2 +; order in time: 1 (forward Euler) or 2 (SSP Runge-Kutta 2) +time_order = 2 +; slope limiter of the MUSCL reconstruction +scalar_limiter = minmod + +[amr] +; periodic directions (override physics.boundary_condition) +periodic_x = 0 +periodic_y = 0 +periodic_z = 0 +; trees of the brick per direction +ntree_x = 20 +ntree_y = 1 +ntree_z = 1 +; length of a tree +ltree = 2 +; cells of a block per direction (a power of 2, at least 4); cubic cells: by = bz = bx +bx = 4 +by = 4 +bz = 4 +; minimum level of the cells (2^level cells per tree and direction) +min_refine = 5 +; maximum level of the cells +max_refine = 5 +; a cell is refined when the refinement criterion exceeds epsilon_refine +epsilon_refine = 0.002 +; and coarsened when it is below epsilon_coarsen +epsilon_coarsen = 0.02 + +[io] +; prefix of the output files +output_prefix = porousflow_backward_facing_step +; number of outputs over the run (0: none, -1: every time step) +save_count = 300 +; derived fields written with the conservative variables +write_variables = V, eps, em, P + +[physics] +; initial condition: physics//initial_conditions/.py +initial_condition = backward_facing_step +; boundary condition: boundary_conditions/.py (overridden by amr if periodic) +boundary_condition = backward_facing_step +; refinement criterion: refine_conditions/.py +refine_condition = eps_gradient +; hyperbolic flux: hyperbolic_fluxes/.py, or none +hyperbolic_flux = allregime +; diffusion flux: diffusion_fluxes/.py, or none +diffusion_flux = viscosity +; relaxation after the time step: relaxations/.py, or none +relaxation = darcy +; source term: sources/.py, or none +source = none + +[backward_facing_step] +; channel 40 x 2 whose step (x < 4, y < 1) is a porous block of porosity eps0, parabolic inflow of +; mean velocity U_m above the step, Reynolds number m0 U_m 2 / mu = 500 (canoP 2.x +; settings_porous_backward_facing_steep_Re500.lua) +x_c = 2.0 +y_c = 0.5 +Lx = 4.0 +Ly = 1.0 +eps0 = 0.4 +m0 = 1.0 +P0 = 100.0 +U_m = 1.0 +inflow = 1 +y_step = 1.0 +y_top = 2.0 + +[param] +darcy_correction_enabled = 0 +lowmach_correction_enabled = 0 +eosFluid.gamma = 1.4 +eosFluid.Cv = 519.711426899086 +eosFluid.mu = 0.004 +eosFluid.eta = -0.002666667 +; Kozeny-Carman permeability eps^3 / ((1 - eps)^2 rp_2C) +eosFluid.rp_2C = 3.81111E7 diff --git a/settings/settings_porousflow_beavers_joseph.ini b/settings/settings_porousflow_beavers_joseph.ini new file mode 100644 index 0000000..e19e7df --- /dev/null +++ b/settings/settings_porousflow_beavers_joseph.ini @@ -0,0 +1,81 @@ +[simulation] +; model: a directory of physics/ +model = porousflow +; final time +tmax = 100. +; CFL number +cfl = 0.5 +; order in space: 1, or 2 (MUSCL reconstruction) +space_order = 2 +; order in time: 1 (forward Euler) or 2 (SSP Runge-Kutta 2) +time_order = 2 +; slope limiter of the MUSCL reconstruction +scalar_limiter = minmod + +[amr] +; periodic directions (override physics.boundary_condition) +periodic_x = 0 +periodic_y = 0 +periodic_z = 0 +; trees of the brick per direction +ntree_x = 1 +ntree_y = 1 +ntree_z = 1 +; length of a tree +ltree = 1 +; cells of a block per direction (a power of 2, at least 4); cubic cells: by = bz = bx +bx = 4 +by = 4 +bz = 4 +; minimum level of the cells (2^level cells per tree and direction) +min_refine = 5 +; maximum level of the cells +max_refine = 5 +; a cell is refined when the refinement criterion exceeds epsilon_refine +epsilon_refine = 0.005 +; and coarsened when it is below epsilon_coarsen +epsilon_coarsen = 0.01 + +[io] +; prefix of the output files +output_prefix = porousflow_beavers_joseph +; number of outputs over the run (0: none, -1: every time step) +save_count = 50 +; derived fields written with the conservative variables +write_variables = emV, em, P, T, V, eps + +[physics] +; initial condition: physics//initial_conditions/.py +initial_condition = beavers_joseph +; boundary condition: boundary_conditions/.py (overridden by amr if periodic) +boundary_condition = beavers_joseph +; refinement criterion: refine_conditions/.py +refine_condition = any_gradient +; hyperbolic flux: hyperbolic_fluxes/.py, or none +hyperbolic_flux = allregime +; diffusion flux: diffusion_fluxes/.py, or none +diffusion_flux = viscosity +; relaxation after the time step: relaxations/.py, or none +relaxation = darcy +; source term: sources/.py, or none +source = none + +[beavers_joseph] +; flow over a porous layer of porosity eps0 below y0, driven by the pressure gradient gradP +; (canoP 2.x settings_porous_joseph_beavers_darcy0.01.lua) +y0 = 0.5 +eps0 = 0.7 +tau = 50 +m0 = 0.2 +P0 = 1.000008 +gradP = -1E-6 + +[param] +; Darcy-Forchheimer drag in the interface velocity of the all-regime flux +darcy_correction_enabled = 1 +eosFluid.gamma = 1.4 +eosFluid.Cv = 519.711426899086 +eosFluid.mu = 1E-3 +eosFluid.eta = -0.666666666666667E-3 +; Kozeny-Carman permeability eps^3 / ((1 - eps)^2 rp_2C): Darcy number 0.01 in the layer (15244.4: 0.001) +eosFluid.rp_2C = 1524.44444444444 diff --git a/settings/settings_porousflow_poiseuille.ini b/settings/settings_porousflow_poiseuille.ini new file mode 100644 index 0000000..d1d124d --- /dev/null +++ b/settings/settings_porousflow_poiseuille.ini @@ -0,0 +1,83 @@ +[simulation] +; model: a directory of physics/ +model = porousflow +; final time +tmax = 400. +; CFL number +cfl = 0.125 +; order in space: 1, or 2 (MUSCL reconstruction) +space_order = 1 +; order in time: 1 (forward Euler) or 2 (SSP Runge-Kutta 2) +time_order = 1 +; slope limiter of the MUSCL reconstruction +scalar_limiter = minmod + +[amr] +; periodic directions (override physics.boundary_condition) +periodic_x = 0 +periodic_y = 0 +periodic_z = 0 +; trees of the brick per direction +ntree_x = 8 +ntree_y = 1 +ntree_z = 1 +; length of a tree +ltree = 1 +; cells of a block per direction (a power of 2, at least 4); cubic cells: by = bz = bx +bx = 4 +by = 4 +bz = 4 +; minimum level of the cells (2^level cells per tree and direction) +min_refine = 4 +; maximum level of the cells +max_refine = 4 +; a cell is refined when the refinement criterion exceeds epsilon_refine +epsilon_refine = 0.05 +; and coarsened when it is below epsilon_coarsen +epsilon_coarsen = 0.01 + +[io] +; prefix of the output files +output_prefix = porousflow_poiseuille +; number of outputs over the run (0: none, -1: every time step) +save_count = 100 +; derived fields written with the conservative variables +write_variables = V, eps, em, P + +[physics] +; initial condition: physics//initial_conditions/.py +initial_condition = poiseuille +; boundary condition: boundary_conditions/.py (overridden by amr if periodic) +boundary_condition = poiseuille +; refinement criterion: refine_conditions/.py +refine_condition = eps_gradient +; hyperbolic flux: hyperbolic_fluxes/.py, or none +hyperbolic_flux = allregime +; diffusion flux: diffusion_fluxes/.py, or none +diffusion_flux = viscosity +; relaxation after the time step: relaxations/.py, or none +relaxation = darcy +; source term: sources/.py, or none +source = none + +[poiseuille] +; porous block of porosity eps0 between x_1 and x_2 in a channel 8 x 1, flow driven by the pressure +; gradient gradP (canoP 2.x settings_porous_plug_darcy0.01.lua) +x_1 = 3.0 +x_2 = 5.0 +eps0 = 0.7 +tau = 50 +m0 = 0.2 +P0 = 1.0 +gradP = -1E-5 + +[param] +; Darcy-Forchheimer drag in the interface velocity of the all-regime flux +darcy_correction_enabled = 1 +lowmach_correction_enabled = 0 +eosFluid.gamma = 1.4 +eosFluid.Cv = 519.711426899086 +eosFluid.mu = 1E-3 +eosFluid.eta = -0.666666666666667E-3 +; Kozeny-Carman permeability eps^3 / ((1 - eps)^2 rp_2C): Darcy number 0.01 in the block (3811.1: 0.001) +eosFluid.rp_2C = 381.111111111 diff --git a/settings/settings_porousflow_riemann_problem.ini b/settings/settings_porousflow_riemann_problem.ini new file mode 100644 index 0000000..540c602 --- /dev/null +++ b/settings/settings_porousflow_riemann_problem.ini @@ -0,0 +1,80 @@ +[simulation] +; model: a directory of physics/ +model = porousflow +; final time +tmax = 0.2 +; CFL number +cfl = 0.5 +; order in space: 1, or 2 (MUSCL reconstruction) +space_order = 2 +; order in time: 1 (forward Euler) or 2 (SSP Runge-Kutta 2) +time_order = 2 +; slope limiter of the MUSCL reconstruction +scalar_limiter = minmod + +[amr] +; periodic directions (override physics.boundary_condition) +periodic_x = 0 +periodic_y = 0 +periodic_z = 0 +; trees of the brick per direction +ntree_x = 2 +ntree_y = 1 +ntree_z = 1 +; length of a tree +ltree = 0.5 +; cells of a block per direction (a power of 2, at least 4); cubic cells: by = bz = bx +bx = 4 +by = 4 +bz = 4 +; minimum level of the cells (2^level cells per tree and direction) +min_refine = 2 +; maximum level of the cells +max_refine = 6 +; a cell is refined when the refinement criterion exceeds epsilon_refine +epsilon_refine = 0.005 +; and coarsened when it is below epsilon_coarsen +epsilon_coarsen = 0.01 + +[io] +; prefix of the output files +output_prefix = porousflow_riemann_problem +; number of outputs over the run (0: none, -1: every time step) +save_count = 50 +; derived fields written with the conservative variables +write_variables = em, emV, emE, eps, m, P, V + +[physics] +; initial condition: physics//initial_conditions/.py +initial_condition = riemann_problem +; boundary condition: boundary_conditions/.py (overridden by amr if periodic) +boundary_condition = neuman +; refinement criterion: refine_conditions/.py +refine_condition = any_gradient +; hyperbolic flux: hyperbolic_fluxes/.py, or none +hyperbolic_flux = allregime +; diffusion flux: diffusion_fluxes/.py, or none +diffusion_flux = none +; relaxation after the time step: relaxations/.py, or none +relaxation = none +; source term: sources/.py, or none +source = none + +[riemann_problem] +; shock tube from a fluid (x < x0) into a porous medium of porosity 0.5 +x0 = 0.5 +m_left = 1.0 +P_left = 1.0 +Vx_left = 0.0 +Vy_left = 0.0 +Vz_left = 0.0 +eps_left = 1.0 +m_right = 0.125 +P_right = 0.1 +Vx_right = 0.0 +Vy_right = 0.0 +Vz_right = 0.0 +eps_right = 0.5 + +[param] +eosFluid.gamma = 1.4 diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3ea2529..388a593 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -21,7 +21,7 @@ add_test(NAME studio_i18n COMMAND ${Python3_EXECUTABLE} ${PROJECT_SOURCE_DIR}/to set_tests_properties(studio_i18n PROPERTIES LABELS unit) # physical properties without reference outputs (label "physics"), with canoP_2d -foreach(CHECK outflow mirror energy) +foreach(CHECK outflow mirror energy porous) add_test( NAME physics_${CHECK} COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/physics/physics.py ${CHECK} --exe-2d diff --git a/test/physics/physics.py b/test/physics/physics.py index cd03cc6..0ac1819 100644 --- a/test/physics/physics.py +++ b/test/physics/physics.py @@ -12,6 +12,10 @@ physics.py energy --exe-2d canoP_2d [--workdir DIR] the relaxations of the 7-equation model conserve the masses and the total energy in a closed domain + physics.py porous --exe-2d canoP_2d [--workdir DIR] + porousflow: a fluid at rest at uniform pressure stays at rest across jumps of porosity (AMR, + every term of the model); the Darcy-Forchheimer drag of a uniform flow follows its ODE; the + mass and the energy are conserved in a closed domain Exit code 77 (CTest SKIP_RETURN_CODE) when numpy or h5py is missing. """ @@ -29,7 +33,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(os.path.dirname(HERE), "regression")) import regression as reg # noqa: E402 -from cases import RELAXATIONS, SHOCK_TUBE_5EQ, SHOCK_TUBE_7EQ, TWO_PHASE, WALLS, Case # noqa: E402 +from cases import POROUS_TUBE, RELAXATIONS, SHOCK_TUBE_5EQ, SHOCK_TUBE_7EQ, TWO_PHASE, WALLS, Case # noqa: E402 def read(path, names): @@ -59,6 +63,9 @@ def outflow(args): (Case("outflow_twophase7eq", "settings_twophase7eq_rarefaction", 5, 0.1, dict(SHOCK_TUBE_7EQ, **{"amr.periodic_y": 0}), reference=None), ["mg", "ml", "ag", "mgEg", "mgVg_x", "mgVg_y", "mlVl_y"]), + (Case("outflow_porousflow", "settings_porousflow_riemann_problem", 5, 0.1, + dict(POROUS_TUBE, **{"amr.periodic_y": 0}), reference=None), + ["em", "emE", "emV_x", "emV_y", "eps"]), ] for case, names in cases: keys, data = read(reg.run_canop(case, args.exe_2d, os.path.join(args.workdir, case.name)), names) @@ -121,15 +128,80 @@ def energy(args): return check("relative change of the total energy", abs(E1 - E0) / E0, 1e-13) and ok +def time_of(path): + """time of an output""" + with h5py.File(path, "r") as f: + return float(f["run"].attrs["time"]) + + +def porous(args): + """porousflow: rest state across jumps of porosity, Darcy-Forchheimer drag, conservation""" + ok = True + # a fluid at rest at uniform pressure in a channel with a porous block: AMR on the porosity, + # second order, viscosity, Darcy correction of the flux and Darcy relaxation + case = Case("porous_rest", "settings_porousflow_poiseuille", (3, 5), 0.5, + {"poiseuille.gradP": 0.0, "simulation.space_order": 2, "simulation.time_order": 2, + "simulation.cfl": 0.5}, reference=None) + _, d = read(reg.run_canop(case, args.exe_2d, os.path.join(args.workdir, case.name)), + ["em", "emV_x", "emV_y", "eps", "P"]) + print(case.name + ": channel with a porous block (eps 1 to 0.7), at rest, AMR on eps") + c = np.sqrt(1.4 * d["P"].max() / (d["em"] / d["eps"]).min()) + v = np.hypot(d["emV_x"], d["emV_y"]) / d["em"] + ok = check("max |V| / c", v.max() / c, 1e-13) and ok + ok = check("max |P - P0| / P0", np.abs(d["P"] - 1.0).max(), 1e-13) and ok + + # uniform flow in a uniform medium (periodic): the fluxes cancel, the drag gives + # dV/dt = -(a + b |V|) V with a = mu eps / (k m), b = C_F eps^2 / sqrt(k) + eps, m, V0, mu, rp_2C = 0.5, 1.0, 0.1, 0.1, 1000.0 + uniform = {"amr.periodic_x": 1, "amr.periodic_y": 1, "param.eosFluid.mu": mu, "param.eosFluid.rp_2C": rp_2C, + "param.darcy_correction_enabled": 1} + for side in ("left", "right"): + uniform.update({"riemann_problem.m_" + side: m, "riemann_problem.P_" + side: 1.0, + "riemann_problem.Vx_" + side: V0, "riemann_problem.Vy_" + side: 0.0, + "riemann_problem.eps_" + side: eps}) + k = eps**3 / ((1 - eps)**2 * rp_2C) + a = mu * eps / (k * m) + b = 1.75 * eps / np.sqrt(150 * eps**5) * eps**2 / np.sqrt(k) + # the relaxation darcy is the exact solution, with Runge-Kutta 2; the source darcy, with forward + # Euler, is exact for a frozen |V| (the average of the two stages of Runge-Kutta 2 is not, when + # the drag is stiff) + for name, options, tol in (("porous_darcy", {"physics.relaxation": "darcy", "simulation.time_order": 2}, 1e-12), + ("porous_darcy_source", {"physics.source": "darcy", "simulation.time_order": 1}, 2e-3)): + case = Case(name, "settings_porousflow_riemann_problem", 5, 0.02, dict(uniform, **options), reference=None) + out = reg.run_canop(case, args.exe_2d, os.path.join(args.workdir, case.name)) + _, d = read(out, ["em", "emV_x"]) + t = time_of(out) + exact = a * V0 * np.exp(-a * t) / (a + b * V0 * (1 - np.exp(-a * t))) + V = d["emV_x"] / d["em"] + print(case.name + ": uniform flow in a medium of porosity 0.5, Darcy-Forchheimer drag (%s), " + "V(t) / V0 = %.4f" % (options.get("physics.relaxation", "source"), exact / V0)) + ok = check("max variation of V / V", np.ptp(V) / np.abs(V).max(), 1e-14) and ok + ok = check("|V - V_exact| / V_exact", np.abs(V - exact).max() / exact, tol) and ok + + # porous shock tube in a closed domain: the mass and the energy are conserved (not the + # momentum: the porosity jump exerts a force) + case = Case("porous_conservation", "settings_porousflow_riemann_problem", 5, 0.4, + dict(POROUS_TUBE, **WALLS, **{"physics.boundary_condition": "reflective"}), reference=None) + out = reg.run_canop(case, args.exe_2d, os.path.join(args.workdir, case.name)) + first = sorted(f for f in os.listdir(os.path.dirname(out)) if f.endswith(".h5") and "_iter" in f)[0] + _, d0 = read(os.path.join(os.path.dirname(out), first), ["em", "emE"]) + _, d1 = read(out, ["em", "emE"]) + print(case.name + ": porous shock tube between walls") + for n in ["em", "emE"]: + ok = check("relative change of the integral of %s" % n, abs(d1[n].sum() - d0[n].sum()) / d0[n].sum(), + 1e-13) and ok + return ok + + def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - p.add_argument("check", choices=["outflow", "mirror", "energy"]) + p.add_argument("check", choices=["outflow", "mirror", "energy", "porous"]) p.add_argument("--exe-2d", required=True) p.add_argument("--workdir", default=os.path.join(os.getcwd(), "physics_runs")) args = p.parse_args() args.exe_2d = os.path.abspath(args.exe_2d) try: - ok = {"outflow": outflow, "mirror": mirror, "energy": energy}[args.check](args) + ok = {"outflow": outflow, "mirror": mirror, "energy": energy, "porous": porous}[args.check](args) except RuntimeError as e: print(e) return 1 diff --git a/test/regression/cases.py b/test/regression/cases.py index bae4467..815aa76 100644 --- a/test/regression/cases.py +++ b/test/regression/cases.py @@ -56,8 +56,9 @@ def __init__(self, name, base, level, tmax, overrides=None, dim=2, reference="le "onephase": ["m", "mE", "mV"], "twophase5eq": ["mg", "ml", "mV", "mE", "ag"], "twophase7eq": ["mg", "mgVg", "mgEg", "ml", "mlVl", "mlEl", "ag"], + "porousflow": ["em", "emE", "emV", "eps"], } -VECTORS = {"mV", "mgVg", "mlVl"} +VECTORS = {"mV", "mgVg", "mlVl", "emV"} #: two different phases (the two-phase settings files use two identical phases) TWO_PHASE = { @@ -124,6 +125,25 @@ def _b7(name): return "settings_twophase7eq_" + name +def _pf(name): + return "settings_porousflow_" + name + + +#: porous shock tube with porosities 0.8 and 0.5 and a transverse velocity, periodic along y +POROUS_TUBE = { + "amr.periodic_y": 1, + "riemann_problem.eps_left": 0.8, + "riemann_problem.Vx_left": 0.3, + "riemann_problem.Vy_left": 0.2, + "riemann_problem.Vy_right": -0.1, +} +#: Darcy-Forchheimer drag in the flux and as a relaxation after the time step +DARCY = {"param.darcy_correction_enabled": 1, "physics.relaxation": "darcy", "param.eosFluid.mu": 0.001, + "param.eosFluid.rp_2C": 10000.0} +#: the drag as a source at each stage, as in canoP 2.x +DARCY_SOURCE = dict(DARCY, **{"physics.relaxation": "none", "physics.source": "darcy"}) + + CASES = [ # ---- the settings files of settings/ Case("onephase_blast", _mono("blast"), 5, 0.1), @@ -225,6 +245,54 @@ def _b7(name): # refinement criterion on a primitive variable Case("onephase_blast_amr_pressure", _mono("blast"), (4, 6), 0.05, {"physics.refine_condition": "P_gradient"}, reference="canop"), +] + [ + # ---- porousflow. The hyperbolic flux, the Darcy correction, the low Mach corrections and the + # sources match canoP 2.x (porousfluid of the branch 38-correct-diffusion-flux-discretization-SEL, + # with the porosities eps_left, eps_right in its riemann_problem) to 1e-14 on these shock + # tubes at time_order = 1, the drag being the source darcy; the references are by canoP. + Case("porousflow_riemann_problem", _pf("riemann_problem"), 5, 0.1, POROUS_TUBE, reference="canop"), + Case("porousflow_riemann_problem_first_order", _pf("riemann_problem"), 5, 0.1, + dict(POROUS_TUBE, **{"simulation.space_order": 1, "simulation.time_order": 1}), reference="canop"), + Case("porousflow_riemann_problem_darcy", _pf("riemann_problem"), 5, 0.1, dict(POROUS_TUBE, **DARCY), + reference="canop"), + Case("porousflow_riemann_problem_darcy_source", _pf("riemann_problem"), 5, 0.1, + dict(POROUS_TUBE, **DARCY_SOURCE, **{"simulation.time_order": 1}), reference="canop"), +] + [ + Case("porousflow_riemann_problem_darcy_lowmach%d" % k, _pf("riemann_problem"), 5, 0.1, + dict(POROUS_TUBE, **DARCY, **{"param.lowmach_correction_enabled": 1, "param.lowmach_correction_scheme": k}), + reference="canop") + for k in (1, 2, 3) +] + [ + Case("porousflow_riemann_problem_walls_gravity", _pf("riemann_problem"), 5, 0.15, + dict(POROUS_TUBE, **WALLS, **{"physics.boundary_condition": "noslip", "physics.source": "gravity", + "param.gravity_x": -1.0, "param.gravity_y": 0.5, + "physics.diffusion_flux": "conductivity", "param.eosFluid.kappa": 0.001}), + reference="canop"), + Case("porousflow_riemann_problem_dirichlet", _pf("riemann_problem"), 5, 0.1, + dict(POROUS_TUBE, **WALLS, **{"physics.boundary_condition": "dirichlet", + "simulation.space_order": 1, "simulation.time_order": 1, + "dirichlet.face0.m": 1.2, "dirichlet.face0.P": 1.5, "dirichlet.face0.Vx": 0.4, + "dirichlet.face0.eps": 0.8, "dirichlet.face1.m": 0.125, + "dirichlet.face1.P": 0.1, "dirichlet.face1.eps": 0.5, + "dirichlet.face2.eps": 0.8, "dirichlet.face3.eps": 0.8}), + reference="canop"), + Case("porousflow_poiseuille", _pf("poiseuille"), 4, 2.0, reference="canop"), + Case("porousflow_beavers_joseph", _pf("beavers_joseph"), 4, 1.0, reference="canop"), + Case("porousflow_backward_facing_step", _pf("backward_facing_step"), 3, 1.0, reference="canop"), + Case("porousflow_plug_flow", _pf("poiseuille"), 4, 0.5, + {"physics.initial_condition": "plug_flow", "physics.boundary_condition": "plug_flow", + "plug_flow.m0": 0.2, "plug_flow.P0": 1.0, "plug_flow.Vx_in": 0.05}, reference="canop"), + Case("porousflow_flow_around_cylinder", _pf("backward_facing_step"), 4, 0.5, + {"amr.ntree_x": 4, "amr.ltree": 1, "physics.initial_condition": "flow_around_cylinder", + "physics.boundary_condition": "flow_around_cylinder", "flow_around_cylinder.x_c": 1.0, + "flow_around_cylinder.y_c": 0.5, "flow_around_cylinder.radius": 0.2}, reference="canop"), + Case("porousflow_riemann_problem_amr", _pf("riemann_problem"), (3, 6), 0.1, + dict(POROUS_TUBE, **DARCY, **{"simulation.time_order": 2, "physics.refine_condition": "any_gradient"}), + reference="canop"), + Case("porousflow_riemann_problem_3d", _pf("riemann_problem"), 4, 0.1, dict(POROUS_TUBE, **DARCY, + **{"amr.periodic_z": 1, "riemann_problem.Vz_left": 0.1}), dim=3, reference="canop"), + Case("porousflow_poiseuille_amr", _pf("poiseuille"), (3, 5), 1.0, + {"physics.refine_condition": "eps_gradient"}, reference="canop"), ] CASES_BY_NAME = {c.name: c for c in CASES} diff --git a/test/regression/references/porousflow_backward_facing_step.h5 b/test/regression/references/porousflow_backward_facing_step.h5 new file mode 100644 index 0000000..6e14a0d Binary files /dev/null and b/test/regression/references/porousflow_backward_facing_step.h5 differ diff --git a/test/regression/references/porousflow_beavers_joseph.h5 b/test/regression/references/porousflow_beavers_joseph.h5 new file mode 100644 index 0000000..d65e0eb Binary files /dev/null and b/test/regression/references/porousflow_beavers_joseph.h5 differ diff --git a/test/regression/references/porousflow_flow_around_cylinder.h5 b/test/regression/references/porousflow_flow_around_cylinder.h5 new file mode 100644 index 0000000..33b3b54 Binary files /dev/null and b/test/regression/references/porousflow_flow_around_cylinder.h5 differ diff --git a/test/regression/references/porousflow_plug_flow.h5 b/test/regression/references/porousflow_plug_flow.h5 new file mode 100644 index 0000000..7118adc Binary files /dev/null and b/test/regression/references/porousflow_plug_flow.h5 differ diff --git a/test/regression/references/porousflow_poiseuille.h5 b/test/regression/references/porousflow_poiseuille.h5 new file mode 100644 index 0000000..26259ab Binary files /dev/null and b/test/regression/references/porousflow_poiseuille.h5 differ diff --git a/test/regression/references/porousflow_poiseuille_amr.h5 b/test/regression/references/porousflow_poiseuille_amr.h5 new file mode 100644 index 0000000..00bc5cc Binary files /dev/null and b/test/regression/references/porousflow_poiseuille_amr.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem.h5 b/test/regression/references/porousflow_riemann_problem.h5 new file mode 100644 index 0000000..6941e8d Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_3d.h5 b/test/regression/references/porousflow_riemann_problem_3d.h5 new file mode 100644 index 0000000..7616289 Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_3d.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_amr.h5 b/test/regression/references/porousflow_riemann_problem_amr.h5 new file mode 100644 index 0000000..0b95c0c Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_amr.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_darcy.h5 b/test/regression/references/porousflow_riemann_problem_darcy.h5 new file mode 100644 index 0000000..844f57d Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_darcy.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_darcy_lowmach1.h5 b/test/regression/references/porousflow_riemann_problem_darcy_lowmach1.h5 new file mode 100644 index 0000000..9e359b7 Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_darcy_lowmach1.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_darcy_lowmach2.h5 b/test/regression/references/porousflow_riemann_problem_darcy_lowmach2.h5 new file mode 100644 index 0000000..8d7b865 Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_darcy_lowmach2.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_darcy_lowmach3.h5 b/test/regression/references/porousflow_riemann_problem_darcy_lowmach3.h5 new file mode 100644 index 0000000..7bddcab Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_darcy_lowmach3.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_darcy_source.h5 b/test/regression/references/porousflow_riemann_problem_darcy_source.h5 new file mode 100644 index 0000000..a85b702 Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_darcy_source.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_dirichlet.h5 b/test/regression/references/porousflow_riemann_problem_dirichlet.h5 new file mode 100644 index 0000000..94e6cf8 Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_dirichlet.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_first_order.h5 b/test/regression/references/porousflow_riemann_problem_first_order.h5 new file mode 100644 index 0000000..3bb2372 Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_first_order.h5 differ diff --git a/test/regression/references/porousflow_riemann_problem_walls_gravity.h5 b/test/regression/references/porousflow_riemann_problem_walls_gravity.h5 new file mode 100644 index 0000000..07dd9d9 Binary files /dev/null and b/test/regression/references/porousflow_riemann_problem_walls_gravity.h5 differ diff --git a/tools/canop_core.py b/tools/canop_core.py index dcad412..2d80780 100644 --- a/tools/canop_core.py +++ b/tools/canop_core.py @@ -644,7 +644,8 @@ def choices_for(entry, model): "``none``.", ("physics", "diffusion_flux"): "Diffusion flux (viscosity, heat conduction): a file of " "``physics//diffusion_fluxes/``, or ``none``.", - ("physics", "relaxation"): "Instantaneous relaxation: a file of ``physics//relaxations/``, or ``none``.", + ("physics", "relaxation"): "Relaxation after the time step (projection on an equilibrium, or stiff source " + "solved exactly): a file of ``physics//relaxations/``, or ``none``.", ("physics", "source"): "Source term: a file of ``physics//sources/``, or ``none``.", ("diagnostic", "conservativity_checks"): "Print the volume integrals of the conservative variables at the " "beginning and at the end of the run.",