Peano
Loading...
Searching...
No Matches
Coupling of various solvers I: Introduction and reuse of auxiliary variables
This documentation is autogenerated from ./tutorials/exahype2/45_coupling-sharing-auxiliary-variables.ipynb. Once you clone the Peano repository, please work against this notebook or study Peano's generic description how to generate web docu from Jupyter notebooks.

If you want to solve systems of PDEs where some PDEs advance on different time scales, solve different problems, are active in different domains, and so forth, you have two options on the table: You can model the solvers as one big system or you can logically code the solvers as two totally separate things and couple them. If you have to run some postprocessing, you also have two options: Either make the postprocessing a "real" postprocessing by adding it as postprocessing step to your solvers of choice, or you add separate mesh sweeps which perform the postprocessing.

The former version is faster, as you read/write data only once and you do not impose additional mesh traversals. The latter version is the way to go if you need some boundary exchange prior such that halos, for example, are up-to-date. It might also be appropriate if you want to couple the hyperbolic solvers to other solvers, such as an elliptic term or a solid in a fluid-structure interaction scenario. When it comes to the coupling of two solvers, the first approach sketched is simple: If the two solvers feature \( N_1\) and \( N_2\) unknowns, you simply create one new solver with \( N_1+N_2\) unknowns and you provide flux functionsm, ncps, ...for all of the components. The big disadvantage of this approach is that all solvers have to advance in time at the same speed, that you might replicate code if you have already two existing solvers, and that you also might run a lot of unneeded calculations if only some PDE equations evolve actually in time. Technically, the implementation of this variant however is straightforward and we will not discuss it further here, i.e. our description from hereon assumes that you work with two solvers and/or separate mesh sweeps.

Using multiple solvers within ExaHyPE is, in principle, straightforward, too. You create two solver instances and you add them to your project. Both solvers then will be embedded into the mesh and run independently. They will hence interact through the adaptive mesh refinement - if one solver refines, the other one will follow - but otherwise be totally independent. While this approach allows us to have a clear separation-of-solvers, the coupling of the two systems is not that straightforward. And we have to couple them if we want to solver our initial setup phrased as system of PDEs.

This tutorial introduces the two flavours of coupling and then walks through the simplest one hands-on: two solvers which run next to each other and share their auxiliary variables, i.e. they reuse one set of data rather than holding a copy each. Afterwards, we postprocess the outputs of the two solvers and compare them. The remaining sections sketch the mechanisms to couple solvers whose solutions feed into each other over time. They are not part of the hands-on part of this tutorial.

Preparing the PDEs to be coupled

How to couple the PDEs depends upon the fact if you want to directly project the solutions onto each other or if you make one PDE feed into the other one via the right-hand side (or in general some "auxiliary" parameters within its PDE other than the evolution unknowns). If you couple PDEs directly, you can use your PDE solvers as they stand.

If one PDE feeds into the other one, there are two cases:

  1. The coupling term is constant in time. The sea floor of a tsunami simulation is an example. You model it as a set of auxiliary variables (exahype2::api::AuxiliaryVariables) which you attach to the solvers (exahype2.api.Solver.add_auxiliary_variables()). A solver can have an arbitrary number of such sets, each of them holds an arbitrary number of (vector-valued) variables in a cell data object of its own, and several solvers can share one set. This is what we do below.
  2. The coupling term changes over time. Auxiliary variables are written once, when the simulation is set up, and the hyperbolic kernels never touch them. If you have two solver A and B and B has an impact on A through a scalar, and A influences B through a vector, add one unknown to A and three to B which do not feature any flux. B then sets the additional unknowns of A and vice versa through the hook-ins below.

Two tsunamis over one sea floor

We rerun the tsunami of A tsunami simulation with source code injection, SymPy, auxiliary variables, non-conservative fluxes, and external files, but we run it twice at the same time. Both simulations live in the same project, i.e. they run on the same mesh, but they are two independent solvers: they have their own unknowns, their own time stamps and their own time step sizes. The two simulations only differ in their initial conditions: the hump of water sits at \( x=0\) in the first simulation and at \( x=0.1\) in the second one. Both tsunamis travel over the same sea floor, i.e. the logo of Durham University.

