diff --git a/CHANGELOG.md b/CHANGELOG.md index d0e8a30..14c949b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ The user-visible changes of canoP, by version (see `CONTRIBUTING.md` for the ver ## Unreleased +- Model `particleflow`: a disperse phase of particles (spray) by a quadrature method of moments with + two velocity nodes, dragged by a carrier flow, ported from canoP legacy; kinetic flux, exact drag + and gravity after each time step, examples `settings/settings_particleflow_*.ini`. +- The relaxations of the physics (`physics.relaxation`) receive the time step: + `relaxation(w, qn, p, dt, dim)`. - canoP studio in English or in French: a FR/EN switch in the top bar, saved in the settings. New installations start in English; studios set up before keep French. - Tutorial of canoP studio in the documentation: the build, a run of the blast example, and a diff --git a/Readme.md b/Readme.md index dc315ac..19e0974 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)); +- **particleflow**: disperse phase of particles (spray) by a quadrature method of moments in + velocity with two nodes, dragged by a carrier flow. 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/developer-guide/tests.md b/docs/developer-guide/tests.md index 4a4609e..c414ff9 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, exact drag ``` The regression and physics tests need `python3` with numpy and h5py. @@ -21,9 +21,10 @@ The regression and physics tests need `python3` with numpy and h5py. `test/regression` runs short cases and compares them cell by cell with stored reference outputs (`test/regression/references/`). The cases cover every flux, limiter, space and time order, boundary -condition, source term and diffusion flux of each model, two-phase states, uniform and adaptive -meshes, in 2D and 3D. `test/regression/cases.py` lists them; `test/regression/README.md` explains how -to add a case and produce its reference. +condition, source term and diffusion flux of each model, the initial conditions and relaxations of +the model particleflow, two-phase states, uniform and adaptive meshes, in 2D and 3D. +`test/regression/cases.py` lists them; `test/regression/README.md` explains how to add a case and +produce its reference. ## Continuous integration @@ -32,7 +33,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 (57 kernels, about 5 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/index.md b/docs/index.md index 6ae1e09..6d81bbb 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)); +- **particleflow**: disperse phase of particles (spray) by a quadrature method of moments in + velocity with two nodes, dragged by a carrier flow. 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/user-guide/models.md b/docs/user-guide/models.md index e8ead47..47ffbed 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,24 @@ Seven-equation Baer-Nunziato model: each phase has its velocity, pressure and en `velocity_relaxation`, `pressure_velocity_relaxation`); - viscous and thermal fluxes, gravity. +## particleflow + +Disperse phase of particles (spray), described by the moments of its velocity distribution up to +the third order and closed by two velocity nodes (quadrature method of moments, QMOM), dragged +towards the velocity of a carrier flow given in each cell (one-way coupling). Ported from the model +`particlefluid` of canoP legacy. + +- conservative variables: moments `M0`, `M1_x`, `M1_y` (`M1_z`), `M2_xx`, `M2_xy`, `M2_yy` (`M2_xz`, + `M2_yz`, `M2_zz`), `M3_x`, `M3_y` (`M3_z`), carrier velocity `Uf_x`, `Uf_y` (`Uf_z`); primitive + variables: the nodes `n1`, `n2`, `V1_*`, `V2_*`; +- flux: kinetic, upwinded node by node; at second order in space only the densities of the nodes + are reconstructed (quasi-second order), which keeps the moments realizable within the CFL + condition; +- after each time step, the moments are projected on the two nodes, then the drag towards the + carrier velocity with gravity, the gravity alone or the drag with a BGK relaxation of the + velocities is integrated exactly on the moments over the time step (relaxations `reprojection`, + `drag`, `gravity`, `drag_bgk`). + ## 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 2de8353..6589a70 100644 --- a/physics/common.py +++ b/physics/common.py @@ -608,9 +608,9 @@ def _kernels(self, initial, boundary): "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"])})) 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] + + _switch("relaxation", {k + 1: ["relaxation_relax_%s(w, qn, p, dt, dim)" % 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, " @@ -731,10 +731,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 of the time step dt to Unew in the owned octants, after the time step.""" 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, relaxation=self.relaxation, dt=dt) 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..50c4410 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.""" + relaxation: int, dt: float) -> None: + """Apply the relaxation to the cell i of Unew, once 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) diff --git a/physics/onephase/relaxations/__init__.py b/physics/onephase/relaxations/__init__.py index fe3353d..78efe99 100644 --- a/physics/onephase/relaxations/__init__.py +++ b/physics/onephase/relaxations/__init__.py @@ -1,11 +1,12 @@ # 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: -- ``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. +- ``relaxation(w, qn, p, dt, dim)``: replaces the conservative state ``w`` of a cell by its state + after a relaxation during the time step ``dt`` (its projection on the equilibrium for an + instantaneous relaxation), ``qn`` being the primitive state of ``w``. It applies once per time + step, after the time integration (after the average of the stages at ``time_order = 2``). """ diff --git a/physics/particleflow/__init__.py b/physics/particleflow/__init__.py new file mode 100644 index 0000000..81e1fea --- /dev/null +++ b/physics/particleflow/__init__.py @@ -0,0 +1,119 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Model particleflow: a disperse phase of particles (spray), quadrature method of moments (QMOM). + +The particles of a cell are described by moments of their velocity distribution f(v), up to the +third order: the mass ``M0``, the momentum ``M1``, the full second-order tensor ``M2`` and the +diagonal third-order moments ``M3_i = int v_i^3 f``. The closure approximates f by two weighted +velocity nodes (quadrature with two nodes):: + + f(v) = n1 delta(v - V1) + n2 delta(v - V2) + +The moments are those of the kinetic equation of the particles, transported at their velocity, +dragged towards the velocity ``Uf`` of a carrier fluid (given in each cell, constant in time: +one-way coupling) with the relaxation time ``tau`` and accelerated by the gravity ``g``:: + + d_t f + v.grad_x f + div_v(f ((Uf - v) / tau + g)) = 0 + +for example ``d_t M0 + div(M1) = 0`` and ``d_t M1 + div(M2) = (M0 Uf - M1) / tau + M0 g``; the +fluxes of the highest moments are those of the two nodes (``hyperbolic_fluxes/kinetic.py``). Each +time step: + +- the face fluxes are the kinetic fluxes of the nodes, upwinded node by node; at second order in + space, only the densities n1, n2 of the nodes are reconstructed at the faces, the velocities of the + cell being kept (quasi-second order, Vikas et al. 2011), which keeps the moments realizable; +- after the time integration (after the average of the stages at ``time_order = 2``), the moments + are projected on the two-node closure, then the drag and the gravity are integrated exactly over + the time step (``physics.relaxation``: ``reprojection`` alone, ``drag``, ``gravity`` or + ``drag_bgk``): they move every velocity of the distribution by the same affine map, so the moments + stay on the two nodes. The drag is split from the transport (Lie splitting). + +The time step is ``cfl h / max(sum_d |V1_d|, sum_d |V2_d|, cfl_velocity)``. In a stage, with the +velocities at its start, the outflow of a node from a cell stays below its density (the moments stay +realizable) for ``cfl <= 1`` at first order in space, ``cfl <= 2/3`` with the minmod limiter and +``cfl <= 1/2`` with the other limiters; the second stage of ``time_order = 2`` keeps the time step of +the first, so take a margin. + +canoP legacy applied the drag in each stage, before the average of the stages: the average of two +distributions whose velocities differ changes the weights of the nodes after the reprojection, and +the drag is exact only to first order in ``dt / tau``. Applied once after the time step, it is exact +for a uniform state at any order in time and for any ``dt / tau``. + +Ported from the model ``particlefluid`` of canoP legacy (branch +``48-temporary-spray-model-implementation-as-an-independent-model``). + +Variables, in the order of the arrays of canoP (names of the outputs and checkpoints), d being the +dimension and ``M2`` stored as its lower triangle (``xx, xy, yy`` in 2D, ``xx, xy, yy, xz, yz, zz`` +in 3D):: + + conservative M0, M1_, M2_, M3_, Uf_ + primitive n1, n2, V1_, V2_, Uf_ + derived Up_ (mean velocity), a_ (covariance of the velocity), + a_ (third-order central moments) + +The nodes are labelled so that ``n1 >= n2``. + +Parameters (section ``[param]``): + +- ``tau``: relaxation time of the drag (``relaxations/drag.py``, ``relaxations/drag_bgk.py``); +- ``tau_BGK``: relaxation time of the velocities to their mean (``relaxations/drag_bgk.py``); +- ``gravity_x``, ``gravity_y``, ``gravity_z``: gravity (``relaxations/drag.py``, + ``relaxations/drag_bgk.py``, ``relaxations/gravity.py``); +- ``cfl_velocity``: lower bound of the velocity of the time step, for particles at rest at the start + (in a carrier flow, take its maximum ``sum_d |Uf_d|``); +- ``energy_preserving``: 1: replace the cross correlation ``a_ij`` by ``sign(a_ij) sqrt(a_ii a_jj)`` + in the inversion, which keeps the energy of the moments (experimental); +- ``thresh_rho``: densities below it are vacuum; +- ``thresh_var``: below this trace of the covariance, the cell has a single node. +""" +from physics.common import AXES, get_int, get_real + + +def sym_names(dim): + """Return the suffixes of the components of a symmetric tensor, in the order of the arrays. + + Lower triangle, row by row: ``xx, xy, yy`` in 2D, ``xx, xy, yy, xz, yz, zz`` in 3D. + """ + return [AXES[j] + AXES[i] for i in range(dim) for j in range(i + 1)] + + +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": (["M0"] + ["M1_" + a for a in axes] + ["M2_" + s for s in sym_names(dim)] + + ["M3_" + a for a in axes] + ["Uf_" + a for a in axes]), + "primitive": ["n1", "n2"] + ["V1_" + a for a in axes] + ["V2_" + a for a in axes] + + ["Uf_" + a for a in axes], + "derived": (["Up_" + a for a in axes] + ["a_" + s for s in sym_names(dim)] + + ["a_" + a * 3 for a in axes]), + "nonconservative": False} + + +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["tau"] = get_real("param", "tau", 1.0) + res["tau_BGK"] = get_real("param", "tau_BGK", 1.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["cfl_velocity"] = get_real("param", "cfl_velocity", 0.0) + res["energy_preserving"] = get_int("param", "energy_preserving", 0) + + res["thresh_rho"] = get_real("param", "thresh_rho", 1e-12) + res["thresh_var"] = get_real("param", "thresh_var", 1e-9) + + return res diff --git a/physics/particleflow/boundary_conditions/__init__.py b/physics/particleflow/boundary_conditions/__init__.py new file mode 100644 index 0000000..d29881e --- /dev/null +++ b/physics/particleflow/boundary_conditions/__init__.py @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: 2025 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/particleflow/boundary_conditions/jet_crossing.py b/physics/particleflow/boundary_conditions/jet_crossing.py new file mode 100644 index 0000000..50826bc --- /dev/null +++ b/physics/particleflow/boundary_conditions/jet_crossing.py @@ -0,0 +1,87 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""jet_crossing: two jets of particles injected through faces of the domain, vacuum elsewhere (2D). + +The jet k enters through the face ``face`` (0 xmin, 1 xmax, 2 ymin, 3 ymax), centred on the +coordinate ``coord_c`` along the face, with the velocity ``v_perp`` across the face (inwards) +and ``v_para`` along it. A cell next to the face is in the jet when its centre is within +``radius`` of the centre of the jet, or when the centre of the jet is along its side. Every face +imposes its ghost state (wall kind 4): the jets, or vacuum, which lets the particles leave freely. + +Parameters (section ``[jet_crossing]``), for k = 1, 2: + +- ``face``: face of the jet; +- ``coord_c``: centre of the jet along the face; +- ``radius``: half width of the jet; +- ``rho_in``: density of the jet; +- ``v_para``, ``v_perp``: velocity along and across the face. +""" +import pykokkos as pk + +from physics.common import get_int, get_real +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + res["face1"] = get_int("jet_crossing", "face1", 0) + res["coord1_c"] = get_real("jet_crossing", "coord1_c", 0.1) + res["radius1"] = get_real("jet_crossing", "radius1", 0.05) + res["rho1_in"] = get_real("jet_crossing", "rho1_in", 1.1) + res["v1_para"] = get_real("jet_crossing", "v1_para", 1.0) + res["v1_perp"] = get_real("jet_crossing", "v1_perp", 1.0) + res["face2"] = get_int("jet_crossing", "face2", 0) + res["coord2_c"] = get_real("jet_crossing", "coord2_c", 0.9) + res["radius2"] = get_real("jet_crossing", "radius2", 0.05) + res["rho2_in"] = get_real("jet_crossing", "rho2_in", 1.1) + res["v2_para"] = get_real("jet_crossing", "v2_para", -1.0) + res["v2_perp"] = get_real("jet_crossing", "v2_perp", 1.0) + return res + + +@pk.function +def add_jet(q: Prim, face: int, xa: float, ya: float, h: float, coord_c: float, radius: float, rho: float, + v_para: float, v_perp: float) -> None: + """Put the jet in the node 1 of q when the inside cell (xa, ya) of size h is in it.""" + # Centre of the jet on the face and its velocity + x_c: float = coord_c + y_c: float = coord_c + v_x: float = v_para + v_y: float = v_para + if face == 0 or face == 1: + x_c = xa - 0.5 * h + v_x = v_perp + if face == 1: + x_c = xa + 0.5 * h + v_x = -v_perp + else: + y_c = ya - 0.5 * h + v_y = v_perp + if face == 3: + y_c = ya + 0.5 * h + v_y = -v_perp + centre_in_cell: int = 0 + if pk.fabs(x_c - xa) <= 0.5 * h and pk.fabs(y_c - ya) <= 0.5 * h: + centre_in_cell = 1 + if (xa - x_c) * (xa - x_c) + (ya - y_c) * (ya - y_c) < radius * radius or centre_in_cell == 1: + q.n1 = rho + q.V1x = v_x + q.V1y = v_y + + +@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 = zero_prim() + if face == bp.face1: + add_jet(q, face, xa, ya, h, bp.coord1_c, bp.radius1, bp.rho1_in, bp.v1_para, bp.v1_perp) + if face == bp.face2: + add_jet(q, face, xa, ya, h, bp.coord2_c, bp.radius2, bp.rho2_in, bp.v2_para, bp.v2_perp) + return prim_to_cons(q, p, dim) + + +@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/particleflow/boundary_conditions/left_inlet.py b/physics/particleflow/boundary_conditions/left_inlet.py new file mode 100644 index 0000000..d1cfc0f --- /dev/null +++ b/physics/particleflow/boundary_conditions/left_inlet.py @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""left_inlet: two jets of particles through the face xmin, free outflow at xmax, walls elsewhere. + +At xmin (wall kind 4, imposed state), a cell is in the jet k when its centre is within ``radius`` +of the centre ``(x_c, y_c, z_c)`` of the jet, or when that centre is in the cell; the jets +take the node 1 (the jet 2 where they overlap), with the density ``rho_in`` and the velocity +``v_in``. The node 2 carries a background of density ``rho`` at the carrier velocity. At xmax the +ghost cells copy the inside cells (wall kind 3); the other faces reflect the particles (wall kind 1). + +Parameters (section ``[left_inlet]``), for k = 1, 2: + +- ``x_c``, ``y_c``, ``z_c``: centre of the jet on the face xmin; +- ``radius``: radius of the jet; +- ``rho_in``: density of the jet; +- ``vx_in``, ``vy_in``, ``vz_in``: velocity of the jet; +- ``rho``: density of the background. +""" +import pykokkos as pk + +from physics.common import get_real +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + res["x1_c"] = get_real("left_inlet", "x1_c", 0.0) + res["y1_c"] = get_real("left_inlet", "y1_c", 0.18) + res["z1_c"] = get_real("left_inlet", "z1_c", 0.02) if dim == 3 else 0.0 + res["radius1"] = get_real("left_inlet", "radius1", 0.01) + res["rho1_in"] = get_real("left_inlet", "rho1_in", 1.0) + res["v1x_in"] = get_real("left_inlet", "v1x_in", 1.0) + res["v1y_in"] = get_real("left_inlet", "v1y_in", -1.0) + res["v1z_in"] = get_real("left_inlet", "v1z_in", 0.5) if dim == 3 else 0.0 + res["x2_c"] = get_real("left_inlet", "x2_c", 0.0) + res["y2_c"] = get_real("left_inlet", "y2_c", 0.02) + res["z2_c"] = get_real("left_inlet", "z2_c", 0.02) if dim == 3 else 0.0 + res["radius2"] = get_real("left_inlet", "radius2", 0.01) + res["rho2_in"] = get_real("left_inlet", "rho2_in", 1.0) + res["v2x_in"] = get_real("left_inlet", "v2x_in", 1.0) + res["v2y_in"] = get_real("left_inlet", "v2y_in", 1.0) + res["v2z_in"] = get_real("left_inlet", "v2z_in", 0.5) if dim == 3 else 0.0 + res["rho"] = get_real("left_inlet", "rho", 0.0) + return res + + +@pk.function +def in_jet(xa: float, ya: float, za: float, h: float, x_c: float, y_c: float, z_c: float, radius: float, + dim: int) -> int: + """Return 1 when the cell of centre (xa, ya, za) and size h is in the jet of centre (x_c, y_c, z_c).""" + inside: int = 0 + if pk.fabs(x_c - xa) <= 0.5 * h and pk.fabs(y_c - ya) <= 0.5 * h: + inside = 1 + if dim == 3 and pk.fabs(z_c - za) > 0.5 * h: + inside = 0 + if dist2(xa, ya, za, x_c, y_c, z_c, dim) < radius * radius: + inside = 1 + return inside + + +@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 + if face == 0: + q: Prim = zero_prim() + if in_jet(xa, ya, za, h, bp.x1_c, bp.y1_c, bp.z1_c, bp.radius1, dim) == 1: + q.n1 = bp.rho1_in + q.V1x = bp.v1x_in + q.V1y = bp.v1y_in + q.V1z = bp.v1z_in + if in_jet(xa, ya, za, h, bp.x2_c, bp.y2_c, bp.z2_c, bp.radius2, dim) == 1: + q.n1 = bp.rho2_in + q.V1x = bp.v2x_in + q.V1y = bp.v2y_in + q.V1z = bp.v2z_in + q.n2 = bp.rho + q.V2x = uadj.Ufx + q.V2y = uadj.Ufy + q.V2z = uadj.Ufz + q.Ufx = uadj.Ufx + q.Ufy = uadj.Ufy + q.Ufz = uadj.Ufz + u = prim_to_cons(q, p, dim) + elif face != 1: + u = umirror + reflect_moments(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: + if face == 0: + return 4 + if face == 1: + return 3 + return 1 diff --git a/physics/particleflow/boundary_conditions/neuman.py b/physics/particleflow/boundary_conditions/neuman.py new file mode 100644 index 0000000..51443ad --- /dev/null +++ b/physics/particleflow/boundary_conditions/neuman.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""neuman: free outflow on every face of the domain. + +The ghost cells copy the adjacent inside cell, and the face states of the flux use the outflow +treatment (wall kind 3): the nodes leaving the domain cross the face, and those of the copy moving +inwards come in. +""" +import pykokkos as pk + +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/particleflow/boundary_conditions/reflective.py b/physics/particleflow/boundary_conditions/reflective.py new file mode 100644 index 0000000..157523a --- /dev/null +++ b/physics/particleflow/boundary_conditions/reflective.py @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""reflective: specular reflection of the particles on every face of the domain. + +The ghost cells mirror the inside cells, the moments odd in the normal velocity reversed, and the +face states of the flux reverse the normal velocity of the nodes (wall kind 1): no mass crosses the +faces. +""" +import pykokkos as pk + +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 + reflect_moments(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/particleflow/boundary_conditions/top_inlet.py b/physics/particleflow/boundary_conditions/top_inlet.py new file mode 100644 index 0000000..aa86cb2 --- /dev/null +++ b/physics/particleflow/boundary_conditions/top_inlet.py @@ -0,0 +1,77 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""top_inlet: two annular jets of particles through the face ymax, free outflow elsewhere. + +At ymax (wall kind 4, imposed state), with d the distance of the cell to the axis ``(x_c, z_c)`` +(``|x - x_c|`` in 2D): the jet 1 (node 1) fills ``|d - R1| < r1 / 2`` with a parabolic density of +maximum ``rho1_in``, the speed ``v1`` and an angle below the horizontal ``angle1 - 0.25 s``, s in +[-1, 1] the position across the jet; the jet 2 (node 2) fills ``|d - R2| < r2 / 2`` with a parabolic +density of maximum ``rho2_in``, the speed ``v2`` and the angle ``angle2``. The jets move away from the +axis and downwards. The other faces copy the inside cells (wall kind 3). + +Parameters (section ``[top_inlet]``): + +- ``x_c``, ``z_c``: axis of the jets; +- ``R1``, ``r1``, ``rho1_in``, ``angle1``, ``v1``: radius, width, density, angle (radians) and + speed of the jet 1; +- ``R2``, ``r2``, ``rho2_in``, ``angle2``, ``v2``: the same for the jet 2. +""" +import math + +import pykokkos as pk + +from physics.common import get_real +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("top_inlet", "x_c", 0.5) + res["z_c"] = get_real("top_inlet", "z_c", 0.5) if dim == 3 else 0.0 + res["R1"] = get_real("top_inlet", "R1", 0.09) + res["r1"] = get_real("top_inlet", "r1", 0.15) + res["rho1_in"] = get_real("top_inlet", "rho1_in", 1.0) + res["angle1"] = get_real("top_inlet", "angle1", 0.2 * math.pi / 2.0) + res["v1"] = get_real("top_inlet", "v1", 1.0) + res["R2"] = get_real("top_inlet", "R2", 0.23) + res["r2"] = get_real("top_inlet", "r2", 0.05) + res["rho2_in"] = get_real("top_inlet", "rho2_in", 0.9) + res["angle2"] = get_real("top_inlet", "angle2", 0.8 * math.pi / 2.0) + res["v2"] = get_real("top_inlet", "v2", 0.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 = uadj + if face == 3: + q: Prim = zero_prim() + dx: float = xa - bp.x_c + dz: float = 0.0 + if dim == 3: + dz = za - bp.z_c + d: float = pk.sqrt(dx * dx + dz * dz) + if pk.fabs(d - bp.R1) < bp.r1 / 2.0: + s: float = (d - bp.R1) / (bp.r1 / 2.0) + angle: float = bp.angle1 - 0.25 * s + q.n1 = bp.rho1_in * (1.0 - s * s) + q.V1x = dx / d * pk.cos(angle) * bp.v1 + q.V1y = -pk.sin(angle) * bp.v1 + q.V1z = dz / d * pk.cos(angle) * bp.v1 + if pk.fabs(d - bp.R2) < bp.r2 / 2.0: + q.n2 = bp.rho2_in * (bp.R2 - bp.r2 / 2.0 - d) * (d - bp.R2 - bp.r2 / 2.0) / (bp.r2 * bp.r2) * 4.0 + q.V2x = dx / d * pk.cos(bp.angle2) * bp.v2 + q.V2y = -pk.sin(bp.angle2) * bp.v2 + q.V2z = dz / d * pk.cos(bp.angle2) * bp.v2 + u = 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: + if face == 3: + return 4 + return 3 diff --git a/physics/particleflow/hyperbolic_fluxes/__init__.py b/physics/particleflow/hyperbolic_fluxes/__init__.py new file mode 100644 index 0000000..6769574 --- /dev/null +++ b/physics/particleflow/hyperbolic_fluxes/__init__.py @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: 2025 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)``: 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/particleflow/hyperbolic_fluxes/kinetic.py b/physics/particleflow/hyperbolic_fluxes/kinetic.py new file mode 100644 index 0000000..0c57bef --- /dev/null +++ b/physics/particleflow/hyperbolic_fluxes/kinetic.py @@ -0,0 +1,51 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""kinetic: kinetic flux of the two velocity nodes, upwinded node by node. + +A node of density n and velocity V crosses the face from the side it leaves: the nodes of the left +face state with ``V_x > 0`` and those of the right face state with ``V_x < 0``. Each carries the +moments of its velocity, ``n V_x (1, V, V V, V_i^3)``. The velocity of the carrier fluid has no +flux. The face densities are never negative (``face_state`` of ``model.py``), and a time step within +the CFL condition keeps the moments realizable. +""" +import pykokkos as pk + +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +@pk.function +def node_flux(c: float, vx: float, vy: float, vz: float, dim: int, F: Cons) -> None: + """Add to F the flux of the moments of a node of mass flux c = n V_x and velocity V.""" + F.M0 += c + F.M1x += c * vx + F.M1y += c * vy + F.M2xx += c * vx * vx + F.M2xy += c * vx * vy + F.M2yy += c * vy * vy + F.M3x += c * vx * vx * vx + F.M3y += c * vy * vy * vy + if dim == 3: + F.M1z += c * vz + F.M2xz += c * vx * vz + F.M2yz += c * vy * vz + F.M2zz += c * vz * vz + F.M3z += c * vz * vz * vz + + +@pk.function +def riemann(qL: Prim, qR: Prim, uL: Cons, uR: Cons, p: Params, dim: int, GL: Cons, GR: Cons) -> None: + """Kinetic flux of the face: the flux in GL (conservative model). + + The fluxes of the two sides are summed apart, then added: the flux of the mirror image of the + face (left and right states exchanged and mirrored) is then exactly the opposite, and symmetric + initial conditions stay symmetric to the last bit. + """ + FL: Cons = zero_cons() + node_flux(qL.n1 * pk.fmax(qL.V1x, 0.0), qL.V1x, qL.V1y, qL.V1z, dim, FL) + node_flux(qL.n2 * pk.fmax(qL.V2x, 0.0), qL.V2x, qL.V2y, qL.V2z, dim, FL) + FR: Cons = zero_cons() + node_flux(qR.n1 * pk.fmin(qR.V1x, 0.0), qR.V1x, qR.V1y, qR.V1z, dim, FR) + node_flux(qR.n2 * pk.fmin(qR.V2x, 0.0), qR.V2x, qR.V2y, qR.V2z, dim, FR) + add_cons(GL, FL) + add_cons(GL, FR) diff --git a/physics/particleflow/initial_conditions/__init__.py b/physics/particleflow/initial_conditions/__init__.py new file mode 100644 index 0000000..b08ba64 --- /dev/null +++ b/physics/particleflow/initial_conditions/__init__.py @@ -0,0 +1,15 @@ +# SPDX-FileCopyrightText: 2025 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/particleflow/initial_conditions/bump.py b/physics/particleflow/initial_conditions/bump.py new file mode 100644 index 0000000..7a557df --- /dev/null +++ b/physics/particleflow/initial_conditions/bump.py @@ -0,0 +1,42 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""bump: a Gaussian bump of particles with a uniform velocity, one node. + +Parameters (section ``[bump]``): + +- ``x_c``, ``y_c``, ``z_c``: centre of the bump; +- ``radius``: radius, ``n1 = rho exp(-r^2 / radius^2)``; +- ``rho``: density at the centre; +- ``v_x``, ``v_y``, ``v_z``: velocity of the particles. +""" +import pykokkos as pk + +from physics.common import get_real +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("bump", "x_c", 0.5) + res["y_c"] = get_real("bump", "y_c", 0.5) + res["z_c"] = get_real("bump", "z_c", 0.5) if dim == 3 else 0.0 + res["radius"] = get_real("bump", "radius", 0.1) + res["rho"] = get_real("bump", "rho", 0.9) + res["v_x"] = get_real("bump", "v_x", 1.1) + res["v_y"] = get_real("bump", "v_y", 1.2) + res["v_z"] = get_real("bump", "v_z", 1.3) if dim == 3 else 0.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 = zero_prim() + q.n1 = ip.rho * pk.exp(-dist2(x, y, z, ip.x_c, ip.y_c, ip.z_c, dim) / (ip.radius * ip.radius)) + q.V1x = ip.v_x + q.V1y = ip.v_y + if dim == 3: + q.V1z = ip.v_z + return q diff --git a/physics/particleflow/initial_conditions/confining_channel.py b/physics/particleflow/initial_conditions/confining_channel.py new file mode 100644 index 0000000..ce05ef0 --- /dev/null +++ b/physics/particleflow/initial_conditions/confining_channel.py @@ -0,0 +1,44 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""confining_channel: particles in a carrier flow along x that converges towards the axis y = y_c. + +The carrier velocity is ``(vx, -trans_v_grad (y - y_c), -trans_v_grad z)``; the particles start +at the carrier velocity. + +Parameters (section ``[confining_channel]``): + +- ``vx``: velocity of the carrier fluid along x; +- ``trans_v_grad``: transverse gradient of the carrier velocity; +- ``y_c``: axis of the channel; +- ``rho``: density of the particles. +""" +import pykokkos as pk + +from physics.common import get_real +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + res["vx"] = get_real("confining_channel", "vx", 0.2) + res["trans_v_grad"] = get_real("confining_channel", "trans_v_grad", 1.0) + res["y_c"] = get_real("confining_channel", "y_c", 1.0) + res["rho"] = get_real("confining_channel", "rho", 0.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 = zero_prim() + q.Ufx = ip.vx + q.Ufy = -ip.trans_v_grad * (y - ip.y_c) + if dim == 3: + q.Ufz = -ip.trans_v_grad * z + q.n1 = ip.rho + q.V1x = q.Ufx + q.V1y = q.Ufy + q.V1z = q.Ufz + return q diff --git a/physics/particleflow/initial_conditions/empty.py b/physics/particleflow/initial_conditions/empty.py new file mode 100644 index 0000000..cf9e44d --- /dev/null +++ b/physics/particleflow/initial_conditions/empty.py @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""empty: a uniform density of particles at rest, vacuum by default (inflow problems). + +Parameters (section ``[empty]``): + +- ``rho``: density of the particles. +""" +import pykokkos as pk + +from physics.common import get_real +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + return {"rho": get_real("empty", "rho", 0.0)} + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = zero_prim() + q.n1 = ip.rho + return q diff --git a/physics/particleflow/initial_conditions/focusing_ring.py b/physics/particleflow/initial_conditions/focusing_ring.py new file mode 100644 index 0000000..ed7f945 --- /dev/null +++ b/physics/particleflow/initial_conditions/focusing_ring.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""focusing_ring: a ring of particles moving towards its centre, no carrier flow. + +In the ring ``radius <= r <= radius + thickness`` around ``(x_c, y_c)``, r being the distance to the +centre, the particles move towards the centre with the velocity ``-(dx, dy) / (dx^2 + dy^2)`` +(dx, dy: position from the centre) and cross there: a particle at r reaches the centre at +``t = r^2 / 2``. In 3D the ring is a spherical shell and the velocity stays in the plane (x, y). + +Parameters (section ``[focusing_ring]``): + +- ``x_c``, ``y_c``, ``z_c``: centre of the ring; +- ``radius``, ``thickness``: inner radius and thickness of the ring; +- ``rho``: density of the ring. +""" +import pykokkos as pk + +from physics.common import get_real +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("focusing_ring", "x_c", 1.0) + res["y_c"] = get_real("focusing_ring", "y_c", 1.0) + res["z_c"] = get_real("focusing_ring", "z_c", 0.0) if dim == 3 else 0.0 + res["radius"] = get_real("focusing_ring", "radius", 0.6) + res["thickness"] = get_real("focusing_ring", "thickness", 0.3) + res["rho"] = get_real("focusing_ring", "rho", 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 = zero_prim() + r2: float = dist2(x, y, z, ip.x_c, ip.y_c, ip.z_c, dim) + rout: float = ip.radius + ip.thickness + if r2 >= ip.radius * ip.radius: + if r2 <= rout * rout: + dx: float = x - ip.x_c + dy: float = y - ip.y_c + q.n1 = ip.rho + q.V1x = -dx / (dx * dx + dy * dy) + q.V1y = -dy / (dx * dx + dy * dy) + return q diff --git a/physics/particleflow/initial_conditions/jet_crossing_1d.py b/physics/particleflow/initial_conditions/jet_crossing_1d.py new file mode 100644 index 0000000..0fcbdf1 --- /dev/null +++ b/physics/particleflow/initial_conditions/jet_crossing_1d.py @@ -0,0 +1,54 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""jet_crossing_1d: two slabs of particles moving along x towards each other, in a carrier flow. + +The slab 1 (node 1) is centred on ``x = coord1_c`` with the velocity ``(v1_para, 0)``, the slab 2 +(node 2) on ``x = coord2_c`` with the velocity ``(v2_para, 0)``; a slab thinner than a cell may +miss every cell centre. The carrier velocity is uniform. + +Parameters (section ``[jet_crossing_1d]``): + +- ``coord1_c``, ``radius1``, ``rho1_in``, ``v1_para``: centre, half width, density and + velocity of the slab 1; +- ``coord2_c``, ``radius2``, ``rho2_in``, ``v2_para``: the same for the slab 2; +- ``Uf_x``, ``Uf_y``, ``Uf_z``: velocity of the carrier fluid. +""" +import pykokkos as pk + +from physics.common import get_real +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + res = {} + res["coord1_c"] = get_real("jet_crossing_1d", "coord1_c", 0.1) + res["radius1"] = get_real("jet_crossing_1d", "radius1", 0.05) + res["rho1_in"] = get_real("jet_crossing_1d", "rho1_in", 1.1) + res["v1_para"] = get_real("jet_crossing_1d", "v1_para", 1.0) + res["coord2_c"] = get_real("jet_crossing_1d", "coord2_c", 0.9) + res["radius2"] = get_real("jet_crossing_1d", "radius2", 0.05) + res["rho2_in"] = get_real("jet_crossing_1d", "rho2_in", 1.1) + res["v2_para"] = get_real("jet_crossing_1d", "v2_para", -1.0) + res["Uf_x"] = get_real("jet_crossing_1d", "Uf_x", 1.0) + res["Uf_y"] = get_real("jet_crossing_1d", "Uf_y", 1.0) + res["Uf_z"] = get_real("jet_crossing_1d", "Uf_z", 0.0) if dim == 3 else 0.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 = zero_prim() + q.Ufx = ip.Uf_x + q.Ufy = ip.Uf_y + if dim == 3: + q.Ufz = ip.Uf_z + if pk.fabs(x - ip.coord1_c) < ip.radius1: + q.n1 = ip.rho1_in + q.V1x = ip.v1_para + if pk.fabs(x - ip.coord2_c) < ip.radius2: + q.n2 = ip.rho2_in + q.V2x = ip.v2_para + return q diff --git a/physics/particleflow/initial_conditions/rotational_channel.py b/physics/particleflow/initial_conditions/rotational_channel.py new file mode 100644 index 0000000..26e2ab6 --- /dev/null +++ b/physics/particleflow/initial_conditions/rotational_channel.py @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""rotational_channel: a disk of particles at rest in a carrier flow in solid rotation. + +The carrier velocity is ``((y - y_c) / tau_rot, -(x - x_c) / tau_rot, 0)``. Particles at rest give +a zero time step: set ``param.cfl_velocity`` (``radius / tau_rot`` and more as they spread). + +Parameters (section ``[rotational_channel]``): + +- ``x_c``, ``y_c``, ``z_c``: centre of the rotation and of the disk (sphere in 3D); +- ``tau_rot``: time scale of the rotation; +- ``radius``, ``rho``: radius and density of the disk. +""" +import pykokkos as pk + +from physics.common import get_real +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("rotational_channel", "x_c", 1.0) + res["y_c"] = get_real("rotational_channel", "y_c", 1.0) + res["z_c"] = get_real("rotational_channel", "z_c", 0.0) if dim == 3 else 0.0 + res["tau_rot"] = get_real("rotational_channel", "tau_rot", 1.0) + res["radius"] = get_real("rotational_channel", "radius", 0.1) + res["rho"] = get_real("rotational_channel", "rho", 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 = zero_prim() + q.Ufx = (y - ip.y_c) / ip.tau_rot + q.Ufy = -(x - ip.x_c) / ip.tau_rot + if dist2(x, y, z, ip.x_c, ip.y_c, ip.z_c, dim) <= ip.radius * ip.radius: + q.n1 = ip.rho + return q diff --git a/physics/particleflow/initial_conditions/straight_channel.py b/physics/particleflow/initial_conditions/straight_channel.py new file mode 100644 index 0000000..df22cef --- /dev/null +++ b/physics/particleflow/initial_conditions/straight_channel.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""straight_channel: particles at the velocity of a uniform carrier flow along x. + +Parameters (section ``[straight_channel]``): + +- ``rho``: density of the particles; +- ``Uf_x``: velocity of the carrier fluid, along x. +""" +import pykokkos as pk + +from physics.common import get_real +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + return {"rho": get_real("straight_channel", "rho", 0.0), "Uf_x": get_real("straight_channel", "Uf_x", 1.2)} + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = zero_prim() + q.Ufx = ip.Uf_x + q.n1 = ip.rho + q.V1x = ip.Uf_x + return q diff --git a/physics/particleflow/initial_conditions/taylor_green.py b/physics/particleflow/initial_conditions/taylor_green.py new file mode 100644 index 0000000..74b9f1a --- /dev/null +++ b/physics/particleflow/initial_conditions/taylor_green.py @@ -0,0 +1,71 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""taylor_green: a uniform density of particles in the Taylor-Green vortices of a carrier flow. + +With ``(x, y)`` the position in the domain scaled to [0, 1]^2, the carrier velocity is +``(sin(2 pi x) cos(2 pi y), -sin(2 pi y) cos(2 pi x), 0)``, evaluated in the first quarter +``[0, 1/4]^2`` and mirrored, so that the field of the cells has the symmetries of the vortices to the +last bit. The particles start at rest, or at the carrier velocity with ``warm_start``. Particles at +rest give a zero time step: set ``param.cfl_velocity`` (1 for this flow). + +Parameters (section ``[taylor_green]``): + +- ``rho``: density of the particles; +- ``warm_start``: 1: the particles start at the carrier velocity. +""" +import math + +import pykokkos as pk + +from physics.common import get_int, get_real +from ..model import * # noqa: F401,F403 (states and physics of the model) + + +def params(dim): + """Parameters read from the input file.""" + return {"rho": get_real("taylor_green", "rho", 1.0), "warm_start": get_int("taylor_green", "warm_start", 0)} + + +@pk.function +def initial_state(x: float, y: float, z: float, ip: ICParameters, domain: pk.View1D[pk.double], + dim: int) -> Prim: + q: Prim = zero_prim() + xs: float = (x - domain[0]) / domain[3] + ys: float = (y - domain[1]) / domain[4] + # Fold the position into [0, 1/4]^2: x -> 1 - x, then x -> 1/2 - x, the same for y + mirror_x: int = 0 + mirror_y: int = 0 + if xs > 0.5: + xs = 1.0 - xs + mirror_x = 1 + if ys > 0.5: + ys = 1.0 - ys + mirror_y = 1 + mirror_bis_x: int = 0 + mirror_bis_y: int = 0 + if xs > 0.25: + xs = 0.5 - xs + mirror_bis_x = 1 + if ys > 0.25: + ys = 0.5 - ys + mirror_bis_y = 1 + ux: float = pk.sin(2.0 * math.pi * xs) * pk.cos(2.0 * math.pi * ys) + uy: float = -pk.sin(2.0 * math.pi * ys) * pk.cos(2.0 * math.pi * xs) + # x -> 1/2 - x changes the sign of uy, y -> 1/2 - y that of ux; x -> 1 - x that of ux, + # y -> 1 - y that of uy + if mirror_bis_x == 1: + uy = -uy + if mirror_bis_y == 1: + ux = -ux + if mirror_x == 1: + ux = -ux + if mirror_y == 1: + uy = -uy + q.Ufx = ux + q.Ufy = uy + q.n1 = ip.rho + if ip.warm_start == 1: + q.V1x = ux + q.V1y = uy + return q diff --git a/physics/particleflow/model.py b/physics/particleflow/model.py new file mode 100644 index 0000000..ee3d3ad --- /dev/null +++ b/physics/particleflow/model.py @@ -0,0 +1,871 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""Kernel functions of the particleflow model: states, inversion of the moments, face states, walls. + +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``, with the components of 3D, those of z unused in 2D) and their +arrays ``[octant][variable][cell]``, d being the dimension:: + + conservative M0, M1 (d), M2 (lower triangle: xx, xy, yy[, xz, yz, zz]), M3 (d), Uf (d) + primitive n1, n2, V1 (d), V2 (d), Uf (d) + +``M3_i`` is the diagonal third-order moment ``int v_i^3 f``. The two nodes ``(n1, V1)`` and +``(n2, V2)`` are labelled so that ``n1 >= n2``; an empty node has a zero density and velocity. + +``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 and parameters +# ============================================================================= +# Primitive state: densities and velocities of the two nodes, velocity of the carrier fluid +@pk.classtype +class Prim: + def __init__(self, n1: float, n2: float, V1x: float, V1y: float, V1z: float, V2x: float, V2y: float, + V2z: float, Ufx: float, Ufy: float, Ufz: float): + self.n1: float = n1 + self.n2: float = n2 + self.V1x: float = V1x + self.V1y: float = V1y + self.V1z: float = V1z + self.V2x: float = V2x + self.V2y: float = V2y + self.V2z: float = V2z + self.Ufx: float = Ufx + self.Ufy: float = Ufy + self.Ufz: float = Ufz + + +# Conservative state: moments of order 0 to 3 of the velocity distribution, velocity of the carrier +@pk.classtype +class Cons: + def __init__(self, M0: float, M1x: float, M1y: float, M1z: float, M2xx: float, M2xy: float, M2yy: float, + M2xz: float, M2yz: float, M2zz: float, M3x: float, M3y: float, M3z: float, Ufx: float, Ufy: float, + Ufz: float): + self.M0: float = M0 + self.M1x: float = M1x + self.M1y: float = M1y + self.M1z: float = M1z + self.M2xx: float = M2xx + self.M2xy: float = M2xy + self.M2yy: float = M2yy + self.M2xz: float = M2xz + self.M2yz: float = M2yz + self.M2zz: float = M2zz + self.M3x: float = M3x + self.M3y: float = M3y + self.M3z: float = M3z + self.Ufx: float = Ufx + self.Ufy: float = Ufy + self.Ufz: float = Ufz + + +# Parameters of the model, built by make_params +@pk.classtype +class Params: + def __init__(self, tau: float, tau_BGK: float, gravity_x: float, gravity_y: float, gravity_z: float, + cfl_velocity: float, energy_preserving: int, thresh_rho: float, thresh_var: float): + self.tau: float = tau + self.tau_BGK: float = tau_BGK + self.gravity_x: float = gravity_x + self.gravity_y: float = gravity_y + self.gravity_z: float = gravity_z + self.cfl_velocity: float = cfl_velocity + self.energy_preserving: int = energy_preserving + self.thresh_rho: float = thresh_rho + self.thresh_var: float = thresh_var + + +@pk.function +def make_params(m: ModelParameters) -> Params: + """Return the parameters of the model from the named parameters (params of __init__.py).""" + return Params(m.tau, m.tau_BGK, m.gravity_x, m.gravity_y, m.gravity_z, m.cfl_velocity, m.energy_preserving, + m.thresh_rho, m.thresh_var) + + +@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, 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, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + + +# ============================================================================= +# Components +# ============================================================================= +@pk.function +def vel(q: Prim, k: int, d: int) -> float: + """Return the component d of the velocity of the node k (1 or 2).""" + if k == 1: + if d == 0: + return q.V1x + if d == 1: + return q.V1y + return q.V1z + if d == 0: + return q.V2x + if d == 1: + return q.V2y + return q.V2z + + +@pk.function +def set_vel(q: Prim, k: int, d: int, v: float) -> None: + """Set the component d of the velocity of the node k (1 or 2).""" + if k == 1: + if d == 0: + q.V1x = v + elif d == 1: + q.V1y = v + else: + q.V1z = v + else: + if d == 0: + q.V2x = v + elif d == 1: + q.V2y = v + else: + q.V2z = v + + +@pk.function +def uf_prim(q: Prim, d: int) -> float: + """Return the component d of the velocity of the carrier fluid of a primitive state.""" + if d == 0: + return q.Ufx + if d == 1: + return q.Ufy + return q.Ufz + + +@pk.function +def set_uf_prim(q: Prim, d: int, v: float) -> None: + """Set the component d of the velocity of the carrier fluid of a primitive state.""" + if d == 0: + q.Ufx = v + elif d == 1: + q.Ufy = v + else: + q.Ufz = v + + +@pk.function +def uf_cons(u: Cons, d: int) -> float: + """Return the component d of the velocity of the carrier fluid of a conservative state.""" + if d == 0: + return u.Ufx + if d == 1: + return u.Ufy + return u.Ufz + + +@pk.function +def set_uf_cons(u: Cons, d: int, v: float) -> None: + """Set the component d of the velocity of the carrier fluid of a conservative state.""" + if d == 0: + u.Ufx = v + elif d == 1: + u.Ufy = v + else: + u.Ufz = v + + +@pk.function +def m1(u: Cons, d: int) -> float: + """Return the component d of the first-order moment.""" + if d == 0: + return u.M1x + if d == 1: + return u.M1y + return u.M1z + + +@pk.function +def set_m1(u: Cons, d: int, v: float) -> None: + """Set the component d of the first-order moment.""" + if d == 0: + u.M1x = v + elif d == 1: + u.M1y = v + else: + u.M1z = v + + +@pk.function +def sym(i: int, j: int) -> int: + """Return the index of the component (i, j) of a symmetric tensor in its lower triangle. + + xx 0, xy 1, yy 2, xz 3, yz 4, zz 5. + """ + if i < j: + return j * (j + 1) // 2 + i + return i * (i + 1) // 2 + j + + +@pk.function +def sym_row(k: int) -> int: + """Return the row i of the component k of the lower triangle of a symmetric tensor (i >= j).""" + if k == 0: + return 0 + if k <= 2: + return 1 + return 2 + + +@pk.function +def sym_col(k: int) -> int: + """Return the column j of the component k of the lower triangle of a symmetric tensor (i >= j).""" + if k == 0 or k == 1 or k == 3: + return 0 + if k == 2 or k == 4: + return 1 + return 2 + + +@pk.function +def m2(u: Cons, i: int, j: int) -> float: + """Return the component (i, j) of the second-order moment.""" + k: int = sym(i, j) + if k == 0: + return u.M2xx + if k == 1: + return u.M2xy + if k == 2: + return u.M2yy + if k == 3: + return u.M2xz + if k == 4: + return u.M2yz + return u.M2zz + + +@pk.function +def set_m2(u: Cons, i: int, j: int, v: float) -> None: + """Set the component (i, j) of the second-order moment.""" + k: int = sym(i, j) + if k == 0: + u.M2xx = v + elif k == 1: + u.M2xy = v + elif k == 2: + u.M2yy = v + elif k == 3: + u.M2xz = v + elif k == 4: + u.M2yz = v + else: + u.M2zz = v + + +@pk.function +def m3(u: Cons, d: int) -> float: + """Return the component d of the diagonal third-order moment.""" + if d == 0: + return u.M3x + if d == 1: + return u.M3y + return u.M3z + + +@pk.function +def set_m3(u: Cons, d: int, v: float) -> None: + """Set the component d of the diagonal third-order moment.""" + if d == 0: + u.M3x = v + elif d == 1: + u.M3y = v + else: + u.M3z = v + + +# ============================================================================= +# 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.""" + u: Cons = zero_cons() + u.M0 = A[iOct][0][ic] + if dim == 3: + u.M1x = A[iOct][1][ic] + u.M1y = A[iOct][2][ic] + u.M1z = A[iOct][3][ic] + u.M2xx = A[iOct][4][ic] + u.M2xy = A[iOct][5][ic] + u.M2yy = A[iOct][6][ic] + u.M2xz = A[iOct][7][ic] + u.M2yz = A[iOct][8][ic] + u.M2zz = A[iOct][9][ic] + u.M3x = A[iOct][10][ic] + u.M3y = A[iOct][11][ic] + u.M3z = A[iOct][12][ic] + u.Ufx = A[iOct][13][ic] + u.Ufy = A[iOct][14][ic] + u.Ufz = A[iOct][15][ic] + else: + u.M1x = A[iOct][1][ic] + u.M1y = A[iOct][2][ic] + u.M2xx = A[iOct][3][ic] + u.M2xy = A[iOct][4][ic] + u.M2yy = A[iOct][5][ic] + u.M3x = A[iOct][6][ic] + u.M3y = A[iOct][7][ic] + u.Ufx = A[iOct][8][ic] + u.Ufy = A[iOct][9][ic] + return u + + +@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.M0 + if dim == 3: + A[iOct][1][ic] = u.M1x + A[iOct][2][ic] = u.M1y + A[iOct][3][ic] = u.M1z + A[iOct][4][ic] = u.M2xx + A[iOct][5][ic] = u.M2xy + A[iOct][6][ic] = u.M2yy + A[iOct][7][ic] = u.M2xz + A[iOct][8][ic] = u.M2yz + A[iOct][9][ic] = u.M2zz + A[iOct][10][ic] = u.M3x + A[iOct][11][ic] = u.M3y + A[iOct][12][ic] = u.M3z + A[iOct][13][ic] = u.Ufx + A[iOct][14][ic] = u.Ufy + A[iOct][15][ic] = u.Ufz + else: + A[iOct][1][ic] = u.M1x + A[iOct][2][ic] = u.M1y + A[iOct][3][ic] = u.M2xx + A[iOct][4][ic] = u.M2xy + A[iOct][5][ic] = u.M2yy + A[iOct][6][ic] = u.M3x + A[iOct][7][ic] = u.M3y + A[iOct][8][ic] = u.Ufx + A[iOct][9][ic] = u.Ufy + + +@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.""" + q: Prim = zero_prim() + q.n1 = A[iOct][0][ic] + q.n2 = A[iOct][1][ic] + if dim == 3: + q.V1x = A[iOct][2][ic] + q.V1y = A[iOct][3][ic] + q.V1z = A[iOct][4][ic] + q.V2x = A[iOct][5][ic] + q.V2y = A[iOct][6][ic] + q.V2z = A[iOct][7][ic] + q.Ufx = A[iOct][8][ic] + q.Ufy = A[iOct][9][ic] + q.Ufz = A[iOct][10][ic] + else: + q.V1x = A[iOct][2][ic] + q.V1y = A[iOct][3][ic] + q.V2x = A[iOct][4][ic] + q.V2y = A[iOct][5][ic] + q.Ufx = A[iOct][6][ic] + q.Ufy = A[iOct][7][ic] + return q + + +@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.n1 + A[iOct][1][ic] = q.n2 + if dim == 3: + A[iOct][2][ic] = q.V1x + A[iOct][3][ic] = q.V1y + A[iOct][4][ic] = q.V1z + A[iOct][5][ic] = q.V2x + A[iOct][6][ic] = q.V2y + A[iOct][7][ic] = q.V2z + A[iOct][8][ic] = q.Ufx + A[iOct][9][ic] = q.Ufy + A[iOct][10][ic] = q.Ufz + else: + A[iOct][2][ic] = q.V1x + A[iOct][3][ic] = q.V1y + A[iOct][4][ic] = q.V2x + A[iOct][5][ic] = q.V2y + A[iOct][6][ic] = q.Ufx + A[iOct][7][ic] = q.Ufy + + +# ============================================================================= +# 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 (``derived`` of ``variables`` of __init__.py). + + The mean velocity ``Up_i = M1_i / M0`` (k < d), the covariance + ``a_ij = M2_ij / M0 - Up_i Up_j``, then the central third-order moments + ``a_iii = M3_i / M0 - Up_i^3 - 3 a_ii Up_i`` (zero when a_ii <= thresh_var); all zero in vacuum. + """ + rho: float = u.M0 + if rho <= p.thresh_rho: + return 0.0 + ns: int = dim * (dim + 1) // 2 + if k < dim: + return m1(u, k) / rho + if k < dim + ns: + ia: int = sym_row(k - dim) + ja: int = sym_col(k - dim) + return m2(u, ia, ja) / rho - m1(u, ia) * m1(u, ja) / (rho * rho) + ib: int = k - dim - ns + vi: float = m1(u, ib) / rho + aii: float = m2(u, ib, ib) / rho - vi * vi + if aii <= p.thresh_var: + return 0.0 + return m3(u, ib) / rho - vi * vi * vi - 3.0 * aii * vi + + +# ============================================================================= +# Moments of the nodes and inversion +# ============================================================================= +@pk.function +def prim_to_cons(q: Prim, p: Params, dim: int) -> Cons: + """Return the moments of the two nodes of q, and its carrier velocity.""" + w: Cons = zero_cons() + w.M0 = q.n1 + q.n2 + for i in range(dim): + set_uf_cons(w, i, uf_prim(q, i)) + v1: float = vel(q, 1, i) + v2: float = vel(q, 2, i) + set_m1(w, i, q.n1 * v1 + q.n2 * v2) + set_m3(w, i, q.n1 * v1 * v1 * v1 + q.n2 * v2 * v2 * v2) + for j in range(i + 1): + set_m2(w, i, j, q.n1 * v1 * vel(q, 1, j) + q.n2 * v2 * vel(q, 2, j)) + return w + + +@pk.function +def swap_nodes(r: Prim) -> None: + """Exchange the two nodes of r.""" + n: float = r.n1 + r.n1 = r.n2 + r.n2 = n + t: float = r.V1x + r.V1x = r.V2x + r.V2x = t + t = r.V1y + r.V1y = r.V2y + r.V2y = t + t = r.V1z + r.V1z = r.V2z + r.V2z = t + + +@pk.function +def cons_to_prim(w: Cons, p: Params, dim: int) -> Prim: + """Return the two nodes of the moments w (inversion of the moments), with its carrier velocity. + + With the mean velocity v, the covariance a_ij and the central third-order moments b_i, the + nodes lie on the line through v along the main axis m (largest variance): their weights give the + skewness b_m of that axis, ``n1,2 = rho (1 +- beta) / 2`` with + ``beta = b_m / sqrt(b_m^2 + 4 a_mm^3)``, and the deviations along the axis i are proportional to + the cross correlation a_im. A cell whose variances sum below thresh_var has one node, at v; a + density below thresh_rho is vacuum. + """ + r: Prim = zero_prim() + for d in range(dim): + set_uf_prim(r, d, uf_cons(w, d)) + rho: float = w.M0 + if rho <= p.thresh_rho: + return r + + # Mean velocity v, covariance a (lower triangle) and central third-order moments b + v: List[float] = [0.0, 0.0, 0.0] + for d in range(dim): + v[d] = m1(w, d) / rho + a: List[float] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + for i in range(dim): + for j in range(i + 1): + a[sym(i, j)] = m2(w, i, j) / rho - v[i] * v[j] + b: List[float] = [0.0, 0.0, 0.0] + for i in range(dim): + b[i] = m3(w, i) / rho - 3.0 * m2(w, i, i) / rho * v[i] + 2.0 * v[i] * v[i] * v[i] + + # Negative variances come from rounding errors on realizable moments: zero + var: float = 0.0 + for i in range(dim): + if a[sym(i, i)] < 0.0: + a[sym(i, i)] = 0.0 + var += a[sym(i, i)] + + # Main axis: the largest variance; none when the variances vanish + im: int = -1 + if var > p.thresh_var: + amax: float = 0.0 + for i in range(dim): + if a[sym(i, i)] > amax: + im = i + amax = a[sym(i, i)] + if im == -1: + r.n1 = rho + for d in range(dim): + set_vel(r, 1, d, v[d]) + return r + + if p.energy_preserving == 1: + for i in range(dim): + for j in range(i): + aij: float = a[sym(i, j)] + sq: float = pk.sqrt(a[sym(i, i)] * a[sym(j, j)]) + if aij > 0.0: + a[sym(i, j)] = sq + elif aij < 0.0: + a[sym(i, j)] = -sq + + amm: float = a[sym(im, im)] + beta: float = b[im] / pk.sqrt(b[im] * b[im] + 4.0 * amm * amm * amm) + + n1: float = rho * (1.0 + beta) / 2.0 + n2: float = rho * (1.0 - beta) / 2.0 + if n1 <= p.thresh_rho and n2 <= p.thresh_rho: + return r + if n1 <= p.thresh_rho or n2 <= p.thresh_rho: + # One node left: the mean velocity + r.n1 = rho + for d in range(dim): + set_vel(r, 1, d, v[d]) + return r + r.n1 = n1 + r.n2 = n2 + sm: float = pk.sqrt(amm) + s12: float = pk.sqrt(n2 / n1) + s21: float = pk.sqrt(n1 / n2) + for i in range(dim): + dev: float = a[sym(i, im)] / sm + if i == im: + dev = sm + set_vel(r, 1, i, v[i] - dev * s12) + set_vel(r, 2, i, v[i] + dev * s21) + if r.n2 > r.n1: + swap_nodes(r) + return r + + +# ============================================================================= +# Time step +# ============================================================================= +@pk.function +def hyperbolic_inv_dt(q: Prim, p: Params, h: float, dim: int) -> float: + """Return the inverse stable time step, ``max(sum_d |V1_d|, sum_d |V2_d|, cfl_velocity) / h``.""" + s1: float = 0.0 + s2: float = 0.0 + for d in range(dim): + s1 += pk.fabs(vel(q, 1, d)) + s2 += pk.fabs(vel(q, 2, d)) + return pk.fmax(p.cfl_velocity, pk.fmax(s1, s2)) / h + + +# ============================================================================= +# Face states, rotations +# ============================================================================= +@pk.function +def rotate_prim(q: Prim, d: int) -> None: + """Swap the components x and d of the velocities: the direction d becomes x, and back.""" + t: float = 0.0 + if d == 1: + t = q.V1x + q.V1x = q.V1y + q.V1y = t + t = q.V2x + q.V2x = q.V2y + q.V2y = t + t = q.Ufx + q.Ufx = q.Ufy + q.Ufy = t + elif d == 2: + t = q.V1x + q.V1x = q.V1z + q.V1z = t + t = q.V2x + q.V2x = q.V2z + q.V2z = t + t = q.Ufx + q.Ufx = q.Ufz + q.Ufz = t + + +@pk.function +def rotate_cons(u: Cons, d: int) -> None: + """Swap the axes x and d of the moments: the direction d becomes x, and back.""" + t: float = 0.0 + if d == 1: + t = u.M1x + u.M1x = u.M1y + u.M1y = t + t = u.M2xx + u.M2xx = u.M2yy + u.M2yy = t + t = u.M2xz + u.M2xz = u.M2yz + u.M2yz = t + t = u.M3x + u.M3x = u.M3y + u.M3y = t + t = u.Ufx + u.Ufx = u.Ufy + u.Ufy = t + elif d == 2: + t = u.M1x + u.M1x = u.M1z + u.M1z = t + t = u.M2xx + u.M2xx = u.M2zz + u.M2zz = t + t = u.M2xy + u.M2xy = u.M2yz + u.M2yz = t + t = u.M3x + u.M3x = u.M3z + u.M3z = t + t = u.Ufx + u.Ufx = u.Ufz + u.Ufz = t + + +@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.n1 = wa * a.n1 + wb * b.n1 + q.n2 = wa * a.n2 + wb * b.n2 + for d in range(dim): + set_vel(q, 1, d, wa * vel(a, 1, d) + wb * vel(b, 1, d)) + set_vel(q, 2, d, wa * vel(a, 2, d) + wb * vel(b, 2, d)) + set_uf_prim(q, d, wa * uf_prim(a, d) + wb * uf_prim(b, d)) + 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). + + Quasi-second order (Vikas et al. 2011): at second order (so2 == 2), the densities of the nodes + get half their limited slope, their velocities stay those of the cell. The face densities lie + between those of the neighbour cells, so they are not negative. + """ + q: Prim = load_prim(Qg, iOct, cell_index(c0, c1, c2, bx + 4, 2, dim), dim) + if so2 == 2: + ics: int = cell_index(c0, c1, c2, bx + 2, 1, dim) + q.n1 += 0.5 * s * S[iOct][0][ics] + q.n2 += 0.5 * s * S[iOct][1][ics] + 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 the reconstructed face state of the ghost cell +# ============================================================================= +@pk.function +def reverse_velocities(q: Prim, d: int, noslip: int, dim: int) -> None: + """Reverse the component d of the velocities of the nodes, or every component when noslip == 1.""" + for k in range(dim): + if noslip == 1 or k == d: + set_vel(q, 1, k, -vel(q, 1, k)) + set_vel(q, 2, k, -vel(q, 2, k)) + + +@pk.function +def reflect_moments(u: Cons, d: int, dim: int) -> None: + """Mirror the moments through a plane of normal d: the moments odd in v_d change sign.""" + set_m1(u, d, -m1(u, d)) + set_m3(u, d, -m3(u, d)) + for j in range(dim): + if j != d: + set_m2(u, d, j, -m2(u, d, j)) + + +@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) of the nodes reversed, or unchanged (3); kind 4 takes qghost; the other + kinds keep qface. + """ + q: Prim = qface + if kind == 1 or kind == 2 or kind == 3: + q = qin + if kind != 3: + noslip: int = 0 + if kind == 2: + noslip = 1 + reverse_velocities(q, d, noslip, dim) + elif kind == 4: + q = qghost + 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. + + Mirror image of that of the inside cell gin (diffusion fluxes; this model has none). + """ + 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 +# ============================================================================= +@pk.function +def add_cons(F: Cons, D: Cons) -> None: + """Add the flux D to the flux F.""" + F.M0 += D.M0 + F.M1x += D.M1x + F.M1y += D.M1y + F.M1z += D.M1z + F.M2xx += D.M2xx + F.M2xy += D.M2xy + F.M2yy += D.M2yy + F.M2xz += D.M2xz + F.M2yz += D.M2yz + F.M2zz += D.M2zz + F.M3x += D.M3x + F.M3y += D.M3y + F.M3z += D.M3z + F.Ufx += D.Ufx + F.Ufy += D.Ufy + F.Ufz += D.Ufz + + +@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.""" + G: Cons = zero_cons() + G.M0 = F.M0 * dtdx + G.M1x = F.M1x * dtdx + G.M1y = F.M1y * dtdx + G.M1z = F.M1z * dtdx + G.M2xx = F.M2xx * dtdx + G.M2xy = F.M2xy * dtdx + G.M2yy = F.M2yy * dtdx + G.M2xz = F.M2xz * dtdx + G.M2yz = F.M2yz * dtdx + G.M2zz = F.M2zz * dtdx + G.M3x = F.M3x * dtdx + G.M3y = F.M3y * dtdx + G.M3z = F.M3z * dtdx + G.Ufx = F.Ufx * dtdx + G.Ufy = F.Ufy * dtdx + G.Ufz = F.Ufz * dtdx + store_cons(A, iOct, f, dim, G) + + +# ============================================================================= +# Relaxations: exact maps of the moments +# ============================================================================= +@pk.function +def affine_velocity_map(w: Cons, alpha: float, bx: float, by: float, bz: float, dim: int) -> None: + """Map every velocity v of the distribution of w to ``alpha v + beta``: exact on the moments. + + ``M1 -> alpha M1 + beta M0``, ``M2_ij -> alpha^2 M2_ij + alpha (beta_j M1_i + beta_i M1_j) + + beta_i beta_j M0``, ``M3_i -> alpha^3 M3_i + 3 alpha^2 beta_i M2_ii + 3 alpha beta_i^2 M1_i + + beta_i^3 M0``. The moments stay realizable. + """ + o: Cons = w + beta: List[float] = [0.0, 0.0, 0.0] + beta[0] = bx + beta[1] = by + beta[2] = bz + for i in range(dim): + bi: float = beta[i] + set_m1(w, i, alpha * m1(o, i) + bi * o.M0) + set_m3(w, i, alpha * alpha * alpha * m3(o, i) + 3.0 * alpha * alpha * bi * m2(o, i, i) + + 3.0 * alpha * bi * bi * m1(o, i) + bi * bi * bi * o.M0) + for j in range(i + 1): + set_m2(w, i, j, alpha * alpha * m2(o, i, j) + alpha * (beta[j] * m1(o, i) + bi * m1(o, j)) + + bi * beta[j] * o.M0) + + +@pk.function +def copy_cons(w: Cons, u: Cons) -> None: + """Copy the state u into w.""" + w.M0 = u.M0 + w.M1x = u.M1x + w.M1y = u.M1y + w.M1z = u.M1z + w.M2xx = u.M2xx + w.M2xy = u.M2xy + w.M2yy = u.M2yy + w.M2xz = u.M2xz + w.M2yz = u.M2yz + w.M2zz = u.M2zz + w.M3x = u.M3x + w.M3y = u.M3y + w.M3z = u.M3z + w.Ufx = u.Ufx + w.Ufy = u.Ufy + w.Ufz = u.Ufz + + +# ============================================================================= +# 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 + + +# ============================================================================= +# 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/particleflow/refine_conditions/M0_gradient.py b/physics/particleflow/refine_conditions/M0_gradient.py new file mode 100644 index 0000000..c72363b --- /dev/null +++ b/physics/particleflow/refine_conditions/M0_gradient.py @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""M0_gradient: relative jump of the density M0 of the particles.""" +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/particleflow/refine_conditions/__init__.py b/physics/particleflow/refine_conditions/__init__.py new file mode 100644 index 0000000..e58c5f8 --- /dev/null +++ b/physics/particleflow/refine_conditions/__init__.py @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: 2025 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/particleflow/refine_conditions/any_gradient.py b/physics/particleflow/refine_conditions/any_gradient.py new file mode 100644 index 0000000..989fe0f --- /dev/null +++ b/physics/particleflow/refine_conditions/any_gradient.py @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""any_gradient: max of the relative jumps of the density M0 and of the momentum M1 of the particles.""" +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: + eps: float = scalar_gradient(Ug[iOct][0][ia], Ug[iOct][0][ib]) + for d in range(dim): + eps = pk.fmax(eps, scalar_gradient(Ug[iOct][1 + d][ia], Ug[iOct][1 + d][ib])) + return eps diff --git a/physics/particleflow/relaxations/__init__.py b/physics/particleflow/relaxations/__init__.py new file mode 100644 index 0000000..78efe99 --- /dev/null +++ b/physics/particleflow/relaxations/__init__.py @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2025 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: + +- ``relaxation(w, qn, p, dt, dim)``: replaces the conservative state ``w`` of a cell by its state + after a relaxation during the time step ``dt`` (its projection on the equilibrium for an + instantaneous relaxation), ``qn`` being the primitive state of ``w``. It applies once per time + step, after the time integration (after the average of the stages at ``time_order = 2``). +""" diff --git a/physics/particleflow/relaxations/drag.py b/physics/particleflow/relaxations/drag.py new file mode 100644 index 0000000..f895cb4 --- /dev/null +++ b/physics/particleflow/relaxations/drag.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""drag: reprojection, then the drag towards the carrier velocity Uf with the gravity, exact over dt. + +After each time step, the moments are projected on their two nodes (as ``reprojection``), then each +particle follows ``dV/dt = (Uf - V) / tau + g`` (``param.tau``, ``param.gravity_x``, +``param.gravity_y``, ``param.gravity_z``) during the time step dt, Uf constant: +``V -> alpha V + (1 - alpha) (Uf + tau g)``, ``alpha = exp(-dt / tau)``. This affine map is applied +exactly to the moments: they stay realizable and on the two nodes for any dt / tau. The drag is +split from the transport (Lie splitting), outside the average of the stages at ``time_order = 2``. +""" +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: + u: Cons = prim_to_cons(qn, p, dim) + copy_cons(w, u) + alpha: float = pk.exp(-dt / p.tau) + bx: float = (1.0 - alpha) * (w.Ufx + p.tau * gravity(p, 0)) + by: float = (1.0 - alpha) * (w.Ufy + p.tau * gravity(p, 1)) + bz: float = 0.0 + if dim == 3: + bz = (1.0 - alpha) * (w.Ufz + p.tau * gravity(p, 2)) + affine_velocity_map(w, alpha, bx, by, bz, dim) diff --git a/physics/particleflow/relaxations/drag_bgk.py b/physics/particleflow/relaxations/drag_bgk.py new file mode 100644 index 0000000..367c258 --- /dev/null +++ b/physics/particleflow/relaxations/drag_bgk.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""drag_bgk: reprojection, the drag with gravity (as ``drag``), then a BGK relaxation, exact over dt. + +After the projection on the two nodes and the drag of ``drag``, every velocity relaxes to the mean +velocity ``Up = M1 / M0`` of the cell with the relaxation time ``param.tau_BGK``: +``V -> beta V + (1 - beta) Up``, ``beta = exp(-dt / tau_BGK)``, applied exactly to the moments. The +mean velocity is kept; the covariance decreases as ``beta^2``. +""" +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: + u: Cons = prim_to_cons(qn, p, dim) + copy_cons(w, u) + # Drag towards Uf with the gravity: V -> alpha V + (1 - alpha) (Uf + tau g) + alpha: float = pk.exp(-dt / p.tau) + bx: float = (1.0 - alpha) * (w.Ufx + p.tau * gravity(p, 0)) + by: float = (1.0 - alpha) * (w.Ufy + p.tau * gravity(p, 1)) + bz: float = 0.0 + if dim == 3: + bz = (1.0 - alpha) * (w.Ufz + p.tau * gravity(p, 2)) + affine_velocity_map(w, alpha, bx, by, bz, dim) + # BGK: V -> beta V + (1 - beta) Up + if w.M0 > p.thresh_rho: + beta: float = pk.exp(-dt / p.tau_BGK) + cx: float = (1.0 - beta) * w.M1x / w.M0 + cy: float = (1.0 - beta) * w.M1y / w.M0 + cz: float = 0.0 + if dim == 3: + cz = (1.0 - beta) * w.M1z / w.M0 + affine_velocity_map(w, beta, cx, cy, cz, dim) diff --git a/physics/particleflow/relaxations/gravity.py b/physics/particleflow/relaxations/gravity.py new file mode 100644 index 0000000..b8b03cb --- /dev/null +++ b/physics/particleflow/relaxations/gravity.py @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""gravity: reprojection, then the gravity alone, every velocity shifted by ``g dt``, exact. + +After each time step, the moments are projected on their two nodes (as ``reprojection``), then every +velocity moves by ``g dt`` (``param.gravity_x``, ``param.gravity_y``, ``param.gravity_z``), exactly +on the moments (Lie splitting from the transport). +""" +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: + u: Cons = prim_to_cons(qn, p, dim) + copy_cons(w, u) + gz: float = 0.0 + if dim == 3: + gz = gravity(p, 2) * dt + affine_velocity_map(w, 1.0, gravity(p, 0) * dt, gravity(p, 1) * dt, gz, dim) diff --git a/physics/particleflow/relaxations/reprojection.py b/physics/particleflow/relaxations/reprojection.py new file mode 100644 index 0000000..8e63aff --- /dev/null +++ b/physics/particleflow/relaxations/reprojection.py @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: 2026 canoP authors +# +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +"""reprojection: projection of the moments on the two-node closure, after each time step, no drag. + +The update by the fluxes and the average of the Runge-Kutta stages give realizable moments that two +nodes do not reproduce in general. The moments are replaced by those of their two nodes +(``prim_to_cons(cons_to_prim(w))``), so that each step starts from the closure: the information that +the nodes cannot carry is discarded once, instead of entering the average of the next step. The +particles move freely (no carrier flow, no 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: + u: Cons = prim_to_cons(qn, p, dim) + copy_cons(w, u) diff --git a/physics/twophase5eq/relaxations/__init__.py b/physics/twophase5eq/relaxations/__init__.py index fe3353d..78efe99 100644 --- a/physics/twophase5eq/relaxations/__init__.py +++ b/physics/twophase5eq/relaxations/__init__.py @@ -1,11 +1,12 @@ # 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: -- ``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. +- ``relaxation(w, qn, p, dt, dim)``: replaces the conservative state ``w`` of a cell by its state + after a relaxation during the time step ``dt`` (its projection on the equilibrium for an + instantaneous relaxation), ``qn`` being the primitive state of ``w``. It applies once per time + step, after the time integration (after the average of the stages at ``time_order = 2``). """ diff --git a/physics/twophase7eq/relaxations/__init__.py b/physics/twophase7eq/relaxations/__init__.py index fe3353d..78efe99 100644 --- a/physics/twophase7eq/relaxations/__init__.py +++ b/physics/twophase7eq/relaxations/__init__.py @@ -1,11 +1,12 @@ # 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: -- ``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. +- ``relaxation(w, qn, p, dt, dim)``: replaces the conservative state ``w`` of a cell by its state + after a relaxation during the time step ``dt`` (its projection on the equilibrium for an + instantaneous relaxation), ``qn`` being the primitive state of ``w``. It applies once per time + step, after the time integration (after the average of the stages at ``time_order = 2``). """ diff --git a/physics/twophase7eq/relaxations/pressure_relaxation.py b/physics/twophase7eq/relaxations/pressure_relaxation.py index 01fcfdc..46b064c 100644 --- a/physics/twophase7eq/relaxations/pressure_relaxation.py +++ b/physics/twophase7eq/relaxations/pressure_relaxation.py @@ -40,5 +40,5 @@ def pressure_relaxation(w: Cons, qn: Prim, eg: Eos, el: Eos, dim: int) -> None: @pk.function -def relaxation(w: Cons, qn: Prim, p: Params, dim: int) -> None: +def relaxation(w: Cons, qn: Prim, p: Params, dt: float, dim: int) -> None: pressure_relaxation(w, qn, p.eg, p.el, dim) diff --git a/physics/twophase7eq/relaxations/pressure_velocity_relaxation.py b/physics/twophase7eq/relaxations/pressure_velocity_relaxation.py index 58a62af..8dd5742 100644 --- a/physics/twophase7eq/relaxations/pressure_velocity_relaxation.py +++ b/physics/twophase7eq/relaxations/pressure_velocity_relaxation.py @@ -66,7 +66,7 @@ def velocity_relaxation(w: Cons, qn: Prim, eg: Eos, el: Eos, dim: int) -> None: @pk.function -def relaxation(w: Cons, qn: Prim, p: Params, dim: int) -> None: +def relaxation(w: Cons, qn: Prim, p: Params, dt: float, dim: int) -> None: pressure_relaxation(w, qn, p.eg, p.el, dim) qp: Prim = cons_to_prim(w, p, dim) velocity_relaxation(w, qp, p.eg, p.el, dim) diff --git a/physics/twophase7eq/relaxations/velocity_relaxation.py b/physics/twophase7eq/relaxations/velocity_relaxation.py index 6f4ad52..99b9881 100644 --- a/physics/twophase7eq/relaxations/velocity_relaxation.py +++ b/physics/twophase7eq/relaxations/velocity_relaxation.py @@ -37,5 +37,5 @@ def velocity_relaxation(w: Cons, qn: Prim, eg: Eos, el: Eos, dim: int) -> None: @pk.function -def relaxation(w: Cons, qn: Prim, p: Params, dim: int) -> None: +def relaxation(w: Cons, qn: Prim, p: Params, dt: float, dim: int) -> None: velocity_relaxation(w, qn, p.eg, p.el, dim) diff --git a/settings/settings_particleflow_focusing_ring.ini b/settings/settings_particleflow_focusing_ring.ini new file mode 100644 index 0000000..7594f0b --- /dev/null +++ b/settings/settings_particleflow_focusing_ring.ini @@ -0,0 +1,66 @@ +[simulation] +; model: a directory of physics/ +model = particleflow +; final time +tmax = 0.6 +; CFL number (realizable moments up to 2/3 with minmod; margin for the second stage) +cfl = 0.4 +; order in space: 1, or 2 (densities of the nodes reconstructed, velocities of the cell) +space_order = 2 +; order in time: 1 (forward Euler) or 2 (SSP Runge-Kutta 2) +time_order = 2 +; slope limiter of the 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: the domain [0, 2] x [0, 2] +ntree_x = 2 +ntree_y = 2 +ntree_z = 2 +; 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 = 8 +by = 8 +bz = 8 +; uniform mesh of 128 x 128 cells +min_refine = 6 +max_refine = 6 +epsilon_refine = -1 +epsilon_coarsen = -1 + +[io] +; prefix of the output files +output_prefix = particleflow_focusing_ring +; number of outputs over the run (0: none, -1: every time step) +save_count = 30 +; fields written with the moments: nodes, mean velocity, covariance +write_variables = n1, n2, V1_x, V1_y, V2_x, V2_y, Up_x, Up_y, a_xx, a_xy, a_yy + +[physics] +; initial condition: physics//initial_conditions/.py +initial_condition = focusing_ring +; boundary condition: boundary_conditions/.py (overridden by amr if periodic) +boundary_condition = neuman +; refinement criterion: refine_conditions/.py +refine_condition = M0_gradient +; hyperbolic flux: hyperbolic_fluxes/.py, or none +hyperbolic_flux = kinetic +; diffusion flux: diffusion_fluxes/.py, or none +diffusion_flux = none +; projection of the moments on the two nodes after each step (free particles) +relaxation = reprojection +; source term: sources/.py, or none +source = none + +[focusing_ring] +; centre, inner radius and thickness of the ring, density +x_c = 1.0 +y_c = 1.0 +radius = 0.6 +thickness = 0.3 +rho = 1.0 diff --git a/settings/settings_particleflow_jet_crossing.ini b/settings/settings_particleflow_jet_crossing.ini new file mode 100644 index 0000000..36b40dc --- /dev/null +++ b/settings/settings_particleflow_jet_crossing.ini @@ -0,0 +1,76 @@ +[simulation] +; model: a directory of physics/ +model = particleflow +; final time +tmax = 1.5 +; CFL number (realizable moments up to 2/3 with minmod; margin for the second stage) +cfl = 0.4 +; order in space: 1, or 2 (densities of the nodes reconstructed, velocities of the cell) +space_order = 2 +; order in time: 1 (forward Euler) or 2 (SSP Runge-Kutta 2) +time_order = 2 +; slope limiter of the 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 = 8 +by = 8 +bz = 8 +; minimum level of the cells (2^level cells per tree and direction) +min_refine = 5 +; maximum level of the cells +max_refine = 8 +; 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 = particleflow_jet_crossing +; number of outputs over the run (0: none, -1: every time step) +save_count = 30 +; fields written with the moments: nodes, mean velocity, covariance +write_variables = n1, n2, V1_x, V1_y, V2_x, V2_y, Up_x, Up_y, a_xx, a_xy, a_yy + +[physics] +; initial condition: physics//initial_conditions/.py +initial_condition = empty +; boundary condition: boundary_conditions/.py (overridden by amr if periodic) +boundary_condition = jet_crossing +; refinement criterion: refine_conditions/.py +refine_condition = M0_gradient +; hyperbolic flux: hyperbolic_fluxes/.py, or none +hyperbolic_flux = kinetic +; diffusion flux: diffusion_fluxes/.py, or none +diffusion_flux = none +; projection of the moments on the two nodes after each step (free particles) +relaxation = reprojection +; source term: sources/.py, or none +source = none + +[jet_crossing] +; the two jets enter through xmin, at y = 0.3 upwards and y = 0.7 downwards, and cross at x = 0.2 +face1 = 0 +coord1_c = 0.3 +radius1 = 0.05 +rho1_in = 1.0 +v1_para = 1.0 +v1_perp = 1.0 +face2 = 0 +coord2_c = 0.7 +radius2 = 0.05 +rho2_in = 1.0 +v2_para = -1.0 +v2_perp = 1.0 diff --git a/settings/settings_particleflow_taylor_green.ini b/settings/settings_particleflow_taylor_green.ini new file mode 100644 index 0000000..9509c08 --- /dev/null +++ b/settings/settings_particleflow_taylor_green.ini @@ -0,0 +1,71 @@ +[simulation] +; model: a directory of physics/ +model = particleflow +; final time +tmax = 4.0 +; CFL number (realizable moments up to 2/3 with minmod; margin for the second stage) +cfl = 0.4 +; order in space: 1, or 2 (densities of the nodes reconstructed, velocities of the cell) +space_order = 2 +; order in time: 1 (forward Euler) or 2 (SSP Runge-Kutta 2) +time_order = 2 +; slope limiter of the reconstruction +scalar_limiter = minmod + +[amr] +; periodic directions (override physics.boundary_condition) +periodic_x = 1 +periodic_y = 1 +periodic_z = 1 +; 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 = 8 +by = 8 +bz = 8 +; uniform mesh of 128 x 128 cells +min_refine = 7 +max_refine = 7 +epsilon_refine = -1 +epsilon_coarsen = -1 + +[io] +; prefix of the output files +output_prefix = particleflow_taylor_green +; number of outputs over the run (0: none, -1: every time step) +save_count = 40 +; fields written with the moments: nodes, mean velocity, covariance +write_variables = n1, n2, V1_x, V1_y, V2_x, V2_y, Up_x, Up_y, a_xx, a_xy, a_yy + +[physics] +; initial condition: physics//initial_conditions/.py +initial_condition = taylor_green +; boundary condition: boundary_conditions/.py (overridden by amr if periodic) +boundary_condition = neuman +; refinement criterion: refine_conditions/.py +refine_condition = M0_gradient +; hyperbolic flux: hyperbolic_fluxes/.py, or none +hyperbolic_flux = kinetic +; diffusion flux: diffusion_fluxes/.py, or none +diffusion_flux = none +; after each step: projection of the moments on the two nodes, then the drag towards the carrier +; velocity, exact over the time step +relaxation = drag +; source term: sources/.py, or none +source = none + +[param] +; relaxation time of the drag: the particles cross the vortices for tau > 1 / (8 pi) +tau = 0.1 +; the particles start at rest: time step of the carrier velocity +cfl_velocity = 1.0 + +[taylor_green] +; density of the particles +rho = 1.0 +; 1: the particles start at the carrier velocity +warm_start = 0 diff --git a/src/Simulation.h b/src/Simulation.h index cc56a5f..c8bcde4 100644 --- a/src/Simulation.h +++ b/src/Simulation.h @@ -11,7 +11,7 @@ * its equations are in its kernels. The numerical options are read from the section `[simulation]` * of the input file (SchemeOptions), the options of the physics from the section `[physics]`. * - * A time step applies the stages of the time integration, then the instantaneous relaxations. + * A time step applies the stages of the time integration, then the relaxations of the model. * A stage \f$ U \to U + \Delta t\,(L(U) + S(U)) \f$ (Simulation::euler_stage) computes: * 1. the ghost cells of the conservative state (two layers; the octants outside the domain hold * the boundary conditions of the physics) and the primitive variables (physics); @@ -30,8 +30,9 @@ * U_2 = U_1 + \Delta t\,(L + S)(U_1), \qquad * U^{n+1} = \frac{1}{2}\,(U^n + U_2). * \f] - * The instantaneous relaxations of the 7-equation model (projections onto the equilibrium) are - * then applied to \f$ U^{n+1} \f$. + * The relaxations of the model over the time step (projections onto the equilibrium of the + * 7-equation model, or any relaxation that depends on the time step) are then applied to + * \f$ U^{n+1} \f$. */ #ifndef CANOP_SIMULATION_H_ #define CANOP_SIMULATION_H_ diff --git a/src/Simulation_impl.h b/src/Simulation_impl.h index 08d2798..b751d3d 100644 --- a/src/Simulation_impl.h +++ b/src/Simulation_impl.h @@ -483,7 +483,7 @@ Simulation::time_step(real_t dt) else euler_stage(m_U, m_U2, dt); - // instantaneous relaxations (7-equation model), after the time step + // relaxations of the model over the time step (7-equation model), after it m_physics->relaxations(m_U, m_U2, num_owned, dt); Kokkos::deep_copy(m_U.logical_view(), m_U2.logical_view()); diff --git a/src/python/Physics.h b/src/python/Physics.h index 5b7a8b9..2bb4ddb 100644 --- a/src/python/Physics.h +++ b/src/python/Physics.h @@ -391,7 +391,7 @@ class Physics call([&] { m_backend.attr("sources")(np_block(Uin), np_block(Uout), num_owned, dt); }); } - //! Instantaneous relaxations of Unew after the time step (Uold: state at its beginning). + //! Relaxations of Unew over the time step dt, after it (Uold: state at its beginning). void relaxations(Block Uold, Block Unew, int32_t num_owned, real_t dt) { diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3ea2529..81d9f2d 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 drag) 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..d61f57e 100644 --- a/test/physics/physics.py +++ b/test/physics/physics.py @@ -7,15 +7,19 @@ physics.py outflow --exe-2d canoP_2d [--workdir DIR] a problem along x stays uniform along y with outflow (neuman) faces in y physics.py mirror --exe-2d canoP_2d [--workdir DIR] - a reflective wall is a symmetry plane, viscous fluxes included: the half domain with the - wall gives the half of the symmetric full domain + a reflective wall is a symmetry plane, viscous fluxes and kinetic fluxes of particles + included: the half domain with the wall gives the half of the symmetric full domain 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 drag --exe-2d canoP_2d [--workdir DIR] + the drag and the gravity of the particles (particleflow) are exact over a time step: a + uniform velocity follows the exact solution of dV/dt = (Uf - V) / tau + g Exit code 77 (CTest SKIP_RETURN_CODE) when numpy or h5py is missing. """ import argparse +import math import os import sys @@ -59,6 +63,12 @@ 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"]), + # two slabs of particles crossing along x (two-node states), dragged by a carrier flow + # towards (1, 1): they leave through the face ymax + (Case("outflow_particleflow", "settings_particleflow_focusing_ring", 5, 0.5, + {"amr.ntree_x": 1, "amr.ntree_y": 1, "physics.initial_condition": "jet_crossing_1d", + "physics.relaxation": "drag", "param.tau": 0.5, "param.cfl_velocity": 1.0}, reference=None), + ["M0", "M1_x", "M1_y", "M2_xx", "M2_xy", "M2_yy", "M3_x", "M3_y"]), ] for case, names in cases: keys, data = read(reg.run_canop(case, args.exe_2d, os.path.join(args.workdir, case.name)), names) @@ -71,17 +81,26 @@ def outflow(args): def mirror(args): - """viscous blast with walls: the half domain [0, 0.5] x [0, 1] with a wall at x = 0.5 equals - the half x < 0.5 of the full domain, symmetric about x = 0.5 (onephase, twophase7eq)""" + """viscous blast with walls (onephase, twophase7eq), ring of particles focusing on a point of the + symmetry plane, with walls, the drag, the BGK relaxation and the gravity (particleflow): the half + domain [0, 0.5] x [0, 1] with a wall at x = 0.5 equals the half x < 0.5 of the full domain, + symmetric about x = 0.5""" ok = True viscous = {"amr.periodic_x": 0, "amr.periodic_y": 0, "simulation.time_order": 2, "blast.x_c": 0.5, "blast.y_c": 0.4, "physics.diffusion_flux": "viscosity"} + # the particles of the ring cross at its centre, on the wall of the half domain, from t ~ 0.02 + ring = {"amr.ntree_x": 1, "amr.ntree_y": 1, "physics.boundary_condition": "reflective", + "focusing_ring.x_c": 0.5, "focusing_ring.y_c": 0.45, "focusing_ring.radius": 0.15, + "focusing_ring.thickness": 0.15, "physics.relaxation": "drag_bgk", "param.tau": 0.5, "param.tau_BGK": 0.2, + "param.gravity_y": -1.0} models = [ ("settings_onephase_blast", dict(viscous, **{"param.eosFluid.mu": 0.02, "param.eosFluid.eta": 0.01}), ["m", "mE", "mV_x", "mV_y"]), ("settings_twophase7eq_blast", dict(viscous, **TWO_PHASE, **RELAXATIONS, **{ "param.eos_g.mu": 0.02, "param.eos_l.mu": 0.03, "param.eos_g.eta": 0.01}), ["mg", "ml", "ag", "mgEg", "mlEl", "mgVg_x", "mgVg_y", "mlVl_x", "mlVl_y"]), + ("settings_particleflow_focusing_ring", ring, + ["M0", "M1_x", "M1_y", "M2_xx", "M2_xy", "M2_yy", "M3_x", "M3_y"]), ] for base, over, names in models: full = Case(base + "_full", base, 5, 0.08, over, reference=None) @@ -121,15 +140,49 @@ def energy(args): return check("relative change of the total energy", abs(E1 - E0) / E0, 1e-13) and ok +def drag(args): + """bump of particles with a uniform velocity V0, no carrier flow (Uf = 0), periodic (particleflow, + time_order = 2): the drag and the gravity are applied once after each time step, exactly, so the + velocity M1 / M0 stays uniform and is, at the final time t, V0 exp(-t / tau) + g tau (1 - exp(-t / tau)) + with the drag (relaxations drag and drag_bgk), V0 + g t with the gravity alone; the mass is + conserved""" + tau, g, v0 = 0.05, (0.3, -1.0), (1.1, 1.2) + bump = {"physics.initial_condition": "bump", "bump.radius": 0.3, "bump.v_x": v0[0], "bump.v_y": v0[1], + "param.tau": tau, "param.gravity_x": g[0], "param.gravity_y": g[1]} + names = ["M0", "M1_x", "M1_y"] + ok = True + for relaxation in ("drag", "drag_bgk", "gravity"): + case = Case("drag_particleflow_" + relaxation, "settings_particleflow_taylor_green", 5, 0.2, + dict(bump, **{"physics.relaxation": relaxation}), 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), names) + _, d1 = read(out, names) + with h5py.File(out, "r") as f: + t, nsteps = float(f["run"].attrs["time"]), int(f["run"].attrs["iteration"]) + if relaxation == "gravity": + exact = [v0[d] + g[d] * t for d in range(2)] + else: + e = math.exp(-t / tau) + exact = [v0[d] * e + g[d] * tau * (1.0 - e) for d in range(2)] + print("%s: uniform velocity, t = %g, %d steps, mean dt / tau = %.2f" % (case.name, t, nsteps, + t / nsteps / tau)) + err = max(np.abs(d1["M1_" + a] / d1["M0"] - exact[d]).max() for d, a in enumerate("xy")) + ok = check("max |M1 / M0 - exact velocity| / |V0|", err / math.hypot(*v0), 1e-12) and ok + ok = check("relative change of the integral of M0", abs(d1["M0"].sum() - d0["M0"].sum()) / d0["M0"].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", "drag"]) 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, "drag": drag}[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..a39c7a5 100644 --- a/test/regression/README.md +++ b/test/regression/README.md @@ -10,9 +10,10 @@ Regression tests Each case of ``cases.py`` is a settings file of ``settings/`` modified by overrides (mesh level, final time, options), run by canoP and compared, cell by cell, with ``references/.h5``: same number of time steps, same mesh, and for every conservative variable -``max|canoP - reference| / max|reference| <= 1e-8`` (the scale of a vector component is the -maximum of the vector). The derived variables (pressures, temperatures) are not compared: with -stiffened gases they amplify the round-off errors of the conservative variables. +``max|canoP - reference| / max|reference| <= 1e-8`` (the scale of a component of a vector or of a +symmetric tensor is the maximum of all its components). The derived variables (pressures, +temperatures) are not compared: with stiffened gases they amplify the round-off errors of the +conservative variables. Run one case (``ctest -R regression_`` does the same): @@ -60,7 +61,14 @@ Treatments checked by canoP references right) differences; * 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 bulk viscosity of the gas of the 5 equations model: ``param.eos_g.eta``; +* the model ``particleflow``, all its cases: its counterpart in canoP legacy (``particlefluid``, + branch ``48-temporary-spray-model-implementation-as-an-independent-model``) limits the moments + (maximum principle) and applies the drag in each stage of the time integration, which canoP does + not do (see ``physics/particleflow/__init__.py``). Its cases cover its initial, boundary and + refinement conditions, its relaxations, the option ``param.energy_preserving``, the first order, + AMR and 3D; ``test/physics`` checks its mirror symmetry with walls, its outflow faces and its + exact drag. 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..1fffd3b 100644 --- a/test/regression/cases.py +++ b/test/regression/cases.py @@ -17,7 +17,9 @@ 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. +AMR. The cases of the model particleflow cover its initial, boundary and refinement conditions, its +relaxations and its option energy_preserving; their references are produced by canoP (see +README.md). """ @@ -51,13 +53,18 @@ def __init__(self, name, base, level, tmax, overrides=None, dim=2, reference="le self.tol = tol -#: conservative variables of each model, compared with the reference output (vectors not expanded) +#: conservative variables of each model, compared with the reference output (vectors and tensors +#: not expanded) CONSERVATIVE = { "onephase": ["m", "mE", "mV"], "twophase5eq": ["mg", "ml", "mV", "mE", "ag"], "twophase7eq": ["mg", "mgVg", "mgEg", "ml", "mlVl", "mlEl", "ag"], + "particleflow": ["M0", "M1", "M2", "M3", "Uf"], } -VECTORS = {"mV", "mgVg", "mlVl"} +#: vectors: one component per direction (mV_x, mV_y) +VECTORS = {"mV", "mgVg", "mlVl", "M1", "M3", "Uf"} +#: symmetric tensors, stored as their lower triangle (M2_xx, M2_xy, M2_yy in 2D) +SYM_TENSORS = {"M2"} #: two different phases (the two-phase settings files use two identical phases) TWO_PHASE = { @@ -124,6 +131,14 @@ def _b7(name): return "settings_twophase7eq_" + name +def _pf(name): + return "settings_particleflow_" + name + + +#: Taylor-Green vortices with tau = 1: the particles cross the vortices, two-node states from t ~ 0.75 +PF_CROSSING = {"param.tau": 1.0} + + CASES = [ # ---- the settings files of settings/ Case("onephase_blast", _mono("blast"), 5, 0.1), @@ -225,6 +240,50 @@ 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"), + # ---- particleflow: the moments of a spray closed on two velocity nodes (reference produced by + # canoP, see README.md) + # drag towards the Taylor-Green vortices (tau = 0.1), periodic, second order + Case("particleflow_taylor_green", _pf("taylor_green"), 5, 1.0, reference="canop"), + # tau = 1: two-node states where the particles cross; first order; energy-preserving inversion + Case("particleflow_taylor_green_crossing", _pf("taylor_green"), 5, 1.5, PF_CROSSING, reference="canop"), + Case("particleflow_taylor_green_first_order", _pf("taylor_green"), 5, 1.5, + dict(PF_CROSSING, **{"simulation.space_order": 1, "simulation.time_order": 1}), reference="canop"), + Case("particleflow_taylor_green_energy_preserving", _pf("taylor_green"), 5, 1.5, + dict(PF_CROSSING, **{"param.energy_preserving": 1}), reference="canop"), + # free particles crossing at the centre (reprojection alone), outflow faces + Case("particleflow_focusing_ring", _pf("focusing_ring"), 4, 0.6, reference="canop"), + # walls (specular reflection) and the gravity alone + Case("particleflow_focusing_ring_walls_gravity", _pf("focusing_ring"), 4, 0.6, + {"physics.boundary_condition": "reflective", "physics.relaxation": "gravity", + "param.gravity_x": 0.5, "param.gravity_y": -2.0}, reference="canop"), + # particles at rest in a carrier flow in solid rotation, walls + Case("particleflow_rotational_channel", _pf("focusing_ring"), 4, 0.5, + {"physics.initial_condition": "rotational_channel", "physics.boundary_condition": "reflective", + "physics.relaxation": "drag", "param.tau": 0.2, "param.cfl_velocity": 1.5, + "rotational_channel.radius": 0.4}, reference="canop"), + # two jets through xmin crossing in a converging carrier flow with a background of particles, + # drag and BGK relaxation + Case("particleflow_confining_channel", _pf("focusing_ring"), 4, 0.8, + {"physics.initial_condition": "confining_channel", "physics.boundary_condition": "left_inlet", + "physics.relaxation": "drag_bgk", "param.tau": 0.5, "param.tau_BGK": 0.3, "param.cfl_velocity": 1.0, + "confining_channel.rho": 0.5, "left_inlet.rho": 0.5, + "left_inlet.y1_c": 1.3, "left_inlet.radius1": 0.1, "left_inlet.v1y_in": -0.5, + "left_inlet.y2_c": 0.7, "left_inlet.radius2": 0.1, "left_inlet.v2y_in": 0.5}, reference="canop"), + # AMR: two crossing jets in vacuum; two annular jets with the gravity, drag and BGK relaxation + Case("particleflow_jet_crossing_amr", _pf("jet_crossing"), (4, 6), 0.6, reference="canop"), + Case("particleflow_top_inlet_amr", _pf("jet_crossing"), (4, 6), 0.6, + {"physics.boundary_condition": "top_inlet", "physics.refine_condition": "any_gradient", + "physics.relaxation": "drag_bgk", "param.tau": 0.5, "param.tau_BGK": 0.2, "param.gravity_y": -1.0}, + reference="canop"), + # 3D: two annular jets (two-node states in 3D); jets in a uniform carrier flow with a background + Case("particleflow_top_inlet_3d", _pf("jet_crossing"), 4, 0.6, + {"physics.boundary_condition": "top_inlet", "physics.relaxation": "drag", "param.tau": 0.5}, + dim=3, reference="canop"), + Case("particleflow_straight_channel_3d", _pf("jet_crossing"), 4, 0.5, + {"physics.initial_condition": "straight_channel", "physics.boundary_condition": "left_inlet", + "physics.relaxation": "drag", "param.tau": 0.2, "straight_channel.rho": 0.5, "left_inlet.rho": 0.5, + "left_inlet.y1_c": 0.7, "left_inlet.z1_c": 0.5, "left_inlet.radius1": 0.1, + "left_inlet.y2_c": 0.3, "left_inlet.z2_c": 0.5, "left_inlet.radius2": 0.1}, dim=3, reference="canop"), ] CASES_BY_NAME = {c.name: c for c in CASES} diff --git a/test/regression/references/particleflow_confining_channel.h5 b/test/regression/references/particleflow_confining_channel.h5 new file mode 100644 index 0000000..d51dbfc Binary files /dev/null and b/test/regression/references/particleflow_confining_channel.h5 differ diff --git a/test/regression/references/particleflow_focusing_ring.h5 b/test/regression/references/particleflow_focusing_ring.h5 new file mode 100644 index 0000000..5d2a9e3 Binary files /dev/null and b/test/regression/references/particleflow_focusing_ring.h5 differ diff --git a/test/regression/references/particleflow_focusing_ring_walls_gravity.h5 b/test/regression/references/particleflow_focusing_ring_walls_gravity.h5 new file mode 100644 index 0000000..46d630f Binary files /dev/null and b/test/regression/references/particleflow_focusing_ring_walls_gravity.h5 differ diff --git a/test/regression/references/particleflow_jet_crossing_amr.h5 b/test/regression/references/particleflow_jet_crossing_amr.h5 new file mode 100644 index 0000000..22572cd Binary files /dev/null and b/test/regression/references/particleflow_jet_crossing_amr.h5 differ diff --git a/test/regression/references/particleflow_rotational_channel.h5 b/test/regression/references/particleflow_rotational_channel.h5 new file mode 100644 index 0000000..1f8bcce Binary files /dev/null and b/test/regression/references/particleflow_rotational_channel.h5 differ diff --git a/test/regression/references/particleflow_straight_channel_3d.h5 b/test/regression/references/particleflow_straight_channel_3d.h5 new file mode 100644 index 0000000..9d78616 Binary files /dev/null and b/test/regression/references/particleflow_straight_channel_3d.h5 differ diff --git a/test/regression/references/particleflow_taylor_green.h5 b/test/regression/references/particleflow_taylor_green.h5 new file mode 100644 index 0000000..47479e0 Binary files /dev/null and b/test/regression/references/particleflow_taylor_green.h5 differ diff --git a/test/regression/references/particleflow_taylor_green_crossing.h5 b/test/regression/references/particleflow_taylor_green_crossing.h5 new file mode 100644 index 0000000..936ba96 Binary files /dev/null and b/test/regression/references/particleflow_taylor_green_crossing.h5 differ diff --git a/test/regression/references/particleflow_taylor_green_energy_preserving.h5 b/test/regression/references/particleflow_taylor_green_energy_preserving.h5 new file mode 100644 index 0000000..ee5e37a Binary files /dev/null and b/test/regression/references/particleflow_taylor_green_energy_preserving.h5 differ diff --git a/test/regression/references/particleflow_taylor_green_first_order.h5 b/test/regression/references/particleflow_taylor_green_first_order.h5 new file mode 100644 index 0000000..f009c36 Binary files /dev/null and b/test/regression/references/particleflow_taylor_green_first_order.h5 differ diff --git a/test/regression/references/particleflow_top_inlet_3d.h5 b/test/regression/references/particleflow_top_inlet_3d.h5 new file mode 100644 index 0000000..361a120 Binary files /dev/null and b/test/regression/references/particleflow_top_inlet_3d.h5 differ diff --git a/test/regression/references/particleflow_top_inlet_amr.h5 b/test/regression/references/particleflow_top_inlet_amr.h5 new file mode 100644 index 0000000..53099b3 Binary files /dev/null and b/test/regression/references/particleflow_top_inlet_amr.h5 differ diff --git a/test/regression/regression.py b/test/regression/regression.py index 7d98054..e628d25 100644 --- a/test/regression/regression.py +++ b/test/regression/regression.py @@ -18,8 +18,8 @@ (provenance "canoP VERSION") The comparison checks the number of time steps, the mesh (cell centres) and every conservative -variable: max|new - ref| / max|ref| <= tol (case.tol, 1e-8 by default; the scale of a vector -component is the maximum of the whole vector). The pressures and the other derived variables are +variable: max|new - ref| / max|ref| <= tol (case.tol, 1e-8 by default; the scale of a component of +a vector or of a tensor is the maximum of all its components). The pressures and the other derived variables are not compared: with stiffened gases (pinf ~ 1e9) they amplify the round-off errors of the conservative variables. @@ -43,7 +43,7 @@ HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) -from cases import CASES, CASES_BY_NAME, CONSERVATIVE, VECTORS # noqa: E402 +from cases import CASES, CASES_BY_NAME, CONSERVATIVE, SYM_TENSORS, VECTORS # noqa: E402 SOURCE_DIR = os.path.dirname(os.path.dirname(HERE)) SETTINGS_DIR = os.path.join(SOURCE_DIR, "settings") @@ -199,18 +199,22 @@ def sort_cells(c): def expand(names, dim): - """names with the vectors replaced by their components (mV -> mV_x, mV_y)""" + """names with the vectors and the symmetric tensors replaced by their components (mV -> mV_x, + mV_y; M2 -> M2_xx, M2_xy, M2_yy: the lower triangle, row by row, as in the outputs)""" out = [] for n in names: if n in VECTORS: out += ["%s_%s" % (n, AXES[d]) for d in range(dim)] + elif n in SYM_TENSORS: + out += ["%s_%s%s" % (n, AXES[j], AXES[i]) for i in range(dim) for j in range(i + 1)] else: out.append(n) return out def read_canop(path, names, dim): - """cell centres, variables (vectors expanded) and number of time steps of a canoP output""" + """cell centres, variables (vectors and tensors expanded) and number of time steps of a canoP + output""" with h5py.File(path, "r") as f: c = centres(f["unstructured_mesh/connectivity"][()], f["unstructured_mesh/coordinates"][()], dim) data = {n: f["celldata/" + n][()] for n in expand(names, dim)} @@ -263,8 +267,8 @@ def compare(case, output, reference): for n in names: ref = f["data/" + n][()] new = data[n][order] - # components of a vector: scale of the whole vector - group = [m for m in names if re.sub("_[xyz]$", "", m) == re.sub("_[xyz]$", "", n)] + # components of a vector or a tensor: scale of all its components + group = [m for m in names if re.sub("_[xyz]+$", "", m) == re.sub("_[xyz]+$", "", n)] scale = max(max(np.abs(f["data/" + m][()]).max() for m in group), 1e-300) err = np.abs(new - ref).max() / scale status = "ok" if err <= case.tol else "FAILED"