Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/adios2/backend.py: 94%
454 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
1import warnings
2from pathlib import Path
3from typing import Any
5from mpi4py import MPI
7import adios2
8import dolfinx
9import fenicsx_compat
10import numpy as np
11import numpy.typing as npt
13from ...format import METADATA_KEYS, stamp
14from ...structures import ArrayData, FunctionData, MeshData, MeshTagsData, ReadMeshData
15from ...utils import check_file_exists
16from .. import DEFAULT_MESH_NAME, FileMode, ReadMode, function_not_found, get_mesh_name
17from .helpers import (
18 ADIOSFile,
19 adios_to_numpy_dtype,
20 check_variable_exists,
21 create_adios,
22 read_adjacency_list,
23 read_array,
24 read_local_rows,
25)
27# ADIOS2 without MPI is supported through the adios2-serial backend
28adios2 = fenicsx_compat.resolve_adios_scope(adios2, require_mpi=False)
30read_mode = ReadMode.parallel
33def get_default_backend_args(arguments: dict[str, Any] | None) -> dict[str, Any]:
34 """Get default arguements (sets engine to BP4)."""
35 args = dict(arguments) if arguments else {} # Copy: do not mutate the caller's dict
36 if "engine" not in args.keys():
37 args["engine"] = "BP4"
38 if "legacy" not in args.keys():
39 args["legacy"] = False # Only used for legacy HDF5 meshtags
40 if "name" not in args.keys():
41 args["name"] = DEFAULT_MESH_NAME
42 return args
45def mesh_prefix(backend_args: dict[str, Any] | None) -> str:
46 """ADIOS2 variable-name prefix for the mesh named in ``backend_args``.
48 The default mesh gets an *empty* prefix, so that it is stored under exactly
49 the names used before checkpoints could hold more than one mesh. Files
50 written by earlier versions therefore stay readable, and a file holding only
51 the default mesh stays readable by them. Any other mesh is namespaced under
52 ``"<name>/"``.
54 .. note::
55 This is io4dolfinx's own checkpoint schema, not ADIOS2's VTX
56 visualization schema -- no ``vtk.xml`` attribute is written, and these
57 files are not readable by ParaView's VTX reader whether they hold one
58 mesh or several. VTX supports only a single mesh per file, so holding
59 several here costs nothing that was ever available. For a
60 visualizable file with several meshes use the ``vtkhdf`` backend, whose
61 ``MultiBlockDataSet`` is designed for it.
63 Args:
64 backend_args: Arguments to backend
66 Returns:
67 The prefix to prepend to every variable and attribute name of that mesh.
68 """
69 name = get_mesh_name(backend_args)
70 return "" if name == DEFAULT_MESH_NAME else f"{name}/"
73def _function_names(variables, prefix: str) -> set[str]:
74 """Names of the functions of the mesh with ``prefix`` among ADIOS2 ``variables``.
76 Every function has a ``<prefix><name>_time`` variable. The default mesh's prefix is
77 empty, so a name holding ``/`` there belongs to another mesh and is left out.
79 Args:
80 variables: Names of the variables of a step
81 prefix: The mesh's prefix (:func:`mesh_prefix`)
83 Returns:
84 The function names
85 """
86 suffix = "_time"
87 names = set()
88 for variable in variables:
89 if variable.startswith(prefix) and variable.endswith(suffix):
90 name = variable[len(prefix) : -len(suffix)]
91 if name and "/" not in name:
92 names.add(name)
93 return names
96def _seek_step(adios_file, variable: str, start: int = 0) -> int:
97 """Advance the reader to the first step at or after ``start`` holding ``variable``.
99 With several meshes in one file a step no longer holds every variable, so a
100 reader cannot assume the one it wants is in step 0. Leaves the file *inside*
101 the matching step (the caller is responsible for ``EndStep``).
103 Args:
104 adios_file: The open :class:`ADIOSFile`
105 variable: Name of the variable to seek
106 start: First step to consider
108 Returns:
109 Index of the step holding ``variable``.
111 Raises:
112 KeyError: If no step holds ``variable``.
113 """
114 for i in range(start, adios_file.file.Steps()):
115 adios_file.file.BeginStep()
116 if variable in adios_file.io.AvailableVariables().keys():
117 return i
118 adios_file.file.EndStep()
119 raise KeyError(f"'{variable}' not found in file")
122def convert_file_mode(mode: FileMode) -> adios2.Mode: # type: ignore[override]
123 match mode:
124 case FileMode.append:
125 return adios2.Mode.Append
126 case FileMode.write:
127 return adios2.Mode.Write
128 case FileMode.read:
129 return adios2.Mode.Read
130 case _:
131 raise NotImplementedError(f"FileMode {mode} not implemented.")
134def _metadata_prefix(kind: str, name: str | None, backend_args: dict[str, Any]) -> str:
135 """Prefix of the names of the attributes holding the metadata of an object.
137 Args:
138 kind: ``"mesh"``, ``"function"`` or ``"meshtags"``
139 name: Name of the function or mesh tags, unused for a mesh
140 backend_args: Arguments to backend, naming the mesh the object belongs to
141 """
142 prefix = mesh_prefix(backend_args)
143 match kind:
144 case "mesh":
145 return prefix
146 case "function" | "meshtags":
147 return f"{prefix}{name}_"
148 case _:
149 raise ValueError(f"Unknown kind of object {kind!r}")
152def _define_metadata(io: adios2.IO, attribute_prefix: str, metadata: dict[str, Any]):
153 """Store the metadata of an object as attributes, when the object is first written."""
154 for key, value in metadata.items():
155 io.DefineAttribute(f"{attribute_prefix}{key}", value)
158def read_metadata(
159 filename: Path | str,
160 comm: MPI.Comm,
161 kind: str,
162 name: str | None = None,
163 backend_args: dict[str, Any] | None = None,
164) -> dict[str, Any]:
165 """Read the metadata stored with an object, see :mod:`io4dolfinx.format`.
167 Args:
168 filename: Path to file
169 comm: MPI communicator
170 kind: ``"mesh"``, ``"function"`` or ``"meshtags"``
171 name: Name of the function or mesh tags, unused for a mesh
172 backend_args: Arguments to backend
174 Returns:
175 The metadata, empty if the object does not exist or has none
176 """
177 backend_args = get_default_backend_args(backend_args)
178 if not Path(filename).exists():
179 return {}
180 attribute_prefix = _metadata_prefix(kind, name, backend_args)
181 wanted = {f"{attribute_prefix}{key}": key for key in METADATA_KEYS}
182 metadata: dict[str, Any] = {}
183 adios = create_adios(comm)
184 with ADIOSFile(
185 adios=adios,
186 filename=filename,
187 mode=adios2.Mode.Read,
188 engine=backend_args["engine"],
189 io_name="MetadataReader",
190 ) as adios_file:
191 # Attributes become available in the step they were written in
192 for _ in range(adios_file.file.Steps()):
193 adios_file.file.BeginStep()
194 available = adios_file.io.AvailableAttributes()
195 for attribute, key in wanted.items():
196 if key not in metadata and attribute in available:
197 data = adios_file.io.InquireAttribute(attribute)
198 metadata[key] = data.DataString()[0] if data.Type() == "string" else data.Data()
199 adios_file.file.EndStep()
200 if len(metadata) == len(wanted):
201 break
202 return metadata
205def write_attributes(
206 filename: Path | str,
207 comm: MPI.Comm,
208 name: str,
209 attributes: dict[str, np.ndarray],
210 backend_args: dict[str, Any] | None = None,
211):
212 """Write attributes to file using ADIOS2.
214 Args:
215 filename: Path to file to write to
216 comm: MPI communicator used in storage
217 name: Name of the attributes
218 attributes: Dictionary of attributes to write to file
219 engine: ADIOS2 engine to use
220 """
222 adios = create_adios(comm)
223 backend_args = get_default_backend_args(backend_args)
225 with ADIOSFile(
226 adios=adios,
227 filename=filename,
228 mode=adios2.Mode.Append,
229 io_name="AttributeWriter",
230 engine=backend_args["engine"],
231 ) as adios_file:
232 adios_file.file.BeginStep()
234 for k, v in attributes.items():
235 adios_file.io.DefineAttribute(f"{name}_{k}", v)
237 adios_file.file.PerformPuts()
238 adios_file.file.EndStep()
241def read_attributes(
242 filename: Path | str,
243 comm: MPI.Comm,
244 name: str,
245 backend_args: dict[str, Any] | None = None,
246) -> dict[str, np.ndarray]:
247 """Read attributes from file using ADIOS2.
249 Args:
250 filename: Path to file to read from
251 comm: MPI communicator used in storage
252 name: Name of the attributes
253 engine: ADIOS2 engine to use
254 Returns:
255 The attributes
256 """
257 check_file_exists(filename)
258 adios = create_adios(comm)
259 backend_args = get_default_backend_args(backend_args)
260 with ADIOSFile(
261 adios=adios,
262 filename=filename,
263 mode=adios2.Mode.Read,
264 engine=backend_args["engine"],
265 io_name="AttributesReader",
266 ) as adios_file:
267 adios_file.file.BeginStep()
268 attributes = {}
269 for k in adios_file.io.AvailableAttributes().keys():
270 if k.startswith(f"{name}_"):
271 a = adios_file.io.InquireAttribute(k)
272 attributes[k[len(name) + 1 :]] = a.Data()
273 adios_file.file.EndStep()
274 return attributes
277def read_timestamps(
278 filename: Path | str,
279 comm: MPI.Comm,
280 function_name: str,
281 backend_args: dict[str, Any] | None = None,
282) -> npt.NDArray[np.float64 | str]: # type: ignore[type-var]
283 """Read time-stamps from a checkpoint file.
285 Args:
286 comm: MPI communicator
287 filename: Path to file
288 function_name: Name of the function to read time-stamps for
289 backend_args: Arguments for backend, for instance file type.
290 backend: What backend to use for writing.
291 Returns:
292 The time-stamps
294 Raises:
295 KeyError: If the file does not hold the function on that mesh, naming those it does
296 """
297 check_file_exists(filename)
299 adios = create_adios(comm)
300 backend_args = get_default_backend_args(backend_args)
301 prefix = mesh_prefix(backend_args)
302 with ADIOSFile(
303 adios=adios,
304 filename=filename,
305 mode=adios2.Mode.Read,
306 engine=backend_args["engine"],
307 io_name="TimestepReader",
308 ) as adios_file:
309 time_name = f"{prefix}{function_name}_time"
310 time_stamps = []
311 function_names: set[str] = set()
312 for _ in range(adios_file.file.Steps()):
313 adios_file.file.BeginStep()
314 variables = adios_file.io.AvailableVariables()
315 function_names |= _function_names(variables, prefix)
316 if time_name in variables.keys():
317 arr = adios_file.io.InquireVariable(time_name)
318 time_shape = arr.Shape()
319 arr.SetSelection([[0], [time_shape[0]]])
320 times = np.empty(
321 time_shape[0],
322 dtype=adios_to_numpy_dtype[arr.Type()],
323 )
324 adios_file.file.Get(arr, times, adios2.Mode.Sync)
325 time_stamps.append(times[0])
326 adios_file.file.EndStep()
328 if not time_stamps: # Every write of a function writes its time
329 raise function_not_found(
330 filename, function_name, get_mesh_name(backend_args), function_names
331 )
332 return np.array(time_stamps)
335def write_mesh(
336 filename: Path | str,
337 comm: MPI.Comm,
338 mesh: MeshData,
339 backend_args: dict[str, Any] | None = None,
340 mode: FileMode = FileMode.write,
341 time: float = 0.0,
342):
343 """Write a mesh to file using ADIOS2.
345 Args:
346 comm: MPI communicator used in storage
347 mesh: Internal data structure for the mesh data to save to file
348 filename: Path to file to write to
349 backend_args: File mode and potentially the io-name.
350 mode: Mode to use (write or append)
351 time: Time stamp
352 """
353 backend_args = get_default_backend_args(backend_args)
354 if "io_name" not in backend_args.keys():
355 backend_args["io_name"] = "MeshWriter"
356 prefix = mesh_prefix(backend_args)
358 mode = convert_file_mode(mode)
359 gdim = mesh.local_geometry.shape[1]
360 adios = create_adios(comm)
362 # Topology is constant in time and written once. In append mode it may
363 # already be present either because this mesh was written at an earlier time
364 # step, or because a *different* mesh was written first -- so the test is
365 # whether this mesh's topology exists, not whether the file is new.
366 topology_exists = False
367 if mode == adios2.Mode.Append:
368 topology_exists = check_variable_exists(
369 adios, filename, f"{prefix}Topology", engine=backend_args["engine"]
370 )
372 with ADIOSFile(
373 adios=adios,
374 filename=filename,
375 mode=mode,
376 comm=comm,
377 engine=backend_args["engine"],
378 io_name=backend_args["io_name"],
379 ) as adios_file:
380 adios_file.file.BeginStep()
381 # Write geometry
382 pointvar = adios_file.io.DefineVariable(
383 f"{prefix}Points",
384 mesh.local_geometry,
385 shape=[mesh.num_nodes_global, gdim],
386 start=[mesh.local_geometry_pos[0], 0],
387 count=[mesh.local_geometry_pos[1] - mesh.local_geometry_pos[0], gdim],
388 )
389 adios_file.file.Put(pointvar, mesh.local_geometry, adios2.Mode.Sync)
391 if not topology_exists:
392 _define_metadata(adios_file.io, prefix, mesh.metadata)
393 adios_file.io.DefineAttribute(f"{prefix}CellType", mesh.cell_type)
394 adios_file.io.DefineAttribute(
395 f"{prefix}Degree", np.array([mesh.degree], dtype=np.int32)
396 )
397 adios_file.io.DefineAttribute(
398 f"{prefix}LagrangeVariant", np.array([mesh.lagrange_variant], dtype=np.int32)
399 )
400 # Write topology (on;y on first write as topology is constant)
401 num_dofs_per_cell = mesh.local_topology.shape[1]
402 dvar = adios_file.io.DefineVariable(
403 f"{prefix}Topology",
404 mesh.local_topology,
405 shape=[mesh.num_cells_global, num_dofs_per_cell],
406 start=[mesh.local_topology_pos[0], 0],
407 count=[
408 mesh.local_topology_pos[1] - mesh.local_topology_pos[0],
409 num_dofs_per_cell,
410 ],
411 )
412 adios_file.file.Put(dvar, mesh.local_topology)
414 # Add partitioning data
415 if mesh.store_partition:
416 assert mesh.partition_range is not None
417 par_data = adios_file.io.DefineVariable(
418 f"{prefix}PartitioningData",
419 mesh.ownership_array,
420 shape=[mesh.partition_global],
421 start=[mesh.partition_range[0]],
422 count=[
423 mesh.partition_range[1] - mesh.partition_range[0],
424 ],
425 )
426 adios_file.file.Put(par_data, mesh.ownership_array)
427 assert mesh.ownership_offset is not None
428 par_offset = adios_file.io.DefineVariable(
429 f"{prefix}PartitioningOffset",
430 mesh.ownership_offset,
431 shape=[mesh.num_cells_global + 1],
432 start=[mesh.local_topology_pos[0]],
433 count=[mesh.local_topology_pos[1] - mesh.local_topology_pos[0] + 1],
434 )
435 adios_file.file.Put(par_offset, mesh.ownership_offset)
436 assert mesh.partition_processes is not None
437 adios_file.io.DefineAttribute(
438 f"{prefix}PartitionProcesses",
439 np.array([mesh.partition_processes], dtype=np.int32),
440 )
441 if topology_exists and mesh.store_partition:
442 warnings.warn("Partitioning data is not written in append mode")
444 # Add time step to file
445 t_arr = np.array([time], dtype=np.float64)
446 time_var = adios_file.io.DefineVariable(
447 f"{prefix}MeshTime",
448 t_arr,
449 shape=[1],
450 start=[0],
451 count=[1 if comm.rank == 0 else 0],
452 )
453 adios_file.file.Put(time_var, t_arr)
455 adios_file.file.PerformPuts()
456 adios_file.file.EndStep()
459def read_mesh_data(
460 filename: Path | str,
461 comm: MPI.Comm,
462 time: str | float | None = 0.0,
463 read_from_partition: bool = False,
464 backend_args: dict[str, Any] | None = None,
465) -> ReadMeshData:
466 """Read an ADIOS2 mesh data for use with DOLFINx.
468 Args:
469 filename: Path to input file
470 comm: The MPI communciator to distribute the mesh over
471 engine: ADIOS engine to use for reading (BP4, BP5 or HDF5)
472 time: Time stamp associated with mesh
473 legacy: If checkpoint was made prior to time-dependent mesh-writer set to True
474 read_from_partition: Read mesh with partition from file
475 Returns:
476 The mesh topology, geometry, UFL domain and partition function
477 """
479 adios = create_adios(comm)
480 backend_args = get_default_backend_args(backend_args)
481 legacy = backend_args.get("legacy", False)
482 if legacy:
483 warnings.warn(
484 "Reading adios4dolfinx checkpoints (format 0) with legacy=True is deprecated. "
485 "Convert the file once with io4dolfinx.convert or the io4dolfinx-convert command.",
486 DeprecationWarning,
487 stacklevel=3,
488 )
489 io_name = backend_args.get("io_name", "MeshReader")
490 engine = backend_args["engine"]
491 prefix = mesh_prefix(backend_args)
492 with ADIOSFile(
493 adios=adios,
494 filename=filename,
495 mode=adios2.Mode.Read,
496 engine=engine,
497 io_name=io_name,
498 ) as adios_file:
499 # Get time independent mesh variables (mesh topology and cell type info)
500 # first. With several meshes in the file this mesh's topology need not be
501 # in step 0, so seek the step holding it.
502 try:
503 step = _seek_step(adios_file, f"{prefix}Topology")
504 except KeyError as e:
505 raise KeyError(f"Mesh topology not found at {prefix}Topology in {filename}") from e
506 mesh_topology, _, _ = read_local_rows(
507 adios_file, comm, f"{prefix}Topology", mode=adios2.Mode.Deferred
508 )
510 # Check validity of partitioning information
511 if read_from_partition:
512 if f"{prefix}PartitionProcesses" not in adios_file.io.AvailableAttributes().keys():
513 raise KeyError(f"Partitioning information not found in {filename}")
514 par_num_procs = adios_file.io.InquireAttribute(f"{prefix}PartitionProcesses")
515 num_procs = par_num_procs.Data()[0]
516 if num_procs != comm.size:
517 raise ValueError(f"Number of processes in file ({num_procs})!=({comm.size=})")
519 # Get mesh cell type
520 if f"{prefix}CellType" not in adios_file.io.AvailableAttributes().keys():
521 raise KeyError(f"Mesh cell type not found at {prefix}CellType in {filename}")
522 celltype = adios_file.io.InquireAttribute(f"{prefix}CellType")
523 cell_type = celltype.DataString()[0]
525 # Get basix info
526 if f"{prefix}LagrangeVariant" not in adios_file.io.AvailableAttributes().keys():
527 raise KeyError(f"Mesh LagrangeVariant not found in {filename}")
528 lvar = adios_file.io.InquireAttribute(f"{prefix}LagrangeVariant").Data()[0]
529 if f"{prefix}Degree" not in adios_file.io.AvailableAttributes().keys():
530 raise KeyError(f"Mesh degree not found in {filename}")
531 degree = adios_file.io.InquireAttribute(f"{prefix}Degree").Data()[0]
533 if not legacy:
534 # Geometry for this time stamp is written in the same step as the
535 # topology or a later one, so resume the scan from there.
536 time_name = f"{prefix}MeshTime"
537 for i in range(step, adios_file.file.Steps()):
538 if i > step:
539 adios_file.file.BeginStep()
540 if time_name in adios_file.io.AvailableVariables().keys():
541 arr = adios_file.io.InquireVariable(time_name)
542 time_shape = arr.Shape()
543 arr.SetSelection([[0], [time_shape[0]]])
544 times = np.empty(time_shape[0], dtype=adios_to_numpy_dtype[arr.Type()])
545 adios_file.file.Get(arr, times, adios2.Mode.Sync)
546 if times[0] == time:
547 break
548 if i == adios_file.file.Steps() - 1:
549 raise KeyError(
550 f"No data associated with {time_name}={time} found in {filename}"
551 )
553 adios_file.file.EndStep()
555 if time_name not in adios_file.io.AvailableVariables().keys():
556 raise KeyError(f"No data associated with {time_name}={time} found in {filename}")
558 # Get mesh geometry
559 if f"{prefix}Points" not in adios_file.io.AvailableVariables().keys():
560 raise KeyError(f"Mesh coordinates not found at {prefix}Points in {filename}")
561 mesh_geometry, _, _ = read_local_rows(
562 adios_file, comm, f"{prefix}Points", mode=adios2.Mode.Deferred
563 )
564 adios_file.file.PerformGets()
565 adios_file.file.EndStep()
567 if read_from_partition:
568 partition_graph = read_adjacency_list(
569 adios,
570 comm,
571 filename,
572 f"{prefix}PartitioningData",
573 f"{prefix}PartitioningOffset",
574 backend_args["engine"],
575 )
576 else:
577 partition_graph = None
579 return ReadMeshData(
580 cells=mesh_topology.astype(np.int64, copy=False),
581 cell_type=cell_type,
582 x=mesh_geometry,
583 degree=degree,
584 lvar=lvar,
585 partition_graph=partition_graph,
586 )
589def write_meshtags(
590 filename: str | Path,
591 comm: MPI.Comm,
592 data: MeshTagsData,
593 backend_args: dict[str, Any] | None = None,
594):
595 """Write mesh tags to file.
597 Args:
598 filename: Path to file to write to
599 comm: MPI communicator used in storage
600 data: Internal data structure for the mesh tags to save to file
601 backend_args: Arguments to backend
602 """
603 backend_args = {} if backend_args is None else backend_args
604 io_name = backend_args.get("io_name", "MeshTagWriter")
605 engine = backend_args.get("engine", "BP4")
606 prefix = mesh_prefix(backend_args)
607 adios = create_adios(comm)
608 with ADIOSFile(
609 adios=adios,
610 filename=filename,
611 mode=adios2.Mode.Append,
612 engine=engine,
613 io_name=io_name,
614 ) as adios_file:
615 adios_file.file.BeginStep()
617 # Write meshtag topology
618 topology_var = adios_file.io.DefineVariable(
619 f"{prefix}{data.name}_topology",
620 data.indices,
621 shape=[data.num_entities_global, data.num_dofs_per_entity],
622 start=[data.local_start, 0],
623 count=[len(data.indices), data.num_dofs_per_entity],
624 )
625 adios_file.file.Put(topology_var, data.indices, adios2.Mode.Sync)
627 # Write meshtag values
628 vals = np.array(data.values)
629 values_var = adios_file.io.DefineVariable(
630 f"{prefix}{data.name}_values",
631 vals,
632 shape=[data.num_entities_global],
633 start=[data.local_start],
634 count=[len(data.indices)],
635 )
636 adios_file.file.Put(values_var, vals, adios2.Mode.Sync)
638 # Write meshtag dim
639 adios_file.io.DefineAttribute(
640 f"{prefix}{data.name}_dim", np.array([data.dim], dtype=np.uint8)
641 )
642 _define_metadata(adios_file.io, f"{prefix}{data.name}_", data.metadata)
643 adios_file.file.PerformPuts()
644 adios_file.file.EndStep()
647def read_meshtags_data(
648 filename: str | Path, comm: MPI.Comm, name: str, backend_args: dict[str, Any] | None = None
649) -> MeshTagsData:
650 """Read mesh tags from file.
652 Args:
653 filename: Path to file to read from
654 comm: MPI communicator used in storage
655 name: Name of the mesh tags to read
656 backend_args: Arguments to backend
658 Returns:
659 Internal data structure for the mesh tags read from file
660 """
662 adios = create_adios(comm)
663 backend_args = get_default_backend_args(backend_args)
664 io_name = backend_args.get("io_name", "MeshTagsReader")
665 engine = backend_args["engine"]
666 legacy = backend_args["legacy"]
667 prefix = mesh_prefix(backend_args)
668 with ADIOSFile(
669 adios=adios,
670 filename=filename,
671 mode=adios2.Mode.Read,
672 engine=engine,
673 io_name=io_name,
674 ) as adios_file:
675 if not legacy:
676 # Get mesh cell type
677 dim_attr_name = f"{prefix}{name}_dim"
678 step = 0
679 for i in range(adios_file.file.Steps()):
680 adios_file.file.BeginStep()
681 if dim_attr_name in adios_file.io.AvailableAttributes().keys():
682 step = i
683 break
684 adios_file.file.EndStep()
685 if dim_attr_name not in adios_file.io.AvailableAttributes().keys():
686 raise KeyError(f"{dim_attr_name} not found in {filename}")
688 m_dim = adios_file.io.InquireAttribute(dim_attr_name)
689 dim = int(m_dim.Data()[0])
691 # Get mesh tags entites
692 topology_name = f"{prefix}{name}_topology"
693 for i in range(step, adios_file.file.Steps()):
694 if i > step:
695 adios_file.file.BeginStep()
696 if topology_name in adios_file.io.AvailableVariables().keys():
697 break
698 adios_file.file.EndStep()
699 if topology_name not in adios_file.io.AvailableVariables().keys():
700 raise KeyError(f"{topology_name} not found in {filename}")
702 mesh_entities, _, num_entities = read_local_rows(
703 adios_file, comm, topology_name, mode=adios2.Mode.Deferred
704 )
706 # Get mesh tags values
707 values_name = f"{prefix}{name}_values"
708 if values_name not in adios_file.io.AvailableVariables().keys():
709 raise KeyError(f"{values_name} not found")
710 tag_values, _, num_values = read_local_rows(
711 adios_file, comm, values_name, mode=adios2.Mode.Deferred
712 )
713 assert num_values == num_entities
715 adios_file.file.PerformGets()
716 adios_file.file.EndStep()
717 else:
718 # Get mesh cell type
719 dim_attr_name = f"{name}_dim"
720 assert adios_file.file.Steps() == 0
721 if (ct_key := f"/{name}/topology/celltype") in adios_file.io.AvailableAttributes():
722 cell_type = adios_file.io.InquireAttribute(ct_key)
723 else:
724 raise ValueError(f"Celltype not found for meshtags {name} in {filename}.")
725 dim = dolfinx.mesh.cell_dim(dolfinx.mesh.to_type(cell_type.DataString()[0]))
727 # Get mesh tags entites
728 if (top_key := f"/{name}/topology") not in adios_file.io.AvailableVariables():
729 raise ValueError(f"Topology not found for meshtags {name} in {filename}.")
731 mesh_entities, _, num_entities = read_local_rows(
732 adios_file, comm, top_key, mode=adios2.Mode.Deferred
733 )
735 # Get mesh tags values
736 if (val_key := f"/{name}/values") not in adios_file.io.AvailableVariables():
737 raise ValueError(f"Values not found for meshtags {name} in {filename}.")
738 tag_values, _, num_values = read_local_rows(
739 adios_file, comm, val_key, mode=adios2.Mode.Deferred
740 )
741 assert num_values == num_entities
743 adios_file.file.PerformGets()
744 adios_file.file.EndStep()
746 # Tag values are int32 unless the caller asks for something wider. The
747 # submesh post codes are global cell indices, which need int64.
748 values_dtype = np.dtype(backend_args.get("values_dtype", np.int32))
749 return MeshTagsData(
750 name=name,
751 values=tag_values.astype(values_dtype),
752 indices=mesh_entities.astype(np.int64, copy=False),
753 dim=dim,
754 )
757def read_dofmap(
758 filename: str | Path, comm: MPI.Comm, name: str, backend_args: dict[str, Any] | None = None
759) -> dolfinx.graph.AdjacencyList:
760 """Read the dofmap of a function with a given name.
762 Args:
763 filename: Path to file to read from
764 comm: MPI communicator used in storage
765 name: Name of the function to read the dofmap for
766 backend_args: Arguments to backend
768 Returns:
769 Dofmap as an AdjacencyList
770 """
771 backend_args = {} if backend_args is None else backend_args
772 prefix = mesh_prefix(backend_args)
774 # Handles legacy io4dolfinx files, modern files, and custom location of dofmap.
775 legacy = backend_args.get("legacy", False)
776 xdofmap_path: str | None
777 dofmap_path: str | None
778 if (dofmap_path := backend_args.get("dofmap", None)) is None:
779 if legacy:
780 dofmap_path = "Dofmap"
781 else:
782 dofmap_path = f"{prefix}{name}_dofmap"
784 if (xdofmap_path := backend_args.get("offsets", None)) is None:
785 if legacy:
786 xdofmap_path = "XDofmap"
787 else:
788 xdofmap_path = f"{prefix}{name}_XDofmap"
790 engine = backend_args.get("engine", "BP4")
792 adios = create_adios(comm)
793 check_file_exists(filename)
794 assert isinstance(xdofmap_path, str)
795 return read_adjacency_list(adios, comm, filename, dofmap_path, xdofmap_path, engine=engine)
798def read_dofs(
799 filename: str | Path,
800 comm: MPI.Comm,
801 name: str,
802 time: float,
803 backend_args: dict[str, Any] | None = None,
804) -> tuple[npt.NDArray[np.float32 | np.float64 | np.complex64 | np.complex128], int]:
805 """Read the dofs (values) of a function with a given name from a given timestep.
807 Args:
808 filename: Path to file to read from
809 comm: MPI communicator used in storage
810 name: Name of the function to read the dofs for
811 time: Time stamp associated with the function to read
812 backend_args: Arguments to backend
814 Returns:
815 Contiguous sequence of degrees of freedom (with respect to input data)
816 and the global starting point on the process.
817 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
818 """
820 backend_args = {} if backend_args is None else backend_args
821 legacy = backend_args.get("legacy", False)
822 engine = backend_args.get("engine", "BP4")
823 io_name = backend_args.get("io_name", f"{name}_FunctionReader")
824 prefix = mesh_prefix(backend_args)
825 # Check that file contains the function to read
826 adios = create_adios(comm)
827 check_file_exists(filename)
829 if not legacy:
830 with ADIOSFile(
831 adios=adios,
832 filename=filename,
833 mode=adios2.Mode.Read,
834 engine=engine,
835 io_name=io_name,
836 ) as adios_file:
837 variables = set(
838 sorted(
839 map(
840 lambda x: x[len(prefix) :].split("_time")[0],
841 filter(
842 lambda x: x.startswith(prefix) and x.endswith("_time"),
843 adios_file.io.AvailableVariables(),
844 ),
845 )
846 )
847 )
848 if name not in variables:
849 raise KeyError(f"{name} not found in {filename}. Did you mean one of {variables}?")
851 if legacy:
852 array_path = "Values"
853 else:
854 array_path = f"{prefix}{name}_values"
856 time_name = f"{prefix}{name}_time"
857 return read_array(adios, filename, array_path, engine, comm, time, time_name, legacy=legacy)
860def read_cell_perms(
861 comm: MPI.Comm, filename: Path | str, backend_args: dict[str, Any] | None = None
862) -> npt.NDArray[np.uint32]:
863 """
864 Read cell permutation from file with given communicator,
865 Split in continuous chunks based on number of cells in the mesh (global).
867 Args:
868 adios: The ADIOS instance
869 comm: The MPI communicator used to read the data
870 filename: Path to input file
871 variable: Name of cell-permutation variable
872 num_cells_global: Number of cells in the mesh (global)
873 engine: Type of ADIOS engine to use for reading data
875 Returns:
876 Cell-permutations local to the process
878 .. note::
879 No MPI communication is done during this call
880 """
881 adios = create_adios(comm)
882 check_file_exists(filename)
884 # Open ADIOS engine
885 backend_args = {} if backend_args is None else backend_args
886 engine = backend_args.get("engine", "BP4")
887 prefix = mesh_prefix(backend_args)
889 cell_perms, _ = read_array(
890 adios, filename, f"{prefix}CellPermutations", engine=engine, comm=comm, legacy=True
891 )
893 return cell_perms.astype(np.uint32)
896def read_hdf5_array(
897 comm: MPI.Comm,
898 filename: Path | str,
899 group: str,
900 backend_args: dict[str, Any] | None = None,
901) -> tuple[np.ndarray, int]:
902 adios = create_adios(comm)
903 """Read an array from an HDF5 file.
905 Args:
906 comm: MPI communicator used in storage
907 filename: Path to file to read from
908 group: Group in HDF5 file where array is stored
909 backend_args: Arguments to backend
911 Returns:
912 Tuple containing:
913 - Numpy array read from file
914 - Global starting point on the process.
915 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
916 """
917 return read_array(adios, filename, group, engine="HDF5", comm=comm, legacy=True)
920def write_function(
921 filename: Path,
922 comm: MPI.Comm,
923 u: FunctionData,
924 time: float = 0.0,
925 mode: FileMode = FileMode.append,
926 backend_args: dict[str, Any] | None = None,
927):
928 """
929 Write a function to file using ADIOS2
931 Args:
932 comm: MPI communicator used in storage
933 u: Internal data structure for the function data to save to file
934 filename: Path to file to write to
935 engine: ADIOS2 engine to use
936 mode: ADIOS2 mode to use (write or append)
937 time: Time stamp associated with function
938 io_name: Internal name used for the ADIOS IO object
939 """
940 adios_mode = convert_file_mode(mode)
941 backend_args = get_default_backend_args(backend_args)
942 engine = backend_args["engine"]
943 io_name = backend_args.get("io_name", "{name}_writer")
944 prefix = mesh_prefix(backend_args)
946 adios = create_adios(comm)
947 cell_permutations_exists = False
948 dofmap_exists = False
949 XDofmap_exists = False
950 if adios_mode == adios2.Mode.Append:
951 cell_permutations_exists = check_variable_exists(
952 adios, filename, f"{prefix}CellPermutations", engine=engine
953 )
954 dofmap_exists = check_variable_exists(
955 adios, filename, f"{prefix}{u.name}_dofmap", engine=engine
956 )
957 XDofmap_exists = check_variable_exists(
958 adios, filename, f"{prefix}{u.name}_XDofmap", engine=engine
959 )
961 with ADIOSFile(
962 adios=adios, filename=filename, mode=adios_mode, engine=engine, io_name=io_name, comm=comm
963 ) as adios_file:
964 adios_file.file.BeginStep()
966 if not cell_permutations_exists:
967 # Add mesh permutations. These belong to the mesh, not the function,
968 # so they are shared by every function on that mesh.
969 pvar = adios_file.io.DefineVariable(
970 f"{prefix}CellPermutations",
971 u.cell_permutations,
972 shape=[u.num_cells_global],
973 start=[u.local_cell_range[0]],
974 count=[u.local_cell_range[1] - u.local_cell_range[0]],
975 )
976 adios_file.file.Put(pvar, u.cell_permutations)
978 if not dofmap_exists:
979 _define_metadata(adios_file.io, f"{prefix}{u.name}_", u.metadata)
980 # Add dofmap
981 dofmap_var = adios_file.io.DefineVariable(
982 f"{prefix}{u.name}_dofmap",
983 u.dofmap_array,
984 shape=[u.global_dofs_in_dofmap],
985 start=[u.dofmap_range[0]],
986 count=[u.dofmap_range[1] - u.dofmap_range[0]],
987 )
988 adios_file.file.Put(dofmap_var, u.dofmap_array)
990 if not XDofmap_exists:
991 # Add XDofmap
992 xdofmap_var = adios_file.io.DefineVariable(
993 f"{prefix}{u.name}_XDofmap",
994 u.dofmap_offsets,
995 shape=[u.num_cells_global + 1],
996 start=[u.local_cell_range[0]],
997 count=[u.local_cell_range[1] - u.local_cell_range[0] + 1],
998 )
999 adios_file.file.Put(xdofmap_var, u.dofmap_offsets)
1001 val_var = adios_file.io.DefineVariable(
1002 f"{prefix}{u.name}_values",
1003 u.values,
1004 shape=[u.num_dofs_global],
1005 start=[u.dof_range[0]],
1006 count=[u.dof_range[1] - u.dof_range[0]],
1007 )
1008 adios_file.file.Put(val_var, u.values)
1010 # Add time step to file
1011 t_arr = np.array([time], dtype=np.float64)
1012 time_var = adios_file.io.DefineVariable(
1013 f"{prefix}{u.name}_time",
1014 t_arr,
1015 shape=[1],
1016 start=[0],
1017 count=[1 if comm.rank == 0 else 0],
1018 )
1019 adios_file.file.Put(time_var, t_arr)
1020 adios_file.file.PerformPuts()
1021 adios_file.file.EndStep()
1024def read_format0_checkpoint(
1025 filename: Path, comm: MPI.Comm, engine: str
1026) -> tuple[MeshData, list[dict[str, Any]]]:
1027 """The mesh and the data of each function of a checkpoint written by adios4dolfinx 0.7
1028 or older (format 0), as stored.
1030 Args:
1031 filename: The checkpoint.
1032 comm: The communicator to read with.
1033 engine: The ADIOS2 engine the checkpoint was written with.
1035 Returns:
1036 The mesh, and for each function in the order of the file the arguments of its
1037 :class:`io4dolfinx.structures.FunctionData` except the name.
1038 """
1039 adios = create_adios(comm)
1040 mesh: MeshData | None = None
1041 cell_permutations = None
1042 functions: list[dict[str, Any]] = []
1043 with ADIOSFile(
1044 adios=adios, filename=filename, engine=engine, mode=adios2.Mode.Read, io_name="Format0"
1045 ) as adios_file:
1046 for _ in range(adios_file.file.Steps()):
1047 adios_file.file.BeginStep()
1048 variables = adios_file.io.AvailableVariables()
1049 if "MeshTime" in variables:
1050 raise ValueError(
1051 f"{filename} is not an adios4dolfinx checkpoint of format 0: its mesh has "
1052 "time stamps, so it can be read directly."
1053 )
1054 if "Topology" in variables:
1055 topology, cell_range, num_cells = read_local_rows(adios_file, comm, "Topology")
1056 points, node_range, num_nodes = read_local_rows(adios_file, comm, "Points")
1057 cell_permutations, _, _ = read_local_rows(adios_file, comm, "CellPermutations")
1058 attributes = adios_file.io
1059 mesh = MeshData(
1060 metadata=stamp(),
1061 local_geometry=points,
1062 local_geometry_pos=node_range,
1063 num_nodes_global=num_nodes,
1064 local_topology=topology,
1065 local_topology_pos=cell_range,
1066 num_cells_global=num_cells,
1067 cell_type=attributes.InquireAttribute("CellType").DataString()[0],
1068 degree=int(attributes.InquireAttribute("Degree").Data()[0]),
1069 lagrange_variant=int(attributes.InquireAttribute("LagrangeVariant").Data()[0]),
1070 store_partition=False,
1071 )
1072 if "Values" in variables:
1073 values, dof_range, num_dofs = read_local_rows(adios_file, comm, "Values")
1074 offsets, function_cells, num_function_cells = read_local_rows(
1075 adios_file, comm, "XDofmap", overlap=1
1076 )
1077 dofmap_var = adios_file.io.InquireVariable("Dofmap")
1078 dofmap_range = (int(offsets[0]), int(offsets[-1]))
1079 dofmap_var.SetSelection([[dofmap_range[0]], [dofmap_range[1] - dofmap_range[0]]])
1080 dofmap = np.empty(dofmap_range[1] - dofmap_range[0], dtype=np.int64)
1081 adios_file.file.Get(dofmap_var, dofmap, adios2.Mode.Sync)
1082 functions.append(
1083 dict(
1084 local_cell_range=function_cells,
1085 num_cells_global=num_function_cells,
1086 dofmap_array=dofmap,
1087 dofmap_offsets=offsets.astype(np.int64),
1088 dofmap_range=dofmap_range,
1089 global_dofs_in_dofmap=int(dofmap_var.Shape()[0]),
1090 values=values,
1091 dof_range=dof_range,
1092 num_dofs_global=num_dofs,
1093 )
1094 )
1095 adios_file.file.EndStep()
1096 if mesh is None or cell_permutations is None:
1097 raise ValueError(f"No mesh found in {filename}")
1098 for function in functions:
1099 # Cells are divided over the processes in the same way as for the mesh
1100 function["cell_permutations"] = cell_permutations
1101 return mesh, functions
1104def read_legacy_mesh(
1105 filename: Path | str, comm: MPI.Comm, group: str
1106) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.floating], str | None]:
1107 """Read in the mesh topology, geometry and (optionally) cell type from a
1108 legacy DOLFIN HDF5-file.
1110 Args:
1111 filename: Path to file to read from
1112 comm: MPI communicator used in storage
1113 group: Group in HDF5 file where mesh is stored
1115 Returns:
1116 Tuple containing:
1117 - Topology as a (num_cells, num_vertices_per_cell) array of global vertex indices
1118 - Geometry as a (num_vertices, geometric_dimension) array of vertex coordinates
1119 - Cell type as a string (e.g. "tetrahedron") or None if not found
1120 """
1121 # Create ADIOS2 reader
1122 adios = create_adios(comm)
1123 with ADIOSFile(
1124 adios=adios,
1125 filename=filename,
1126 mode=adios2.Mode.Read,
1127 io_name="Mesh reader",
1128 engine="HDF5",
1129 ) as adios_file:
1130 # Get mesh topology (distributed)
1131 if f"{group}/topology" not in adios_file.io.AvailableVariables().keys():
1132 raise KeyError(f"Mesh topology not found at '{group}/topology'")
1133 mesh_topology, _, _ = read_local_rows(adios_file, comm, f"{group}/topology")
1135 # Get mesh cell type
1136 cell_type = None
1137 if f"{group}/topology/celltype" in adios_file.io.AvailableAttributes().keys():
1138 celltype = adios_file.io.InquireAttribute(f"{group}/topology/celltype")
1139 cell_type = celltype.DataString()[0]
1141 # Get mesh geometry
1143 for geometry_key in [f"{group}/geometry", f"{group}/coordinates"]:
1144 if geometry_key in adios_file.io.AvailableVariables().keys():
1145 break
1146 else:
1147 raise KeyError(
1148 f"Mesh coordinates not found at '{group}/coordinates' or '{group}/geometry'"
1149 )
1151 mesh_geometry, _, _ = read_local_rows(adios_file, comm, geometry_key)
1153 return mesh_topology, mesh_geometry, cell_type
1156def snapshot_checkpoint(
1157 filename: Path | str,
1158 mode: FileMode,
1159 u: dolfinx.fem.Function,
1160 backend_args: dict[str, Any] | None,
1161):
1162 """Create a snapshot checkpoint of a dolfinx function.
1164 Args:
1165 filename: Path to file to read from
1166 mode: File-mode to store the function
1167 u: dolfinx function to create a snapshot checkpoint for
1168 backend_args: Arguments to backend
1169 """
1170 adios_mode = convert_file_mode(mode)
1171 adios = create_adios(u.function_space.mesh.comm)
1172 backend_args = {} if backend_args is None else backend_args
1173 io_name = backend_args.get("io_name", "SnapshotCheckPoint")
1174 engine = backend_args.get("engine", "BP4")
1175 with ADIOSFile(
1176 adios=adios,
1177 filename=filename,
1178 mode=adios_mode,
1179 io_name=io_name,
1180 engine=engine,
1181 ) as adios_file:
1182 if adios_mode == adios2.Mode.Write:
1183 dofmap = u.function_space.dofmap
1184 num_dofs_local = dofmap.index_map.size_local * dofmap.index_map_bs
1185 local_dofs = u.x.array[:num_dofs_local].copy()
1187 # Write to file
1188 adios_file.file.BeginStep()
1189 dofs = adios_file.io.DefineVariable("dofs", local_dofs, count=[num_dofs_local])
1190 adios_file.file.Put(dofs, local_dofs, adios2.Mode.Sync)
1191 adios_file.file.EndStep()
1192 elif adios_mode == adios2.Mode.Read:
1193 adios_file.file.BeginStep()
1194 in_variable = adios_file.io.InquireVariable("dofs")
1195 in_variable.SetBlockSelection(u.function_space.mesh.comm.rank)
1196 adios_file.file.Get(in_variable, u.x.array, adios2.Mode.Sync)
1197 adios_file.file.EndStep()
1198 u.x.scatter_forward()
1199 else:
1200 raise NotImplementedError(f"Mode {mode} is not implemented for snapshot checkpoint")
1203def read_function_names(
1204 filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None
1205) -> list[str]:
1206 """Read all function names from a file.
1208 Args:
1209 filename: Path to file
1210 comm: MPI communicator to launch IO on.
1211 backend_args: Arguments to backend
1213 Returns:
1214 A list of function names.
1215 """
1216 raise NotImplementedError("Reading function names are not implemented with ADIOS2")
1219def read_point_data(
1220 filename: Path | str,
1221 name: str,
1222 comm: MPI.Comm,
1223 time: float | str | None,
1224 backend_args: dict[str, Any] | None,
1225) -> tuple[np.ndarray, int]:
1226 """Read data from the nodes of a mesh.
1228 Args:
1229 filename: Path to file
1230 name: Name of point data
1231 comm: Communicator to launch IO on.
1232 time: The time stamp
1233 backend_args: The backend arguments
1235 Returns:
1236 Data local to process (contiguous, no mpi comm) and local start range
1237 """
1238 raise NotImplementedError("The ADIOS2 backend cannot read point data.")
1241def read_cell_data(
1242 filename: Path | str,
1243 name: str,
1244 comm: MPI.Comm,
1245 time: str | float | None,
1246 backend_args: dict[str, Any] | None,
1247) -> tuple[npt.NDArray[np.int64], np.ndarray]:
1248 """Read data from the cells of a mesh.
1250 Args:
1251 filename: Path to file
1252 name: Name of point data
1253 comm: Communicator to launch IO on.
1254 time: The time stamp
1255 backend_args: The backend arguments
1256 Returns:
1257 A tuple (topology, dofs) where topology contains the
1258 vertex indices of the cells, dofs the degrees of
1259 freedom within that cell.
1260 """
1261 raise NotImplementedError("The ADIOS2 backend does not support reading cell data.")
1264def write_data(
1265 filename: Path | str,
1266 array_data: ArrayData,
1267 comm: MPI.Comm,
1268 time: str | float | None,
1269 mode: FileMode,
1270 backend_args: dict[str, Any] | None,
1271):
1272 """Write a 2D-array to file (distributed across proceses with MPI).
1275 Args:
1276 filename: Path to file
1277 array_data: Data to write to file
1278 comm: MPI communicator to open the file with.
1279 time: Time stamp
1280 mode: Append or write
1281 backend_args: The backend arguments
1282 """
1283 raise NotImplementedError("ADIOS2 has not implemented this yet")