Debian Codegraph @

tests/test_original_checkpoint.py

raw
1 from __future__ import annotations
2
3 import itertools
4 import os
5 from collections.abc import Callable
6 from pathlib import Path
7
8 from mpi4py import MPI
9
10 import basix
11 import basix.ufl
12 import dolfinx
13 import numpy as np
14 import pytest
15
16 import adios4dolfinx
17
18 dtypes = [np.float64, np.float32] # Mesh geometry dtypes
19
20 two_dimensional_cell_types = [
21 dolfinx.mesh.CellType.triangle,
22 dolfinx.mesh.CellType.quadrilateral,
23 ]
24 three_dimensional_cell_types = [
25 dolfinx.mesh.CellType.tetrahedron,
26 dolfinx.mesh.CellType.hexahedron,
27 ]
28
29 two_dim_combinations = itertools.product(dtypes, two_dimensional_cell_types)
30 three_dim_combinations = itertools.product(dtypes, three_dimensional_cell_types)
31
32
33 @pytest.fixture(scope="module")
34 def create_simplex_mesh_2D(tmp_path_factory):
35 mesh = dolfinx.mesh.create_unit_square(
36 MPI.COMM_WORLD,
37 10,
38 10,
39 cell_type=dolfinx.mesh.CellType.triangle,
40 dtype=np.float64,
41 )
42 fname = tmp_path_factory.mktemp("output") / "original_mesh_2D_simplex.xdmf"
43 fname = MPI.COMM_WORLD.bcast(fname, root=0)
44 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "w") as xdmf:
45 xdmf.write_mesh(mesh)
46 return fname
47
48
49 @pytest.fixture(scope="module")
50 def create_simplex_mesh_3D(tmp_path_factory):
51 mesh = dolfinx.mesh.create_unit_cube(
52 MPI.COMM_WORLD,
53 5,
54 5,
55 5,
56 cell_type=dolfinx.mesh.CellType.tetrahedron,
57 dtype=np.float64,
58 )
59 fname = tmp_path_factory.mktemp("output") / "original_mesh_3D_simplex.xdmf"
60 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "w") as xdmf:
61 xdmf.write_mesh(mesh)
62 return fname
63
64
65 @pytest.fixture(scope="module")
66 def create_non_simplex_mesh_2D(tmp_path_factory):
67 mesh = dolfinx.mesh.create_unit_square(
68 MPI.COMM_WORLD,
69 10,
70 10,
71 cell_type=dolfinx.mesh.CellType.quadrilateral,
72 dtype=np.float64,
73 )
74 fname = tmp_path_factory.mktemp("output") / "original_mesh_2D_non_simplex.xdmf"
75 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "w") as xdmf:
76 xdmf.write_mesh(mesh)
77 return fname
78
79
80 @pytest.fixture(scope="module")
81 def create_non_simplex_mesh_3D(tmp_path_factory):
82 mesh = dolfinx.mesh.create_unit_cube(
83 MPI.COMM_WORLD,
84 5,
85 5,
86 5,
87 cell_type=dolfinx.mesh.CellType.hexahedron,
88 dtype=np.float64,
89 )
90 fname = tmp_path_factory.mktemp("output") / "original_mesh_3D_non_simplex.xdmf"
91 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "w") as xdmf:
92 xdmf.write_mesh(mesh)
93 return fname
94
95
96 @pytest.fixture(params=two_dim_combinations, scope="module")
97 def create_2D_mesh(request, tmpdir_factory):
98 dtype, cell_type = request.param
99 mesh = dolfinx.mesh.create_unit_square(MPI.COMM_WORLD, 5, 7, cell_type=cell_type, dtype=dtype)
100 fname = Path(tmpdir_factory.mktemp("output")) / f"original_mesh_2D_{dtype}_{cell_type}.xdmf"
101 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "w") as xdmf:
102 xdmf.write_mesh(mesh)
103 return fname
104
105
106 @pytest.fixture(params=three_dim_combinations, scope="module")
107 def create_3D_mesh(request, tmpdir_factory):
108 dtype, cell_type = request.param
109 mesh = dolfinx.mesh.create_unit_cube(MPI.COMM_WORLD, 5, 7, 3, cell_type=cell_type, dtype=dtype)
110 fname = Path(tmpdir_factory.mktemp("output")) / f"original_mesh_3D_{dtype}_{cell_type}.xdmf"
111 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "w") as xdmf:
112 xdmf.write_mesh(mesh)
113 return fname
114
115
116 def write_function_original(
117 write_mesh: bool,
118 mesh: dolfinx.mesh.Mesh,
119 el: basix.ufl._ElementBase,
120 f: Callable[[np.ndarray], np.ndarray],
121 dtype: np.dtype,
122 name: str,
123 path: Path,
124 ) -> Path:
125 """Convenience function for writing function to file on the original input mesh"""
126 V = dolfinx.fem.functionspace(mesh, el)
127 uh = dolfinx.fem.Function(V, dtype=dtype)
128 uh.interpolate(f)
129 uh.name = name
130 el_hash = (
131 adios4dolfinx.utils.element_signature(V)
132 .replace(" ", "")
133 .replace(",", "")
134 .replace("(", "")
135 .replace(")", "")
136 .replace("[", "")
137 .replace("]", "")
138 )
139
140 file_hash = f"{el_hash}_{np.dtype(dtype).name}"
141 filename = path / f"mesh_{file_hash}.bp"
142 if write_mesh:
143 adios4dolfinx.write_mesh_input_order(filename, mesh)
144 adios4dolfinx.write_function_on_input_mesh(filename, uh, time=0.0)
145 return filename
146
147
148 def read_function_original(
149 mesh_fname: Path,
150 u_fname: Path,
151 u_name: str,
152 family: str,
153 degree: int,
154 f: Callable[[np.ndarray], np.ndarray],
155 u_dtype: np.dtype,
156 ):
157 """
158 Convenience function for reading mesh with IPython-parallel and compare to exact solution
159 """
160 from mpi4py import MPI
161
162 import dolfinx
163
164 import adios4dolfinx
165
166 assert MPI.COMM_WORLD.size > 1
167 if mesh_fname.suffix == ".xdmf":
168 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, mesh_fname, "r") as xdmf:
169 mesh = xdmf.read_mesh()
170 elif mesh_fname.suffix == ".bp":
171 mesh = adios4dolfinx.read_mesh(
172 mesh_fname, MPI.COMM_WORLD, "BP4", dolfinx.mesh.GhostMode.shared_facet
173 )
174 el = basix.ufl.element(
175 family,
176 mesh.basix_cell(),
177 degree,
178 basix.LagrangeVariant.gll_warped,
179 shape=(mesh.geometry.dim,),
180 dtype=mesh.geometry.x.dtype,
181 )
182
183 V = dolfinx.fem.functionspace(mesh, el)
184 u = dolfinx.fem.Function(V, name=u_name, dtype=u_dtype)
185 adios4dolfinx.read_function(u_fname, u, time=0.0)
186 MPI.COMM_WORLD.Barrier()
187
188 u_ex = dolfinx.fem.Function(V, name="exact", dtype=u_dtype)
189 u_ex.interpolate(f)
190 u_ex.x.scatter_forward()
191 atol = 10 * np.finfo(u_dtype).resolution
192 np.testing.assert_allclose(u.x.array, u_ex.x.array, atol=atol) # type: ignore
193
194
195 def write_function_vector(
196 write_mesh: bool,
197 fname: Path,
198 family: str,
199 degree: int,
200 f: Callable[[np.ndarray], np.ndarray],
201 dtype: np.dtype,
202 name: str,
203 dir: Path,
204 ) -> Path:
205 """Convenience function for writing function to file on the original input mesh"""
206 from mpi4py import MPI
207
208 import basix.ufl
209 import dolfinx
210
211 import adios4dolfinx
212
213 assert MPI.COMM_WORLD.size > 1
214 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "r") as xdmf:
215 mesh = xdmf.read_mesh()
216 el = basix.ufl.element(family, mesh.basix_cell(), degree, dtype=mesh.geometry.x.dtype)
217 V = dolfinx.fem.functionspace(mesh, el)
218 uh = dolfinx.fem.Function(V, dtype=dtype)
219 uh.interpolate(f)
220 uh.name = name
221 el_hash = (
222 adios4dolfinx.utils.element_signature(V)
223 .replace(" ", "")
224 .replace(",", "")
225 .replace("(", "")
226 .replace(")", "")
227 .replace("[", "")
228 .replace("]", "")
229 )
230
231 file_hash = f"{el_hash}_{np.dtype(dtype).name}"
232 filename = dir / f"mesh_{file_hash}.bp"
233
234 if write_mesh:
235 adios4dolfinx.write_mesh_input_order(filename, mesh)
236 adios4dolfinx.write_function_on_input_mesh(filename, uh, time=0.0)
237 return filename
238
239
240 def read_function_vector(
241 mesh_fname: Path,
242 u_fname: Path,
243 u_name: str,
244 family: str,
245 degree: int,
246 f: Callable[[np.ndarray], np.ndarray],
247 u_dtype: np.dtype,
248 ):
249 """
250 Convenience function for reading mesh with IPython-parallel and compare to exact solution
251 """
252
253 if mesh_fname.suffix == ".xdmf":
254 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, mesh_fname, "r") as xdmf:
255 mesh = xdmf.read_mesh()
256 elif mesh_fname.suffix == ".bp":
257 mesh = adios4dolfinx.read_mesh(
258 mesh_fname, MPI.COMM_WORLD, "BP4", dolfinx.mesh.GhostMode.shared_facet
259 )
260 el = basix.ufl.element(family, mesh.basix_cell(), degree)
261
262 V = dolfinx.fem.functionspace(mesh, el)
263 u = dolfinx.fem.Function(V, name=u_name, dtype=u_dtype)
264 adios4dolfinx.read_function(u_fname, u, time=0.0)
265 MPI.COMM_WORLD.Barrier()
266
267 u_ex = dolfinx.fem.Function(V, name="exact", dtype=u_dtype)
268 u_ex.interpolate(f)
269 u_ex.x.scatter_forward()
270 atol = 10 * np.finfo(u_dtype).resolution
271 np.testing.assert_allclose(u.x.array, u_ex.x.array, atol=atol) # type: ignore
272
273
274 @pytest.mark.skipif(
275 os.cpu_count() == 1, reason="Test requires that the system has more than one process"
276 )
277 @pytest.mark.skipif(MPI.COMM_WORLD.size > 1, reason="Test uses ipythonparallel for MPI")
278 @pytest.mark.parametrize("is_complex", [True, False])
279 @pytest.mark.parametrize("family", ["Lagrange", "DG"])
280 @pytest.mark.parametrize("degree", [1, 4])
281 @pytest.mark.parametrize("write_mesh", [True, False])
282 def test_read_write_P_2D(
283 write_mesh, family, degree, is_complex, create_2D_mesh, cluster, get_dtype, tmp_path
284 ):
285 fname = create_2D_mesh
286 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "r") as xdmf:
287 mesh = xdmf.read_mesh()
288 f_dtype = get_dtype(mesh.geometry.x.dtype, is_complex)
289
290 el = basix.ufl.element(
291 family,
292 mesh.basix_cell(),
293 degree,
294 basix.LagrangeVariant.gll_warped,
295 shape=(mesh.geometry.dim,),
296 dtype=mesh.geometry.x.dtype,
297 )
298
299 def f(x):
300 values = np.empty((2, x.shape[1]), dtype=f_dtype)
301 values[0] = np.full(x.shape[1], np.pi) + x[0]
302 values[1] = x[0]
303 if is_complex:
304 values[0] -= 3j * x[1]
305 values[1] += 2j * x[0]
306 return values
307
308 hash = write_function_original(write_mesh, mesh, el, f, f_dtype, "u_original", tmp_path)
309
310 if write_mesh:
311 mesh_fname = hash
312 else:
313 mesh_fname = fname
314 query = cluster[:].apply_async(
315 read_function_original, mesh_fname, hash, "u_original", family, degree, f, f_dtype
316 )
317 query.wait()
318 assert query.successful(), query.error
319
320
321 @pytest.mark.skipif(
322 os.cpu_count() == 1, reason="Test requires that the system has more than one process"
323 )
324 @pytest.mark.skipif(MPI.COMM_WORLD.size > 1, reason="Test uses ipythonparallel for MPI")
325 @pytest.mark.parametrize("is_complex", [True, False])
326 @pytest.mark.parametrize("family", ["Lagrange", "DG"])
327 @pytest.mark.parametrize("degree", [1, 4])
328 @pytest.mark.parametrize("write_mesh", [True, False])
329 def test_read_write_P_3D(
330 write_mesh, family, degree, is_complex, create_3D_mesh, cluster, get_dtype, tmp_path
331 ):
332 fname = create_3D_mesh
333 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, fname, "r") as xdmf:
334 mesh = xdmf.read_mesh()
335 f_dtype = get_dtype(mesh.geometry.x.dtype, is_complex)
336 el = basix.ufl.element(
337 family,
338 mesh.basix_cell(),
339 degree,
340 basix.LagrangeVariant.gll_warped,
341 shape=(mesh.geometry.dim,),
342 )
343
344 def f(x):
345 values = np.empty((3, x.shape[1]), dtype=f_dtype)
346 values[0] = np.pi + x[0]
347 values[1] = x[1] + 2 * x[0]
348 values[2] = np.cos(x[2])
349 if is_complex:
350 values[0] -= np.pi * x[1]
351 values[1] += 3j * x[2]
352 values[2] += 2j
353 return values
354
355 hash = write_function_original(write_mesh, mesh, el, f, f_dtype, "u_original", tmp_path)
356 MPI.COMM_WORLD.Barrier()
357
358 if write_mesh:
359 mesh_fname = hash
360 else:
361 mesh_fname = fname
362
363 query = cluster[:].apply_async(
364 read_function_original, mesh_fname, hash, "u_original", family, degree, f, f_dtype
365 )
366 query.wait()
367 assert query.successful(), query.error
368
369
370 @pytest.mark.skipif(
371 os.cpu_count() == 1, reason="Test requires that the system has more than one process"
372 )
373 @pytest.mark.skipif(MPI.COMM_WORLD.size > 1, reason="Test uses ipythonparallel for MPI")
374 @pytest.mark.parametrize("write_mesh", [True, False])
375 @pytest.mark.parametrize("is_complex", [True, False])
376 @pytest.mark.parametrize("family", ["N1curl", "RT"])
377 @pytest.mark.parametrize("degree", [1, 4])
378 def test_read_write_2D_vector_simplex(
379 write_mesh, family, degree, is_complex, create_simplex_mesh_2D, cluster, get_dtype, tmp_path
380 ):
381 fname = create_simplex_mesh_2D
382
383 f_dtype = get_dtype(np.float64, is_complex)
384
385 def f(x):
386 values = np.empty((2, x.shape[1]), dtype=f_dtype)
387 values[0] = np.full(x.shape[1], np.pi) + x[0]
388 values[1] = x[1]
389 if is_complex:
390 values[0] -= np.sin(x[1]) * 2j
391 values[1] += 3j
392 return values
393
394 query = cluster[:].apply_async(
395 write_function_vector, write_mesh, fname, family, degree, f, f_dtype, "u_original", tmp_path
396 )
397 query.wait()
398 assert query.successful(), query.error
399 paths = query.result()
400 file_path = paths[0]
401 assert all([file_path == path for path in paths])
402 if write_mesh:
403 mesh_fname = file_path
404 else:
405 mesh_fname = fname
406
407 read_function_vector(mesh_fname, file_path, "u_original", family, degree, f, f_dtype)
408
409
410 @pytest.mark.skipif(
411 os.cpu_count() == 1, reason="Test requires that the system has more than one process"
412 )
413 @pytest.mark.skipif(MPI.COMM_WORLD.size > 1, reason="Test uses ipythonparallel for MPI")
414 @pytest.mark.parametrize("write_mesh", [True, False])
415 @pytest.mark.parametrize("is_complex", [True, False])
416 @pytest.mark.parametrize("family", ["N1curl", "RT"])
417 @pytest.mark.parametrize("degree", [1, 4])
418 def test_read_write_3D_vector_simplex(
419 write_mesh, family, degree, is_complex, create_simplex_mesh_3D, cluster, get_dtype, tmp_path
420 ):
421 fname = create_simplex_mesh_3D
422
423 f_dtype = get_dtype(np.float64, is_complex)
424
425 def f(x):
426 values = np.empty((3, x.shape[1]), dtype=f_dtype)
427 values[0] = np.full(x.shape[1], np.pi)
428 values[1] = x[1] + 2 * x[0]
429 values[2] = np.cos(x[2])
430 if is_complex:
431 values[0] += 2j * x[2]
432 values[1] += 2j * np.cos(x[2])
433 return values
434
435 query = cluster[:].apply_async(
436 write_function_vector, write_mesh, fname, family, degree, f, f_dtype, "u_original", tmp_path
437 )
438 query.wait()
439 assert query.successful(), query.error
440 paths = query.result()
441 file_path = paths[0]
442 assert all([file_path == path for path in paths])
443 if write_mesh:
444 mesh_fname = file_path
445 else:
446 mesh_fname = fname
447
448 read_function_vector(mesh_fname, file_path, "u_original", family, degree, f, f_dtype)
449
450
451 @pytest.mark.skipif(
452 os.cpu_count() == 1, reason="Test requires that the system has more than one process"
453 )
454 @pytest.mark.skipif(MPI.COMM_WORLD.size > 1, reason="Test uses ipythonparallel for MPI")
455 @pytest.mark.parametrize("write_mesh", [True, False])
456 @pytest.mark.parametrize("is_complex", [True, False])
457 @pytest.mark.parametrize("family", ["RTCF"])
458 @pytest.mark.parametrize("degree", [1, 2, 3])
459 def test_read_write_2D_vector_non_simplex(
460 write_mesh, family, degree, is_complex, create_non_simplex_mesh_2D, cluster, get_dtype, tmp_path
461 ):
462 fname = create_non_simplex_mesh_2D
463
464 f_dtype = get_dtype(np.float64, is_complex)
465
466 def f(x):
467 values = np.empty((2, x.shape[1]), dtype=f_dtype)
468 values[0] = np.full(x.shape[1], np.pi)
469 values[1] = x[1] + 2 * x[0]
470 if is_complex:
471 values[0] += 2j * x[1]
472 values[1] -= np.sin(x[0]) * 9j
473 return values
474
475 query = cluster[:].apply_async(
476 write_function_vector, write_mesh, fname, family, degree, f, f_dtype, "u_original", tmp_path
477 )
478 query.wait()
479 assert query.successful(), query.error
480 paths = query.result()
481 file_path = paths[0]
482 assert all([file_path == path for path in paths])
483 if write_mesh:
484 mesh_fname = file_path
485 else:
486 mesh_fname = fname
487
488 read_function_vector(mesh_fname, file_path, "u_original", family, degree, f, f_dtype)
489
490
491 @pytest.mark.skipif(
492 os.cpu_count() == 1, reason="Test requires that the system has more than one process"
493 )
494 @pytest.mark.skipif(MPI.COMM_WORLD.size > 1, reason="Test uses ipythonparallel for MPI")
495 @pytest.mark.parametrize("write_mesh", [True, False])
496 @pytest.mark.parametrize("is_complex", [True, False])
497 @pytest.mark.parametrize("family", ["NCF"])
498 @pytest.mark.parametrize("degree", [1, 4])
499 def test_read_write_3D_vector_non_simplex(
500 write_mesh, family, degree, is_complex, create_non_simplex_mesh_3D, cluster, get_dtype, tmp_path
501 ):
502 fname = create_non_simplex_mesh_3D
503
504 f_dtype = get_dtype(np.float64, is_complex)
505
506 def f(x):
507 values = np.empty((3, x.shape[1]), dtype=f_dtype)
508 values[0] = np.full(x.shape[1], np.pi) + x[0]
509 values[1] = np.cos(x[2])
510 values[2] = x[0]
511 if is_complex:
512 values[2] += x[0] * x[1] * 3j
513 return values
514
515 query = cluster[:].apply_async(
516 write_function_vector, write_mesh, fname, family, degree, f, f_dtype, "u_original", tmp_path
517 )
518 query.wait()
519 assert query.successful(), query.error
520 paths = query.result()
521 file_path = paths[0]
522 assert all([file_path == path for path in paths])
523 if write_mesh:
524 mesh_fname = file_path
525 else:
526 mesh_fname = fname
527
528 read_function_vector(mesh_fname, file_path, "u_original", family, degree, f, f_dtype)