Peano
Loading...
Searching...
No Matches
11_tsunami.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 11_tsunami.ipynb
6
7The script builds the tutorial's shallow water setup, runs it and writes
8snapshots of the water height into the directory of this script. It does
9so twice: for the flat sea floor and for the sea floor shaped like the logo
10of Durham University (section "Adding bathymetry and external files", which
11reads the logo from tutorials/exahype2/bathymetry). The tutorial derives
12flux and eigenvalue of the latter with SymPy, whereas we use the handwritten
13versions here. Both give the same results. Finally, it runs the setup of
14section "Letting the bathymetry shape the flow", which uses the surface
15elevation eta as unknown, and plots it at t=0, 0.1, 0.2 and 0.4. Call the
16script from anywhere:
17
18 python3 tutorials/exahype2/illustrations/11_tsunami.py
19
20All builds and outputs go into a temporary directory (or --work-directory).
21
22"""
23import argparse
24import os
25import subprocess
26import sys
27import tempfile
28
29Here = os.path.dirname(os.path.abspath(__file__))
30PeanoRoot = os.path.abspath(os.path.join(Here, "..", "..", ".."))
31sys.path.insert(0, os.path.join(PeanoRoot, "src"))
32
33import matplotlib
34
35matplotlib.use("Agg")
36import matplotlib.pyplot as plt
37
38import peano4.api
39import exahype2
41
42
43Flux = """
44 constexpr double g = 9.81;
45 const double h = Q[Variables::h];
46 const double un = Q[Variables::hu + normal] / h;
47 F[Variables::h] = Q[Variables::hu + normal];
48 F[Variables::hu] = Q[Variables::hu] * un;
49 F[Variables::hv] = Q[Variables::hv] * un;
50 F[Variables::hu + normal] += 0.5 * g * h * h;
51"""
52
53MaxEigenvalue = """
54 constexpr double g = 9.81;
55 const double h = Q[Variables::h];
56 const double un = Q[Variables::hu + normal] / h;
57 lambdaMax[0] = std::abs(un) + std::sqrt(g * h);
58"""
59
60InitPointWisely = """
61 Q[Variables::h] = 1.0 + 0.1 * std::exp(-100.0 * (x[0] * x[0] + x[1] * x[1]));
62 Q[Variables::hu] = 0.0;
63 Q[Variables::hv] = 0.0;
64"""
65
66InitPointWiselyWithLogo = """
67 const int column = std::clamp(static_cast<int>((x[0] + 1.0) / 2.0 * DurhamLogoSize), 0, DurhamLogoSize - 1);
68 const int row = std::clamp(static_cast<int>((1.0 - x[1]) / 2.0 * DurhamLogoSize), 0, DurhamLogoSize - 1);
69 const double depth = DurhamLogo[row][column] == '1' ? 4.0 : 1.0;
70
71 Q[Variables::h] = depth + 0.1 * std::exp(-100.0 * (x[0] * x[0] + x[1] * x[1]));
72 Q[Variables::hu] = 0.0;
73 Q[Variables::hv] = 0.0;
74 bathymetry[Bathymetry::b] = -depth;
75"""
76
77FluxEta = """
78 constexpr double g = 9.81;
79 const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
80 const double un = Q[Variables::hu + normal] / h;
81 F[Variables::eta] = Q[Variables::hu + normal];
82 F[Variables::hu] = Q[Variables::hu] * un;
83 F[Variables::hv] = Q[Variables::hv] * un;
84 F[Variables::hu + normal] += 0.5 * g * h * h;
85"""
86
87MaxEigenvalueEta = """
88 constexpr double g = 9.81;
89 const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
90 const double un = Q[Variables::hu + normal] / h;
91 lambdaMax[0] = std::abs(un) + std::sqrt(g * h);
92"""
93
94NonconservativeProductEta = """
95 constexpr double g = 9.81;
96 const double h = Q[Variables::eta] - bathymetry[Bathymetry::b];
97 BTimesDeltaQ[Variables::eta] = 0.0;
98 BTimesDeltaQ[Variables::hu] = 0.0;
99 BTimesDeltaQ[Variables::hv] = 0.0;
100 BTimesDeltaQ[Variables::hu + normal] = g * h * deltaBathymetry[Bathymetry::b];
101"""
102
103InitPointWiselyEta = """
104 const int column = std::clamp(static_cast<int>((x[0] + 1.0) / 2.0 * DurhamLogoSize), 0, DurhamLogoSize - 1);
105 const int row = std::clamp(static_cast<int>((1.0 - x[1]) / 2.0 * DurhamLogoSize), 0, DurhamLogoSize - 1);
106 const double depth = DurhamLogo[row][column] == '1' ? 4.0 : 1.0;
107
108 Q[Variables::eta] = 0.1 * std::exp(-100.0 * (x[0] * x[0] + x[1] * x[1]));
109 Q[Variables::hu] = 0.0;
110 Q[Variables::hv] = 0.0;
111 bathymetry[Bathymetry::b] = -depth;
112"""
113
114Bathymetry = os.path.join(Here, "..", "bathymetry")
115
116PatchFile = "solution-SWE.peano-patch-file"
117
118
120 directory,
121 init=InitPointWisely,
122 with_logo=False,
123 first_unknown="h",
124 flux=Flux,
125 max_eigenvalue=MaxEigenvalue,
126 nonconservative_product=None,
127):
128 """!
129
130 Generate, compile and run the tutorial setup within directory
131
132 with_logo adds the depth map DurhamLogo from Bathymetry to the build.
133 first_unknown is the name of the first unknown, i.e. h or eta.
134
135 """
136 project = exahype2.api.Project(
137 namespace=["tutorials", "exahype2", "tsunami"],
138 project_name="Tsunami",
139 directory=directory,
140 executable="tsunami",
141 )
142 solver = exahype2.api.Solver("SWE", {first_unknown: 1, "hu": 1, "hv": 1})
143 if with_logo:
144 solver.add_auxiliary_variables(
146 "Bathymetry",
147 {"b": 1},
148 mode=exahype2.api.AuxiliaryVariables.Mode.STATIONARY_ON_FACES,
149 )
150 )
151 solver.add_user_solver_includes("#include <cmath>\n#include <algorithm>\n")
152 if with_logo:
153 solver.add_user_solver_includes('#include "DurhamLogo.h"\n')
154 solver.add_pde_term(exahype2.api.Flux(implementation=flux, stateless=True))
155 solver.add_pde_term(
156 exahype2.api.MaxEigenvalue(implementation=max_eigenvalue, stateless=True)
157 )
158 if nonconservative_product is not None:
159 solver.add_pde_term(
161 implementation=nonconservative_product, stateless=True
162 )
163 )
164 solver.add_pde_term(
165 exahype2.api.InitPointWisely(implementation=init, stateless=False)
166 )
167 solver.numerical_scheme = exahype2.api.fv.RusanovWithExplicitEuler(solver, 9)
168 solver.grid_construction = exahype2.api.fv.SetupSimulationOverRegularGrid(
169 solver, volume_size=0.01
170 )
171 solver.plotter = exahype2.api.fv.PlotAsVTKFile(
172 solver, first_plot_time_stamp=0.0, time_in_between_plots=0.05
173 )
174 project.add_solver(solver)
175 project.set_global_simulation_parameters(
176 dimensions=2,
177 offset=[-1.0, -1.0],
178 size=[2.0, 2.0],
179 min_end_time=0.4,
180 max_end_time=0.4,
181 periodic_BC=[True, True, True],
182 )
183 project.set_Peano4_installation(PeanoRoot, peano4.api.output.CompileMode.RELEASE)
184 peano4_project = project.generate_Peano4_project()
185 if with_logo:
186 makefile = peano4_project.output.makefile
187 makefile.add_cpp_file(os.path.join(Bathymetry, "DurhamLogo.cpp"))
188 makefile.add_h_file(os.path.join(Bathymetry, "DurhamLogo.h"))
189 makefile.add_header_search_path(Bathymetry)
190 peano4_project.generate()
191 subprocess.run(["make", "-j"], cwd=directory, check=True, stdout=subprocess.DEVNULL)
192 subprocess.run(["./tsunami"], cwd=directory, check=True, stdout=subprocess.DEVNULL)
193
194
195def plot_snapshots(directory, prefix, label="water height h", with_early=False):
196 """!
197
198 First unknown at the start, half way through and at the end
199
200 with_early adds the snapshot at a quarter of the simulated time.
201
202 """
203 file_name = os.path.join(directory, PatchFile)
204 snapshots = len(tarch.plotter.api.notebook.read_snapshots(file_name))
205 selection = [
206 (0, "start"),
207 ((snapshots - 1) // 2, "middle"),
208 (snapshots - 1, "end"),
209 ]
210 if with_early:
211 selection.insert(1, ((snapshots - 1) // 4, "early"))
212 for snapshot, suffix in selection:
213 fig, ax = plt.subplots(figsize=(6, 5))
215 file_name, snapshot, 0, ax=ax, label=label
216 )
217 fig.savefig(
218 os.path.join(Here, prefix + suffix + ".png"),
219 dpi=100,
220 bbox_inches="tight",
221 )
222 plt.close(fig)
223
224
225def plot_sea_floor(directory, prefix):
226 """! Sea floor b, which does not change over time"""
227 fig, ax = plt.subplots(figsize=(6, 5))
229 os.path.join(directory, "solution-SWE-Bathymetry.peano-patch-file"), 0, 0, ax=ax, cmap="Purples_r", label="sea floor b"
230 )
231 fig.savefig(os.path.join(Here, prefix + "b.png"), dpi=100, bbox_inches="tight")
232 plt.close(fig)
233
234
235if __name__ == "__main__":
236 parser = argparse.ArgumentParser(
237 description="Create the PNGs of the tutorial 11_tsunami.ipynb"
238 )
239 parser.add_argument(
240 "--work-directory",
241 default=None,
242 help="Directory for builds and outputs (default: temporary directory)",
243 )
244 args = parser.parse_args()
245
246 work_directory = args.work_directory or tempfile.mkdtemp(prefix="11_tsunami-")
247 print("build and run in {}".format(work_directory))
248 flat = os.path.join(work_directory, "flat")
249 build_and_run(flat)
250 plot_snapshots(flat, "11_tsunami-")
251
252 bathymetry = os.path.join(work_directory, "bathymetry")
253 build_and_run(bathymetry, InitPointWiselyWithLogo, with_logo=True)
254 plot_snapshots(bathymetry, "11_tsunami-bathymetry-")
255 plot_sea_floor(bathymetry, "11_tsunami-bathymetry-")
256
257 ncp = os.path.join(work_directory, "ncp")
259 ncp,
260 InitPointWiselyEta,
261 with_logo=True,
262 first_unknown="eta",
263 flux=FluxEta,
264 max_eigenvalue=MaxEigenvalueEta,
265 nonconservative_product=NonconservativeProductEta,
266 )
268 ncp, "11_tsunami-ncp-", label="surface elevation eta", with_early=True
269 )
270 print("wrote PNGs into {}".format(Here))
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...
build_and_run(directory, init=InitPointWisely, with_logo=False, first_unknown="h", flux=Flux, max_eigenvalue=MaxEigenvalue, nonconservative_product=None)
Generate, compile and run the tutorial setup within directory.
plot_sea_floor(directory, prefix)
Sea floor b, which does not change over time.
plot_snapshots(directory, prefix, label="water height h", with_early=False)
First unknown at the start, half way through and at the end.
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_snapshots(file_name)
Return list of (time stamp, list of patch files) from a patch meta file.
Definition notebook.py:30