File: conftest.py

package info (click to toggle)
io4dolfinx 1.1.2-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 832 kB
  • sloc: python: 8,419; sh: 29; makefile: 3
file content (250 lines) | stat: -rw-r--r-- 7,583 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import typing
from collections import ChainMap

from mpi4py import MPI

import dolfinx
import ipyparallel as ipp
import numpy as np
import numpy.typing
import numpy.typing as npt
import pytest

import io4dolfinx


def find_backends():
    backends = []
    try:
        import adios2

        if adios2.is_built_with_mpi:
            backends.append("adios2")
    except ModuleNotFoundError:
        pass
    try:
        import h5py

        if h5py.get_config().mpi:
            backends.append("h5py")
    except ModuleNotFoundError:
        pass
    return backends


@pytest.fixture(params=find_backends(), scope="function")
def backend(request):
    yield request.param


@pytest.fixture(scope="module")
def cluster():
    cluster = ipp.Cluster(engines="mpi", n=2)
    rc = cluster.start_and_connect_sync()
    rc.wait_for_engines(n=2)
    yield rc
    cluster.stop_cluster_sync()


@pytest.fixture(scope="function")
def write_function(tmp_path):
    def _write_function(
        mesh,
        el,
        f,
        dtype,
        backend: typing.Literal["adios2", "h5py"],
        name="uh",
        append: bool = False,
    ) -> str:
        V = dolfinx.fem.functionspace(mesh, el)
        uh = dolfinx.fem.Function(V, dtype=dtype)
        uh.interpolate(f)
        uh.name = name
        el_hash = (
            io4dolfinx.utils.element_signature(V)
            .replace(" ", "")
            .replace(",", "")
            .replace("(", "")
            .replace(")", "")
            .replace("[", "")
            .replace("]", "")
        )
        # Consistent tmp dir across processes
        f_path = MPI.COMM_WORLD.bcast(tmp_path, root=0)
        file_hash = f"{el_hash}_{np.dtype(dtype).name}"
        if backend == "adios2":
            suffix = ".bp"
        else:
            suffix = ".h5"

        filename = (f_path / f"mesh_{file_hash}").with_suffix(suffix)
        if mesh.comm.size != 1:
            if not append:
                io4dolfinx.write_mesh(filename, mesh, backend=backend)
            io4dolfinx.write_function(filename, uh, time=0.0, backend=backend)
        else:
            if MPI.COMM_WORLD.rank == 0:
                if not append:
                    io4dolfinx.write_mesh(filename, mesh, backend=backend)
                io4dolfinx.write_function(filename, uh, time=0.0, backend=backend)

        return filename

    return _write_function


@pytest.fixture(scope="function")
def read_function():
    def _read_function(
        comm, el, f, path, dtype, backend: typing.Literal["adios2", "h5py"], name="uh"
    ):
        mesh = io4dolfinx.read_mesh(
            path,
            comm,
            ghost_mode=dolfinx.mesh.GhostMode.shared_facet,
            backend=backend,
        )
        V = dolfinx.fem.functionspace(mesh, el)
        v = dolfinx.fem.Function(V, dtype=dtype)
        v.name = name
        io4dolfinx.read_function(path, v, backend=backend)
        v_ex = dolfinx.fem.Function(V, dtype=dtype)
        v_ex.interpolate(f)

        res = np.finfo(dtype).resolution
        np.testing.assert_allclose(v.x.array, v_ex.x.array, atol=10 * res, rtol=10 * res)

    return _read_function


@pytest.fixture(scope="function")
def get_dtype():
    def _get_dtype(in_dtype: np.dtype, is_complex: bool):
        dtype: numpy.typing.DTypeLike
        if in_dtype == np.float32:
            if is_complex:
                dtype = np.complex64
            else:
                dtype = np.float32
        elif in_dtype == np.float64:
            if is_complex:
                dtype = np.complex128
            else:
                dtype = np.float64
        else:
            raise ValueError("Unsuported dtype")
        return dtype

    return _get_dtype