The sea floor is constant in time. Rather than storing and initialising it twice, we model it as one set of auxiliary variables. The first solver which the set is attached to owns the set: it initialises it. The second solver attaches the same set and reuses the data.

We use the surface elevation \( \eta\) as unknown and the PDE terms from A tsunami simulation with source code injection, SymPy, auxiliary variables, non-conservative fluxes, and external files with the non-conservative product. Please consult that tutorial for their derivation.

Configuring the environment

import sys, os
sys.path.insert(0, os.path.abspath("../../src"))
import peano4.api
import exahype2
try:
import ipywidgets, matplotlib
except ImportError:
!{sys.executable} -m pip install ipywidgets matplotlib

The PDE terms

The three terms read the sea floor from the pointer bathymetry, which ExaHyPE passes in right behind Q. The struct Bathymetry hosts the position of the variable b within the set. We attach the set below, i.e. we do not have to write the signature: ExaHyPE generates it.

flux_implementation = '''
constexpr double g = 9.81;
const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
const double un = Q[Variables::hu + normal] / h;
F[Variables::eta] = Q[Variables::hu + normal];
F[Variables::hu] = Q[Variables::hu] * un;
F[Variables::hv] = Q[Variables::hv] * un;
F[Variables::hu + normal] += 0.5 * g * h * h;
'''
max_eigenvalue_implementation = '''
constexpr double g = 9.81;
const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
const double un = Q[Variables::hu + normal] / h;
lambdaMax[0] = std::abs(un) + std::sqrt(g * h);
'''
nonconservative_product_implementation = '''
constexpr double g = 9.81;
const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
BTimesDeltaQ[Variables::eta] = 0.0;
BTimesDeltaQ[Variables::hu] = 0.0;
BTimesDeltaQ[Variables::hv] = 0.0;
BTimesDeltaQ[Variables::hu + normal] = g * h * deltaBathymetry[Bathymetry::b];
'''

Behind each Q, the signature of a term hosts a pointer to each attached set. Behind each deltaQ, it hosts a pointer to the jump of each set. The latter is the pointer deltaBathymetry in the non-conservative product. If we attached a second set, e.g. a mesh distortion, we would find another pointer behind the pointer to the bathymetry.

The two solvers

Next, we create the project and the set of auxiliary variables. We write a small function which creates a solver. It attaches the very same set object to each solver. That is the only thing we have to do to share the sea floor. The initial condition of the owner writes the sea floor. The initial condition of the second solver does not: as it only shares the set, ExaHyPE passes it a const pointer. The sea floor is written with the same C++ code as in A tsunami simulation with source code injection, SymPy, auxiliary variables, non-conservative fluxes, and external files, i.e. the depth is looked up in the external files:

