Debian Codegraph @

docs/snapshot_checkpoint.py

raw
1 # # Snapshot checkpoint (non-persistent)
2 # The checkpoint method described in [Writing function checkpoints](./writing_functions_checkpoint)
3 # are *N-to-M*, meaning that you can write them out on N-processes and read them in on M processes.
4 #
5 # As discussed in that chapter, these checkpoints need to be associated with a mesh.
6 # This is because the function is defined on a specific function space, which in turn is
7 # defined on a specific mesh.
8 #
9 # However, there are certain scenarios where you simply want to store a checkpoint associated
10 # with the current mesh, that should only be possible to use during this simulation.
11 # An example use-case is when running an iterative solver, and wanting a fall-back mechanism that
12 # does not require extra RAM.
13
14 # In this example, we will demonstrate how to write a
15 # {py:func}`snapshot checkpoint<adios4dolfinx.snapshot_checkpoint>` to disk.
16
17 # First we define a {py:class}`function<dolfinx.fem.Function>` `f` that we want to represent in
18 # the {py:class}`function space<dolfinx.fem.FunctionSpace>`.
19
20 # +
21 import logging
22 from pathlib import Path
23
24 import ipyparallel as ipp
25
26
27 def f(x):
28 import numpy as np
29
30 return np.sin(x[0]) + 0.1 * x[1]
31
32
33 # -
34
35 # Next, we create a mesh and an appropriate function space and read and write from file.
36 # Note that for both these operations, we use {py:func}`adios4dolfinx.snapshot_checkpoint`,
37 # with different read and write modes.
38
39
40 def read_write_snapshot(filename: Path):
41 from mpi4py import MPI
42
43 import dolfinx
44 import numpy as np
45
46 import adios4dolfinx
47
48 mesh = dolfinx.mesh.create_unit_cube(MPI.COMM_WORLD, 3, 7, 4)
49 V = dolfinx.fem.functionspace(mesh, ("Lagrange", 5))
50 u = dolfinx.fem.Function(V)
51 u.interpolate(f)
52 u.name = "Current_solution"
53 # Next, we store the solution to file
54 adios4dolfinx.snapshot_checkpoint(u, filename, adios4dolfinx.adios2_helpers.adios2.Mode.Write)
55
56 # Next, we create a new function and load the solution into it
57 u_new = dolfinx.fem.Function(V)
58 u_new.name = "Read_solution"
59 adios4dolfinx.snapshot_checkpoint(
60 u_new, filename, adios4dolfinx.adios2_helpers.adios2.Mode.Read
61 )
62
63 # Next, we verify that the solution is correct
64 np.testing.assert_allclose(u_new.x.array, u.x.array, atol=np.finfo(float).eps)
65
66 print(f"{MPI.COMM_WORLD.rank + 1}/{MPI.COMM_WORLD.size}: Successfully wrote and read snapshot")
67
68
69 # +
70
71 mesh_file = Path("snapshot.bp")
72
73 with ipp.Cluster(engines="mpi", n=3, log_level=logging.ERROR) as cluster:
74 cluster[:].push({"f": f})
75 query = cluster[:].apply_async(
76 read_write_snapshot,
77 mesh_file,
78 )
79 query.wait()
80 assert query.successful(), query.error
81 print("".join(query.stdout))
82 # -