Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ The user-visible changes of canoP, by version (see `CONTRIBUTING.md` for the ver

## Unreleased

- All-regime GRU scheme (Glimm Random Upwind) for a sharp material interface, ported from the branch
implem-gru: `simulation.gru_enabled = 1`, for the model `twophase5eq` (`physics/twophase5eq/gru.py`,
impedance factor `param.K`). First order; the volume fraction stays exactly 0 or 1; transport and
pressure work conservative across AMR levels; well-balanced gravity with walls and AMR. Options
`simulation.gru_coarsen`, `gru_omega0`, `gru_omega0_amr`. `settings_twophase5eq_gru_square.ini`,
whose `gru_enabled = 1` was ignored, now runs with GRU.
- canoP studio with VS Code Remote-SSH, where code-server is not allowed: the user guide describes the
installation, the canoP icon and Claude Code (proxy of the Claude API); `open_studio` of the MCP
bridge recognises a Remote-SSH window and points to the canoP icon or the Ports panel of VS Code
Expand Down
7 changes: 6 additions & 1 deletion docs/developer-guide/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ src/
├── canoP.cpp main program, compiled once per dimension (canoP_2d, canoP_3d)
├── Simulation.h the solver: mesh, ghost cells, time integration, AMR, outputs
├── Simulation_impl.h
├── scheme/ finite volume kernels: slopes, update, Runge-Kutta, scheme options, limiters
├── scheme/ finite volume kernels: slopes, update, Runge-Kutta, scheme options, limiters, GRU
├── python/ embedded interpreter and the model seen by the solver
└── settings/ parameters of a run and their translation for kalypsso-core
physics/ the models, in Python with pykokkos (see the physics guide)
Expand All @@ -38,6 +38,11 @@ cells. A time step:
4. for `time_order = 2`, does a second stage and averages (`scheme/RungeKutta.h`);
5. applies the relaxations of the model.

With `simulation.gru_enabled = 1`, steps 2 to 4 are the GRU scheme (`scheme/GRU.h`): the interface
states of the faces (model), the upwind transport with a random draw at the material interface, the
end of the update (model); after an AMR cycle, refined cells copy their parent and coarsened cells
crossed by the interface take the state of one child (`gru::RemapFunctor`).

The mesh is adapted with the refinement criterion of the model every `amr.cycle_frequency` steps (every
step by default), and the load is balanced between the MPI processes every
`amr.load_balancing_frequency` steps.
Expand Down
4 changes: 2 additions & 2 deletions docs/developer-guide/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Configure with `-DCANOP_ENABLE_TESTING=ON`, then:
cd _build
ctest -L unit # variables, limiters, settings (googletest)
ctest -L regression # short runs compared with reference outputs
ctest -L physics # physical properties: symmetry, conservation
ctest -L physics # physical properties: symmetry, conservation, GRU
```

The regression and physics tests need `python3` with numpy and h5py.
Expand All @@ -32,7 +32,7 @@ for a push that changes the documentation alone); its check, `Build and tests (O
to merge into `main` (see `CONTRIBUTING.md`). It is a build of canoP for CPUs (OpenMP) on Ubuntu
24.04 with gcc, OpenMPI and HDF5, then all the tests (unit, regression, physics), a skipped test
counting as a failure. ccache keeps the compilations from one run to the next, and the kernels of
the physics compiled by pykokkos are kept too (49 kernels, about 4 minutes to compile): a run takes a
the physics compiled by pykokkos are kept too (53 kernels, about 4 minutes to compile): a run takes a
few minutes, about 15 without these caches. A failed test is reported as an annotation of the run,
and the logs and input files of its runs of canoP are kept for 7 days as an artifact of the run
(`logs`).
Expand Down
3 changes: 2 additions & 1 deletion docs/physics-guide/kernels.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ loop of `loops.py`, in `<build>/pykokkos_cache/sources/<model>/<kernel>_<hash>.p
the option files are renamed (`initial_state` of `blast.py` becomes `initial_state_ic_blast`) and the
kernel calls the option of the run through its index. A file of options is therefore in the kernels of
its category whatever the option of the run: an error in `blast.py` stops the runs of the model with
another initial condition too.
another initial condition too. The kernels of the GRU scheme (`gru_*_kernel`, with `gru.py` of the
model) are assembled only for the runs with `simulation.gru_enabled = 1`.

## Compilation and cache

Expand Down
1 change: 1 addition & 0 deletions docs/physics-guide/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ physics/
└── <model>/ one directory per model (simulation.model)
├── __init__.py variables(dim) and params(dim) of the model
├── model.py states, equation of state, conversions, reconstruction, walls
├── gru.py what the model gives to the GRU scheme (optional)
├── initial_conditions/ one file per value of physics.initial_condition
├── boundary_conditions/ ... of physics.boundary_condition
├── refine_conditions/ ... of physics.refine_condition
Expand Down
4 changes: 3 additions & 1 deletion docs/physics-guide/writing-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,6 @@ define its own helper functions with `@pk.function`; they are visible only in it

A model is a directory of `physics/` with `__init__.py` (`variables(dim)`, `params(dim)`),
`model.py` and the directories of its options; `simulation.model = <directory>` selects it. Copy the
closest model and change its variables, states and equation of state.
closest model and change its variables, states and equation of state. A model may add `gru.py`, what
it gives to the GRU scheme (`simulation.gru_enabled`): its colour variable `COLOUR` and the functions
`gru_star`, `gru_gravity`, `gru_hydrostatic` and `gru_finish` (see `physics/twophase5eq/gru.py`).
2 changes: 2 additions & 0 deletions docs/user-guide/input-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ P_in = 10.0
first or second order in space (MUSCL reconstruction of the primitive variables with a scalar
limiter) and in time (forward Euler or SSP Runge-Kutta 2). Use `time_order = 2` with
`space_order = 2`: forward Euler with the MUSCL reconstruction is only held by the limiter.
`gru_enabled = 1` selects the GRU scheme, for a sharp interface between two fluids (see
{doc}`models`).

`[amr]`
: The mesh: a brick of `ntree_x` x `ntree_y` (x `ntree_z`) trees of length `ltree`, each one refined
Expand Down
31 changes: 30 additions & 1 deletion docs/user-guide/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ transport of the volume fraction as a non-conservative product
`mV_y` (`mV_z`), total energy `mE`, volume fraction of the gas `ag`;
- fluxes: HLLC and all-regime, each face with a left and a right flux that differ by the
non-conservative product;
- viscous and thermal fluxes, gravity.
- viscous and thermal fluxes, gravity;
- the GRU scheme for a sharp interface between the gas and the liquid (below).

## twophase7eq

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

## GRU scheme

`simulation.gru_enabled = 1` replaces the scheme by the all-regime GRU scheme (Glimm Random Upwind,
[ghost GRU](https://hal.science/hal-05315640)) for the models with a `gru.py` (`twophase5eq`): the
volume fraction of the gas stays exactly 0 or 1, a sharp interface without numerical mixing.

- First order in space and time (`space_order` and `time_order` are set to 1). The velocity u* and
pressure P* of each face come from an acoustic solver with one impedance `K max(m c)` of the two
cells (`param.K`) and the low Mach correction of `param.lowmach_correction_enabled`;
`physics.hyperbolic_flux` is not used.
- Away from the interface a cell follows the upwind transport at u*, with the pressure work of P*.
A cell that receives fluid of the other colour takes the state of one of its incoming neighbours,
or keeps its own, drawn with probabilities proportional to the volumes that enter it. There is
one sample per time step for all the cells (a low-discrepancy sequence from
`simulation.gru_omega0`). Mass and energy are conserved exactly away from the interface, in
expectation at the interface.
- AMR: the transport and the pressure work are conservative at coarse/fine faces. A refined cell
copies its parent; with `simulation.gru_coarsen = 1` (the default) a coarsened cell crossed by
the interface takes the state of one of its children, drawn with one sample for all the cells
(from `simulation.gru_omega0_amr`), so that straight interfaces stay straight. The refinement
criterion `ag_gradient` keeps the interface in the finest cells: the mesh is adapted at every
time step and the interface moves by less than a cell per step.
- Gravity (`param.gravity_*`) is in the scheme and well balanced: a fluid at rest in the discrete
hydrostatic equilibrium, `P(j+1) - P(j) = (m(j) + m(j+1)) / 2 g h` with the density jump on a face,
stays exactly at rest, with reflective walls and AMR. `physics.source` must be `none`.
- The transport needs `sum_d dt |u*_d| / dx <= 1`: `simulation.cfl <= 0.8` is safe.
- The samples are not saved in the restart files: a restart starts them again.

## Common numerics

- MUSCL reconstruction of the primitive variables with the limiters minmod, maxmod, mc, smart,
Expand Down
95 changes: 87 additions & 8 deletions physics/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,23 +137,27 @@ def _is_pk(node, text):
ast.get_source_segment(text, d).startswith("pk.") for d in node.decorator_list)


def option_host(model, category, name):
"""Return the namespace of the host side of an option file (``params``, ``NEEDS_PRIMITIVE``).
def host_namespace(path, name):
"""Return the namespace of the host side of a file of the physics.

The file is executed without its pykokkos functions and classes and without its relative
imports: the classes that its kernels use (``Prim``, ``ICParameters``, ...) exist only in the
file of a kernel.
"""
path = option_path(model, category, name)
with open(path, encoding="utf-8") as f:
text = f.read()
tree = ast.parse(text, filename=path)
tree.body = [n for n in tree.body if not _is_pk(n, text) and not (isinstance(n, ast.ImportFrom) and n.level > 0)]
namespace = {"__name__": "physics_option_%s_%s_%s" % (model, category, name), "__file__": path}
namespace = {"__name__": name, "__file__": path}
exec(compile(tree, path, "exec"), namespace) # pylint: disable=exec-used
return namespace


def option_host(model, category, name):
"""Return the namespace of the host side of an option file (``params``, ``NEEDS_PRIMITIVE``)."""
return host_namespace(option_path(model, category, name), "physics_option_%s_%s_%s" % (model, category, name))


@contextlib.contextmanager
def _defaults():
"""Read the parameters with their default values, without recording them in the run."""
Expand All @@ -179,6 +183,12 @@ def option_path(model, category, name):
return os.path.join(MODELS_DIR, model, category, name + ".py")


def gru_path(model):
"""Return the path of <model>/gru.py, what the model gives to the GRU scheme, or None without it."""
path = os.path.join(MODELS_DIR, model, "gru.py")
return path if os.path.isfile(path) else None


# =============================================================================
# Views
# =============================================================================
Expand Down Expand Up @@ -463,6 +473,13 @@ def _switch(index, cases, indent=" "):
# State and gradients at a face given to diffusion_flux (loops.fluxes_kernel)
_GRADIENTS = "q: Prim, g0: Prim, g1: Prim, g2: Prim"
_GRADIENT_NAMES = "q, g0, g1, g2"
# Interface state of a face of the GRU scheme, written by gru_star of <model>/gru.py
_GRU_STAR = """@pk.classtype
class GruStar:
def __init__(self, u: float, p: float, rho: float):
self.u: float = u
self.p: float = p
self.rho: float = rho"""


class Physics:
Expand Down Expand Up @@ -512,6 +529,25 @@ def index(selection, category, first):
self.eps_refine = get_real("amr", "epsilon_refine", 0.01)
self.eps_coarsen = get_real("amr", "epsilon_coarsen", 0.001)

# GRU scheme (simulation.gru_enabled, src/scheme/GRU.h): what the model gives to it, in
# <model>/gru.py, whose COLOUR is the conservative variable of the colour
self.gru = get_int("simulation", "gru_enabled", 0) != 0
self.gru_colour = -1
gru = gru_path(model)
if gru:
colour = host_namespace(gru, "physics_gru_%s" % model).get("COLOUR")
if colour not in self.vars["conservative"]:
raise ValueError("physics/%s/gru.py: COLOUR = %r is not a conservative variable of the model (%s)"
% (model, colour, ", ".join(self.vars["conservative"])))
self.gru_colour = self.vars["conservative"].index(colour)
if self.gru:
if not gru:
raise ValueError("simulation.gru_enabled = 1: the model %s has no physics/%s/gru.py, the GRU scheme is "
"not available for it" % (model, model))
if self.source != 0:
raise ValueError("simulation.gru_enabled = 1: the GRU scheme has the gravity of the model in its "
"interface states (well balanced) and no other source: physics.source must be none")

# Named parameters of the options of the run: {name: value}
ic = option_host(model, "initial_conditions", initial[1])
self.ic_params = ic["params"](dim) if "params" in ic else {}
Expand Down Expand Up @@ -624,7 +660,18 @@ def _kernels(self, initial, boundary):
"return %d" % (1 if self.vars["nonconservative"] else 0)])
diffusion = self._parts("diffusion_fluxes")
boundaries = self._parts("boundary_conditions")
return {
kernels = {}
if self.gru:
# GRU: the functions of <model>/gru.py, and the class of its interface states
gru = [("gru.py", entities(gru_path(m)))]
star = [_piece(_GRU_STAR, None)]
kernels = {
"gru_ghosts_kernel": kernel_module(m, "gru_ghosts_kernel", model + star, gru),
"gru_faces_kernel": kernel_module(m, "gru_faces_kernel", model + bc + star, gru + boundaries,
[wall_kind]),
"gru_finish_kernel": kernel_module(m, "gru_finish_kernel", model + star, gru),
"gru_shift_kernel": kernel_module(m, "gru_shift_kernel", model + star, gru)}
return kernels | {
"fields_kernel": kernel_module(m, "fields_kernel", model),
"cons_to_prim_kernel": kernel_module(m, "cons_to_prim_kernel", model),
"inv_dt_kernel": kernel_module(m, "inv_dt_kernel", model, diffusion, [diffusion_inv_dt, inv_dt]),
Expand All @@ -643,11 +690,13 @@ def _kernels(self, initial, boundary):
def variables(self):
"""Return the variables of the model.

Names of the conservative and primitive variables and of the output fields, and whether the
model has non-conservative products.
Names of the conservative and primitive variables and of the output fields, whether the
model has non-conservative products, and the index of the colour variable of the GRU scheme
(-1 when the model has no gru.py).
"""
return {"conservative": list(self.vars["conservative"]), "primitive": list(self.vars["primitive"]),
"fields": [f[0] for f in self.vars["fields"]], "nonconservative": bool(self.vars["nonconservative"])}
"fields": [f[0] for f in self.vars["fields"]], "nonconservative": bool(self.vars["nonconservative"]),
"gru_colour": int(self.gru_colour)}

def output_fields(self, U, Q, out, num_owned, fields):
"""Compute the output fields of index fields (in variables()["fields"]) of the owned octants."""
Expand Down Expand Up @@ -749,3 +798,33 @@ def refine_flags(self, Ug, Qg, flags, num_owned, level_min, level_max):
run_teams(num_owned, size, self.K["refine_kernel"], Ug=view(Ug), Qg=view(Qg), flags=view(flags, np.int32),
level=self.level, level_min=level_min, level_max=level_max, eps_refine=self.eps_refine,
eps_coarsen=self.eps_coarsen, criterion=self.criterion, bx=self.bx, dim=self.dim)

# ---- GRU scheme (simulation.gru_enabled, src/scheme/GRU.h)
def gru_ghosts(self, Ug, coarser, num_owned):
"""With gravity, give the hydrostatic pressure to the ghost cells of the owned blocks copied from a coarser
neighbour (faces of bit ``2 d + side`` in coarser)."""
if num_owned > 0:
nt = self.bx ** (self.dim - 1)
run(num_owned * 4 * self.dim * nt, self.K["gru_ghosts_kernel"], Ug=view(Ug),
coarser=view(coarser, np.int32), dx=self.dx, par=self.par, bx=self.bx, dim=self.dim)

def gru_faces(self, dr, Qg, faces, num_all):
"""Compute the interface states faces (``gru::FaceVar``) of the faces normal to dr of num_all octants."""
if num_all > 0:
nf = self.bx ** (self.dim - 1) * (self.bx + 1)
run(num_all * nf, self.K["gru_faces_kernel"], Qg=view(Qg), faces=view(faces), centers=self.centers,
par=self.par, bpar=self.bpar, dx=self.dx, border=self.border, periodic=self.periodic, dr=dr,
dim=self.dim, bx=self.bx, boundary=self.boundary)

def gru_finish(self, Uin, Uout, work, num_owned):
"""End the update of the owned cells of Uout (work: ``gru::WorkVar``, Uin: state at the start of the step)."""
if num_owned > 0:
run(num_owned * self.ncells, self.K["gru_finish_kernel"], Uin=view(Uin), Uout=view(Uout), work=view(work),
par=self.par, ncells=self.ncells, dim=self.dim)

def gru_shift(self, U, offsets, num_owned):
"""With gravity, give the hydrostatic pressure of their new position to the states moved by an AMR cycle
(offsets: new minus old position)."""
if num_owned > 0:
run(num_owned * self.ncells, self.K["gru_shift_kernel"], U=view(U), offsets=view(offsets), par=self.par,
ncells=self.ncells, dim=self.dim)
Loading
Loading