namespace = ["tutorials", "exahype2", "tsunami"],
project_name = "Coupling",
directory = "45_coupling-sharing-auxiliary-variables",
executable = "coupling",
)
bathymetry = exahype2.api.AuxiliaryVariables("Bathymetry", {"b": 1})
initial_sea_floor = '''
const int column = std::clamp(static_cast<int>((x[0] + 1.0) / 2.0 * DurhamLogoSize), 0, DurhamLogoSize - 1);
const int row = std::clamp(static_cast<int>((1.0 - x[1]) / 2.0 * DurhamLogoSize), 0, DurhamLogoSize - 1);
bathymetry[Bathymetry::b] = DurhamLogo[row][column] == '1' ? -4.0 : -1.0;
'''
initial_water = '''
const double dx = x[0] - {hump_centre};
Q[Variables::eta] = 0.1 * std::exp(-100.0 * (dx * dx + x[1] * x[1]));
Q[Variables::hu] = 0.0;
Q[Variables::hv] = 0.0;
'''
def create_solver(name, hump_centre, initialises_sea_floor):
solver = exahype2.api.Solver(name, {"eta": 1, "hu": 1, "hv": 1})
solver.add_auxiliary_variables(bathymetry)
solver.add_user_solver_includes(
"#include <cmath>\n#include <algorithm>\n#include \"DurhamLogo.h\"\n"
)
solver.add_pde_term(exahype2.api.Flux(implementation=flux_implementation, stateless=True))
solver.add_pde_term(exahype2.api.MaxEigenvalue(implementation=max_eigenvalue_implementation, stateless=True))
solver.add_pde_term(exahype2.api.NonconservativeProduct(implementation=nonconservative_product_implementation, stateless=True))
solver.add_pde_term(exahype2.api.InitPointWisely(
implementation = initial_water.format(hump_centre=hump_centre)
+ (initial_sea_floor if initialises_sea_floor else ""),
stateless = False,
))
solver.numerical_scheme = exahype2.api.fv.RusanovWithExplicitEuler(solver, 9)
solver.grid_construction = exahype2.api.fv.SetupSimulationOverRegularGrid(solver, volume_size=0.01)
solver,
first_plot_time_stamp = 0.0,
time_in_between_plots = 0.01,
)
project.add_solver(solver)
return solver
solver_a = create_solver("TsunamiA", hump_centre=0.0, initialises_sea_floor=True)
solver_b = create_solver("TsunamiB", hump_centre=0.1, initialises_sea_floor=False)
A set of auxiliary variables of a solver.
The conservative flux F(Q) of a hyperbolic PDE.
Definition Flux.py:8
Point-wise initial condition: given the physical position of a single degree of freedom,...
The maximum absolute eigenvalue of the flux Jacobian in a given direction, i.e.
The non-conservative product B(Q) applied to a jump deltaQ in a given direction, i....
ExaHyPE 2 project.
Definition Project.py:15
Abstract base class for all ExaHyPE 2 solvers.
Definition Solver.py:17
Plotting counterpart to RusanovWithExplicitEuler: maps the patch data of a Finite Volume scheme with ...
Finite Volumes with a Rusanov Riemann solver and explicit Euler time stepping, realised over a block-...
Setup phase counterpart to RusanovWithExplicitEuler: sets the initial condition for a Finite Volume s...

The solver which owns the set has to be added to the project first, as the setup of the second solver has to run after the setup of the first one: the initial condition of the sharing solver may read the sea floor, so ExaHyPE makes it depend on the initial condition of the owner. ExaHyPE complains if you add the solvers in the opposite order.

We plot every 0.01 time units, as we want to compare the two simulations over time afterwards. The rest of the setup is the same as in tutorials_exahype2_11_tsunami:

project.set_global_simulation_parameters(
dimensions = 2,
offset = [-1.0, -1.0],
size = [ 2.0, 2.0],
min_end_time = 0.4,
max_end_time = 0.4,
periodic_BC = [True, True, True],
)
project.set_Peano4_installation(os.path.abspath("../../"), peano4.api.output.CompileMode.RELEASE)
peano4_project = project.generate_Peano4_project()
peano4_project.output.makefile.add_cpp_file("../bathymetry/DurhamLogo.cpp")
peano4_project.output.makefile.add_h_file("../bathymetry/DurhamLogo.h")
peano4_project.output.makefile.add_header_search_path("../bathymetry")
peano4_project.generate()

What ExaHyPE generated

The sea floor is held by one cell data object, which both solvers use. Each solver additionally has a temporary cell data object which holds the sea floor including a halo layer around the patch, as the Finite Volume scheme needs the sea floor of the neighbouring volumes to evaluate fluxes. These halos belong to one solver, so the two solvers do not overwrite each other's halos while they run next to each other:

!ls 45_coupling-sharing-auxiliary-variables/celldata | grep "\.h$" | grep -i "bathymetry\|Q\.h"

The signatures of the PDE terms follow from the set. Both solvers get the pointer to the sea floor behind Q. The second solver is a plain user of the set, i.e. its initial condition receives the pointer as const pointer, whereas the owner receives a non-const pointer:

