Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/readers.py: 97%
209 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 12:02 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 12:02 +0000
1# Copyright (C) 2023 Jørgen Schartum Dokken
2#
3# This file is part of io4dolfinx
4#
5# SPDX-License-Identifier: MIT
7from __future__ import annotations
9import logging
10import pathlib
11import typing
12from pathlib import Path
13from typing import Any
15from mpi4py import MPI
17import basix
18import dolfinx
19import fenicsx_compat
20import numpy as np
21import numpy.typing as npt
22import ufl
24from .backends import ReadMode, get_backend, with_mesh_name
25from .comm_helpers import all_to_all, send_dofs_and_recv_values
26from .utils import (
27 check_file_exists,
28 compute_dofmap_pos,
29 compute_insert_position,
30 compute_local_range,
31 index_owner,
32)
34__all__ = ["read_mesh_from_legacy_h5", "read_function_from_legacy_h5", "read_point_data"]
35logger = logging.getLogger(__name__)
38def map_dofmap(dofmap: dolfinx.graph.AdjacencyList, bs: int | np.int64) -> npt.NDArray[np.int64]:
39 """
40 Map xxxyyyzzz to xyzxyz
41 """
43 in_dofmap = dofmap.array
44 in_offsets = dofmap.offsets
46 mapped_dofmap = np.empty_like(in_dofmap)
47 for i in range(len(in_offsets) - 1):
48 pos_begin, pos_end = (
49 in_offsets[i] - in_offsets[0],
50 in_offsets[i + 1] - in_offsets[0],
51 )
52 dofs_i = in_dofmap[pos_begin:pos_end]
53 assert (pos_end - pos_begin) % bs == 0
54 num_dofs_local = int((pos_end - pos_begin) // bs)
55 for k in range(bs):
56 for j in range(num_dofs_local):
57 mapped_dofmap[int(pos_begin + j * bs + k)] = dofs_i[int(num_dofs_local * k + j)]
58 return mapped_dofmap.astype(np.int64)
61def send_cells_and_receive_dofmap_index(
62 filename: pathlib.Path,
63 comm: MPI.Comm,
64 source_ranks: npt.NDArray[np.int32],
65 dest_ranks: npt.NDArray[np.int32],
66 dest_size: npt.NDArray[np.int32],
67 output_owners: npt.NDArray[np.int32],
68 input_cells: npt.NDArray[np.int64],
69 dofmap_pos: npt.NDArray[np.int32],
70 num_cells_global: int | np.int64,
71 dofmap_path: str,
72 xdofmap_path: str,
73 bs: int | np.int64,
74 backend: str | None,
75) -> npt.NDArray[np.int64]:
76 """
77 Given a set of positions in input dofmap, give the global input index of this dofmap entry
78 in input file.
79 """
80 check_file_exists(filename)
82 recv_size = np.zeros(len(source_ranks), dtype=np.int32)
83 assert isinstance(comm, MPI.Intracomm)
84 mesh_to_data_comm = comm.Create_dist_graph_adjacent(
85 source_ranks.tolist(), dest_ranks.tolist(), reorder=False
86 )
87 # Send sizes to create data structures for receiving from NeighAlltoAllv
88 all_to_all(mesh_to_data_comm, dest_size, recv_size)
90 # Sort output for sending and fill send data
91 out_cells = np.zeros(len(output_owners), dtype=np.int64)
92 out_pos = np.zeros(len(output_owners), dtype=np.int32)
93 proc_to_dof = np.zeros_like(input_cells, dtype=np.int32)
94 insertion_array = compute_insert_position(output_owners, dest_ranks, dest_size)
95 out_cells[insertion_array] = input_cells
96 out_pos[insertion_array] = dofmap_pos
97 proc_to_dof[insertion_array] = np.arange(len(input_cells), dtype=np.int32)
98 del insertion_array
100 # Prepare data-structures for receiving
101 total_incoming = sum(recv_size)
102 inc_cells = np.zeros(total_incoming, dtype=np.int64)
103 inc_pos = np.zeros(total_incoming, dtype=np.intc)
105 # Send data
106 s_msg = [out_cells, dest_size, MPI.INT64_T]
107 r_msg = [inc_cells, recv_size, MPI.INT64_T]
108 mesh_to_data_comm.Neighbor_alltoallv(s_msg, r_msg)
110 s_msg = [out_pos, dest_size, MPI.INT32_T]
111 r_msg = [inc_pos, recv_size, MPI.INT32_T]
112 mesh_to_data_comm.Neighbor_alltoallv(s_msg, r_msg)
113 mesh_to_data_comm.Free()
115 backend_cls = get_backend(backend)
116 # Read dofmap from file
117 backend_args = {"dofmap": dofmap_path, "offsets": xdofmap_path}
118 if backend in ("adios2", "adios2-serial"):
119 backend_args.update({"engine": "HDF5"})
120 input_dofs = backend_cls.read_dofmap(filename, comm, name="", backend_args=backend_args)
121 # Map to xyz
122 mapped_dofmap = map_dofmap(input_dofs, bs).astype(np.int64)
124 # Extract dofmap data
125 local_cell_range = compute_local_range(comm, num_cells_global)
126 input_cell_positions = inc_cells - local_cell_range[0]
127 in_offsets = input_dofs.offsets
128 read_pos = (in_offsets[input_cell_positions] + inc_pos - in_offsets[0]).astype(np.int32)
129 input_dofs = mapped_dofmap[read_pos]
130 del input_cell_positions, read_pos
132 # Send input dofs back to owning process
133 data_to_mesh_comm = comm.Create_dist_graph_adjacent(
134 dest_ranks.tolist(), source_ranks.tolist(), reorder=False
135 )
137 incoming_global_dofs = np.zeros(sum(dest_size), dtype=np.int64)
138 s_msg = [input_dofs, recv_size, MPI.INT64_T]
139 r_msg = [incoming_global_dofs, dest_size, MPI.INT64_T]
140 data_to_mesh_comm.Neighbor_alltoallv(s_msg, r_msg)
142 # Sort incoming global dofs as they were inputted
143 sorted_global_dofs = np.zeros_like(incoming_global_dofs, dtype=np.int64)
144 assert len(incoming_global_dofs) == len(input_cells)
145 sorted_global_dofs[proc_to_dof] = incoming_global_dofs
146 data_to_mesh_comm.Free()
147 return sorted_global_dofs
150def read_mesh_from_legacy_h5(
151 filename: pathlib.Path,
152 comm: MPI.Comm,
153 group: str,
154 cell_type: str = "tetrahedron",
155 backend: str | None = None,
156 max_facet_to_cell_links: int = 2,
157) -> dolfinx.mesh.Mesh:
158 """
159 Read mesh from `h5`-file generated by legacy DOLFIN `HDF5File.write` or `XDMF.write_checkpoint`.
161 Args:
162 comm: MPI communicator to distribute mesh over
163 filename: Path to `h5` or `xdmf` file
164 group: Name of mesh in `h5`-file
165 cell_type: What type of cell type, by default tetrahedron.
166 backend: The IO backend to use when reading the mesh (must
167 support legacy mesh reading, e.g., "adios2").
168 max_facet_to_cell_links: Maximum number of cells a facet
169 can be connected to.
170 """
171 logger.debug(f"Reading mesh from {filename} at group {group}")
172 logger.debug(f"Using backend {backend} with max_facet_to_cell_links {max_facet_to_cell_links}")
173 # Make sure we use the HDF5File and check that the file is present
174 check_file_exists(filename)
176 backend_cls = get_backend(backend)
177 mesh_topology, mesh_geometry, ct = backend_cls.read_legacy_mesh(filename, comm, group)
178 if ct is not None:
179 cell_type = ct
180 # Create DOLFINx mesh
181 element = basix.ufl.element(
182 basix.ElementFamily.P,
183 cell_type,
184 1,
185 basix.LagrangeVariant.equispaced,
186 shape=(mesh_geometry.shape[1],),
187 )
188 domain = ufl.Mesh(element)
190 return dolfinx.mesh.create_mesh(
191 comm=MPI.COMM_WORLD,
192 cells=mesh_topology,
193 x=mesh_geometry,
194 e=domain,
195 partitioner=None,
196 max_facet_to_cell_links=max_facet_to_cell_links,
197 )
200def read_function_from_legacy_h5(
201 filename: pathlib.Path,
202 comm: MPI.Comm,
203 u: dolfinx.fem.Function,
204 group: str = "mesh",
205 step: typing.Optional[int] = None,
206 vector_group: str | None = None,
207 backend: str | None = None,
208):
209 """
210 Read function from a `h5`-file generated by legacy DOLFIN `HDF5File.write`
211 or `XDMF.write_checkpoint`.
214 Args:
215 comm : MPI communicator to distribute mesh over
216 filename : Path to `h5` or `xdmf` file
217 u : The function used to stored the read values
218 group : Group within the `h5` file where the function is stored, by default "mesh"
219 step : The time step used when saving the checkpoint. If not provided it will assume that
220 the function is saved as a regular function (i.e with `HDF5File.write`)
221 backend: The IO backend
222 """
223 logger.debug(f"Reading function from {filename} at group {group}")
224 logger.debug(f"Using backend {backend} with group {group} and step {step}")
225 # Make sure we use the HDF5File and check that the file is present
226 filename = pathlib.Path(filename)
227 if filename.suffix == ".xdmf":
228 filename = filename.with_suffix(".h5")
229 if not filename.is_file():
230 raise FileNotFoundError(f"File {filename} does not exist")
232 V = u.function_space
233 mesh = u.function_space.mesh
234 if u.function_space.element.needs_dof_transformations:
235 raise RuntimeError(
236 "Function-spaces requiring dof permutations are not compatible with legacy data"
237 )
238 # ----------------------Step 1---------------------------------
239 # Compute index of input cells, and position in input dofmap
240 local_cells, dof_pos = compute_dofmap_pos(u.function_space)
241 input_cells = mesh.topology.original_cell_index[local_cells]
243 # Compute mesh->input communicator
244 # 1.1 Compute mesh->input communicator
245 num_cells_global = mesh.topology.index_map(mesh.topology.dim).size_global
246 backend_cls = get_backend(backend)
247 owners: npt.NDArray[np.int32]
248 if backend_cls.read_mode == ReadMode.serial:
249 owners = np.zeros(len(input_cells), dtype=np.int32)
250 elif backend_cls.read_mode == ReadMode.parallel:
251 owners = index_owner(V.mesh.comm, input_cells, num_cells_global)
252 else:
253 raise NotImplementedError(f"{backend_cls.read_mode} not implemented")
255 unique_owners, owner_count = np.unique(owners, return_counts=True)
256 # FIXME: In C++ use NBX to find neighbourhood
257 assert isinstance(mesh.comm, MPI.Intracomm)
258 _tmp_comm = mesh.comm.Create_dist_graph(
259 [mesh.comm.rank], [len(unique_owners)], unique_owners.tolist(), reorder=False
260 )
261 source, dest, _ = _tmp_comm.Get_dist_neighbors()
262 _tmp_comm.Free()
263 # Strip out any /
264 group = group.strip("/")
265 if step is not None:
266 group = f"{group}/{group}_{step}"
267 vector_group = vector_group or "vector"
268 else:
269 vector_group = vector_group or "vector_0"
271 # ----------------------Step 2--------------------------------
272 # Get global dofmap indices from input process
273 bs = V.dofmap.bs
274 num_cells_global = mesh.topology.index_map(mesh.topology.dim).size_global
275 dofmap_indices = send_cells_and_receive_dofmap_index(
276 filename,
277 comm,
278 np.asarray(source, dtype=np.int32),
279 np.asarray(dest, dtype=np.int32),
280 owner_count.astype(np.int32),
281 owners,
282 input_cells,
283 dof_pos,
284 num_cells_global,
285 f"/{group}/cell_dofs",
286 f"/{group}/x_cell_dofs",
287 bs,
288 backend=backend,
289 )
291 # ----------------------Step 3---------------------------------
292 dof_owner: npt.NDArray[np.int32]
293 if backend_cls.read_mode == ReadMode.serial:
294 dof_owner = np.zeros(len(dofmap_indices), dtype=np.int32)
295 elif backend_cls.read_mode == ReadMode.parallel:
296 # Compute owner of global dof on distributed input data
297 num_dof_global = V.dofmap.index_map_bs * V.dofmap.index_map.size_global
298 dof_owner = index_owner(comm=mesh.comm, indices=dofmap_indices, N=num_dof_global)
299 else:
300 raise NotImplementedError(f"{backend_cls.read_mode} not implemented")
302 # Create MPI neigh comm to owner.
303 # NOTE: USE NBX in C++
305 # Read input data
306 local_array, starting_pos = backend_cls.read_hdf5_array(
307 comm, filename, f"/{group}/{vector_group}", backend_args=None
308 )
310 # Send global dof indices to correct input process, and receive value of given dof
311 local_values = send_dofs_and_recv_values(
312 dofmap_indices, dof_owner, comm, local_array, starting_pos
313 )
315 # ----------------------Step 4---------------------------------
316 # Populate local part of array and scatter forward
317 u.x.array[: len(local_values)] = local_values
318 u.x.scatter_forward()
321def create_geometry_function_space(
322 mesh: dolfinx.mesh.Mesh, N: int, value_shape: tuple[int, ...] | None = None
323) -> dolfinx.fem.FunctionSpace:
324 """Reconstruct a vector space with the N components using the geometry dofmap to ensure
325 a 1-1 mapping between mesh nodes and DOFs.
327 Args:
328 mesh: The mesh.
329 N: Number of components.
330 value_shape: Value shape of the space, with ``N`` values. Defaults to a scalar for
331 ``N=1``, otherwise to a vector of length ``N``.
333 Returns:
334 The function space, with one block of ``N`` degrees of freedom per mesh node
336 Raises:
337 ValueError: If ``value_shape`` does not have ``N`` values.
338 NotImplementedError: For a mesh with several cell types, which has no UFL domain.
339 """
340 if value_shape is not None and int(np.prod(value_shape)) != N:
341 raise ValueError(f"Value shape {value_shape} does not have {N} components.")
342 ufl_domain = mesh.ufl_domain()
343 if ufl_domain is None:
344 raise NotImplementedError("Point data on meshes with several cell types is not supported.")
345 geom_imap = mesh.geometry.index_map()
346 geom_dofmap = fenicsx_compat.dofmap(mesh)
347 sub_el = ufl_domain.ufl_coordinate_element().sub_elements[0]
348 adj_list = dolfinx.cpp.graph.AdjacencyList_int32(geom_dofmap)
350 if value_shape is None:
351 value_shape = () if N == 1 else (N,)
352 if value_shape == ():
353 ufl_el = sub_el
354 else:
355 ufl_el = basix.ufl.blocked_element(sub_el, shape=value_shape)
357 _fe_constructor: (
358 type[dolfinx.cpp.fem.FiniteElement_float32] | type[dolfinx.cpp.fem.FiniteElement_float64]
359 )
360 _fem_constructor: (
361 type[dolfinx.cpp.fem.FunctionSpace_float32] | type[dolfinx.cpp.fem.FunctionSpace_float64]
362 )
363 if ufl_el.dtype == np.float32:
364 _fe_constructor = dolfinx.cpp.fem.FiniteElement_float32
365 _fem_constructor = dolfinx.cpp.fem.FunctionSpace_float32
366 elif ufl_el.dtype == np.float64:
367 _fe_constructor = dolfinx.cpp.fem.FiniteElement_float64
368 _fem_constructor = dolfinx.cpp.fem.FunctionSpace_float64
369 else:
370 raise RuntimeError(f"Unsupported type {ufl_el.dtype}")
371 cpp_el = fenicsx_compat.finite_element_ctor_kwargs(
372 _fe_constructor,
373 ufl_el.basix_element._e,
374 gdim=mesh.geometry.dim,
375 # As in DOLFINx, only blocked elements have a value shape (a vector of length 1
376 # is a scalar)
377 value_shape=value_shape if N > 1 else (),
378 )
379 dof_layout = dolfinx.cpp.fem.create_element_dof_layout(cpp_el, [])
380 cpp_dofmap = dolfinx.cpp.fem.DofMap(
381 dof_layout, fenicsx_compat.unwrap_index_map(geom_imap), N, adj_list, N
382 )
384 # Create function space
385 cpp_space = _fem_constructor(mesh._cpp_object, cpp_el, cpp_dofmap) # type: ignore[arg-type]
387 return dolfinx.fem.FunctionSpace(mesh, ufl_el, cpp_space)
390def _function_dtype(data_dtype: np.dtype, mesh: dolfinx.mesh.Mesh) -> np.dtype:
391 """The dtype of a function holding data read from file.
393 Real data takes the precision of the mesh (a function space only allows its mesh's real type,
394 e.g. float32 data on a float64 mesh), complex data the complex type of that precision.
395 """
396 real = np.dtype(mesh.geometry.x.dtype)
397 if np.issubdtype(data_dtype, np.complexfloating):
398 return np.result_type(real, np.complex64)
399 return real
402def _stored_value_shape(
403 backend_cls: Any,
404 filename: Path | str,
405 name: str,
406 comm: MPI.Comm,
407 backend_args: dict[str, Any] | None,
408 entity: str,
409) -> tuple[int, ...] | None:
410 """The value shape of point or cell data, as recorded by the backend.
412 ``read_value_shape`` is an optional backend function, for file formats that change
413 the layout of vectors and tensors (and so need to record their value shape).
415 Args:
416 backend_cls: The backend module
417 filename: Path to file
418 name: Name of the array
419 comm: MPI communicator used in storage
420 backend_args: Arguments to backend
421 entity: ``"Point"`` for point data, ``"Cell"`` for cell data
423 Returns:
424 The value shape, or ``None`` if the backend or the file does not record it
425 """
426 read_value_shape = getattr(backend_cls, "read_value_shape", None)
427 if read_value_shape is None:
428 return None
429 return read_value_shape(
430 filename=filename, name=name, comm=comm, backend_args=backend_args, entity=entity
431 )
434def read_point_data(
435 filename: Path | str,
436 name: str,
437 mesh: dolfinx.mesh.Mesh,
438 time: float | None = None,
439 backend_args: dict[str, Any] | None = None,
440 backend: str = "xdmf",
441 mesh_name: str | None = None,
442) -> dolfinx.fem.Function:
443 """Read data from the nodes of a mesh.
445 Note:
446 Backend has to implement :meth:`io4dolfinx.backends.IOBackend.read_point_data`.
448 Args:
449 filename: Path to file
450 name: Name of point data
451 mesh: The corresponding :py:class:`dolfinx.mesh.Mesh`. Its numbering must
452 match the one the data was written in; see :ref:`input-ordering`.
453 time: Time-step to read from.
454 mesh_name: Name of the mesh in the file the data belongs to. Defaults
455 to the mesh written without an explicit name.
457 Returns:
458 A function in the space equivalent to the mesh
459 coordinate element (up to shape).
460 """
462 backend_args = with_mesh_name(backend_args, mesh_name)
463 logger.debug(f"Reading point data from {filename} with name {name} at time {time}")
464 logger.debug(f"Using backend {backend} with arguments {backend_args}")
465 backend_cls = get_backend(backend)
466 dataset, local_range_start = backend_cls.read_point_data(
467 filename=filename, name=name, comm=mesh.comm, time=time, backend_args=backend_args
468 )
470 num_components = dataset.shape[1]
471 value_shape = _stored_value_shape(backend_cls, filename, name, mesh.comm, backend_args, "Point")
473 # Create appropriate function space (based on coordinate map)
474 V = create_geometry_function_space(mesh, num_components, value_shape=value_shape)
475 uh = dolfinx.fem.Function(V, name=name, dtype=_function_dtype(dataset.dtype, mesh))
476 # Assume that mesh is first order for now
477 x_dofmap = fenicsx_compat.dofmap(mesh)
478 igi = np.array(mesh.geometry.input_global_indices, dtype=np.int64)
480 # This is dependent on how the data is read in. If distributed equally this is correct
481 global_geom_input = igi[x_dofmap]
483 if backend_cls.read_mode == ReadMode.parallel:
484 num_nodes_global = mesh.geometry.index_map().size_global
485 global_geom_owner = index_owner(mesh.comm, global_geom_input.reshape(-1), num_nodes_global)
486 elif backend_cls.read_mode == ReadMode.serial:
487 # This is correct if everything is read in on rank 0
488 global_geom_owner = np.zeros(len(global_geom_input.flatten()), dtype=np.int32)
489 else:
490 raise NotImplementedError(f"{backend_cls.read_mode} not implemented")
492 for i in range(num_components):
493 arr_i = send_dofs_and_recv_values(
494 global_geom_input.reshape(-1),
495 global_geom_owner,
496 mesh.comm,
497 dataset[:, i],
498 local_range_start,
499 )
500 dof_pos = x_dofmap.reshape(-1) * num_components + i
501 uh.x.array[dof_pos] = arr_i
502 uh.x.scatter_forward()
503 return uh
506def read_cell_data(
507 filename: Path | str,
508 name: str,
509 mesh: dolfinx.mesh.Mesh,
510 time: float | None = None,
511 backend_args: dict[str, Any] | None = None,
512 backend: str = "xdmf",
513 mesh_name: str | None = None,
514) -> dolfinx.fem.Function:
515 """Read data from the cells of a mesh.
517 Note:
518 Backend has to implement :meth:`io4dolfinx.backends.IOBackend.read_cell_data`.
520 Args:
521 filename: Path to file
522 name: Name of point data
523 mesh: The corresponding :py:class:`dolfinx.mesh.Mesh`. Its numbering must
524 match the one the data was written in; see :ref:`input-ordering`.
525 time: Time-step to read from.
526 mesh_name: Name of the mesh in the file the data belongs to. Defaults
527 to the mesh written without an explicit name.
529 Returns:
530 A function in a DG-0 space on the mesh. The cells not found in input is set to zero.
531 """
532 backend_args = with_mesh_name(backend_args, mesh_name)
534 backend_cls = get_backend(backend)
536 topology, dofs = backend_cls.read_cell_data(
537 filename=filename, name=name, comm=mesh.comm, time=time, backend_args=backend_args
538 )
539 num_components = dofs.shape[1]
540 shape = _stored_value_shape(backend_cls, filename, name, mesh.comm, backend_args, "Cell")
541 if shape is None:
542 shape = () if num_components == 1 else (num_components,)
543 V = dolfinx.fem.functionspace(mesh, ("DG", 0, shape))
544 u = dolfinx.fem.Function(V, dtype=_function_dtype(dofs.dtype, mesh))
545 data_array = u.x.array.reshape(-1, num_components)
546 for i in range(num_components):
547 local_entities, local_values = dolfinx.io.distribute_entity_data(
548 mesh, mesh.topology.dim, topology, dofs[:, i].copy()
549 )
550 adj = dolfinx.graph.adjacencylist(local_entities)
551 order = np.arange(len(local_values), dtype=np.int32)
552 mt = dolfinx.mesh.meshtags_from_entities(mesh, mesh.topology.dim, adj, order)
553 data_array[mt.indices, i] = local_values[mt.values]
554 u.x.scatter_forward()
555 return u