@pytest.fixture(scope="function")
def write_function_time_dep(tmp_path):
    def _write_function_time_dep(
        mesh, el, f0, f1, t0, t1, dtype, backend: typing.Literal["adios2", "h5py"]
    ) -> str:
        V = dolfinx.fem.functionspace(mesh, el)
        uh = dolfinx.fem.Function(V, dtype=dtype)
        uh.interpolate(f0)
        el_hash = (
            io4dolfinx.utils.element_signature(V)
            .replace(" ", "")
            .replace(",", "")
            .replace("(", "")
            .replace(")", "")
            .replace("[", "")
            .replace("]", "")
        )
        file_hash = f"{el_hash}_{np.dtype(dtype).name}"
        # Consistent tmp dir across processes
        f_path = MPI.COMM_WORLD.bcast(tmp_path, root=0)
        if backend == "adios2":
            suffix = ".bp"
        else:
            suffix = ".h5"
        filename = (f_path / f"mesh_{file_hash}").with_suffix(suffix)
        if mesh.comm.size != 1:
            io4dolfinx.write_mesh(filename, mesh, backend=backend)
            io4dolfinx.write_function(filename, uh, time=t0, backend=backend)
            uh.interpolate(f1)
            io4dolfinx.write_function(filename, uh, time=t1, backend=backend)

        else:
            if MPI.COMM_WORLD.rank == 0:
                io4dolfinx.write_mesh(filename, mesh, backend=backend)
                io4dolfinx.write_function(filename, uh, time=t0, backend=backend)
                uh.interpolate(f1)
                io4dolfinx.write_function(filename, uh, time=t1, backend=backend)

        return filename

    return _write_function_time_dep


@pytest.fixture(scope="function")
def read_function_time_dep():
    def _read_function_time_dep(
        comm, el, f0, f1, t0, t1, path, dtype, backend: typing.Literal["adios2", "h5py"]
    ):
        mesh = io4dolfinx.read_mesh(
            path,
            comm,
            ghost_mode=dolfinx.mesh.GhostMode.shared_facet,
            backend=backend,
        )
        V = dolfinx.fem.functionspace(mesh, el)
        v = dolfinx.fem.Function(V, dtype=dtype)

        io4dolfinx.read_function(path, v, time=t1, backend=backend)
        v_ex = dolfinx.fem.Function(V, dtype=dtype)
        v_ex.interpolate(f1)

        res = np.finfo(dtype).resolution
        assert np.allclose(v.x.array, v_ex.x.array, atol=10 * res, rtol=10 * res)

        io4dolfinx.read_function(path, v, time=t0, backend=backend)
        v_ex = dolfinx.fem.Function(V, dtype=dtype)
        v_ex.interpolate(f0)

        res = np.finfo(dtype).resolution
        assert np.allclose(v.x.array, v_ex.x.array, atol=10 * res, rtol=10 * res)

    return _read_function_time_dep


def _generate_reference_map(
    mesh: dolfinx.mesh.Mesh,
    meshtag: dolfinx.mesh.MeshTags,
    comm: MPI.Intracomm,
    root: int,
) -> typing.Optional[dict[str, tuple[int, npt.NDArray]]]:
    """
    Helper function to generate map from meshtag value to its corresponding index and midpoint.

    Args:
        mesh: The mesh
        meshtag: The associated meshtag
        comm: MPI communicator to gather the map from all processes with
        root (int): Rank to store data on
    Returns:
        Root rank returns the map, all other ranks return None
    """
    mesh.topology.create_connectivity(meshtag.dim, mesh.topology.dim)
    midpoints = dolfinx.mesh.compute_midpoints(mesh, meshtag.dim, meshtag.indices)
    e_map = mesh.topology.index_map(meshtag.dim)
    value_to_midpoint = {}
    for index, value in zip(meshtag.indices, meshtag.values):
        value_to_midpoint[value] = (
            int(e_map.local_range[0] + index),
            midpoints[index],
        )
    global_map = comm.gather(value_to_midpoint, root=root)
    if comm.rank == root:
        return dict(ChainMap(*global_map))  # type: ignore
    return None


@pytest.fixture
def generate_reference_map():
    return _generate_reference_map