!grep -h -A3 "void initPointWisely(" 45_coupling-sharing-auxiliary-variables/AbstractTsunamiA.h 45_coupling-sharing-auxiliary-variables/AbstractTsunamiB.h

Stateless terms are called by compute kernels which do not know anything about auxiliary variables. ExaHyPE therefore generates a second overload without the pointers for every stateless term. It slices the pointers out of the data which the kernel works on and forwards the call. We have never written this adapter, and our terms never see it:

!grep -n -B2 -A4 "::flux(" 45_coupling-sharing-auxiliary-variables/AbstractTsunamiA.cpp | head -40

Build and run

%%writefile 45_coupling-sharing-auxiliary-variables/exahype2.log-filter
debug tarch -1 black always-on
debug peano4 -1 black always-on
debug exahype2 -1 black always-on
debug toolbox -1 black always-on
debug tutorials -1 black always-on
trace tarch -1 black always-on
trace peano4 -1 black always-on
trace exahype2 -1 black always-on
trace toolbox -1 black always-on
trace tutorials -1 black always-on
info tarch -1 white always-on
info peano4 -1 white always-on
info exahype2 -1 white always-on
info toolbox -1 white always-on
info tutorials -1 white always-on
!cd 45_coupling-sharing-auxiliary-variables && make -j
!cd 45_coupling-sharing-auxiliary-variables && ./coupling

What we get

The two solvers write their own output files. The solver which owns the sea floor writes the sea floor into a file of its own, too. The solver which only shares it does not write anything for it: the data would be identical anyway.

!ls 45_coupling-sharing-auxiliary-variables | grep "peano-patch-file$" | grep -v "[0-9]\.peano-patch-file$"
"45_coupling-sharing-auxiliary-variables/solution-TsunamiA.peano-patch-file",
unknown = 0,
)
Interactive visualisation of Peano patch files within Jupyter notebooks.
Definition notebook.py:1
show_solution(file_name, unknown=0, unknown_names=None, clim=None)
Interactive viewer for a patch file within a Jupyter notebook.
Definition notebook.py:159
"45_coupling-sharing-auxiliary-variables/solution-TsunamiB.peano-patch-file",
unknown = 0,
)

The two pictures show the surface elevation at \( t=0\) . The hump of the second tsunami sits to the right of the hump of the first one:

Surface elevation of both tsunamis at t=0

Both waves feel the same sea floor, which they find in the very same cell data. They run fast above the deep, purple parts of the logo and slowly above the shallow parts, as we have seen in A tsunami simulation with source code injection, SymPy, auxiliary variables, non-conservative fluxes, and external files.

Postprocessing: Comparing the arrival of the waves

Does the shifted hump make a difference? We compare when the waves reach a point of the domain. We call the arrival time of a wave in a point the first time at which the surface elevation \( \eta\) is at least 0.002.

We read the outputs of the two solvers. The two solvers advance with their own, adaptive time step sizes. The time stamps of their snapshots hence do not match exactly. The postprocessing therefore keeps the time stamps of each solver, and it interpolates the arrival time linearly between the two snapshots which enclose the moment at which the threshold is exceeded. First, we assemble the volumes of all patches of one snapshot into one array over the whole domain:

