Peano
Loading...
Searching...
No Matches
WriteCheckpoint.py
Go to the documentation of this file.
1# This file is part of the ExaHyPE2 project. For conditions of distribution and
2# use, please see the copyright notice at www.peano-framework.org
3import os
4
5import peano4.api
7
8from ..Solver import Solver
9from .PlotAsVTKFile import _PlotPatchesIfPlotterIsActive
10from .actionsets import ApplyDirichletBoundaryConditions
11
12
14 """!
15
16 Write checkpoints of the fourth-order Finite Differences
17
18 The checkpoint is configured like PlotAsVTKFile, i.e. it is written in
19 regular time intervals. Different to a plot, it writes the whole state
20 of the solver such that a simulation can continue from it. It hence has
21 neither plot filters nor a selection of quantities: It writes all
22 entries of Q, i.e. the unknowns and the auxiliary variables, of all
23 cells which the solver updates.
24
25 - It writes each patch together with its halo. Before it writes the
26 data, it reconstructs the halo exactly as the first Runge-Kutta stage
27 of the time step does: It sets the ghost grid cells along the domain
28 boundary (Dirichlet boundary conditions), interpolates the hanging
29 faces on adaptive meshes and gathers patch and face data into
30 solver._patch_with_halo
31 (toolbox.blockstructured.api.ReconstructPatchWithHalo). A patch
32 with N grid cells per axis and a halo of M grid cells is written as a
33 patch with N+2M grid cells per axis. Its box covers the cell plus the
34 halo, so every grid cell sits at its true position, and neighbouring
35 patches overlap.
36 - It writes all values without loss: values, patch offsets and sizes
37 carry 17 significant digits by default, and the writer does not set
38 small values to zero
39 (@ref tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter).
40 - The meta-data block in the header of each file holds the solver's
41 state (@ref exahype2::Solver::toCheckpointMetaData()): its time
42 stamps, time step sizes, admissible time step size and mesh sizes,
43 plus the attributes the Python API adds to the solver's class, e.g.
44 the time stamps of the next outputs of all of its plotters.
45
46 The files are called checkpoint-SolverName by default. A solver can
47 have a checkpoint next to its other plotters
48 (@ref exahype2.api.Solver.Solver.add_plotter()).
49 A simulation continues from a checkpoint with
50 @ref exahype2.api.blockstructured.LoadCheckpoint.LoadCheckpoint instead of
51 its usual grid construction.
52
53 The reconstruction only reads the patch and face data, i.e. a
54 checkpoint does not change the solution. The Dirichlet boundary
55 conditions overwrite the ghost grid cells with the values they have at
56 the current time stamp anyway, and the next time step sets them again.
57
58 The class is the counterpart of exahype2.api.fv.WriteCheckpoint, as rkfd4
59 does not depend on the Finite Volume package.
60
61 """
62
64 self,
65 solver: Solver,
66 first_plot_time_stamp=0.0,
67 time_in_between_plots=0.1,
68 plotter_precision=17,
69 output_path=".",
70 filename="checkpoint",
71 name: str = None,
72 binary=True,
73 ):
74 """!
75
76 @param solver: exahype2.api.Solver
77 The solver whose state is written.
78
79 @param first_plot_time_stamp: float
80 Time stamp of the first checkpoint.
81
82 @param time_in_between_plots: float
83 Time in between two checkpoints. Has to be positive.
84
85 @param plotter_precision: int
86 Number of significant digits written per value. The default of 17
87 ensures that the values are read back without loss.
88
89 @param output_path: str
90 Directory the checkpoint files are written into.
91
92 @param filename: str
93 The checkpoint files are called filename-SolverName.
94
95 @param name: str or None
96 Name of the plotter (@ref exahype2.api.Solver.Solver.Plotter).
97
98 @param binary: bool
99 Write the values as raw doubles instead of text
100 (@ref tarch::plotter::griddata::blockstructured::PeanoBinaryPatchFileWriter).
101 The checkpoint reader (@ref exahype2::CheckpointReader) reads both
102 formats. Pass False to get human-readable checkpoints.
103
104 """
105 super().__init__(solver, name)
106
107 if time_in_between_plots <= 0:
108 raise Exception("Time in between checkpoints has to be bigger than 0")
109 if plotter_precision <= 0:
110 raise Exception("Precision has to be bigger than 0")
111 self._first_plot_time_stamp = first_plot_time_stamp
112 self._time_in_between_plots = time_in_between_plots
113 self._plotter_precision = plotter_precision
114 self._output_path = output_path
115 self._filename = filename
116 self._binary = binary
117
119 return os.path.join(self._output_path, self._filename + "-" + self._solver.name)
120
121 def construct_output(self, exahype2_project, peano_project, plot):
122 """!
123
124 Add the reconstruction of the halo and the writing of the checkpoint
125 to the plot graph
126
127 All action sets are guarded by the checkpoint's is<Name>Active(),
128 i.e. the tasks do no work in plot phases without checkpoint. The
129 writing task is the last one, so it moves the checkpoint on to its
130 next time stamp.
131
132 """
133 if self._solver.auxiliary_variables:
134 raise NotImplementedError(
135 f"Solver {self._solver.name}: checkpoints do not cover auxiliary variables yet."
136 )
137 peano4.api.Logger().log(
138 "Create checkpoint task graph for fourth-order Finite Differences with Runge-Kutta over block-structured meshes"
139 )
140
141 for attribute in [
142 "_patch",
143 "_patch_with_halo",
144 "_patch_overlap_current_time_step",
145 ]:
146 assert hasattr(self._solver, attribute), (
147 f"Solver {self._solver.name} has no attribute {attribute}. "
148 "WriteCheckpoint assumes the numerical scheme has added this field "
149 "to the solver immediately upon construction."
150 )
151
154 )
155 self._solver._add_checkpoint_meta_data_to_solver()
156
157 Access = peano4.api.taskgraph.Task.DataAccess
158 is_active = self.create_is_active_predicate()
159 cell_guard = (
160 "("
161 + is_active
162 + ") and ("
163 + self._solver.grid_selector.createCellGuard()
164 + ")"
165 )
166 includes = (
167 self._solver._get_default_includes() + self._solver.user_solver_includes
168 )
169
170 reconstruction_task = peano4.api.taskgraph.Task(
171 name=f"{self._solver.name}_{self.name}_Reconstruct",
172 entity=peano4.api.taskgraph.Task.GridEntity.CELL,
173 may_spawn_background_tasks=False,
174 )
175 write_checkpoint_task = peano4.api.taskgraph.Task(
176 name=f"{self._solver.name}_{self.name}_Write checkpoint",
177 entity=peano4.api.taskgraph.Task.GridEntity.CELL,
178 may_spawn_background_tasks=False,
179 )
180 plot.add_task(reconstruction_task)
181 plot.add_task(write_checkpoint_task)
182
183
184 reconstruction_task.use_cell(self._solver._patch, Access.READ_AND_WRITE)
185 reconstruction_task.use_cell(self._solver._patch_with_halo, Access.WRITE)
186 reconstruction_task.use_face(
187 self._solver._patch_overlap_current_time_step, Access.READ_AND_WRITE
188 )
189 reconstruction_task.add_action_set(
190 toolbox.blockstructured.api.ReconstructPatchWithHalo(
191 patch=self._solver._patch,
192 patch_overlap=self._solver._patch_overlap_current_time_step,
193 reconstructed_patch=self._solver._patch_with_halo,
194 guard=cell_guard,
195 add_assertions_to_halo_exchange=False,
196 additional_includes=includes,
197 )
198 )
199
201 reconstruction_task.add_action_set(
202 toolbox.blockstructured.api.InterpolateHangingFaces(
203 self._solver._patch_overlap_current_time_step,
204 scheme=self._solver.numerical_scheme.interpolation,
205 guard=is_active,
206 additional_includes=includes,
207 )
208 )
209
211 ApplyDirichletBoundaryConditions.add_task_to_time_step(
212 self._solver,
213 exahype2_project,
214 plot,
215 reconstruction_task,
216 name_suffix=f" for {self.name}",
217 relative_time_step_size=0.0,
218 additional_guard=is_active,
219 )
220
221
222 write_checkpoint_task.add_dependency(reconstruction_task)
223 write_checkpoint_task.use_cell(
224 self._solver._patch_with_halo, Access.READ_AND_DISCARD
225 )
226 write_checkpoint_task.add_action_set(
228 is_active_predicate=is_active,
229 finish_call=self.create_finish_call(),
230 filename=self.output_file_prefix(),
231 patch=self._solver._patch_with_halo,
232 dataset_name=self._solver._patch_with_halo.name,
233 description=", ".join(self._solver.variable_names_per_entry())
234 or self._solver._unknown_identifier(),
235 guard=self._solver.grid_selector.createCellGuard(),
236 additional_includes="""
237#include "../repositories/SolverRepository.h"
238""",
239 precision=self._plotter_precision,
240 binary=self._binary,
241 time_stamp_evaluation="0.5*(repositories::getMinTimeStamp()+repositories::getMaxTimeStamp())",
242 patch_scaling=self._solver._patch_with_halo.dim[0]
243 / self._solver._patch.dim[0],
244 metadata_evaluation="repositories::"
245 + self._solver.get_name_of_global_instance()
246 + ".toCheckpointMetaData()",
247 )
248 )
249
250 if peano4.api.Logger().is_visualisation:
251 plot.visualise(title="Plot task graph for {}".format(self._solver.name))
252 if peano4.api.Logger().is_text:
253 plot.log_as_text(title="Plot task graph for {}".format(self._solver.name))
How a Solver writes out its solution.
Definition Solver.py:264
_add_time_interval_bookkeeping_to_solver(self, float first_time_stamp, float time_in_between)
Make the plotter active in regular time intervals.
Definition Solver.py:385
str create_is_active_predicate(self)
C++ predicate which holds if the plotter is active.
Definition Solver.py:350
str create_finish_call(self)
C++ statement which moves the plotter on to its next output.
Definition Solver.py:366
PlotPatchesInPeanoBlockFormat which only does something if its plotter is active.
Write checkpoints of the fourth-order Finite Differences.
output_file_prefix(self)
Prefix of the files the plotter writes, including the path.
construct_output(self, exahype2_project, peano_project, plot)
Add the reconstruction of the halo and the writing of the checkpoint to the plot graph.
__init__(self, Solver solver, first_plot_time_stamp=0.0, time_in_between_plots=0.1, plotter_precision=17, output_path=".", filename="checkpoint", str name=None, binary=True)
Singleton logger for the Peano 4 Python API.
Definition Logger.py:37
One task within a peano4.api.taskgraph.Graph.
Definition Task.py:8