diff --git a/CHANGELOG.md b/CHANGELOG.md index eaee7cb..e108f31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/developer-guide/architecture.md b/docs/developer-guide/architecture.md index b553eba..8973c7f 100644 --- a/docs/developer-guide/architecture.md +++ b/docs/developer-guide/architecture.md @@ -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) @@ -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. diff --git a/docs/developer-guide/tests.md b/docs/developer-guide/tests.md index c979c66..fee2568 100644 --- a/docs/developer-guide/tests.md +++ b/docs/developer-guide/tests.md @@ -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. @@ -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`). diff --git a/docs/physics-guide/kernels.md b/docs/physics-guide/kernels.md index 6bc794a..2d9e2a3 100644 --- a/docs/physics-guide/kernels.md +++ b/docs/physics-guide/kernels.md @@ -14,7 +14,8 @@ loop of `loops.py`, in `/pykokkos_cache/sources//_.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 diff --git a/docs/physics-guide/overview.md b/docs/physics-guide/overview.md index 890eadd..beb17ad 100644 --- a/docs/physics-guide/overview.md +++ b/docs/physics-guide/overview.md @@ -19,6 +19,7 @@ physics/ └── / 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 diff --git a/docs/physics-guide/writing-options.md b/docs/physics-guide/writing-options.md index bebf398..9e2f5b6 100644 --- a/docs/physics-guide/writing-options.md +++ b/docs/physics-guide/writing-options.md @@ -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 = ` 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`). diff --git a/docs/user-guide/input-file.md b/docs/user-guide/input-file.md index e6d4a8e..57bd94d 100644 --- a/docs/user-guide/input-file.md +++ b/docs/user-guide/input-file.md @@ -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 diff --git a/docs/user-guide/models.md b/docs/user-guide/models.md index e8ead47..d07f0bf 100644 --- a/docs/user-guide/models.md +++ b/docs/user-guide/models.md @@ -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 @@ -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, diff --git a/physics/common.py b/physics/common.py index b196ba1..64fbecd 100644 --- a/physics/common.py +++ b/physics/common.py @@ -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.""" @@ -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 /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 # ============================================================================= @@ -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 /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: @@ -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 + # /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 {} @@ -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 /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]), @@ -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.""" @@ -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) diff --git a/physics/loops.py b/physics/loops.py index cd8bfcd..ce799b5 100644 --- a/physics/loops.py +++ b/physics/loops.py @@ -35,7 +35,10 @@ (``initial_conditions``), ``ghost_state`` and ``wall_kind`` (``boundary_conditions``), ``riemann`` (``hyperbolic_fluxes``), ``diffusion_flux`` (``diffusion_fluxes``), ``inv_dt`` (``hyperbolic_inv_dt`` of ``model.py`` and ``diffusion_fluxes``), ``sources`` (``sources``), - ``relaxations`` (``relaxations``), ``indicator`` (``refine_conditions``). + ``relaxations`` (``relaxations``), ``indicator`` (``refine_conditions``); +- from ``/gru.py``, in the kernels of the GRU scheme only (``simulation.gru_enabled``, + ``src/scheme/GRU.h``): ``gru_star`` (interface state of a face, in the class ``GruStar`` written + by ``common.Physics``), ``gru_gravity``, ``gru_hydrostatic`` and ``gru_finish``. """ # The functions of the model and of the options are defined in the assembled file of each kernel # pylint: disable=undefined-variable @@ -489,3 +492,196 @@ def cell_marks(ic: int, acc: pk.Acc[pk.double]): elif level[iOct] < level_max and refine == 1: flag = 1 flags[iOct] = flag + + + +# ============================================================================= +# GRU scheme (simulation.gru_enabled, src/scheme/GRU.h): functions of /gru.py +# ============================================================================= +@pk.workunit +def gru_ghosts_kernel(i: int, Ug: pk.View3D[pk.double], coarser: pk.View1D[pk.int32], dx: pk.View1D[pk.double], + par: pk.View1D[pk.double], bx: int, dim: int) -> None: + """GRU with gravity: hydrostatic pressure of the ghost cell i of an owned block copied from a coarser neighbour. + + The ghost cells of the faces whose neighbour is coarser (bit ``face`` of ``coarser``) are copies of + the coarse cells: each gets the pressure of its own centre (``gru_hydrostatic``), ``g.(x - x_c)`` + with ``x - x_c = (parity - 1/2) h`` along each direction, the parity being that of the cell in + the fine grid. Without gravity the cells are not changed. + """ + nt: int = bx + if dim == 3: + nt = bx * bx + per: int = 4 * dim * nt + iOct: int = i // per + r: int = i % per + face: int = r // (2 * nt) + if bit(coarser[iOct], face) == 1: + layer: int = (r // nt) % 2 + t0: int = (r % nt) % bx + t1: int = (r % nt) // bx + # along the normal, the layer 0 is the one next to the block + a: int = -1 - layer + if face % 2 == 1: + a = bx + layer + c0: int = a + c1: int = t0 + c2: int = t1 + if face // 2 == 1: + c0 = t0 + c1 = a + elif face // 2 == 2: + c0 = t0 + c1 = t1 + c2 = a + mp: ModelParameters = model_parameters(par) + p: Params = make_params(mp) + h: float = dx[iOct] + gdx: float = gru_gravity(p, 0) * ((c0 + 4) % 2 - 0.5) * h + gru_gravity(p, 1) * ((c1 + 4) % 2 - 0.5) * h + if dim == 3: + gdx += gru_gravity(p, 2) * ((c2 + 4) % 2 - 0.5) * h + if gdx != 0.0: + ic: int = cell_index(c0, c1, c2, bx + 4, 2, dim) + u: Cons = load_cons(Ug, iOct, ic, dim) + q: Prim = cons_to_prim(u, p, dim) + gru_hydrostatic(q, gdx) + w: Cons = prim_to_cons(q, p, dim) + store_cons(Ug, iOct, ic, dim, w) + + +@pk.workunit +def gru_faces_kernel(i: int, Qg: pk.View3D[pk.double], faces: pk.View3D[pk.double], centers: pk.View3D[pk.double], + par: pk.View1D[pk.double], bpar: pk.View1D[pk.double], dx: pk.View1D[pk.double], + border: pk.View1D[pk.int32], periodic: pk.View1D[pk.int32], dr: int, dim: int, bx: int, + boundary: int) -> None: + """GRU: interface state of the face i normal to dr, from the states of its two cells (first order). + + faces receives, in the order of ``gru::FaceVar``: u*, p*, p* u*, g rho* and g rho* u*, g being the + gravity along dr (``gru_star`` and ``gru_gravity`` of the model). At a wall of the domain + (reflective or no-slip ``wall_kind``) the ghost state is the mirror of the inside cell with the + hydrostatic pressure of its centre, so that a fluid at rest stays at rest. + """ + # Faces of a block: bx + 1 along dr, bx along the other directions; the face r lies between the + # cells l = r - 1 and r along dr + n0: int = bx + n1: int = bx + n2: int = bx + if dr == 0: + n0 = bx + 1 + elif dr == 1: + n1 = bx + 1 + else: + n2 = bx + 1 + nf: int = n0 * n1 * n2 + if dim == 2: + nf = n0 * n1 + iOct: int = i // nf + f: int = i % nf + r0: int = f % n0 + r1: int = (f // n0) % n1 + r2: int = 0 + if dim == 3: + r2 = f // (n0 * n1) + l0: int = r0 + l1: int = r1 + l2: int = r2 + rc: int = r0 + if dr == 0: + l0 = r0 - 1 + elif dr == 1: + l1 = r1 - 1 + rc = r1 + else: + l2 = r2 - 1 + rc = r2 + h: float = dx[iOct] + mp: ModelParameters = model_parameters(par) + p: Params = make_params(mp) + g: float = gru_gravity(p, dr) + + qL: Prim = load_prim(Qg, iOct, cell_index(l0, l1, l2, bx + 4, 2, dim), dim) + qR: Prim = load_prim(Qg, iOct, cell_index(r0, r1, r2, bx + 4, 2, dim), dim) + # Faces of the domain: ghost state of the boundary condition + upper: int = -1 + if rc == 0: + upper = 0 + elif rc == bx: + upper = 1 + if upper >= 0: + face: int = 2 * dr + upper + if periodic[dr] == 0 and bit(border[iOct], face) == 1: + # Inside cell + i0: int = r0 + i1: int = r1 + i2: int = r2 + if upper == 1: + i0 = l0 + i1 = l1 + i2 = l2 + ici: int = cell_index(i0, i1, i2, bx, 0, dim) + zc: float = 0.0 + if dim == 3: + zc = centers[iOct][2][ici] + kind: int = wall_kind(boundary, face, centers[iOct][0][ici], centers[iOct][1][ici], zc, h, bpar, dim) + if kind != 0: + if upper == 1: + qR = wall_face_state(kind, dr, qL, qR, qR, dim) + if kind == 1 or kind == 2: + gru_hydrostatic(qR, g * h) + else: + qL = wall_face_state(kind, dr, qR, qL, qL, dim) + if kind == 1 or kind == 2: + gru_hydrostatic(qL, -g * h) + + rotate_prim(qL, dr) + rotate_prim(qR, dr) + s: GruStar = GruStar(0.0, 0.0, 0.0) + gru_star(qL, qR, p, g * h, dim, s) + faces[iOct][0][f] = s.u + faces[iOct][1][f] = s.p + faces[iOct][2][f] = s.p * s.u + faces[iOct][3][f] = g * s.rho + faces[iOct][4][f] = g * s.rho * s.u + + +@pk.workunit +def gru_finish_kernel(i: int, Uin: pk.View3D[pk.double], Uout: pk.View3D[pk.double], work: pk.View3D[pk.double], + par: pk.View1D[pk.double], ncells: int, dim: int) -> None: + """GRU: end of the update of the cell i of Uout (``gru_finish`` of the model). + + work holds, in the order of ``gru::WorkVar``: 1 if the state was drawn among the donors (else 0), + the non-conservative upwind transport of the colour variable c, ``sum_k a_k (c_k - c)``, and dt + times the pressure work and gravity of the momentum (3 components) and of the energy. Uin is the + state at the beginning of the time step. + """ + iOct: int = i // ncells + ic: int = i % ncells + mp: ModelParameters = model_parameters(par) + p: Params = make_params(mp) + uc: Cons = load_cons(Uin, iOct, ic, dim) + w: Cons = load_cons(Uout, iOct, ic, dim) + gru_finish(w, uc, int(work[iOct][0][ic]), work[iOct][1][ic], work[iOct][2][ic], work[iOct][3][ic], + work[iOct][4][ic], work[iOct][5][ic], p, dim) + store_cons(Uout, iOct, ic, dim, w) + + +@pk.workunit +def gru_shift_kernel(i: int, U: pk.View3D[pk.double], offsets: pk.View3D[pk.double], par: pk.View1D[pk.double], + ncells: int, dim: int) -> None: + """GRU with gravity: hydrostatic pressure of the cell i moved by an AMR cycle. + + offsets holds the new minus the old position of the state of the cell (zero when it did not move); the + state gets ``gru_hydrostatic`` with ``g.offsets``. Without gravity the cells are not changed. + """ + iOct: int = i // ncells + ic: int = i % ncells + mp: ModelParameters = model_parameters(par) + p: Params = make_params(mp) + gdx: float = gru_gravity(p, 0) * offsets[iOct][0][ic] + gru_gravity(p, 1) * offsets[iOct][1][ic] + if dim == 3: + gdx += gru_gravity(p, 2) * offsets[iOct][2][ic] + if gdx != 0.0: + u: Cons = load_cons(U, iOct, ic, dim) + q: Prim = cons_to_prim(u, p, dim) + gru_hydrostatic(q, gdx) + w: Cons = prim_to_cons(q, p, dim) + store_cons(U, iOct, ic, dim, w) diff --git a/physics/twophase5eq/__init__.py b/physics/twophase5eq/__init__.py index 215a5d0..33f16cf 100644 --- a/physics/twophase5eq/__init__.py +++ b/physics/twophase5eq/__init__.py @@ -37,13 +37,15 @@ volume fractions (``diffusion_fluxes``); - ``gravity_x``, ``gravity_y``, ``gravity_z``: gravity (``sources/gravity.py``); - ``lowmach_correction_enabled``: 1: low Mach correction of the all-regime flux - (``hyperbolic_fluxes/allregime.py``); -- ``eos_g.qp``, ``eos_l.qp``, ``K``: read but not used. + (``hyperbolic_fluxes/allregime.py``) and of the GRU scheme (``gru.py``); +- ``K``: factor of the acoustic impedance of the GRU scheme (``gru.py``); +- ``eos_g.qp``, ``eos_l.qp``: read but not used. 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. +``model.py`` and may call its functions and their own. ``gru.py`` is what the model gives to the +all-regime GRU scheme (``simulation.gru_enabled = 1``), which keeps ag strictly 0 or 1. """ from physics.common import AXES, get_int, get_real @@ -95,6 +97,6 @@ def params(dim): res["gravity_z"] = get_real("param", "gravity_z", 0.0) res["lowmach"] = get_int("param", "lowmach_correction_enabled", 0) - get_real("param", "K", 1.1) + res["K"] = get_real("param", "K", 1.1) return res diff --git a/physics/twophase5eq/gru.py b/physics/twophase5eq/gru.py new file mode 100644 index 0000000..e991eb6 --- /dev/null +++ b/physics/twophase5eq/gru.py @@ -0,0 +1,97 @@ +# SPDX-FileCopyrightText: 2025 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""GRU: the model twophase5eq in the all-regime GRU scheme (``simulation.gru_enabled = 1``). + +GRU (Glimm Random Upwind, https://hal.science/hal-05315640, ``src/scheme/GRU.h``) keeps the gas +volume fraction ag strictly 0 (liquid) or 1 (gas): the colour of a cell is 1 when ag >= 0.5. Away +from the interface it is an upwind transport at the velocity u* of the faces, with the pressure +work of p*; at the interface a cell takes the state of one of its incoming donors, drawn at random. + +Interface state of a face, along its normal x, from the states qL and qR of its two cells (first +order), with the impedance ``a = K max(mL cL, mR cR)`` (``param.K``) and ``m* = (mL + mR) / 2``:: + + u* = (uL + uR) / 2 - (PR - PL - m* g h) / (2 a) + theta = min(|u*| / max(cL, cR), 1) (param.lowmach_correction_enabled, else 1) + P* = (PL + PR) / 2 - theta a (uR - uL) / 2 + +``g h`` is the gravity along the normal (``param.gravity_*``) times the distance between the +centres of the cells. With the source ``dt g m*`` of the momentum at the faces (``src/scheme/GRU.h``), +the discrete hydrostatic equilibrium ``PR - PL = m* g h``, at rest, is exactly preserved: the +gravity is in the scheme, ``physics.source`` must be none. + +The functions called by the kernels of the GRU scheme (``physics/loops.py``): + +- ``gru_star(qL, qR, p, gh, dim, s)``: the interface state (``s.u`` = u*, ``s.p`` = P*, + ``s.rho`` = m*); +- ``gru_gravity(p, d)``: the component d of the gravity; +- ``gru_hydrostatic(q, gdx)``: the pressure of a state moved by a distance dx, ``P + m g.dx`` (ghost + cells of the walls and of the coarse/fine faces, states moved by the AMR); +- ``gru_finish(w, uc, drawn, dag, dm0, dm1, dm2, dE, p, dim)``: the end of the update of a cell. +""" +import pykokkos as pk + +from .model import * # noqa: F401,F403 (states and physics of the model) + +# The colour of a cell: the conservative variable ag (colour 1 when ag >= 0.5) +COLOUR = "ag" + + +# GruStar (fields u, p, rho) is written by physics.common in the file of each kernel of the GRU scheme +@pk.function +def gru_star(qL: Prim, qR: Prim, p: Params, gh: float, dim: int, + s: GruStar) -> None: # pylint: disable=undefined-variable + """Interface state of a face along x: u*, P* and the density m* of the face.""" + mL: float = qL.mg + qL.ml + mR: float = qR.mg + qR.ml + cL: float = soundspeed(qL, p) + cR: float = soundspeed(qR, p) + a: float = p.K * pk.fmax(mL * cL, mR * cR) + s.rho = 0.5 * (mL + mR) + s.u = 0.5 * (qL.vx + qR.vx) - 0.5 * (qR.P - qL.P - s.rho * gh) / a + theta: float = 1.0 + if p.lowmach != 0: + theta = pk.fmin(pk.fabs(s.u) / pk.fmax(cL, cR), 1.0) + s.p = 0.5 * (qL.P + qR.P) - 0.5 * (qR.vx - qL.vx) * a * theta + + +@pk.function +def gru_gravity(p: Params, d: int) -> float: + """Return the component d of the gravity.""" + return gravity(p, d) + + +@pk.function +def gru_hydrostatic(q: Prim, gdx: float) -> None: + """Move the state q by dx in hydrostatic equilibrium: gdx = g.dx, P += m g.dx.""" + q.P += (q.mg + q.ml) * gdx + + +@pk.function +def gru_finish(w: Cons, uc: Cons, drawn: int, dag: float, dm0: float, dm1: float, dm2: float, dE: float, p: Params, + dim: int) -> None: + """End of the update of a cell: w is its transported or drawn state, uc its state at the beginning of the step. + + A drawn state gets the sharp colour of its ag: pure gas or pure liquid of the same density. Otherwise + the volume fraction follows ``d_t ag + V.grad(ag) = 0`` in upwind form, ``ag + dag`` with + ``dag = sum_k a_k (ag_k - ag)`` over the incoming donors k, which keeps a uniform ag exactly 0 or 1; + ag stays in [0, 1] and the partial densities non-negative. Then the pressure work and the gravity + of the momentum and of the energy. + """ + if drawn == 1: + c: float = 0.0 + if w.ag >= 0.5: + c = 1.0 + m: float = w.mg + w.ml + w.ag = c + w.mg = m * c + w.ml = m * (1.0 - c) + else: + w.ag = pk.fmin(1.0, pk.fmax(0.0, uc.ag + dag)) + w.mg = pk.fmax(0.0, w.mg) + w.ml = pk.fmax(0.0, w.ml) + w.mx += dm0 + w.my += dm1 + if dim == 3: + w.mz += dm2 + w.E += dE diff --git a/physics/twophase5eq/model.py b/physics/twophase5eq/model.py index 2e9b060..9152c43 100644 --- a/physics/twophase5eq/model.py +++ b/physics/twophase5eq/model.py @@ -73,13 +73,15 @@ def __init__(self, mg: float, ml: float, mx: float, my: float, mz: float, E: flo # Parameters of the model, built by make_params @pk.classtype class Params: - def __init__(self, eg: Eos, el: Eos, gravity_x: float, gravity_y: float, gravity_z: float, lowmach: int): + def __init__(self, eg: Eos, el: Eos, gravity_x: float, gravity_y: float, gravity_z: float, lowmach: int, + K: float): self.eg: Eos = eg self.el: Eos = el self.gravity_x: float = gravity_x self.gravity_y: float = gravity_y self.gravity_z: float = gravity_z self.lowmach: int = lowmach + self.K: float = K @@ -88,7 +90,7 @@ def make_params(m: ModelParameters) -> Params: """Return the parameters of the model from the named parameters (params of __init__.py).""" eg: Eos = Eos(m.eos_g_gamma, m.eos_g_q, m.eos_g_b, m.eos_g_pinf, m.eos_g_Cv, m.eos_g_mu, m.eos_g_eta, m.eos_g_kappa) el: Eos = Eos(m.eos_l_gamma, m.eos_l_q, m.eos_l_b, m.eos_l_pinf, m.eos_l_Cv, m.eos_l_mu, m.eos_l_eta, m.eos_l_kappa) - return Params(eg, el, m.gravity_x, m.gravity_y, m.gravity_z, m.lowmach) + return Params(eg, el, m.gravity_x, m.gravity_y, m.gravity_z, m.lowmach, m.K) @pk.function def gravity(p: Params, d: int) -> float: diff --git a/src/Simulation.h b/src/Simulation.h index cc56a5f..732e9d1 100644 --- a/src/Simulation.h +++ b/src/Simulation.h @@ -32,6 +32,10 @@ * \f] * The instantaneous relaxations of the 7-equation model (projections onto the equilibrium) are * then applied to \f$ U^{n+1} \f$. + * + * `simulation.gru_enabled = 1` replaces the stages by the all-regime GRU scheme, first order, which + * keeps the colour of a material interface strictly 0 or 1 (scheme/GRU.h, + * Simulation::gru_time_step, for the models with a `physics//gru.py`). */ #ifndef CANOP_SIMULATION_H_ #define CANOP_SIMULATION_H_ @@ -57,6 +61,7 @@ #endif #include +#include #include #include @@ -166,6 +171,24 @@ class Simulation : public kalypsso::SolverBase */ void fill_ghosted_cons(DataArrayBlock_t data, bool with_mpi_ghosts); + //! Fill the blocks of m_Ug of the MPI ghost octants: those of the mirror octants of their owners. + void + exchange_ghosted(); + /** + * \brief One time step of the GRU scheme (`simulation.gru_enabled`, scheme/GRU.h): interface + * states (physics), upwind transport with the draw at the material interface, end of the + * update (physics), relaxations. + */ + void + gru_time_step(real_t dt); + //! The faces of the owned octants whose neighbor is coarser (m_gru_coarser), after a change of + //! the mesh. + void + gru_update_coarser(); + //! GRU after the remap of an AMR cycle (m_U old state, m_U2 remapped state): copy on refinement, + //! draw on coarsening across the interface, hydrostatic pressure of the moved states. + void + gru_remap(amr_hashmap_t hashmap_before); private: //! Initial condition, refined level by level from `amr.level_min` to `amr.level_max`. @@ -240,6 +263,18 @@ class Simulation : public kalypsso::SolverBase DataArrayBlock_t m_FluxesL[3], m_FluxesR[3]; Kokkos::View m_mirror_ids; //!< local index of the mirror octants + // GRU (simulation.gru_enabled) + //! Global samples of the transport and of the AMR. + gru::Sampler m_gru_sampler; + //! Interface states of the faces of each direction (gru::FaceVar). + DataArrayBlock_t m_GruFaces[3]; + //! Work array of the owned cells (gru::WorkVar). + DataArrayBlock_t m_GruWork; + //! New minus old position of the states moved by an AMR cycle. + DataArrayBlock_t m_GruOffsets; + //! Faces of the owned octants whose neighbor is coarser (bit `2 dir + side`). + Kokkos::View m_gru_coarser; + #ifdef KALYPSSO_CORE_USE_HDF5 std::shared_ptr m_hdf5_writer; #endif diff --git a/src/Simulation_impl.h b/src/Simulation_impl.h index 08d2798..17afe0d 100644 --- a/src/Simulation_impl.h +++ b/src/Simulation_impl.h @@ -25,6 +25,7 @@ # include #endif +#include #include #include #include @@ -106,6 +107,21 @@ Simulation::Simulation(ParallelEnv const & par_env, if (m_physics->nonconservative()) m_FluxesR[d] = DataArrayBlock_t(std::string("FluxesR_") + axis[d], fs, ncons, 0); } + if (m_opt.gru) + { + if (m_physics->gru_colour() < 0) + throw std::runtime_error("simulation.gru_enabled = 1: the model " + m_model + + " has no physics/" + m_model + "/gru.py (GRU scheme)"); + m_gru_sampler.omega = m_opt.gru_omega0; + m_gru_sampler.omega_amr = m_opt.gru_omega0_amr; + for (size_t d = 0; d < dim; ++d) + m_GruFaces[d] = DataArrayBlock_t(std::string("GruFaces_") + axis[d], + kalypsso::get_flux_block_sizes(m_block_sizes, d), + gru::NFACE, + 0); + m_GruWork = DataArrayBlock_t("GruWork", m_block_sizes, gru::NWORK, 0); + m_GruOffsets = DataArrayBlock_t("GruOffsets", m_block_sizes, int(dim), 0); + } if (settings.getInteger("run", "restart_enabled", 0)) init_restart(); @@ -123,6 +139,13 @@ Simulation::Simulation(ParallelEnv const & par_env, KALYPSSO_INFO("Boundary condition is {}", settings.getString("physics", "boundary_condition", "neuman")); KALYPSSO_INFO("================================================"); params.print(); + if (m_opt.gru) + KALYPSSO_INFO("Scheme is GRU (all-regime, sharp colour {}), first order", + cons_names()[m_physics->gru_colour()]); + if (m_opt.gru_forced_order) + KALYPSSO_WARN( + "simulation.gru_enabled = 1: the GRU scheme is first order, simulation.space_order and " + "time_order are set to 1"); if (m_opt.space_order == 2 and m_opt.time_order == 1) KALYPSSO_WARN("simulation.space_order = 2 with simulation.time_order = 1: forward Euler is anti-diffusive " "with the MUSCL reconstruction, only the limiter holds it (oscillations at the scale of the " @@ -247,6 +270,13 @@ Simulation::resize_auxiliary_data() if (m_physics->nonconservative()) m_FluxesR[d].resize(num_owned + num_ghosts); } + if (m_opt.gru) + { + for (size_t d = 0; d < dim; ++d) + m_GruFaces[d].resize(num_owned + num_ghosts); + m_GruWork.resize(num_owned); + gru_update_coarser(); + } // the physics keeps the geometry of the mesh m_physics->update_mesh(mesh_context()); } @@ -309,10 +339,16 @@ Simulation::fill_ghosted_cons(DataArrayBlock_t data, bool with_mp m_brick_sizes, m_is_brick_periodic); - if (not with_mpi_ghosts) - return; + if (with_mpi_ghosts) + exchange_ghosted(); +} +template +void +Simulation::exchange_ghosted() +{ #ifdef KALYPSSO_CORE_USE_MPI + const auto num_owned = m_mesh_map->get_amr_mesh_info().local_num_quadrants(); const auto num_ghosts = m_amr_mesh->local_num_ghosts(); const auto num_mirrors = m_amr_mesh->local_num_mirrors(); const auto block_len = m_Ug.flat_view().extent(0) / std::max(1, m_Ug.data().num_quadrants()); @@ -385,6 +421,8 @@ Simulation::adapt_mesh_and_remap() const auto n = m_mesh_map->get_amr_mesh_info().local_num_quadrants_total(); m_U2.resize(n); remapper.remap_block_data(exec_space, m_U, m_U2); + if (m_opt.gru) + gru_remap(hashmap_before); kalypsso::my_swap(m_U, m_U2); m_U2.resize(n); Kokkos::deep_copy(exec_space, m_U2.logical_view(), m_U.logical_view()); @@ -471,6 +509,12 @@ template void Simulation::time_step(real_t dt) { + if (m_opt.gru) + { + gru_time_step(dt); + return; + } + const auto num_owned = m_mesh_map->get_amr_mesh_info().local_num_quadrants(); if (m_opt.time_order == 2) @@ -489,6 +533,115 @@ Simulation::time_step(real_t dt) Kokkos::deep_copy(m_U.logical_view(), m_U2.logical_view()); } +// ============================================================================= +// GRU scheme (simulation.gru_enabled, scheme/GRU.h) +// ============================================================================= +template +void +Simulation::gru_time_step(real_t dt) +{ + const auto num_owned = m_mesh_map->get_amr_mesh_info().local_num_quadrants(); + const auto num_all = num_owned + m_amr_mesh->local_num_ghosts(); + const real_t omega = m_gru_sampler.next(); + + // ghost cells: with gravity, those copied from a coarser neighbor get the hydrostatic pressure of + // their position before the blocks of the MPI ghost octants are exchanged + synchronize_mpi_ghost_data(m_U); + fill_boundaries(m_U); + fill_ghosted_cons(m_U, false); + m_physics->gru_ghosts(m_Ug, m_gru_coarser, num_owned); + exchange_ghosted(); + m_physics->cons_to_prim(m_Ug, m_Qg, num_all); + + // interface states of every face (boundary faces with the boundary conditions) + const auto mesh = mesh_context(); + for (size_t dir = 0; dir < dim; ++dir) + m_physics->gru_faces(mesh, int(dir), m_Qg, m_GruFaces[dir]); + + // upwind transport, with the draw at the material interface + Kokkos::deep_copy(m_U2.logical_view(), m_U.logical_view()); + const gru::UpdateFunctor update{ + typename KernelTypes::StencilHelper_t(m_mesh_map->hashmap(), + m_mesh_map->orchard_keys(), + m_U.block_size(), + m_brick_sizes, + m_is_brick_periodic), + m_mesh_map->orchard_keys(), + m_mesh_map->conformal_status(), + m_Ug, + { m_GruFaces[0], m_GruFaces[1], m_GruFaces[2] }, + m_U2, + m_GruWork, + to_icoord(m_block_sizes), + m_physics->ncons(), + m_physics->gru_colour(), + m_scaling_factor, + dt, + omega + }; + gru::UpdateFunctor::apply(update, num_owned); + + // sharp colour, transport of the colour, pressure work and gravity + m_physics->gru_finish(m_U, m_U2, m_GruWork, num_owned); + + m_physics->relaxations(m_U, m_U2, num_owned, dt); + Kokkos::deep_copy(m_U.logical_view(), m_U2.logical_view()); +} + +template +void +Simulation::gru_update_coarser() +{ + const auto num_owned = m_mesh_map->get_amr_mesh_info().local_num_quadrants(); + m_gru_coarser = Kokkos::View("gru_coarser", num_owned); + auto coarser = m_gru_coarser; + auto status = m_mesh_map->conformal_status(); + Kokkos::parallel_for( + "canop::gru::coarser", + Kokkos::RangePolicy(0, num_owned), + KOKKOS_LAMBDA(int32_t i) { + using cfs = kalypsso::conformal_face_status_t; + const auto st = status(i); + uint8_t s[6] = { + cfs::face_xmin(st), cfs::face_xmax(st), cfs::face_ymin(st), cfs::face_ymax(st), 0, 0 + }; + if constexpr (dim == 3) + { + s[4] = cfs::face_zmin(st); + s[5] = cfs::face_zmax(st); + } + int mask = 0; + for (int face = 0; face < 2 * int(dim); ++face) + if (s[face] == kalypsso::conformal_neighbor_status::NEIGHBOR_IS_COARSER) + mask |= 1 << face; + coarser(i) = mask; + }); +} + +template +void +Simulation::gru_remap(amr_hashmap_t hashmap_before) +{ + const auto info = m_mesh_map->get_amr_mesh_info(); + const auto num_owned = info.local_num_quadrants(); + m_GruOffsets.resize(info.local_num_quadrants_total()); + Kokkos::deep_copy(m_GruOffsets.logical_view(), real_t(0)); + const gru::RemapFunctor remap{ m_U, + m_U2, + m_GruOffsets, + hashmap_before, + m_mesh_map->orchard_keys(), + to_icoord(m_block_sizes), + m_physics->ncons(), + m_physics->gru_colour(), + m_scaling_factor, + m_opt.gru_coarsen, + m_gru_sampler.next_amr() }; + gru::RemapFunctor::apply(remap, num_owned); + // with gravity, the moved states get the hydrostatic pressure of their new position + m_physics->gru_shift(m_U2, m_GruOffsets, num_owned); +} + template void Simulation::next_iteration_impl() diff --git a/src/python/Physics.h b/src/python/Physics.h index 5b7a8b9..d35d426 100644 --- a/src/python/Physics.h +++ b/src/python/Physics.h @@ -153,6 +153,7 @@ class Physics m_prim_names = variables["primitive"].template cast>(); m_field_names = variables["fields"].template cast>(); m_nonconservative = variables["nonconservative"].template cast(); + m_gru_colour = variables["gru_colour"].template cast(); }); } @@ -405,6 +406,57 @@ class Physics return m_refine_needs_primitive; } + //! Index of the colour variable of the GRU scheme (`COLOUR` of `physics//gru.py`), -1 when + //! the model has no gru.py. + int + gru_colour() const + { + return m_gru_colour; + } + + /** + * \brief GRU with gravity: hydrostatic pressure in the ghost cells of the owned blocks copied + * from a coarser neighbor. + * + * \param Ug conservative state with its ghost cells + * \param coarser faces of each owned octant whose neighbor is coarser (bit `2 dir + side`) + * \param num_owned number of owned octants + */ + void + gru_ghosts(Ghosted Ug, Kokkos::View coarser, int32_t num_owned) + { + call([&] { m_backend.attr("gru_ghosts")(np_ghosted(Ug), np_view(coarser), num_owned); }); + } + + //! GRU: interface states (scheme/GRU.h, gru::FaceVar) of the faces of direction dir of the owned + //! and MPI ghost octants, from the primitive variables Qg. + void + gru_faces(Mesh const & mesh, int dir, Ghosted Qg, Block faces) + { + call([&] { + m_backend.attr("gru_faces")( + dir, np_ghosted(Qg), np_block(faces), mesh.num_owned() + mesh.num_ghosts); + }); + } + + //! GRU: end of the update of the owned cells of Uout (Uin: state at the beginning of the time + //! step, work: gru::WorkVar). + void + gru_finish(Block Uin, Block Uout, Block work, int32_t num_owned) + { + call([&] { + m_backend.attr("gru_finish")(np_block(Uin), np_block(Uout), np_block(work), num_owned); + }); + } + + //! GRU with gravity: hydrostatic pressure of the states moved by an AMR cycle (offsets: new minus + //! old position of each cell, zero when it did not move). + void + gru_shift(Block U, Block offsets, int32_t num_owned) + { + call([&] { m_backend.attr("gru_shift")(np_block(U), np_block(offsets), num_owned); }); + } + //! Refinement flags of the owned octants: 1 refine, -1 coarsen, 0 keep. void refine_flags(Mesh const & mesh, Ghosted Ug, Ghosted Qg, typename T::amrflags_view_t flags) @@ -465,6 +517,7 @@ class Physics py::object m_backend; bool m_refine_needs_primitive = false; bool m_nonconservative = false; + int m_gru_colour = -1; std::vector m_cons_names, m_prim_names, m_field_names; // geometry of the mesh given to the Python code diff --git a/src/scheme/GRU.h b/src/scheme/GRU.h new file mode 100644 index 0000000..f7f02da --- /dev/null +++ b/src/scheme/GRU.h @@ -0,0 +1,511 @@ +// SPDX-FileCopyrightText: 2025 canoP authors +// +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +/** + * \file GRU.h + * \brief All-regime GRU (Glimm Random Upwind) scheme for a sharp material colour + * (`simulation.gru_enabled = 1`). + * + * Reference: "ghost GRU", https://hal.science/hal-05315640. Ported from the branch implem-gru of + * canoP (solver godunov_five_eq). + * + * The model gives a colour to each cell (`COLOUR` of `physics//gru.py`: a conservative + * variable, the colour is 1 when it is at least 0.5, else 0), which the scheme keeps strictly 0 + * or 1. A time step is first order in space and time (forward Euler): + * 1. the interface states of every face (physics, `gru_faces_kernel` of `physics/loops.py`): + * normal velocity u*, pressure p*, pressure work p* u*, and the gravity terms g rho* and g rho* u* + * (FaceVar), from the states of the two cells; + * 2. the upwind transport of every cell (UpdateFunctor), written as a positive combination + * \f$ U^{n+1} = a_c U_c + \sum_k a_k U_k \f$ of the cell and of its incoming donors (one per + * face, \f$ 2^{dim-1} \f$ at a face shared with finer cells): + * - when no incoming donor has the other colour, the upwind transport itself; + * - otherwise, the state of one donor (or of the cell), drawn with the probabilities + * \f$ a_k / (a_c + \sum_k a_k) \f$ with one global sample \f$ \omega \f$ shared by every + * cell; + * 3. the end of the update (physics, `gru_finish_kernel`): sharp colour of the drawn cells, + * non-conservative upwind transport of the colour in the others, pressure work and gravity + * (WorkVar). + * + * The samples are low-discrepancy sequences (Sampler), the same on every MPI rank. At a face shared + * with finer cells, the coarse cell takes the fine cells adjacent to the face as donors, each with + * the u* of its own face, and the mean of the fine faces for the pressure work: transport and + * pressure work are conservative across the levels. After an AMR cycle (RemapFunctor), a refined + * cell copies its parent and a coarsened cell crossed by the interface takes the state of one of + * its children, drawn with a global sample (coherent_pick), so that straight interfaces stay + * straight. With gravity, the states moved by the AMR (and the ghost cells copied from a coarser + * neighbor) get the hydrostatic pressure of their new position (physics, `gru_shift_kernel` and + * `gru_ghosts_kernel`). + */ +#ifndef CANOP_SCHEME_GRU_H_ +#define CANOP_SCHEME_GRU_H_ + +#include + +#include + +namespace canop +{ + +namespace gru +{ + +//! Variables of the arrays of the interface states, one array per direction (gru_faces_kernel). +enum FaceVar : int +{ + USTAR = 0, //!< normal velocity u* + PSTAR = 1, //!< pressure p* + PUSTAR = 2, //!< pressure work p* u* + GRHOSTAR = 3, //!< gravity along the normal times the density of the face, g rho* + GMSTAR = 4, //!< g rho* u*, work of the gravity + NFACE = 5 +}; + +//! Variables of the work array of the cells, given to gru_finish_kernel. +enum WorkVar : int +{ + DRAWN = 0, //!< 1 when the state of the cell was drawn among its donors, else 0 + DCOLOUR = 1, //!< transport of the colour variable c in non-conservative form, sum_k a_k (c_k - c) + DMOM = 2, //!< DMOM + d: dt times the pressure work and gravity of the momentum d + DENERGY = 5, //!< dt times the pressure work and gravity of the energy + NWORK = 6 +}; + +//! The colour of a cell: 1 when its colour variable is at least 0.5, else 0. +KOKKOS_INLINE_FUNCTION int +colour(real_t c) +{ + return c >= real_t(0.5) ? 1 : 0; +} + +//! One index among n equiprobable ones, from a sample omega in [0, 1). +KOKKOS_INLINE_FUNCTION int +uniform_pick(real_t omega, int n) +{ + const int k = static_cast(omega * static_cast(n)); + return k < 0 ? 0 : (k >= n ? n - 1 : k); +} + +/** + * \brief One of n fine cells drawn coherently (AMR restriction). + * + * The fine cells are sorted virtually, colour 1 first, and the cell floor(omega n) of this list is + * returned: the coarse cell gets the colour 1 with the probability n1 / n (n1 cells of colour 1). + * omega is one global sample shared by every coarse cell, so the coarse cells crossed by a straight + * interface take the same decision: the interface stays straight instead of becoming a comb. + */ +template +KOKKOS_INLINE_FUNCTION int +coherent_pick(real_t omega, const int (&colours)[n]) +{ + int n1 = 0; + for (int i = 0; i < n; ++i) + n1 += colours[i]; + const int k = uniform_pick(omega, n); + const int target = k < n1 ? 1 : 0; + int rank = k < n1 ? k : k - n1; + for (int i = 0; i < n; ++i) + { + if (colours[i] == target) + { + if (rank == 0) + return i; + --rank; + } + } + return 0; +} + +/** + * \brief Global low-discrepancy samples: Weyl sequences of increments the golden ratio (transport) + * and sqrt(2) - 1 (AMR), independent of each other. + * + * They are deterministic and advance in the same way on every MPI rank. They are not saved in the + * restart files: a restart starts them again from `simulation.gru_omega0` and `gru_omega0_amr`. + */ +struct Sampler +{ + double omega = 0.05; //!< last sample of the transport + double omega_amr = 0.35; //!< last sample of the AMR restrictions + + //! Next sample of the transport (one per time step). + real_t + next() + { + omega = std::fmod(omega + 0.6180339887498949, 1.0); + return static_cast(omega); + } + + //! Next sample of the AMR restrictions (one per AMR cycle). + real_t + next_amr() + { + omega_amr = std::fmod(omega_amr + 0.4142135623730951, 1.0); + return static_cast(omega_amr); + } +}; + +/** + * \brief Upwind transport of the owned cells, with the categorical draw at the material interface. + * + * Writes the transported or drawn state in Uout, and in work (WorkVar) whether the state was drawn, + * the non-conservative transport of the colour variable c and the pressure work and gravity, used + * by gru_finish_kernel. The colour variable (a volume fraction) follows \f$ \partial_t c + u \cdot + * \nabla c = 0 \f$: \f$ c + \sum_k a_k (c_k - c) \f$ keeps a uniform colour exactly 0 or 1. + */ +template +struct UpdateFunctor +{ + using T = KernelTypes; + + //! Maximum number of donors through a face: \f$ 2^{dim-1} \f$ fine cells at a coarse/fine face. + static constexpr int NSUB = 1 << (dim - 1); + static constexpr int NFACES = 2 * dim; + + typename T::StencilHelper_t stencil; //!< neighbors across the octants + typename T::orchard_key_view_t keys; //!< keys of the local octants + typename T::conformal_status_view_type conformal_status; //!< level of the neighbor of each face + typename T::DataArrayGhostedBlock_t Ug; //!< state with ghost cells (owned and MPI ghosts) + typename T::DataArrayBlock_t faces[3]; //!< interface states of each direction + typename T::DataArrayBlock_t Uout; //!< transported or drawn state + typename T::DataArrayBlock_t work; //!< WorkVar of the owned cells + ICoord bsize; //!< cells per block in each direction + int nvar; //!< number of conservative variables + int colour_var; //!< index of the colour variable + real_t scaling; //!< length of a tree + real_t dt; //!< time step + real_t omega; //!< global sample of the time step + + //! Update the owned octants 0 to num_owned - 1. + static void + apply(UpdateFunctor const & f, int32_t num_owned) + { + ICoord zero; + for (size_t d = 0; d < dim; ++d) + zero[d] = 0; + for_each_cell( + "canop::gru::Update", 0, num_owned, f.bsize, zero, f); + } + + //! A donor cell: its coordinates in the block of octant iOct of Ug. + struct Donor + { + ICoord c; + int32_t iOct; + }; + + //! The neighbor octant across the face (dir, side) of octant iOct is finer. + KOKKOS_INLINE_FUNCTION bool + neighbor_is_finer(int32_t iOct, int dir, int side) const + { + using cfs = kalypsso::conformal_face_status_t; + const auto st = conformal_status(iOct); + uint8_t s; + if (dir == IX) + s = side < 0 ? cfs::face_xmin(st) : cfs::face_xmax(st); + else if (dir == IY) + s = side < 0 ? cfs::face_ymin(st) : cfs::face_ymax(st); + else + { + if constexpr (dim == 3) + s = side < 0 ? cfs::face_zmin(st) : cfs::face_zmax(st); + else + return false; + } + return s == kalypsso::conformal_neighbor_status::NEIGHBOR_IS_FINER; + } + + /** + * \brief Donors and interface states of the lower (s = 0) or upper (s = 1) face along dir of the + * cell c; returns the number of donors. + * + * At the border of a block whose neighbor is finer: the \f$ 2^{dim-1} \f$ fine cells adjacent to + * the face, each with the u* of its own face, and the mean of the fine faces in avg. Otherwise + * one donor, the neighbor cell (a ghost cell at the border of the block), with the face of the + * block. + */ + KOKKOS_INLINE_FUNCTION int + face_donors(int32_t iOct, + ICoord const & c, + int dir, + int s, + Donor (&donors)[NSUB], + real_t (&ustar)[NSUB], + real_t (&avg)[NFACE]) const + { + const int side = s == 0 ? -1 : 1; + const bool border = s == 0 ? c[dir] == 0 : c[dir] == bsize[dir] - 1; + if (border and neighbor_is_finer(iOct, dir, side)) + { + kalypsso::shift_t shift; + kalypsso::coord_t coords; + for (size_t d = 0; d < dim; ++d) + { + shift[d] = 0; + coords[d] = c[d]; + } + shift[dir] = side; + const kalypsso::CellLocation loc{ coords, keys(iOct), iOct, false }; + const auto fine = stencil.getNeighLocFinerNearer(loc, shift); + for (int v = 0; v < NFACE; ++v) + avg[v] = 0; + for (int k = 0; k < NSUB; ++k) + { + // transverse coordinates of the fine cell k + ICoord cf; + int bit = 0; + for (size_t d = 0; d < dim; ++d) + { + cf[d] = fine.ijk[d]; + if (int(d) == dir) + continue; + cf[d] = (cf[d] / 2) * 2 + ((k >> bit) & 0x1); + ++bit; + } + // the lower face of the cell is the upper face of the fine cell, and the reverse + ICoord face = cf; + if (s == 0) + face[dir] += 1; + donors[k] = Donor{ cf, fine.iOct }; + ustar[k] = at(faces[dir], face, USTAR, fine.iOct); + for (int v = 0; v < NFACE; ++v) + avg[v] += at(faces[dir], face, v, fine.iOct) / NSUB; + } + return NSUB; + } + ICoord face = c; + face[dir] += s; + donors[0] = Donor{ shifted(c, dir, side), iOct }; + for (int v = 0; v < NFACE; ++v) + avg[v] = at(faces[dir], face, v, iOct); + ustar[0] = avg[USTAR]; + return 1; + } + + //! Update of cell c of octant iOct. + KOKKOS_INLINE_FUNCTION void + operator()(int32_t iOct, ICoord const & c) const + { + constexpr real_t eps = 1e-14; + const real_t h = kalypsso::compute_cell_length( + kalypsso::orchard_key_t::level(keys(iOct)), bsize[IX]) * + scaling; + const real_t dtdx = dt / h; + const int colour_c = colour(at(Ug, c, colour_var, iOct)); + + // donors of each face (index 2 d + s) and their coefficients in the upwind transport + Donor donors[NFACES][NSUB]; + real_t coef[NFACES][NSUB]; + real_t avg[NFACES][NFACE]; + int nsub[NFACES]; + real_t coef_c = 1; + real_t coef_total = 0; + bool interface = false; + for (int dir = 0; dir < int(dim); ++dir) + { + for (int s = 0; s < 2; ++s) + { + const int f = 2 * dir + s; + real_t ustar[NSUB]; + nsub[f] = face_donors(iOct, c, dir, s, donors[f], ustar, avg[f]); + // the incoming velocity is positive at the lower face, negative at the upper face + const real_t sgn = s == 0 ? 1 : -1; + const real_t w = real_t(1) / nsub[f]; + for (int k = 0; k < nsub[f]; ++k) + { + const real_t un = sgn * ustar[k]; + coef[f][k] = dtdx * w * Kokkos::fmax(un, real_t(0)); + coef_c -= dtdx * w * Kokkos::fmax(-un, real_t(0)); + coef_total += coef[f][k]; + if (coef[f][k] > eps and + colour(at(Ug, donors[f][k].c, colour_var, donors[f][k].iOct)) != colour_c) + interface = true; + } + } + } + // round-off (a clearly negative value means that the transport CFL condition is violated) + if (coef_c < 0 and coef_c > real_t(-1e-13)) + coef_c = 0; + + real_t dcolour = 0; + if (not interface) + { + // upwind transport away from the material interface + const real_t cc = at(Ug, c, colour_var, iOct); + for (int f = 0; f < NFACES; ++f) + for (int k = 0; k < nsub[f]; ++k) + if (coef[f][k] > 0) + dcolour += + coef[f][k] * (at(Ug, donors[f][k].c, colour_var, donors[f][k].iOct) - cc); + for (int ivar = 0; ivar < nvar; ++ivar) + { + real_t u = coef_c * at(Ug, c, ivar, iOct); + for (int f = 0; f < NFACES; ++f) + for (int k = 0; k < nsub[f]; ++k) + if (coef[f][k] > 0) + u += coef[f][k] * at(Ug, donors[f][k].c, ivar, donors[f][k].iOct); + at(Uout, c, ivar, iOct) = u; + } + } + else + { + // draw among the cell and its incoming donors, with the global sample of the time step + coef_total += coef_c; + int sel_f = -1; // -1: the cell itself + int sel_k = 0; + if (coef_total > eps) + { + const real_t z = omega * coef_total; + real_t threshold = coef_c; + bool found = z < threshold; + for (int f = 0; f < NFACES and not found; ++f) + { + for (int k = 0; k < nsub[f] and not found; ++k) + { + if (coef[f][k] > 0) + { + // the last positive donor is kept if round-off prevents z < threshold + sel_f = f; + sel_k = k; + threshold += coef[f][k]; + found = z < threshold; + } + } + } + } + for (int ivar = 0; ivar < nvar; ++ivar) + at(Uout, c, ivar, iOct) = + sel_f < 0 ? at(Ug, c, ivar, iOct) + : at(Ug, donors[sel_f][sel_k].c, ivar, donors[sel_f][sel_k].iOct); + } + + // pressure work and gravity, with the face states (conservative at coarse/fine faces) + real_t dE = 0; + for (int d = 0; d < 3; ++d) + { + real_t dm = 0; + if (d < int(dim)) + { + auto const & lo = avg[2 * d]; + auto const & up = avg[2 * d + 1]; + dm = dtdx * (lo[PSTAR] - up[PSTAR]) + dt * real_t(0.5) * (lo[GRHOSTAR] + up[GRHOSTAR]); + dE += dtdx * (lo[PUSTAR] - up[PUSTAR]) + dt * real_t(0.5) * (lo[GMSTAR] + up[GMSTAR]); + } + at(work, c, DMOM + d, iOct) = dm; + } + at(work, c, DRAWN, iOct) = interface ? 1 : 0; + at(work, c, DCOLOUR, iOct) = dcolour; + at(work, c, DENERGY, iOct) = dE; + } +}; + +/** + * \brief Sharp colour through an AMR cycle, after the remap of kalypsso-core. + * + * - Refinement: the new cells copy their parent cell (whatever + * `amr.cell_centered_prolongation_type`). + * - Coarsening (`simulation.gru_coarsen`): when the \f$ 2^{dim} \f$ children of a new cell do not + * all have the same colour, the new cell takes the state of one of them, drawn with the global + * sample omega (coherent_pick), instead of their mean. + * + * offsets receives, for every moved state, its new position minus its old one (the hydrostatic + * shift of gru_shift_kernel); it must be zero on entry. + */ +template +struct RemapFunctor +{ + using T = KernelTypes; + using key_t = kalypsso::orchard_key_t; + + typename T::DataArrayBlock_t Uold; //!< state on the mesh before the cycle + typename T::DataArrayBlock_t Unew; //!< state remapped by kalypsso-core, modified here + typename T::DataArrayBlock_t offsets; //!< new minus old position of the moved states + typename T::amr_hashmap_t hashmap_old; //!< key -> index of the octants before the cycle + typename T::orchard_key_view_t keys_new; //!< keys of the octants after the cycle + ICoord bsize; //!< cells per block in each direction + int nvar; //!< number of conservative variables + int colour_var; //!< index of the colour variable + real_t scaling; //!< length of a tree + bool coarsen; //!< coherent draw on coarsening + real_t omega; //!< global sample of the AMR cycle + + //! Process the owned octants 0 to num_owned - 1 of the new mesh. + static void + apply(RemapFunctor const & f, int32_t num_owned) + { + ICoord zero; + for (size_t d = 0; d < dim; ++d) + zero[d] = 0; + for_each_cell("canop::gru::Remap", 0, num_owned, f.bsize, zero, f); + } + + KOKKOS_INLINE_FUNCTION void + operator()(int32_t iOct, ICoord const & c) const + { + const auto key_new = keys_new(iOct); + // same octant: nothing to do + if (hashmap_old.valid_at(hashmap_old.find(key_new))) + return; + const real_t h = kalypsso::compute_cell_length(key_t::level(key_new), bsize[IX]) * scaling; + + // refinement: copy of the parent cell + auto index = hashmap_old.find(key_t::father(key_new)); + if (hashmap_old.valid_at(index)) + { + const int32_t iOct_old = hashmap_old.value_at(index); + const auto fid = static_cast(key_t::family_id(key_new)); + ICoord cold; + for (size_t d = 0; d < dim; ++d) + cold[d] = c[d] / 2 + ((fid >> d) & 0x1) * (bsize[d] / 2); + for (int ivar = 0; ivar < nvar; ++ivar) + at(Unew, c, ivar, iOct) = at(Uold, cold, ivar, iOct_old); + // from the center of the coarse cell to that of the fine cell + for (size_t d = 0; d < dim; ++d) + at(offsets, c, int(d), iOct) = ((c[d] & 0x1) - real_t(0.5)) * h; + return; + } + + // coarsening + if (not coarsen) + return; + index = hashmap_old.find(key_t::eldest_child(key_new)); + if (not hashmap_old.valid_at(index)) + return; + // child octant of the 2^dim fine cells (the children are contiguous) + int32_t ichild = 0; + for (size_t d = 0; d < dim; ++d) + if (c[d] >= bsize[d] / 2) + ichild |= 1 << d; + const int32_t iOct_old = hashmap_old.value_at(index) + ichild; + + constexpr int nfine = 1 << dim; + ICoord cfine[nfine]; + int colours[nfine]; + int n1 = 0; + for (int i = 0; i < nfine; ++i) + { + for (size_t d = 0; d < dim; ++d) + { + const int v = 2 * c[d] + ((i >> d) & 0x1); + cfine[i][d] = v >= bsize[d] ? v - bsize[d] : v; + } + colours[i] = colour(at(Uold, cfine[i], colour_var, iOct_old)); + n1 += colours[i]; + } + // one colour: the mean of kalypsso-core is kept + if (n1 == 0 or n1 == nfine) + return; + const int pick = coherent_pick(omega, colours); + for (int ivar = 0; ivar < nvar; ++ivar) + at(Unew, c, ivar, iOct) = at(Uold, cfine[pick], ivar, iOct_old); + // from the center of the fine cell to that of the coarse cell (fine cells of size h / 2) + for (size_t d = 0; d < dim; ++d) + at(offsets, c, int(d), iOct) = -(((pick >> d) & 0x1) - real_t(0.5)) * real_t(0.5) * h; + } +}; + +} // namespace gru + +} // namespace canop + +#endif // CANOP_SCHEME_GRU_H_ diff --git a/src/scheme/SchemeOptions.h b/src/scheme/SchemeOptions.h index af41cf2..2f2fbf1 100644 --- a/src/scheme/SchemeOptions.h +++ b/src/scheme/SchemeOptions.h @@ -80,6 +80,15 @@ struct SchemeOptions real_t cfl = 0.9; //!< CFL number Limiter limiter = Limiter::MINMOD; //!< limiter of the slopes (space_order = 2) + //! `gru_enabled`: all-regime GRU scheme for a sharp material colour (scheme/GRU.h), first order + bool gru = false; + //! `gru_coarsen`: draw among the children when coarsening across the interface (default: gru) + bool gru_coarsen = false; + //! `gru_omega0`, `gru_omega0_amr`: first values of the samples of the transport and of the AMR + double gru_omega0 = 0.05, gru_omega0_amr = 0.35; + //! The input file asked for space_order or time_order 2 with GRU (forced to 1). + bool gru_forced_order = false; + //! Read and check the options; throws std::runtime_error on an invalid value. static SchemeOptions read(Settings const & cm) @@ -96,6 +105,17 @@ struct SchemeOptions o.cfl = cm.getReal("simulation", "cfl", 0.9); o.limiter = from_name(LIMITERS, cm.getString("simulation", "scalar_limiter", "minmod"), "simulation.scalar_limiter"); + + o.gru = cm.getInteger("simulation", "gru_enabled", 0) != 0; + o.gru_coarsen = cm.getInteger("simulation", "gru_coarsen", o.gru ? 1 : 0) != 0; + o.gru_omega0 = cm.getReal("simulation", "gru_omega0", 0.05); + o.gru_omega0_amr = cm.getReal("simulation", "gru_omega0_amr", 0.35); + if (o.gru and (o.space_order != 1 or o.time_order != 1)) + { + o.gru_forced_order = true; + o.space_order = 1; + o.time_order = 1; + } return o; } }; diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3ea2529..37a4e04 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 gru) 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..44d28b3 100644 --- a/test/physics/physics.py +++ b/test/physics/physics.py @@ -12,6 +12,9 @@ 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 gru --exe-2d canoP_2d [--workdir DIR] + the GRU scheme keeps the interface sharp and translates it exactly at a uniform velocity and + pressure, with AMR Exit code 77 (CTest SKIP_RETURN_CODE) when numpy or h5py is missing. """ @@ -121,15 +124,66 @@ def energy(args): return check("relative change of the total energy", abs(E1 - E0) / E0, 1e-13) and ok +def outputs(final): + """the outputs of a run, in the order of the time steps""" + d = os.path.dirname(final) + return [os.path.join(d, f) for f in sorted(os.listdir(d)) if f.endswith(".h5") and "_iter" in f] + + +def cell_sizes(path): + """the sizes of the cells of an output""" + with h5py.File(path, "r") as f: + xyz = f["unstructured_mesh/coordinates"][()][f["unstructured_mesh/connectivity"][()]] + return xyz[:, :, 0].max(axis=1) - xyz[:, :, 0].min(axis=1) + + +def gru(args): + """GRU scheme (twophase5eq): sharp colour and exact translation of a square at uniform velocity and + pressure, with AMR""" + ok = True + names = ["ag", "mg", "ml", "m", "P", "V_x", "V_y"] + + # square of gas in liquid at V = (0.5, 0.25), P = 10, periodic, AMR + case = Case("gru_square", "settings_twophase5eq_gru_square", (4, 6), 0.5, {"io.save_count": 10}, reference=None) + final = reg.run_canop(case, args.exe_2d, os.path.join(args.workdir, case.name)) + print(case.name + ": square transported at a uniform velocity and pressure, AMR") + area0 = centroid0 = None + worst = {"colour": 0.0, "P": 0.0, "V": 0.0, "area": 0.0, "centroid": 0.0} + for path in outputs(final): + keys, d = read(path, names) + h = cell_sizes(path) + with h5py.File(path, "r") as f: + t = f["run"].attrs["time"] + vol = h * h + x = keys / 2.0**20 + area = np.sum(d["ag"] * vol) + centroid = np.sum((d["ag"] * vol)[:, None] * x, axis=0) / area + if area0 is None: + area0, centroid0 = area, centroid + exact = (centroid0 + np.array([0.5, 0.25]) * t) % 1.0 + worst["colour"] = max(worst["colour"], np.abs(d["ag"] - np.round(d["ag"])).max()) + worst["P"] = max(worst["P"], np.abs(d["P"] - 10.0).max() / 10.0) + worst["V"] = max(worst["V"], np.abs(d["V_x"] - 0.5).max(), np.abs(d["V_y"] - 0.25).max()) + worst["area"] = max(worst["area"], abs(area - area0) / area0) + worst["centroid"] = max(worst["centroid"], np.abs(centroid - exact).max() / h.min()) + ok = check("max |ag - round(ag)|", worst["colour"], 0.0) and ok + ok = check("max |P - P0| / P0", worst["P"], 1e-13) and ok + ok = check("max |V - V0| / |V0|", worst["V"] / 0.5, 1e-13) and ok + ok = check("relative change of the area of the gas", worst["area"], 1e-14) and ok + # the interface moves by whole cells (random choice): within about one cell of the exact position + ok = check("distance of the centroid to the exact one / smallest cell", worst["centroid"], 1.5) 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", "gru"]) 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, "gru": gru}[args.check](args) except RuntimeError as e: print(e) return 1 diff --git a/test/regression/README.md b/test/regression/README.md index d0107b8..85e25bd 100644 --- a/test/regression/README.md +++ b/test/regression/README.md @@ -61,6 +61,9 @@ Treatments checked by canoP references * the ``dirichlet`` boundary condition at second order or with diffusion fluxes: the ghost cells hold the imposed state; * the bulk viscosity of the gas of the 5 equations model: ``param.eos_g.eta``. +* the GRU scheme (``simulation.gru_enabled``, ``twophase5eq_gru_*``): transport of a sharp square, + random draws with the low-discrepancy samples, copy on refinement, 2D and 3D; ``test/physics`` (``gru``) checks its exact translation. The cases + ``twophase5eq_square_transport`` run the settings file of GRU without it (``NO_GRU``). The limiters ``maxmod`` and ``charm``, outside the TVD region, give NaN on the blast test case after a few steps. diff --git a/test/regression/cases.py b/test/regression/cases.py index bae4467..00116c2 100644 --- a/test/regression/cases.py +++ b/test/regression/cases.py @@ -16,8 +16,8 @@ The cases cover every hyperbolic flux of every model, every limiter, the space and time orders, every boundary condition, the source terms, the diffusion fluxes, the interface closures of the -7-equation model, two-phase states (different equations of state, volume fraction jumps), 3D and -AMR. +7-equation model, two-phase states (different equations of state, volume fraction jumps), the GRU +scheme (sharp interface), 3D and AMR. """ @@ -72,6 +72,8 @@ def __init__(self, name, base, level, tmax, overrides=None, dim=2, reference="le #: the pressure relaxation, then the velocity relaxation (twophase7eq) RELAXATIONS = {"physics.relaxation": "pressure_velocity_relaxation"} +#: the settings files of the GRU scheme without it (scheme of the hyperbolic flux) +NO_GRU = {"simulation.gru_enabled": 0} #: two-phase shock tube with a volume fraction jump and a shear (transverse velocity jump), periodic #: along y (test/physics/physics.py checks the outflow faces) @@ -172,7 +174,9 @@ def _b7(name): for k in range(1, 6) ] + [ # ---- volume fraction transport (Abgrall), without the GRU scheme - Case("twophase5eq_square_transport", _b5("gru_square"), 5, 0.1, reference="canop"), + Case("twophase5eq_square_transport", _b5("gru_square"), 5, 0.1, NO_GRU, reference="canop"), + # ---- GRU scheme: transport of a sharp interface (AMR cases below) + Case("twophase5eq_gru_square", _b5("gru_square"), 5, 0.3, reference="canop"), # ---- onephase options on the blast with reflective walls Case("onephase_blast_walls", _mono("blast"), 5, 0.15, WALLS), Case("onephase_blast_hll", _mono("blast"), 5, 0.15, @@ -219,7 +223,9 @@ def _b7(name): Case("twophase7eq_jet_3d", _b7("jet"), 4, 1e-3, dim=3, reference="canop"), # ---- AMR (reference produced by canoP) Case("twophase5eq_blast_amr", _b5("blast"), (4, 6), 0.05, reference="canop"), - Case("twophase5eq_square_transport_amr", _b5("gru_square"), (4, 6), 0.1, reference="canop"), + Case("twophase5eq_square_transport_amr", _b5("gru_square"), (4, 6), 0.1, NO_GRU, reference="canop"), + Case("twophase5eq_gru_square_amr", _b5("gru_square"), (4, 6), 0.3, reference="canop"), + Case("twophase5eq_gru_square_amr_3d", _b5("gru_square"), (3, 4), 0.2, dim=3, reference="canop"), Case("twophase7eq_jet_amr", _b7("jet"), (4, 6), 1e-3, reference="canop"), Case("onephase_blast_amr_3d", _mono("blast"), (3, 4), 0.05, dim=3, reference="canop"), # refinement criterion on a primitive variable diff --git a/test/regression/references/twophase5eq_gru_square.h5 b/test/regression/references/twophase5eq_gru_square.h5 new file mode 100644 index 0000000..fbac4c2 Binary files /dev/null and b/test/regression/references/twophase5eq_gru_square.h5 differ diff --git a/test/regression/references/twophase5eq_gru_square_amr.h5 b/test/regression/references/twophase5eq_gru_square_amr.h5 new file mode 100644 index 0000000..4bdae5b Binary files /dev/null and b/test/regression/references/twophase5eq_gru_square_amr.h5 differ diff --git a/test/regression/references/twophase5eq_gru_square_amr_3d.h5 b/test/regression/references/twophase5eq_gru_square_amr_3d.h5 new file mode 100644 index 0000000..c4aa6cf Binary files /dev/null and b/test/regression/references/twophase5eq_gru_square_amr_3d.h5 differ