import numpy as np
def read_field(file_name, snapshot, unknown=0):
"""One unknown of one snapshot as array field[y,x] over the whole domain"""
_, patch_files = tarch.plotter.api.notebook.read_snapshots(file_name)[snapshot]
patches = [p for f in patch_files for p in tarch.plotter.api.notebook.read_patches(f)]
volume_size = patches[0][1][0] / patches[0][2].shape[1]
volumes = round(2.0 / volume_size)
field = np.zeros((volumes, volumes))
for offset, _, values in patches:
x = round((offset[0] + 1.0) / volume_size)
y = round((offset[1] + 1.0) / volume_size)
n = values.shape[0]
field[y:y + n, x:x + n] = values[..., unknown]
return field
def read_time_series(file_name, unknown=0):
"""Time stamps and an array series[snapshot,y,x] of one unknown"""
times = np.array([time for time, _ in snapshots])
series = np.array([read_field(file_name, s, unknown) for s in range(len(snapshots))])
return times, series
times_a, eta_a = read_time_series("45_coupling-sharing-auxiliary-variables/solution-TsunamiA.peano-patch-file")
times_b, eta_b = read_time_series("45_coupling-sharing-auxiliary-variables/solution-TsunamiB.peano-patch-file")
print("snapshots:", len(times_a), len(times_b))
print("first time stamps of A:", times_a[:3])
print("first time stamps of B:", times_b[:3])
read_patches(patch_file_name)
Return list of (offset, size, values) for all patches of one patch file.
Definition notebook.py:49
read_snapshots(file_name)
Return list of (time stamp, list of patch files) from a patch meta file.
Definition notebook.py:30

Now we determine for each volume the first snapshot at which the threshold is exceeded, and interpolate between this snapshot and the one before:

def arrival_times(times, series, threshold):
"""First time at which the surface elevation exceeds the threshold. NaN if the wave never arrives."""
exceeded = series >= threshold
first = np.argmax(exceeded, axis=0)
previous = np.maximum(first - 1, 0)
after = np.take_along_axis(series, first[None], axis=0)[0]
before = np.take_along_axis(series, previous[None], axis=0)[0]
weight = np.where(first > 0, (threshold - before) / np.maximum(after - before, 1e-300), 1.0)
arrival = times[previous] + weight * (times[first] - times[previous])
return np.where(exceeded.any(axis=0), arrival, np.nan)
arrival_a = arrival_times(times_a, eta_a, threshold=0.002)
arrival_b = arrival_times(times_b, eta_b, threshold=0.002)
print("volumes which the wave of A never reaches:", np.isnan(arrival_a).sum())
print("volumes which the wave of B never reaches:", np.isnan(arrival_b).sum())

We pick four points, one on each side of the centre, and compare the arrival times there. As the hump of the second tsunami starts 0.1 further to the right, its wave should arrive earlier on the right and later on the left. As the wave runs with \( \sqrt{gh}\) , i.e. with a speed between 3.13 above the shallow and 6.26 above the deep parts of the logo, we expect shifts between \( 0.1/6.26 \approx 0.016\) and \( 0.1/3.13 \approx 0.032\) time units on the horizontal axis:

def value_at(field, x, y):
n = field.shape[0]
return field[int((y + 1.0) / 2.0 * n), int((x + 1.0) / 2.0 * n)]
print("point first second second - first")
for x, y in [(0.6, 0.0), (-0.6, 0.0), (0.0, 0.6), (0.0, -0.6)]:
a, b = value_at(arrival_a, x, y), value_at(arrival_b, x, y)
print(f"({x:4.1f},{y:4.1f}) {a:.4f} {b:.4f} {b - a:+.4f}")

Right of the centre, the second wave arrives earlier by 0.017 time units, left of the centre it arrives 0.028 time units later. Both values lie in the range which we have estimated. On the vertical axis, the shift of the hump has a much smaller impact, as the second hump is only slightly closer to the upper than to the lower point. The first tsunami is symmetric, i.e. it arrives at the same time at the two points on the horizontal axis. This confirms that the second solver sees exactly the same sea floor as the first one.

The difference of the arrival times over the whole domain shows the same picture. It is negative where the second wave is faster, and positive where it is slower:

import matplotlib.pyplot as plt
difference = arrival_b - arrival_a
bound = np.nanmax(np.abs(difference))
fig, ax = plt.subplots(figsize=(6.5, 5))
image = ax.imshow(difference, origin="lower", extent=(-1, 1, -1, 1), cmap="coolwarm", vmin=-bound, vmax=bound)
fig.colorbar(image, label="arrival time second - arrival time first")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("Arrival of eta >= 0.002")
plt.show()
Difference of the arrival times

The pictures are created by tutorials/exahype2/illustrations/45_coupling.py.

