Peano
Loading...
Searching...
No Matches
45_coupling.py
Go to the documentation of this file.
1# This file is part of the Peano project. For conditions of distribution and
2# use, please see the copyright notice at www.peano-framework.org
3"""!
4
5Create the PNG illustrations of the tutorial
645_coupling-sharing-auxiliary-variables.ipynb
7
8The script builds the two tsunamis which share their sea floor, runs them and
9writes the initial conditions and the difference of their arrival times into
10the directory of this script. It repeats the setup of the notebook, i.e.
11the PDE terms are the ones of tutorial 11_tsunami.ipynb for the surface
12elevation eta as unknown. Call the script from anywhere:
13
14 python3 tutorials/exahype2/illustrations/45_coupling.py
15
16All builds and outputs go into a temporary directory (or --work-directory).
17
18"""
19import argparse
20import os
21import subprocess
22import sys
23import tempfile
24
25Here = os.path.dirname(os.path.abspath(__file__))
26PeanoRoot = os.path.abspath(os.path.join(Here, "..", "..", ".."))
27sys.path.insert(0, os.path.join(PeanoRoot, "src"))
28
29import matplotlib
30
31matplotlib.use("Agg")
32import matplotlib.pyplot as plt
33import numpy as np
34
35import exahype2
36import peano4.api
38
39Flux = """
40 constexpr double g = 9.81;
41 const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
42 const double un = Q[Variables::hu + normal] / h;
43 F[Variables::eta] = Q[Variables::hu + normal];
44 F[Variables::hu] = Q[Variables::hu] * un;
45 F[Variables::hv] = Q[Variables::hv] * un;
46 F[Variables::hu + normal] += 0.5 * g * h * h;
47"""
48
49MaxEigenvalue = """
50 constexpr double g = 9.81;
51 const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
52 const double un = Q[Variables::hu + normal] / h;
53 lambdaMax[0] = std::abs(un) + std::sqrt(g * h);
54"""
55
56NonconservativeProduct = """
57 constexpr double g = 9.81;
58 const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
59 BTimesDeltaQ[Variables::eta] = 0.0;
60 BTimesDeltaQ[Variables::hu] = 0.0;
61 BTimesDeltaQ[Variables::hv] = 0.0;
62 BTimesDeltaQ[Variables::hu + normal] = g * h * deltaBathymetry[Bathymetry::b];
63"""
64
65InitialSeaFloor = """
66 const int column = std::clamp(static_cast<int>((x[0] + 1.0) / 2.0 * DurhamLogoSize), 0, DurhamLogoSize - 1);
67 const int row = std::clamp(static_cast<int>((1.0 - x[1]) / 2.0 * DurhamLogoSize), 0, DurhamLogoSize - 1);
68 bathymetry[Bathymetry::b] = DurhamLogo[row][column] == '1' ? -4.0 : -1.0;
69"""
70
71InitialWater = """
72 const double dx = x[0] - {centre};
73 Q[Variables::eta] = 0.1 * std::exp(-100.0 * (dx * dx + x[1] * x[1]));
74 Q[Variables::hu] = 0.0;
75 Q[Variables::hv] = 0.0;
76"""
77
78Bathymetry = os.path.join(Here, "..", "bathymetry")
79
80# Centre of the hump along the x axis
81CentreOfFirstTsunami = 0.0
82CentreOfSecondTsunami = 0.1
83
84
85def build_and_run(directory):
86 """! Generate, compile and run the coupled setup within directory """
87 project = exahype2.api.Project(
88 namespace=["tutorials", "exahype2", "tsunami"],
89 project_name="Coupling",
90 directory=directory,
91 executable="coupling",
92 )
93 bathymetry = exahype2.api.AuxiliaryVariables("Bathymetry", {"b": 1})
94 for name, centre, owns_sea_floor in [
95 ("TsunamiA", CentreOfFirstTsunami, True),
96 ("TsunamiB", CentreOfSecondTsunami, False),
97 ]:
98 solver = exahype2.api.Solver(name, {"eta": 1, "hu": 1, "hv": 1})
99 solver.add_auxiliary_variables(bathymetry)
100 solver.add_user_solver_includes(
101 '#include <cmath>\n#include <algorithm>\n#include "DurhamLogo.h"\n'
102 )
103 solver.add_pde_term(exahype2.api.Flux(implementation=Flux, stateless=True))
104 solver.add_pde_term(
105 exahype2.api.MaxEigenvalue(implementation=MaxEigenvalue, stateless=True)
106 )
107 solver.add_pde_term(
109 implementation=NonconservativeProduct, stateless=True
110 )
111 )
112 solver.add_pde_term(
114 implementation=InitialWater.format(centre=centre)
115 + (InitialSeaFloor if owns_sea_floor else ""),
116 stateless=False,
117 )
118 )
119 solver.numerical_scheme = exahype2.api.fv.RusanovWithExplicitEuler(solver, 9)
120 solver.grid_construction = exahype2.api.fv.SetupSimulationOverRegularGrid(
121 solver, volume_size=0.01
122 )
123 solver.plotter = exahype2.api.fv.PlotAsVTKFile(
124 solver, first_plot_time_stamp=0.0, time_in_between_plots=0.01
125 )
126 project.add_solver(solver)
127 project.set_global_simulation_parameters(
128 dimensions=2,
129 offset=[-1.0, -1.0],
130 size=[2.0, 2.0],
131 min_end_time=0.4,
132 max_end_time=0.4,
133 periodic_BC=[True, True, True],
134 )
135 project.set_Peano4_installation(PeanoRoot, peano4.api.output.CompileMode.RELEASE)
136 peano4_project = project.generate_Peano4_project()
137 makefile = peano4_project.output.makefile
138 makefile.add_cpp_file(os.path.join(Bathymetry, "DurhamLogo.cpp"))
139 makefile.add_h_file(os.path.join(Bathymetry, "DurhamLogo.h"))
140 makefile.add_header_search_path(Bathymetry)
141 peano4_project.generate()
142 subprocess.run(["make", "-j"], cwd=directory, check=True, stdout=subprocess.DEVNULL)
143 subprocess.run(["./coupling"], cwd=directory, check=True, stdout=subprocess.DEVNULL)
144
145
146def read_field(file_name, snapshot, unknown=0):
147 """! One unknown of one snapshot as array field[y,x] over the whole domain """
148 _, patch_files = tarch.plotter.api.notebook.read_snapshots(file_name)[snapshot]
149 patches = [
150 patch
151 for patch_file in patch_files
152 for patch in tarch.plotter.api.notebook.read_patches(patch_file)
153 ]
154 volume_size = patches[0][1][0] / patches[0][2].shape[1]
155 volumes = round(2.0 / volume_size)
156 field = np.zeros((volumes, volumes))
157 for offset, _, values in patches:
158 x = round((offset[0] + 1.0) / volume_size)
159 y = round((offset[1] + 1.0) / volume_size)
160 n = values.shape[0]
161 field[y : y + n, x : x + n] = values[..., unknown]
162 return field
163
164
165def read_time_series(file_name, unknown=0):
166 """! Time stamps and an array series[snapshot,y,x] of one unknown """
167 snapshots = tarch.plotter.api.notebook.read_snapshots(file_name)
168 times = np.array([time for time, _ in snapshots])
169 series = np.array([read_field(file_name, s, unknown) for s in range(len(snapshots))])
170 return times, series
171
172
173def arrival_times(times, series, threshold):
174 """!
175
176 First time at which the surface elevation exceeds the threshold
177
178 The time is interpolated linearly between the two snapshots which enclose
179 the crossing. Volumes which the wave never reaches hold NaN.
180
181 """
182 exceeded = series >= threshold
183 first = np.argmax(exceeded, axis=0)
184 reached = exceeded.any(axis=0)
185 after = np.take_along_axis(series, first[None], axis=0)[0]
186 before = np.take_along_axis(series, np.maximum(first - 1, 0)[None], axis=0)[0]
187 weight = np.where(first > 0, (threshold - before) / np.maximum(after - before, 1e-300), 1.0)
188 arrival = times[np.maximum(first - 1, 0)] + weight * (times[first] - times[np.maximum(first - 1, 0)])
189 return np.where(reached, arrival, np.nan)
190
191
192def plot_initial_conditions(first_file, second_file, prefix):
193 fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
194 for ax, file_name, title in zip(
195 axes, [first_file, second_file], ["first tsunami (hump at x=0)", "second tsunami (hump at x=0.1)"]
196 ):
198 file_name, 0, 0, ax=ax, label="surface elevation eta"
199 )
200 ax.set_title(title)
201 fig.savefig(os.path.join(Here, prefix + "initial.png"), dpi=100, bbox_inches="tight")
202 plt.close(fig)
203
204
205def plot_arrival_difference(first_file, second_file, prefix, threshold=0.002):
206 times, first = read_time_series(first_file)
207 _, second = read_time_series(second_file)
208 arrival_first = arrival_times(times, first, threshold)
209 arrival_second = arrival_times(times, second, threshold)
210 difference = arrival_second - arrival_first
211 fig, ax = plt.subplots(figsize=(6.5, 5))
212 bound = np.nanmax(np.abs(difference))
213 image = ax.imshow(
214 difference,
215 origin="lower",
216 extent=(-1, 1, -1, 1),
217 cmap="coolwarm",
218 vmin=-bound,
219 vmax=bound,
220 )
221 fig.colorbar(image, label="arrival time second - arrival time first")
222 ax.set_xlabel("x")
223 ax.set_ylabel("y")
224 ax.set_title(f"Arrival of eta >= {threshold}")
225 fig.savefig(os.path.join(Here, prefix + "arrival-difference.png"), dpi=100, bbox_inches="tight")
226 plt.close(fig)
227
228
229if __name__ == "__main__":
230 parser = argparse.ArgumentParser(
231 description="Create the PNGs of the tutorial 45_coupling-sharing-auxiliary-variables.ipynb"
232 )
233 parser.add_argument(
234 "--work-directory",
235 default=None,
236 help="Directory for builds and outputs (default: temporary directory)",
237 )
238 args = parser.parse_args()
239
240 work_directory = args.work_directory or tempfile.mkdtemp(prefix="45_coupling-")
241 print("build and run in {}".format(work_directory))
242 build_and_run(work_directory)
243 first_file = os.path.join(work_directory, "solution-TsunamiA.peano-patch-file")
244 second_file = os.path.join(work_directory, "solution-TsunamiB.peano-patch-file")
245 plot_initial_conditions(first_file, second_file, "45_coupling-")
246 plot_arrival_difference(first_file, second_file, "45_coupling-")
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...
read_time_series(file_name, unknown=0)
Time stamps and an array series[snapshot,y,x] of one unknown.
arrival_times(times, series, threshold)
First time at which the surface elevation exceeds the threshold.
plot_initial_conditions(first_file, second_file, prefix)
read_field(file_name, snapshot, unknown=0)
One unknown of one snapshot as array field[y,x] over the whole domain.
plot_arrival_difference(first_file, second_file, prefix, threshold=0.002)
build_and_run(directory)
Generate, compile and run the coupled setup within directory.
Interactive visualisation of Peano patch files within Jupyter notebooks.
Definition notebook.py:1
plot_snapshot(file_name, snapshot=-1, unknown=0, clim=None, ax=None, cmap="viridis", label=None)
Plot one unknown of one snapshot.
Definition notebook.py:100
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