Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/h5py/backend.py: 92%
423 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"""
2H5py interface to io4dolfinx
4SPDX License identifier: MIT
6Copyright: Jørgen S. Dokken, Henrik N.T. Finsberg, Simula Research Laboratory
7"""
9import contextlib
10import contextvars
11from pathlib import Path
12from typing import Any
14from mpi4py import MPI
16import dolfinx
17import h5py
18import numpy as np
19import numpy.typing as npt
20from dolfinx.graph import adjacencylist
22from ...format import METADATA_KEYS
23from ...structures import ArrayData, FunctionData, MeshData, MeshTagsData, ReadMeshData
24from ...utils import check_file_exists, compute_local_range
25from .. import DEFAULT_MESH_NAME, FileMode, ReadMode, function_not_found, get_mesh_name
26from . import storage as h5_storage
28read_mode = ReadMode.parallel
30#: Open files without MPI on every rank, even with h5py built with MPI. Set by the serial
31#: backends, see :mod:`io4dolfinx.backends.serial`.
32force_serial_files = contextvars.ContextVar("force_serial_files", default=False)
34# try:
35# except ModuleNotFoundError:
36# raise ModuleNotFoundError("This backend requires h5py to be installed.")
39@contextlib.contextmanager
40def h5pyfile(h5name, filemode="r", force_serial: bool = False, comm=None):
41 """Context manager for opening an HDF5 file with h5py.
43 Args:
44 h5name: The name of the HDF5 file.
45 filemode: The file mode.
46 force_serial: Force serial access to the file.
47 comm: The MPI communicator
49 """
50 if comm is None:
51 comm = MPI.COMM_WORLD
52 force_serial = force_serial or force_serial_files.get()
54 if h5py.h5.get_config().mpi and not force_serial:
55 h5file = h5py.File(h5name, filemode, driver="mpio", comm=comm)
56 else:
57 # Every rank may read a file on its own, but not write to it
58 if comm.size > 1 and not force_serial and filemode != "r":
59 raise ValueError(
60 f"h5py is not installed with MPI support, while using {comm.size} processes.",
61 "If you really want to do this, turn on the `force_serial` flag.",
62 )
63 h5file = h5py.File(h5name, filemode)
65 try:
66 yield h5file
67 finally:
68 if h5file.id:
69 h5file.close()
72def read_component_major_rows(
73 dataset: h5py.Dataset, num_entities_global: int, local_range: list[int]
74) -> np.ndarray:
75 """Read rows ``local_range`` of a 2D array stored component by component.
77 The array is a one-dimensional dataset holding all first components, then all
78 second components and so on, i.e. ``x0 x1 ... xn y0 y1 ... yn z0 z1 ... zn``
79 rather than ``x0 y0 z0 x1 y1 z1 ...`` (``MED_NO_INTERLACE`` in the MED format).
80 The rows are one block per component, read as a single hyperslab.
82 Args:
83 dataset: One-dimensional dataset
84 num_entities_global: Number of entities (rows) in the whole dataset
85 local_range: Range ``[start, end)`` of rows to read on this process
87 Returns:
88 Array of shape ``(end - start, num_components)``, where
89 ``num_components = dataset.size // num_entities_global``
90 """
91 if num_entities_global <= 0 or dataset.size == 0 or dataset.size % num_entities_global != 0:
92 raise ValueError(
93 f"Size {dataset.size} of {dataset.name} is not a positive multiple of "
94 f"{num_entities_global} entities."
95 )
96 num_components = dataset.size // num_entities_global
97 num_rows = local_range[1] - local_range[0]
98 if num_rows == 0:
99 # h5py.MultiBlockSlice rejects empty blocks
100 return np.empty((0, num_components), dtype=dataset.dtype)
101 blocks = h5py.MultiBlockSlice(
102 start=local_range[0], stride=num_entities_global, count=num_components, block=num_rows
103 )
104 return np.ascontiguousarray(dataset[blocks].reshape(num_components, num_rows).T)
107def get_default_backend_args(arguments: dict[str, Any] | None) -> dict[str, Any]:
108 args = dict(arguments) if arguments else {}
109 args.setdefault("legacy", False) # If meshtags is read from legacy
110 args.setdefault("name", DEFAULT_MESH_NAME) # Which mesh in the file to act on
111 return args
114def convert_file_mode(mode: FileMode) -> str:
115 match mode:
116 case FileMode.append:
117 return "a"
118 case FileMode.read:
119 return "r"
120 case FileMode.write:
121 return "w"
122 case _:
123 raise NotImplementedError(f"File mode {mode} not implemented")
126def _metadata_group(kind: str, name: str | None, mesh_name: str) -> str:
127 """Path of the group whose attributes hold the metadata of an object.
129 Args:
130 kind: ``"mesh"``, ``"function"`` or ``"meshtags"``
131 name: Name of the function or mesh tags, unused for a mesh
132 mesh_name: Name of the mesh the object belongs to
133 """
134 match kind:
135 case "mesh":
136 return f"/{mesh_name}"
137 case "function":
138 return f"/{mesh_name}/functions/{name}"
139 case "meshtags":
140 return f"/{mesh_name}/tags/{name}"
141 case _:
142 raise ValueError(f"Unknown kind of object {kind!r}")
145def _write_metadata(group: h5py.Group, metadata: dict[str, Any]):
146 """Store the metadata of an object as attributes of its group."""
147 for key, value in metadata.items():
148 group.attrs[key] = value
151def read_metadata(
152 filename: Path | str,
153 comm: MPI.Comm,
154 kind: str,
155 name: str | None = None,
156 backend_args: dict[str, Any] | None = None,
157) -> dict[str, Any]:
158 """Read the metadata stored with an object, see :mod:`io4dolfinx.format`.
160 Args:
161 filename: Path to file
162 comm: MPI communicator
163 kind: ``"mesh"``, ``"function"`` or ``"meshtags"``
164 name: Name of the function or mesh tags, unused for a mesh
165 backend_args: Arguments to backend
167 Returns:
168 The metadata, empty if the object does not exist or has none
169 """
170 backend_args = get_default_backend_args(backend_args)
171 path = _metadata_group(kind, name, get_mesh_name(backend_args))
172 if not Path(filename).exists():
173 return {}
174 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
175 if path not in h5file:
176 return {}
177 attrs = h5file[path].attrs
178 metadata = {key: attrs[key] for key in METADATA_KEYS if key in attrs}
179 return {
180 key: value.decode("utf-8") if isinstance(value, bytes | np.bytes_) else value
181 for key, value in metadata.items()
182 }
185def write_attributes(
186 filename: Path | str,
187 comm: MPI.Comm,
188 name: str,
189 attributes: dict[str, np.ndarray],
190 backend_args: dict[str, Any] | None = None,
191):
192 """Write attributes to file using H5PY.
194 Args:
195 filename: Path to file to write to
196 comm: MPI communicator used in storage
197 name: Name of the attributes
198 attributes: Dictionary of attributes to write to file
199 engine: ADIOS2 engine to use
200 """
201 filemode = "a" if Path(filename).exists() else "w"
202 with h5pyfile(filename, filemode=filemode, comm=comm, force_serial=False) as h5file:
203 if name not in h5file.keys():
204 h5file.create_group(name, track_order=True)
205 group = h5file[name]
207 for key, val in attributes.items():
208 group.attrs[key] = val
211def read_attributes(
212 filename: Path | str,
213 comm: MPI.Comm,
214 name: str,
215 backend_args: dict[str, Any] | None = None,
216) -> dict[str, Any]:
217 """Read attributes from file using H5PY.
219 Args:
220 filename: Path to file to read from
221 comm: MPI communicator used in storage
222 name: Name of the attributes
223 Returns:
224 The attributes
225 """
226 check_file_exists(filename)
227 output_attrs = {}
228 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
229 for key, val in h5file[name].attrs.items():
230 output_attrs[key] = val
231 return output_attrs
234def read_timestamps(
235 filename: Path | str,
236 comm: MPI.Comm,
237 function_name: str,
238 backend_args: dict[str, Any] | None = None,
239) -> npt.NDArray[np.float64 | str]: # type: ignore[type-var]
240 """Read time-stamps from a checkpoint file.
242 Args:
243 comm: MPI communicator
244 filename: Path to file
245 function_name: Name of the function to read time-stamps for
246 backend_args: Arguments for backend, for instance file type.
248 Returns:
249 The time-stamps
251 Raises:
252 KeyError: If the file does not hold the function on that mesh, naming those it does
253 """
254 check_file_exists(filename)
255 mesh_name = get_mesh_name(backend_args)
256 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
257 functions = h5file.get(f"{mesh_name}/functions")
258 if functions is None or function_name not in functions:
259 names = [] if functions is None else list(functions.keys())
260 raise function_not_found(filename, function_name, mesh_name, names)
261 timestamps = functions[function_name].attrs["timestamps"]
262 return timestamps
265def write_mesh(
266 filename: Path | str,
267 comm: MPI.Comm,
268 mesh: MeshData,
269 backend_args: dict[str, Any] | None = None,
270 mode: FileMode = FileMode.write,
271 time: float = 0.0,
272):
273 """Write a mesh to file using H5PY
275 Args:
276 comm: MPI communicator used in storage
277 mesh: Internal data structure for the mesh data to save to file
278 filename: Path to file to write to.
279 mode: Mode to use (write or append)
280 time: Time stamp
281 backend_args: Backend arguments, including the lossless HDF5 storage options
282 documented in :mod:`io4dolfinx.backends.h5py.storage`.
283 """
284 backend_args = get_default_backend_args(backend_args)
285 options = h5_storage.storage_options(comm, backend_args)
286 h5_mode = convert_file_mode(mode)
287 mesh_name = get_mesh_name(backend_args)
288 with h5pyfile(filename, filemode=h5_mode, comm=comm, force_serial=False) as h5file:
289 if mesh_name in h5file.keys() and h5_mode == "a":
290 mesh_directory = h5file[mesh_name]
291 timestamps = mesh_directory.attrs["timestamps"]
292 previous = mesh_directory[f"{len(timestamps) - 1}/Points"]
293 for key in ("Topology", "PartitioningData", "PartitioningOffset"):
294 if key in mesh_directory:
295 h5_storage.check_storage_options(mesh_directory[key], options)
296 h5_storage.check_storage_options(previous, options)
297 if np.isclose(time, timestamps).any():
298 raise ValueError(f"Mesh {mesh_name!r} has already been stored at time={time}.")
299 else:
300 mesh_directory.attrs["timestamps"] = np.append(
301 mesh_directory.attrs["timestamps"], time
302 )
303 idx = len(mesh_directory.attrs["timestamps"]) - 1
304 write_topology = False
305 else:
306 mesh_directory = h5file.create_group(mesh_name)
307 _write_metadata(mesh_directory, mesh.metadata)
308 mesh_directory.attrs["timestamps"] = np.array([time], dtype=np.float64)
309 idx = 0
310 write_topology = True
311 previous = None
313 geometry_group = mesh_directory.create_group(f"{idx}")
315 # Write geometry data
316 gdim = mesh.local_geometry.shape[1]
317 geometry_dataset = h5_storage.create_dataset(
318 geometry_group,
319 "Points",
320 [mesh.num_nodes_global, gdim],
321 mesh.local_geometry.dtype,
322 options,
323 previous,
324 )
325 h5_storage.write_dataset(
326 geometry_dataset, np.s_[slice(*mesh.local_geometry_pos), :], mesh.local_geometry
327 )
329 # Write static partitioning data
330 if "PartitioningData" not in mesh_directory.keys() and mesh.store_partition:
331 assert mesh.partition_global is not None
332 assert mesh.partition_range is not None
333 assert mesh.ownership_array is not None
334 par_dataset = h5_storage.create_dataset(
335 mesh_directory,
336 "PartitioningData",
337 [mesh.partition_global],
338 mesh.ownership_array.dtype,
339 options,
340 )
341 h5_storage.write_dataset(
342 par_dataset, slice(*mesh.partition_range), mesh.ownership_array
343 )
345 if "PartitioningOffset" not in mesh_directory.keys() and mesh.store_partition:
346 assert mesh.ownership_offset is not None
347 par_dataset = h5_storage.create_dataset(
348 mesh_directory, "PartitioningOffset", [mesh.num_cells_global + 1], np.int64, options
349 )
350 # Neighbouring ranks share an offset; only the last rank writes the end.
351 stop = mesh.local_topology_pos[1] + (comm.rank == comm.size - 1)
352 count = stop - mesh.local_topology_pos[0]
353 h5_storage.write_dataset(
354 par_dataset, slice(mesh.local_topology_pos[0], stop), mesh.ownership_offset[:count]
355 )
357 if "PartitionProcesses" not in mesh_directory.attrs.keys() and mesh.store_partition:
358 mesh_directory.attrs["PartitionProcesses"] = mesh.partition_processes
360 # Write static data
361 if write_topology:
362 mesh_directory.attrs["CellType"] = mesh.cell_type
363 mesh_directory.attrs["Degree"] = mesh.degree
364 mesh_directory.attrs["LagrangeVariant"] = mesh.lagrange_variant
365 num_dofs_per_cell = mesh.local_topology.shape[1]
366 topology_dataset = h5_storage.create_dataset(
367 mesh_directory,
368 "Topology",
369 [mesh.num_cells_global, num_dofs_per_cell],
370 np.int64,
371 options,
372 )
373 h5_storage.write_dataset(
374 topology_dataset, np.s_[slice(*mesh.local_topology_pos), :], mesh.local_topology
375 )
378def read_mesh_data(
379 filename: Path | str,
380 comm: MPI.Comm,
381 time: str | float | None = 0.0,
382 read_from_partition: bool = False,
383 backend_args: dict[str, Any] | None = None,
384) -> ReadMeshData:
385 """Read mesh data from h5py based checkpoint files.
387 Args:
388 filename: Path to input file
389 comm: The MPI communciator to distribute the mesh over
390 time: Time stamp associated with mesh
391 read_from_partition: Read mesh with partition from file
392 Returns:
393 The mesh topology, geometry, UFL domain and partition function
394 """
396 backend_args = get_default_backend_args(backend_args)
397 mesh_name = get_mesh_name(backend_args)
399 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
400 if mesh_name not in h5file.keys():
401 raise KeyError(f"Could not find mesh '{mesh_name}' in {filename}")
402 mesh_group = h5file[mesh_name]
403 timestamps = mesh_group.attrs["timestamps"]
404 assert time is not None
405 parent_group = np.flatnonzero(np.isclose(timestamps, time))
406 if len(parent_group) != 1:
407 raise RuntimeError(
408 f"Time step {time} not found in file, available steps is {timestamps}"
409 )
410 time_group = f"{parent_group[0]:d}"
412 # Get mesh topology (distributed)
413 topology = mesh_group["Topology"]
414 local_range = compute_local_range(comm, topology.shape[0])
415 mesh_topology = topology[slice(*local_range), :]
417 cell_type = mesh_group.attrs["CellType"]
418 lvar = mesh_group.attrs["LagrangeVariant"]
419 degree = mesh_group.attrs["Degree"]
421 geometry_group = mesh_group[time_group]
422 geometry_dataset = geometry_group["Points"]
423 x_shape = geometry_dataset.shape
425 geometry_range = compute_local_range(comm, x_shape[0])
426 mesh_geometry = geometry_dataset[slice(*geometry_range), :]
428 # Check validity of partitioning information
429 if read_from_partition:
430 if "PartitionProcesses" not in mesh_group.attrs.keys():
431 raise KeyError(f"Partitioning information not found in {filename}")
432 par_keys = ("PartitioningData", "PartitioningOffset")
433 for key in par_keys:
434 if key not in mesh_group.keys():
435 raise KeyError(f"Partitioning information not found in {filename}")
437 par_num_procs = mesh_group.attrs["PartitionProcesses"]
438 if par_num_procs != comm.size:
439 raise ValueError(f"Number of processes in file ({par_num_procs})!=({comm.size=})")
441 # First read in offsets based on the number of cells [0, num_cells_local]
442 par_offsets = mesh_group["PartitioningOffset"][local_range[0] : local_range[1] + 1]
443 # Then read the data based of offsets
444 par_data = mesh_group["PartitioningData"][par_offsets[0] : par_offsets[-1]]
445 # Then make offsets local
446 par_offsets[:] -= par_offsets[0]
447 partition_graph = adjacencylist(par_data, par_offsets.astype(np.int32))
448 else:
449 partition_graph = None
451 return ReadMeshData(
452 cells=mesh_topology,
453 cell_type=cell_type,
454 x=mesh_geometry,
455 degree=degree,
456 lvar=lvar,
457 partition_graph=partition_graph,
458 )
461def write_meshtags(
462 filename: str | Path,
463 comm: MPI.Comm,
464 data: MeshTagsData,
465 backend_args: dict[str, Any] | None = None,
466):
467 """Write mesh tags to file.
469 Args:
470 filename: Path to file to write to
471 comm: MPI communicator used in storage
472 data: Internal data structure for the mesh tags to save to file
473 backend_args: Arguments to backend
474 """
475 backend_args = get_default_backend_args(backend_args)
476 options = h5_storage.storage_options(comm, backend_args)
478 assert data.num_entities_global is not None
479 assert data.num_dofs_per_entity is not None
480 mesh_name = get_mesh_name(backend_args)
481 with h5pyfile(filename, filemode="a", comm=comm, force_serial=False) as h5file:
482 if mesh_name not in h5file.keys():
483 raise KeyError(f"Could not find mesh '{mesh_name}' in file")
484 mesh_group = h5file[mesh_name]
485 if "tags" not in mesh_group.keys():
486 tags = mesh_group.create_group("tags")
487 else:
488 tags = mesh_group["tags"]
489 if data.name in tags.keys():
490 raise KeyError(f"MeshTags with {data.name=} already exists in this file")
491 tag = tags.create_group(data.name)
492 _write_metadata(tag, data.metadata)
494 # Add topology
495 topology = h5_storage.create_dataset(
496 tag, "Topology", [data.num_entities_global, data.num_dofs_per_entity], np.int64, options
497 )
498 assert data.local_start is not None
499 h5_storage.write_dataset(
500 topology,
501 np.s_[data.local_start : data.local_start + len(data.indices), :],
502 data.indices,
503 )
505 # Add cell_type attribute
506 tag.attrs["CellType"] = data.cell_type
508 # Add values
509 values = h5_storage.create_dataset(
510 tag, "Values", [data.num_entities_global], data.values.dtype, options
511 )
512 h5_storage.write_dataset(
513 values, slice(data.local_start, data.local_start + len(data.indices)), data.values
514 )
516 # Add dimension
517 tag.attrs["dim"] = data.dim
520def read_meshtags_data(
521 filename: str | Path, comm: MPI.Comm, name: str, backend_args: dict[str, Any] | None = None
522) -> MeshTagsData:
523 """Read mesh tags from file.
525 Args:
526 filename: Path to file to read from
527 comm: MPI communicator used in storage
528 name: Name of the mesh tags to read
529 backend_args: Arguments to backend. If "legacy_dolfin" is supplied as argument
530 the HDF5 file is assumed to have been made with DOLFIN
532 Returns:
533 Internal data structure for the mesh tags read from file
534 """
535 backend_args = get_default_backend_args(backend_args)
536 legacy = backend_args["legacy"]
537 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
538 if legacy:
539 if name not in h5file.keys():
540 raise RuntimeError(f"MeshTag {name} not found in {filename}.")
541 mesh = h5file[name]
542 topology = mesh["topology"]
543 cell_type = topology.attrs["celltype"]
544 if isinstance(cell_type, np.bytes_):
545 cell_type = cell_type.decode("utf-8")
546 dim = dolfinx.mesh.cell_dim(dolfinx.mesh.to_type(cell_type))
547 values = mesh["values"]
548 else:
549 mesh_name = get_mesh_name(backend_args)
550 if mesh_name not in h5file.keys():
551 raise KeyError(f"No mesh '{mesh_name}' found")
552 mesh = h5file[mesh_name]
553 if "tags" not in mesh.keys():
554 raise KeyError("Could not find 'tags' in file, are you sure this is a checkpoint?")
555 tags = mesh["tags"]
556 if name not in tags.keys():
557 raise KeyError(f"Could not find {name} in '/{mesh_name}/tags/' in {filename}")
558 tag = tags[name]
560 dim = tag.attrs["dim"]
561 topology = tag["Topology"]
562 values = tag["Values"]
563 num_entities_global = topology.shape[0]
564 topology_range = compute_local_range(comm, num_entities_global)
565 indices = topology[slice(*topology_range), :].astype(np.int64)
566 values_dtype = np.dtype(backend_args.get("values_dtype", np.int32))
567 vals = values[slice(*topology_range)].astype(values_dtype)
568 return MeshTagsData(name=name, values=vals, indices=indices, dim=dim)
571def read_dofmap(
572 filename: str | Path, comm: MPI.Comm, name: str, backend_args: dict[str, Any] | None
573) -> dolfinx.graph.AdjacencyList:
574 """Read the dofmap of a function with a given name.
576 Args:
577 filename: Path to file to read from
578 comm: MPI communicator used in storage
579 name: Name of the function to read the dofmap for
580 backend_args: Arguments to backend
582 Returns:
583 Dofmap as an :class:`dolfinx.graph.AdjacencyList`
584 """
585 backend_args = {} if backend_args is None else backend_args
586 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
587 # If dofmap is read with full path, it is passed through backend_args
588 dofmap_key = backend_args.get("dofmap", None)
589 if dofmap_key is None:
590 mesh_name = get_mesh_name(backend_args)
591 if mesh_name not in h5file.keys():
592 raise KeyError(f"No mesh '{mesh_name}' found in {filename}")
593 mesh = h5file[mesh_name]
594 if "functions" not in mesh.keys():
595 raise KeyError(f"No functions stored in '{mesh_name}' in {filename}")
596 functions = mesh["functions"]
597 if name not in functions.keys():
598 raise KeyError(
599 f"No function with name '{name}' on '{mesh_name}' stored in {filename}"
600 )
601 function = functions[name]
602 offset_key = "dofmap_offsets"
603 dofmap_key = "dofmap"
604 offsets = function[offset_key]
605 dofmap = function[dofmap_key]
606 else:
607 offset_key = backend_args["offsets"]
608 dofmap = h5file[dofmap_key]
609 offsets = h5file[offset_key]
611 num_cells = offsets.shape[0] - 1
612 local_range = compute_local_range(comm, num_cells)
614 # First read in offsets based on the number of cells [0, num_cells_local]
615 glob_offsets = offsets[local_range[0] : local_range[1] + 1].flatten().astype(np.int64)
617 # Then read the data based of offsets
618 dofmap_data = dofmap[glob_offsets[0] : glob_offsets[-1]].flatten()
620 # Then make offsets local
621 loc_offsets = (glob_offsets - glob_offsets[0]).astype(np.int32)
622 return adjacencylist(dofmap_data, loc_offsets)
625def read_dofs(
626 filename: str | Path,
627 comm: MPI.Comm,
628 name: str,
629 time: float,
630 backend_args: dict[str, Any] | None,
631) -> tuple[npt.NDArray[np.float32 | np.float64 | np.complex64 | np.complex128], int]:
632 """Read the dofs (values) of a function with a given name from a given timestep.
634 Args:
635 filename: Path to file to read from
636 comm: MPI communicator used in storage
637 name: Name of the function to read the dofs for
638 time: Time stamp associated with the function to read
639 backend_args: Arguments to backend
641 Returns:
642 Contiguous sequence of degrees of freedom (with respect to input data)
643 and the global starting point on the process.
644 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
645 """
646 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
647 mesh_name = get_mesh_name(backend_args)
648 if mesh_name not in h5file.keys():
649 raise RuntimeError(f"No mesh '{mesh_name}' found in {filename}")
650 mesh = h5file[mesh_name]
651 if "functions" not in mesh.keys():
652 raise RuntimeError(f"No functions stored in '{mesh_name}' in {filename}")
653 functions = mesh["functions"]
654 if name not in functions.keys():
655 raise RuntimeError(
656 f"No function with name '{name}' on '{mesh_name}' stored in {filename}"
657 )
658 function = functions[name]
659 timestamps = function.attrs["timestamps"]
660 idx = np.flatnonzero(np.isclose(timestamps, time))
661 if len(idx) != 1:
662 raise RuntimeError("Could not find {name}(t={time}) on grid {mesh_name} in {filename}.")
663 u_t = function[f"{idx[0]:d}"]
664 data_group = u_t["array"]
665 num_dofs_global = data_group.shape[0]
666 local_range = compute_local_range(comm, num_dofs_global)
667 local_array = data_group[slice(*local_range)]
668 return local_array, local_range[0]
671def read_cell_perms(
672 comm: MPI.Comm, filename: Path | str, backend_args: dict[str, Any] | None
673) -> npt.NDArray[np.uint32]:
674 """
675 Read cell permutation from file with given communicator,
676 Split in continuous chunks based on number of cells in the input data.
678 Args:
679 comm: MPI communicator used in storage
680 filename: Path to file to read from
681 backend_args: Arguments to backend
683 Returns:
684 Contiguous sequence of permutations (with respect to input data)
685 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
686 """
688 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
689 mesh_name = get_mesh_name(backend_args)
690 if mesh_name not in h5file.keys():
691 raise RuntimeError(f"No mesh '{mesh_name}' found in {filename}")
692 mesh = h5file[mesh_name]
693 data_group = mesh["CellPermutations"]
694 num_cells_global = data_group.shape[0]
695 local_range = compute_local_range(comm, num_cells_global)
696 local_array = data_group[slice(*local_range)]
697 return local_array
700def write_function(
701 filename: str | Path,
702 comm: MPI.Comm,
703 u: FunctionData,
704 time: float,
705 mode: FileMode,
706 backend_args: dict[str, Any] | None = None,
707):
708 """Write a function to file.
710 Args:
711 comm: MPI communicator used in storage
712 u: Internal data structure for the function data to save to file
713 filename: Path to file to write to
714 time: Time stamp associated with function
715 mode: File-mode to store the function
716 backend_args: Arguments to backend
717 """
719 mesh_name = get_mesh_name(backend_args)
720 backend_args = get_default_backend_args(backend_args)
721 options = h5_storage.storage_options(comm, backend_args)
722 h5_mode = convert_file_mode(mode)
723 with h5pyfile(filename, filemode=h5_mode, comm=comm, force_serial=False) as h5file:
724 # In write mode the file is new, so every group is created
725 if mesh_name not in h5file.keys():
726 mesh = h5file.create_group(mesh_name)
727 else:
728 mesh = h5file[mesh_name]
730 cell_permutations_exist = "CellPermutations" in mesh.keys()
732 if "functions" not in mesh.keys():
733 functions = mesh.create_group("functions")
734 else:
735 functions = mesh["functions"]
737 if u.name not in functions.keys():
738 function = functions.create_group(u.name)
739 _write_metadata(function, u.metadata)
740 else:
741 function = functions[u.name]
743 previous = None
744 if "timestamps" in function.attrs:
745 previous = function[f"{len(function.attrs['timestamps']) - 1}/array"]
746 h5_storage.check_storage_options(previous, options)
747 for group, key in (
748 (function, "dofmap"),
749 (function, "dofmap_offsets"),
750 ):
751 if key in group:
752 h5_storage.check_storage_options(group[key], options)
754 dofmap_exists = "dofmap" in function.keys()
755 dofmap_offsets_exists = "dofmap_offsets" in function.keys()
757 if not cell_permutations_exist:
758 cell_perms = h5_storage.create_dataset(
759 mesh, "CellPermutations", [u.num_cells_global], np.uint32, options
760 )
761 h5_storage.write_dataset(cell_perms, slice(*u.local_cell_range), u.cell_permutations)
763 if not dofmap_exists:
764 dofmap = h5_storage.create_dataset(
765 function, "dofmap", [u.global_dofs_in_dofmap], np.int64, options
766 )
767 h5_storage.write_dataset(dofmap, slice(*u.dofmap_range), u.dofmap_array)
769 if not dofmap_offsets_exists:
770 dofmap_offsets = h5_storage.create_dataset(
771 function, "dofmap_offsets", [u.num_cells_global + 1], np.int64, options
772 )
773 # Filtered collective writes require each offset to have one writer.
774 stop = u.local_cell_range[1] + (comm.rank == comm.size - 1)
775 count = stop - u.local_cell_range[0]
776 h5_storage.write_dataset(
777 dofmap_offsets, slice(u.local_cell_range[0], stop), u.dofmap_offsets[:count]
778 )
780 # Write timestamp
781 if "timestamps" in function.attrs.keys():
782 timestamps = function.attrs["timestamps"]
783 if np.isclose(time, timestamps).any():
784 raise RuntimeError(f"Function {u.name!r} has already been stored at time={time}.")
785 else:
786 function.attrs["timestamps"] = np.append(function.attrs["timestamps"], time)
787 else:
788 function.attrs["timestamps"] = np.array([time])
789 idx = len(function.attrs["timestamps"]) - 1
791 data_group = function.create_group(f"{idx:d}")
792 array = h5_storage.create_dataset(
793 data_group, "array", [u.num_dofs_global], u.values.dtype, options, previous
794 )
795 h5_storage.write_dataset(array, slice(*u.dof_range), u.values)
798def read_legacy_mesh(
799 filename: Path | str, comm: MPI.Comm, group: str
800) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.floating], str | None]:
801 """Read in the mesh topology, geometry and (optionally) cell type from a
802 legacy DOLFIN HDF5-file.
804 Args:
805 filename: Path to file to read from
806 comm: MPI communicator used in storage
807 group: Group in HDF5 file where mesh is stored
809 Returns:
810 Tuple containing:
811 - Topology as a (num_cells, num_vertices_per_cell) array of global vertex indices
812 - Geometry as a (num_vertices, geometric_dimension) array of vertex coordinates
813 - Cell type as a string (e.g. "tetrahedron") or None if not found
814 """
815 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
816 if group not in h5file.keys():
817 raise KeyError(f"Could not find {group} in {filename}.")
818 mesh = h5file[group]
819 if "topology" not in mesh.keys():
820 raise KeyError(f"Could not find '{group}/topology' in {filename}.")
822 topology = mesh["topology"]
823 shape = topology.shape
824 local_range = compute_local_range(comm, shape[0])
825 mesh_topology = topology[slice(*local_range)].astype(np.int64)
827 # Get mesh cell type
828 cell_type = None
829 if "celltype" in topology.attrs.keys():
830 cell_type = topology.attrs["celltype"]
831 if isinstance(cell_type, np.bytes_):
832 cell_type = cell_type.decode("utf-8")
834 for geometry_key in ["geometry", "coordinates"]:
835 if geometry_key in mesh.keys():
836 break
837 else:
838 raise KeyError(
839 "Could not find geometry in '/mesh/geometry' or '/mesh/coordinates'"
840 + f" in {filename}."
841 )
842 geometry = mesh[geometry_key]
843 g_shape = geometry.shape
844 local_g_range = compute_local_range(comm, g_shape[0])
845 mesh_geometry = geometry[slice(*local_g_range)]
847 return mesh_topology, mesh_geometry, cell_type
850def read_hdf5_array(
851 comm: MPI.Comm,
852 filename: Path | str,
853 group: str,
854 backend_args: dict[str, Any] | None = None,
855) -> tuple[np.ndarray, int]:
856 """Read an array from an HDF5 file.
858 Args:
859 comm: MPI communicator used in storage
860 filename: Path to file to read from
861 group: Group in HDF5 file where array is stored
862 backend_args: Arguments to backend
864 Returns:
865 Tuple containing:
866 - Numpy array read from file
867 - Global starting point on the process.
868 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
869 """
870 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
871 data = h5file[group]
872 shape = data.shape[0]
873 local_range = compute_local_range(comm, shape)
874 out_data = data[slice(*local_range)].flatten()
875 return out_data, local_range[0]
878def snapshot_checkpoint(
879 filename: Path | str,
880 mode: FileMode,
881 u: dolfinx.fem.Function,
882 backend_args: dict[str, Any] | None,
883):
884 """Create a snapshot checkpoint of a dolfinx function.
886 Args:
887 filename: Path to file to read from
888 mode: File-mode to store the function
889 u: dolfinx function to create a snapshot checkpoint for
890 backend_args: Arguments to backend
891 """
892 comm = u.function_space.mesh.comm
893 dofmap = u.function_space.dofmap
894 local_range = np.array(dofmap.index_map.local_range) * dofmap.index_map_bs
895 num_dofs_local = local_range[1] - local_range[0]
896 num_dofs_global = dofmap.index_map.size_global * dofmap.index_map_bs
897 h5mode = convert_file_mode(mode)
898 if h5mode == "w":
899 options = h5_storage.storage_options(comm, backend_args or {})
900 with h5pyfile(filename, filemode=h5mode, comm=comm, force_serial=False) as h5file:
901 local_dofs = u.x.array[:num_dofs_local].copy()
902 data = h5file.create_group("snapshot")
903 dataset = h5_storage.create_dataset(
904 data, "dofs", [num_dofs_global], local_dofs.dtype, options
905 )
906 h5_storage.write_dataset(dataset, slice(*local_range), local_dofs)
907 elif h5mode == "r":
908 with h5pyfile(filename, filemode=h5mode, comm=comm, force_serial=False) as h5file:
909 data = h5file["snapshot"]["dofs"]
910 assert data.shape[0] == num_dofs_global
911 u.x.array[:num_dofs_local] = data[slice(*local_range)]
912 u.x.scatter_forward()
915def read_function_names(
916 filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None
917) -> list[str]:
918 """Read all function names from a file.
920 Args:
921 filename: Path to file
922 comm: MPI communicator to launch IO on.
923 backend_args: Arguments to backend
925 Returns:
926 A list of function names.
927 """
928 check_file_exists(filename)
929 backend_args = get_default_backend_args(backend_args)
930 with h5pyfile(filename, filemode="r", comm=comm, force_serial=False) as h5file:
931 mesh_name = get_mesh_name(backend_args)
932 if mesh_name not in h5file.keys():
933 raise RuntimeError(f"No mesh '{mesh_name}' found in {filename}")
934 mesh = h5file[mesh_name]
935 if "functions" not in mesh.keys():
936 return []
937 else:
938 return list(mesh["functions"].keys())
941def read_point_data(
942 filename: Path | str,
943 name: str,
944 comm: MPI.Comm,
945 time: float | str | None,
946 backend_args: dict[str, Any] | None,
947) -> tuple[np.ndarray, int]:
948 """Read data from the nodes of a mesh.
950 Args:
951 filename: Path to file
952 name: Name of point data
953 comm: Communicator to launch IO on.
954 time: The time stamp
955 backend_args: The backend arguments
957 Returns:
958 Data local to process (contiguous, no mpi comm) and local start range
959 """
960 raise NotImplementedError("The h5py backend cannot read point data.")
963def read_cell_data(
964 filename: Path | str,
965 name: str,
966 comm: MPI.Comm,
967 time: str | float | None,
968 backend_args: dict[str, Any] | None,
969) -> tuple[npt.NDArray[np.int64], np.ndarray]:
970 """Read data from the cells of a mesh.
972 Args:
973 filename: Path to file
974 name: Name of point data
975 comm: Communicator to launch IO on.
976 time: The time stamp
977 backend_args: The backend arguments
978 Returns:
979 A tuple (topology, dofs) where topology contains the
980 vertex indices of the cells, dofs the degrees of
981 freedom within that cell.
982 """
983 raise NotImplementedError("The h5py backend does not support reading cell data.")
986def write_data(
987 filename: Path | str,
988 array_data: ArrayData,
989 comm: MPI.Comm,
990 time: str | float | None,
991 mode: FileMode,
992 backend_args: dict[str, Any] | None,
993):
994 """Write a 2D-array to file (distributed across proceses with MPI).
996 Args:
997 filename: Path to file
998 array_data: Data to write to file
999 comm: MPI communicator to open the file with
1000 time: Time-stamp for data.
1001 mode: Append or write
1002 backend_args: The backend arguments
1003 """
1004 raise NotImplementedError("H5PY has not implemented this yet")