Coupling the solution data

There are two places where we can add coupling, i.e. map solution data onto each other: It can either be a preprocessing step of the time step or a postprocessing step. While, in principle, both approaches do work here, there's a delicate difference: In the pre-processing step, we have access to the patch data plus the halo. In the post-processing step, we have only access to the patch content.

We note that we exclusively discuss volumetric mapping in this section. This is the only coupling we support at the moment within ExaHyPE, i.e. we do not support mapping of face data onto each other (anymore). Besides volumetric coupling, you can obviously "only" couple global properties with each other. This is however similar to the time step synchronisation as discussed below and therefore not subject of further discussion.

Coupling the time step sizes

Unless you use fixed time stepping schemes with hard-coded time step sizes that match, any two solvers with ExaHyPE run at their own speed. Even more, each individual cell runs at its own speed and hosts its own time stamp. For local timestepping, different cells may advance at different speed in time. For adaptive timestepping, all cells of one solver will advance with the same time step size.

For most solvers, it is therefore sufficient to plug into getAdmissibleTimeStepSize() of the superclass. Overwrite it, call the superclass' variant and then alter the returned value.

class mynamespace::MySolver: public MyBaseClass {
...
getAdmissibleTimeStepSize() const override;
};
#include "repositories/SolverRepository.h"
double mynamespace::MySolvergetAdmissibleTimeStepSize() const {
// get vanilla version of time step size, i.e. only the one computed
// by our solver
double myTimeStepSize = MyBaseClass::getAdmissibleTimeStepSize();
double otherTimeStepSize = repositories::MyOtherSolver.getAdmissibleTimeStepSize();
// now we combine it with each other and return result
}

This is the approach used in Euler example with self-gravitation via the Poisson equation. If you want to use local time stepping or run checks on the timestamp per cell, you will have to alter the cell's meta data holding its time stamp. Things in this case become more involved, i.e. you will have to study the underlying action sets and change the generated source code in there.

The actual solution coupling

For the actual solver coupling, four hook-in points are available:

  1. The dedicated solver preprocessing action set.
  2. The hook-in preprocess_reconstructed_patch, which injects code right before the actual compute kernel (Finite Volume scheme, e.g.) is triggered.
  3. The hook-in postprocess_updated_patch, which injects code right after updated time-step data. This snippet is called after the compute kernel has terminated. For Runge-Kutta style solvers, aka multi-step solvers, there are two of these hook-ins: One called after every intermediate step and one called once we compute the final linear combination of these intermediate outcomes.
  4. The dedicated solver postprocessing action set.

These steps all have differen properties. The global preprocessing precedes any solver routine, i.e. it is called before any compute kernel on any solver is launched. It also is guaranteed to run sequentially, i.e. there is nothing running in parallel to the preprocess actino set. For the postprocessing, similar arguments hold. These steps come after all solvers have updated their solution. The kernel hook-ins (2) and (3) in contrast can run in parallel.

Any coupling can be arbitrary complicated, but there are several off-the-shelf routines offered in toolbox::blockstructured. Interesting variants include toolbox::blockstructured::copyUnknown() and toolbox::blockstructured::computeGradientAndReturnMaxDifference(). Besides those guys, you might also want to use the AMR routines within the blockstructured toolbox and the ExaHyPE folders, where you find, for example, linear interpolation and restriction.

Important: If you couple two solvers, you have to carefully take into account

  1. in which order these solvers run; If that makes a difference, you might want to use the dedicated post- and pre-processing action sets.
  2. whether or not you use enclave solvers. The later ones take the data out of the mesh after their primary sweep and insert it back into the mesh. This has to be taken into account when you interpolate: data might be extracted from the mesh and then be put back in;
  3. if you localise a solver, i.e. store it only in some places, you will have garbage on faces around this localised area.
See also
toolbox/blockstructured/Copy.h
toolbox/blockstructured/Derivative.h
toolbox/blockstructured/Interpolation.h
toolbox/blockstructured/Restriction.h