Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/exodus/backend.py: 3%
256 statements
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 11:58 +0000
« prev ^ index » next coverage.py v7.18.0, created at 2026-11-30 11:58 +0000
1"""
2Exodus interface to io4dolfinx.
3The Exodus2 format is described in:
4https://src.fedoraproject.org/repo/pkgs/exodusii/922137.pdf/a45d67f4a1a8762bcf66af2ec6eb35f9/922137.pdf
5Further documentation from CUBIT on node numbering can be found at:
6https://coreform.com/cubit_help/appendix/element_numbering.htm
8SPDX License identifier: MIT
10Copyright: Jørgen S. Dokken, Henrik N.T. Finsberg, Remi Delaporte-Mathurin,
11 and Simula Research Laboratory
12"""
14import re
15from pathlib import Path
16from typing import Any, Literal, cast
18from mpi4py import MPI
20import basix.ufl
21import dolfinx
22import netCDF4
23import numpy as np
24import numpy.typing as npt
26from ...structures import ArrayData, FunctionData, MeshData, MeshTagsData, ReadMeshData
27from ...utils import check_file_exists, serendipity_num_nodes
28from .. import FileMode, ReadMode
30_interval_to_vertex_map = {0: [0, 1]}
31# Based on: https://src.fedoraproject.org/repo/pkgs/exodusii/922137.pdf/a45d67f4a1a8762bcf66af2ec6eb35f9/922137.pdf
32_tetra_facet_to_vertex_map = {0: [0, 1, 3], 1: [1, 2, 3], 2: [0, 2, 3], 3: [0, 1, 2]}
33# https://coreform.com/cubit_help/appendix/element_numbering.htm
34# Note that triangular side-sets goes from 2 to 4 (with 0 base index)
35_triangle_to_vertex_map = {2: [0, 1], 3: [1, 2], 4: [2, 0]}
36_quad_to_vertex_map = {0: [0, 1], 1: [1, 2], 2: [2, 3], 3: [3, 0]}
37_hex_to_vertex_map = {
38 0: [0, 1, 4, 5],
39 1: [1, 2, 5, 6],
40 2: [2, 3, 6, 7],
41 3: [0, 3, 4, 7],
42 4: [0, 1, 2, 3],
43 5: [4, 5, 6, 7],
44}
46_side_set_to_vertex_map = {
47 "interval": _interval_to_vertex_map,
48 "quadrilateral": _quad_to_vertex_map,
49 "triangle": _triangle_to_vertex_map,
50 "tetrahedron": _tetra_facet_to_vertex_map,
51 "hexahedron": _hex_to_vertex_map,
52}
55# Exodus element names without their node count, e.g. "TETRA" for "TETRA10", and the DOLFINx
56# cell they describe. Names are case-insensitive. BAR, BEAM, EDGE and TRUSS are the same line
57# element; the name only tells analysis codes which physics to apply (e.g. a truss carries axial
58# load only, a beam also bends).
59_exodus_cell_types = {
60 "BAR": "interval",
61 "BEAM": "interval",
62 "EDGE": "interval",
63 "TRUSS": "interval",
64 "TRI": "triangle",
65 "TRIANGLE": "triangle",
66 "QUAD": "quadrilateral",
67 "TET": "tetrahedron",
68 "TETRA": "tetrahedron",
69 "HEX": "hexahedron",
70 "HEXAHEDRON": "hexahedron",
71 "WEDGE": "prism",
72}
74# Degree of the supported elements, by cell and number of nodes
75_degrees = {
76 ("interval", 2): 1,
77 ("interval", 3): 2,
78 ("triangle", 3): 1,
79 ("triangle", 6): 2,
80 ("quadrilateral", 4): 1,
81 ("quadrilateral", 8): 2,
82 ("quadrilateral", 9): 2,
83 ("tetrahedron", 4): 1,
84 ("tetrahedron", 10): 2,
85 ("hexahedron", 8): 1,
86 ("hexahedron", 20): 2,
87 ("hexahedron", 27): 2,
88 ("prism", 6): 1,
89}
91# The DOLFINx node of each HEX27 node, from Fig 4.14 of
92# https://sandialabs.github.io/seacas-docs/exodusII-new.pdf. Its face and edge nodes are not
93# numbered as in VTK. HEX20 has the first 20 nodes of HEX27.
94_hex27_exodus_to_dolfinx = np.array(
95 [
96 0,
97 1,
98 5,
99 4,
100 2,
101 3,
102 7,
103 6,
104 8,
105 12,
106 16,
107 10,
108 9,
109 11,
110 18,
111 17,
112 13,
113 15,
114 19,
115 14,
116 26,
117 21,
118 24,
119 22,
120 23,
121 20,
122 25,
123 ]
124)
126read_mode = ReadMode.serial
129def _get_cell_type(connectivity: netCDF4.Variable) -> tuple[dolfinx.mesh.CellType, int]:
130 name = re.sub(r"\d+$", "", connectivity.elem_type.upper())
131 num_nodes = connectivity.shape[1]
132 cell_type = _exodus_cell_types.get(name)
133 degree = _degrees.get((cell_type, num_nodes)) if cell_type is not None else None
134 if cell_type is None or degree is None:
135 raise NotImplementedError(
136 f"Exodus element {connectivity.elem_type} with {num_nodes} nodes is not supported."
137 )
138 return dolfinx.mesh.to_type(cell_type), degree
141def _dolfinx_node_order(cell_type: dolfinx.mesh.CellType, num_nodes: int) -> npt.NDArray[np.int32]:
142 """The position in an Exodus element of each node of the DOLFINx cell."""
143 if cell_type == dolfinx.mesh.CellType.hexahedron and num_nodes in (20, 27):
144 return np.argsort(_hex27_exodus_to_dolfinx[:num_nodes]).astype(np.int32)
145 # The other elements number their nodes as VTK does
146 return np.asarray(dolfinx.cpp.io.perm_vtk(cell_type, num_nodes), dtype=np.int32)
149def _side_nodes(
150 cell_type: dolfinx.mesh.CellType, num_nodes: int
151) -> dict[int, npt.NDArray[np.int32]]:
152 """The positions in a DOLFINx cell of the nodes on each Exodus side (0-based), vertices
153 first, as :func:`dolfinx.io.distribute_entity_data` expects."""
154 name = dolfinx.mesh.to_string(cell_type)
155 if name not in _side_set_to_vertex_map:
156 raise NotImplementedError(f"Side sets on {name} cells are not supported.")
157 serendipity = serendipity_num_nodes.get(name) == num_nodes
158 family = basix.ElementFamily.serendipity if serendipity else "Lagrange"
159 element = basix.ufl.element(family, name, _degrees[(name, num_nodes)])
160 tdim = dolfinx.mesh.cell_dim(cell_type)
161 facets = [set(f) for f in basix.topology(getattr(basix.CellType, name))[tdim - 1]]
162 # The DOLFINx vertex at each Exodus vertex
163 vertex = np.argsort(_dolfinx_node_order(cell_type, num_nodes))
164 nodes = {}
165 for side, exodus_vertices in _side_set_to_vertex_map[name].items():
166 facet = facets.index(set(vertex[exodus_vertices].tolist()))
167 # Closure dofs are sorted, so vertices come first
168 nodes[side] = np.asarray(element.entity_closure_dofs[tdim - 1][facet], dtype=np.int32)
169 return nodes
172def _compute_tdim(connectivity: netCDF4.Variable) -> int:
173 d_ct, _ = _get_cell_type(connectivity)
174 return dolfinx.mesh.cell_dim(d_ct)
177def get_default_backend_args(arguments: dict[str, Any] | None) -> dict[str, Any]:
178 args = arguments or {}
179 return args
182def convert_file_mode(mode: FileMode) -> str:
183 match mode:
184 case FileMode.append:
185 return "a"
186 case FileMode.read:
187 return "r"
188 case FileMode.write:
189 return "w"
190 case _:
191 raise NotImplementedError(f"File mode {mode} not implemented")
194def write_attributes(
195 filename: Path | str,
196 comm: MPI.Comm,
197 name: str,
198 attributes: dict[str, np.ndarray],
199 backend_args: dict[str, Any] | None = None,
200):
201 """Write attributes to file using H5PY.
203 Args:
204 filename: Path to file to write to
205 comm: MPI communicator used in storage
206 name: Name of the attributes
207 attributes: Dictionary of attributes to write to file
208 backend_args: Arguments to backend
209 """
210 raise NotImplementedError("The Exodus backend cannot write attributes.")
213def read_attributes(
214 filename: Path | str,
215 comm: MPI.Comm,
216 name: str,
217 backend_args: dict[str, Any] | None = None,
218) -> dict[str, Any]:
219 """Read attributes from file using H5PY.
221 Args:
222 filename: Path to file to read from
223 comm: MPI communicator used in storage
224 name: Name of the attributes
225 backend_args: Arguments to backend
226 Returns:
227 The attributes
228 """
229 raise NotImplementedError("The Exodus backend cannot read attributes.")
232def snapshot_checkpoint(
233 filename: Path | str,
234 mode: FileMode,
235 u: dolfinx.fem.Function,
236 backend_args: dict[str, Any] | None,
237):
238 """Create a snapshot checkpoint of a dolfinx function.
240 Args:
241 filename: Path to file to read from
242 mode: File-mode to store the function
243 u: dolfinx function to create a snapshot checkpoint for
244 backend_args: Arguments to backend
245 """
246 raise NotImplementedError("The EXODUS backend cannot make checkpoints.")
249def read_hdf5_array(
250 comm: MPI.Comm,
251 filename: Path | str,
252 group: str,
253 backend_args: dict[str, Any] | None,
254) -> tuple[np.ndarray, int]:
255 """Read an array from an HDF5 file.
257 Args:
258 comm: MPI communicator used in storage
259 filename: Path to file to read from
260 group: Group in HDF5 file where array is stored
261 backend_args: Arguments to backend
263 Returns:
264 Tuple containing:
265 - Numpy array read from file
266 - Global starting point on the process.
267 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
268 """
269 raise NotImplementedError("The EXODUS backend cannot read HDF5 arrays")
272def read_timestamps(
273 filename: Path | str,
274 comm: MPI.Comm,
275 function_name: str,
276 backend_args: dict[str, Any] | None = None,
277) -> npt.NDArray[np.float64 | str]: # type: ignore[type-var]
278 """Read time-stamps from a checkpoint file.
280 Args:
281 comm: MPI communicator
282 filename: Path to file
283 comm: MPI communicator
284 function_name: Name of the function to read time-stamps for
285 backend_args: Arguments for backend, for instance file type.
287 Returns:
288 The time-stamps
289 """
290 raise NotImplementedError("The Exodus backend cannot read timestamps.")
293def write_mesh(
294 filename: Path | str,
295 comm: MPI.Comm,
296 mesh: MeshData,
297 backend_args: dict[str, Any] | None = None,
298 mode: FileMode = FileMode.write,
299 time: float = 0.0,
300):
301 """Write a mesh to file using H5PY
303 Args:
304 filename: Path to file to write to.
305 mesh: Internal data structure for the mesh data to save to file
306 comm: MPI communicator used in storage
307 backend_args: Arguments to backend
308 mode: Mode to use (write or append)
309 time: Time stamp
310 """
311 raise NotImplementedError("The Exodus backend cannot write meshes.")
314def _read_mesh_geometry(infile: netCDF4.Dataset) -> tuple[int, npt.NDArray[np.floating]]:
315 # use page 171 of manual to extract data
316 num_nodes = infile.dimensions["num_nodes"].size
317 gdim = infile.dimensions["num_dim"].size
319 # Get coordinates of mesh
320 coord_var = infile.variables.get("coord")
321 if coord_var is None:
322 coordinates = np.zeros((num_nodes, gdim), dtype=np.float64)
323 for i, coord in enumerate(["x", "y", "z"]):
324 coord_i = infile.variables.get(f"coord{coord}")
325 if coord_i is not None:
326 coordinates[: coord_i.size, i] = coord_i[:]
327 else:
328 coordinates = np.asarray(coord_var)
329 return gdim, coordinates
332def _get_entity_blocks(
333 infile: netCDF4.Dataset, search_type: Literal["cell", "facet"]
334) -> tuple[int, list[netCDF4.Variable]]:
335 # use page 171 of manual to extract data
336 num_blocks = infile.dimensions["num_el_blk"].size
338 # Get element connectivity
339 all_connectivity_variables = [infile.variables[f"connect{i + 1}"] for i in range(num_blocks)]
341 # Compute max topological dimension in mesh and find the correct
342 max_tdim = _compute_tdim(max(all_connectivity_variables, key=_compute_tdim))
344 # Extract only the connectivity blocks that we need
345 if search_type == "cell":
346 search_dim = max_tdim
347 elif search_type == "facet":
348 search_dim = max_tdim - 1
349 else:
350 raise RuntimeError(f"Unknown entity type: {search_type}")
351 return search_dim, list(
352 filter(lambda el: _compute_tdim(el) == search_dim, all_connectivity_variables)
353 )
356def _extract_connectivity_data(
357 entity_blocks: list[netCDF4.Variable],
358) -> tuple[list[npt.NDArray[np.int64]], tuple[dolfinx.mesh.CellType, int], list[int]]:
359 connectivity_arrays = []
360 cell_types = []
361 entity_block_index = []
362 for entity_block in entity_blocks:
363 connectivity_arrays.append(entity_block[:] - 1)
364 cell_types.append(_get_cell_type(entity_block))
365 entity_block_index.append(int(entity_block.name.removeprefix("connect")) - 1)
366 for cell in cell_types:
367 assert cell_types[0] == cell, "Mixed cell types not supported"
368 cell_type = cell_types[0]
369 return connectivity_arrays, cell_type, entity_block_index
372def read_mesh_data(
373 filename: Path | str,
374 comm: MPI.Comm,
375 time: str | float | None = 0.0,
376 read_from_partition: bool = False,
377 backend_args: dict[str, Any] | None = None,
378) -> ReadMeshData:
379 """Read mesh data from EXODUS based checkpoint files.
381 Args:
382 filename: Path to input file
383 comm: The MPI communciator to distribute the mesh over
384 time: Time stamp associated with mesh
385 read_from_partition: Read mesh with partition from file
386 backend_args: Arguments to backend
387 Returns:
388 The mesh topology, geometry, UFL domain and partition function
389 """
390 check_file_exists(filename)
391 with netCDF4.Dataset(filename, "r") as infile:
392 if comm.rank == 0:
393 gdim, coordinates = _read_mesh_geometry(infile)
395 _tdim, entity_blocks = _get_entity_blocks(infile, "cell")
396 if len(entity_blocks) > 0:
397 # Extract markers directly from entity-blocks
398 connectivity_arrays, (cell_type, degree), _entity_block_index = (
399 _extract_connectivity_data(entity_blocks)
400 )
402 cells = np.vstack(connectivity_arrays)
403 if isinstance(cells, np.ma.MaskedArray):
404 cells = cells.filled()
405 else:
406 raise ValueError(f"No blocks found in {filename}")
408 perm = _dolfinx_node_order(cell_type, cells.shape[1])
409 cells = cells[:, perm]
410 cell_type, gdim, xtype, degree, num_dofs_per_cell = comm.bcast(
411 (cell_type, gdim, np.dtype(coordinates.dtype).name, degree, cells.shape[1]), root=0
412 )
414 else:
415 cell_type, gdim, xtype, degree, num_dofs_per_cell = comm.bcast(
416 (None, None, None, None), root=0
417 )
418 coordinates = np.zeros((0, gdim), dtype=xtype)
419 cells = np.zeros((0, num_dofs_per_cell), dtype=np.int64)
420 return ReadMeshData(
421 cells=cells,
422 cell_type=dolfinx.mesh.to_string(cell_type),
423 x=coordinates,
424 lvar=int(basix.LagrangeVariant.equispaced),
425 degree=degree,
426 partition_graph=None,
427 serendipity=serendipity_num_nodes.get(dolfinx.mesh.to_string(cell_type))
428 == num_dofs_per_cell,
429 )
432def write_meshtags(
433 filename: str | Path,
434 comm: MPI.Comm,
435 data: MeshTagsData,
436 backend_args: dict[str, Any] | None = None,
437):
438 """Write mesh tags to file.
440 Args:
441 filename: Path to file to write to
442 comm: MPI communicator used in storage
443 data: Internal data structure for the mesh tags to save to file
444 backend_args: Arguments to backend
445 """
446 raise NotImplementedError("The Exodus backend cannot write meshtags.")
449def read_meshtags_data(
450 filename: str | Path,
451 comm: MPI.Comm,
452 name: str,
453 backend_args: dict[str, Any] | None = None,
454) -> MeshTagsData:
455 """Read mesh tags from file.
457 Args:
458 filename: Path to file to read from
459 comm: MPI communicator used in storage
460 name: Name of the mesh tags to read
461 backend_args: Arguments to backend.
463 Returns:
464 Internal data structure for the mesh tags read from file
465 """
466 if comm.rank == 0:
467 with netCDF4.Dataset(filename, "r") as infile:
468 # Compute max topological dimension in mesh and find the correct
469 if name == "cell" or name == "facet":
470 search_dim, entity_blocks = _get_entity_blocks(
471 infile, cast(Literal["cell", "facet"], name)
472 )
473 else:
474 raise RuntimeError("Expected name='cell' or 'facet' got {name}")
476 if len(entity_blocks) > 0:
477 # Extract markers directly from entity-blocks
478 connectivity_arrays, (cell_type, degree), entity_block_index = (
479 _extract_connectivity_data(entity_blocks)
480 )
481 marked_entities = np.vstack(connectivity_arrays)
482 entity_values = np.zeros(marked_entities.shape[0], dtype=np.int64)
483 if "eb_prop1" in infile.variables.keys():
484 block_values = infile.variables["eb_prop1"][:]
486 # First check if entities are in eb_prop1
487 insert_offset = np.zeros(len(connectivity_arrays) + 1, dtype=np.int64)
488 insert_offset[1:] = np.cumsum([c_arr.shape[0] for c_arr in connectivity_arrays])
489 for i, index in enumerate(entity_block_index):
490 entity_values[insert_offset[i] : insert_offset[i + 1]] = block_values[index]
491 else:
492 num_dofs_per_cell = basix.ufl.element(
493 "Lagrange", dolfinx.mesh.to_string(cell_type), degree
494 ).dim
495 assert num_dofs_per_cell == marked_entities.shape[1]
496 marked_entities = np.zeros((0, marked_entities.shape[1]), dtype=np.int64)
497 entity_values = np.zeros(0, dtype=np.int64)
498 elif name == "facet" and "ss_prop1" in infile.variables.keys():
499 # If we haven't found the cell type as a block, we should be extracting facets
500 # (from side-sets), then we need the parent cell
501 tdim, entity_blocks = _get_entity_blocks(infile, "cell")
502 cell_types = []
503 for entity_block in entity_blocks:
504 cell_types.append(_get_cell_type(entity_block))
505 for cell in cell_types:
506 assert cell_types[0] == cell, "Mixed cell types not supported"
507 cell_type, degree = cell_types[0]
508 if "num_side_sets" not in infile.dimensions:
509 facet_type = dolfinx.cpp.mesh.cell_entity_type(cell_type, tdim - 1, 0)
510 num_dofs_per_cell = basix.ufl.element(
511 "Lagrange", dolfinx.mesh.to_string(facet_type), degree
512 ).dim
513 marked_entities = np.zeros((0, num_dofs_per_cell), dtype=np.int64)
514 entity_values = np.zeros(0, dtype=np.int64)
515 else:
516 # Extract facet values
517 num_facet_sets = infile.dimensions["num_side_sets"].size
518 values = infile.variables["ss_prop1"]
519 # Extract all cell blocks to get correct look-up
520 connectivity_arrays = []
521 for entity_block in entity_blocks:
522 connectivity_arrays.append(entity_block[:] - 1)
523 connectivity_array = np.vstack(connectivity_arrays)
524 connectivity_array = connectivity_array[
525 :, _dolfinx_node_order(cell_type, connectivity_array.shape[1])
526 ]
527 side_nodes = _side_nodes(cell_type, connectivity_array.shape[1])
529 # Loop through all side sets to extract the correct connectivity
530 facet_indices = []
531 facet_values = []
532 for i in range(num_facet_sets):
533 value = values[i].reshape(-1)
534 elements = infile.variables[f"elem_ss{i + 1}"]
535 local_facets = infile.variables[f"side_ss{i + 1}"]
536 for element, index in zip(elements, local_facets):
537 facet_indices.append(
538 connectivity_array[element - 1, side_nodes[index - 1]]
539 )
540 facet_values.append(value.data.tolist())
541 marked_entities = np.vstack(facet_indices)
542 entity_values = np.array(facet_values, dtype=np.int64).flatten()
543 else:
544 # If we found no blocks (for instance for facets, we search through the cells)
545 tdim, entity_blocks = _get_entity_blocks(infile, "cell")
546 search_dim = tdim - 1 if name == "facet" else tdim
547 cell_type, degree = _get_cell_type(entity_blocks[0])
548 facet_type = dolfinx.cpp.mesh.cell_entity_type(cell_type, search_dim, 0)
549 num_dofs_per_cell = basix.ufl.element(
550 "Lagrange", dolfinx.mesh.to_string(facet_type), degree
551 ).dim
552 # If we cannot find any information about the blocks we send nothing
553 marked_entities = np.zeros((0, num_dofs_per_cell), dtype=np.int64)
554 entity_values = np.zeros(0, dtype=np.int64)
555 # Broadcast information read by this process to other processes
556 (dim, _, _) = comm.bcast(
557 (search_dim, marked_entities.shape[1], np.dtype(entity_values.dtype).name),
558 root=0,
559 )
561 else:
562 # Other process gets info from process that read the file
563 dim, num_dofs_per_cell, vtype = comm.bcast((None, None, None), root=0)
564 marked_entities = np.zeros((0, num_dofs_per_cell), dtype=np.int64)
565 entity_values = np.zeros(0, dtype=vtype)
566 return MeshTagsData(name=name, values=entity_values, indices=marked_entities, dim=dim)
569def read_dofmap(
570 filename: str | Path,
571 comm: MPI.Comm,
572 name: str,
573 backend_args: dict[str, Any] | None,
574) -> dolfinx.graph.AdjacencyList:
575 """Read the dofmap of a function with a given name.
577 Args:
578 filename: Path to file to read from
579 comm: MPI communicator used in storage
580 name: Name of the function to read the dofmap for
581 backend_args: Arguments to backend
583 Returns:
584 Dofmap as an :class:`dolfinx.graph.AdjacencyList`
585 """
586 raise NotImplementedError("The Exodus backend cannot read dofmap.")
589def read_dofs(
590 filename: str | Path,
591 comm: MPI.Comm,
592 name: str,
593 time: float,
594 backend_args: dict[str, Any] | None,
595) -> tuple[npt.NDArray[np.float32 | np.float64 | np.complex64 | np.complex128], int]:
596 """Read the dofs (values) of a function with a given name from a given timestep.
598 Args:
599 filename: Path to file to read from
600 comm: MPI communicator used in storage
601 name: Name of the function to read the dofs for
602 time: Time stamp associated with the function to read
603 backend_args: Arguments to backend
605 Returns:
606 Contiguous sequence of degrees of freedom (with respect to input data)
607 and the global starting point on the process.
608 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
609 """
610 raise NotImplementedError("The Exodus backend cannot read dofs.")
613def read_cell_perms(
614 comm: MPI.Comm, filename: Path | str, backend_args: dict[str, Any] | None
615) -> npt.NDArray[np.uint32]:
616 """
617 Read cell permutation from file with given communicator,
618 Split in continuous chunks based on number of cells in the input data.
620 Args:
621 comm: MPI communicator used in storage
622 filename: Path to file to read from
623 backend_args: Arguments to backend
625 Returns:
626 Contiguous sequence of permutations (with respect to input data)
627 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
628 """
630 raise NotImplementedError("The Exodus backend cannot read cell perms.")
633def write_function(
634 filename: str | Path,
635 comm: MPI.Comm,
636 u: FunctionData,
637 time: float,
638 mode: FileMode,
639 backend_args: dict[str, Any] | None = None,
640):
641 """Write a function to file.
643 Args:
644 filename: Path to file to write to
645 comm: MPI communicator used in storage
646 u: Internal data structure for the function data to save to file
647 time: Time stamp associated with function
648 mode: File-mode to store the function
649 backend_args: Arguments to backend
650 """
652 raise NotImplementedError("The Exodus backend cannot write function.")
655def read_legacy_mesh(
656 filename: Path | str, comm: MPI.Comm, group: str
657) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.floating], str | None]:
658 """Read in the mesh topology, geometry and (optionally) cell type from a
659 legacy DOLFIN HDF5-file.
661 Args:
662 filename: Path to file to read from
663 comm: MPI communicator used in storage
664 group: Group in HDF5 file where mesh is stored
666 Returns:
667 Tuple containing:
668 - Topology as a (num_cells, num_vertices_per_cell) array of global vertex indices
669 - Geometry as a (num_vertices, geometric_dimension) array of vertex coordinates
670 - Cell type as a string (e.g. "tetrahedron") or None if not found
671 """
672 raise NotImplementedError("The Exodus backend cannot read legacy mesh.")
675def read_point_data(
676 filename: Path | str,
677 name: str,
678 comm: MPI.Comm,
679 time: float | str | None,
680 backend_args: dict[str, Any] | None,
681) -> tuple[np.ndarray, int]:
682 """Read data from the nodes of a mesh.
684 Args:
685 filename: Path to file
686 name: Name of point data
687 comm: Communicator to launch IO on.
688 time: The time stamp
689 backend_args: The backend arguments
691 Returns:
692 Data local to process (contiguous, no mpi comm) and local start range
693 """
694 num_components = 1 # Default assumption, overriden by data read in having multiple components
695 if comm.rank == 0:
696 with netCDF4.Dataset(filename, "r") as infile:
697 raw_names = infile.variables["name_nod_var"][:].data
698 node_names = netCDF4.chartostring(raw_names)
699 if name not in node_names:
700 raise ValueError(
701 f"Point data with name {name} not found in file.",
702 f"Available variables: {node_names}",
703 )
704 index = np.flatnonzero(name == node_names)[0] + 1
706 temporal_dataset = infile.variables[f"vals_nod_var{index}"]
707 time_steps = infile.variables["time_whole"][:].data
708 if time is None:
709 time_idx = time_steps[0]
710 else:
711 time_indices = np.flatnonzero(np.isclose(time_steps, time))
712 if len(time_indices) == 0:
713 raise ValueError(
714 f"Could not find {name}(t={time}), available time steps are {time_steps}"
715 )
716 time_idx = time_indices[0]
718 dataset = temporal_dataset[time_idx]
719 if len(dataset.shape) == 1:
720 dataset = dataset.reshape(-1, num_components)
721 else:
722 num_components = dataset.shape[1]
723 # Broadcast num components to all other ranks
724 num_components = comm.bcast(num_components, root=0)
725 # Zero data on all other processes
726 if comm.rank != 0:
727 dataset = np.zeros((0, num_components), dtype=np.float64)
728 return dataset, 0
731def read_cell_data(
732 filename: Path | str,
733 name: str,
734 comm: MPI.Comm,
735 time: str | float | None,
736 backend_args: dict[str, Any] | None,
737) -> tuple[npt.NDArray[np.int64], np.ndarray]:
738 """Read data from the cells of a mesh.
740 Args:
741 filename: Path to file
742 name: Name of point data
743 comm: Communicator to launch IO on.
744 time: The time stamp
745 backend_args: The backend arguments
746 Returns:
747 A tuple (topology, dofs) where topology contains the
748 vertex indices of the cells, dofs the degrees of
749 freedom within that cell.
750 """
751 num_components = 1 # Default assumption, overriden by data read in having multiple components
752 if comm.rank == 0:
753 with netCDF4.Dataset(filename, "r") as infile:
754 raw_names = infile.variables["name_elem_var"][:].data
755 num_blocks = infile.dimensions["num_el_blk"].size
757 node_names = netCDF4.chartostring(raw_names)
758 if name not in node_names:
759 raise ValueError(
760 f"Cell data with name {name} not found in file.",
761 f"Available variables: {node_names}",
762 )
763 index = np.flatnonzero(name == node_names)[0] + 1
765 entity_blocks = [
766 infile.variables[f"vals_elem_var{index}eb{i + 1}"] for i in range(num_blocks)
767 ]
768 time_steps = infile.variables["time_whole"][:].data
769 if time is None:
770 time_idx = time_steps[0]
771 else:
772 time_indices = np.flatnonzero(np.isclose(time_steps, time))
773 if len(time_indices) == 0:
774 raise ValueError(
775 f"Could not find {name}(t={time}), available time steps are {time_steps}"
776 )
777 time_idx = time_indices[0]
779 if len(entity_blocks) > 0:
780 datasets = []
781 for entity_block in entity_blocks:
782 datasets.append(entity_block[time_idx])
784 dataset = np.hstack(datasets)
786 if len(dataset.shape) == 1:
787 dataset = dataset.reshape(-1, num_components)
788 else:
789 num_components = dataset.shape[1]
790 # Broadcast num components to all other ranks
791 num_components = comm.bcast(num_components, root=0)
793 # Zero data on all other processes
794 if comm.rank != 0:
795 dataset = np.zeros((0, num_components), dtype=np.float64)
796 _time = float(time) if time is not None else None
798 topology = read_mesh_data(filename, comm, _time, False, backend_args=None).cells
799 return topology, dataset
802def read_function_names(
803 filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None
804) -> list[str]:
805 """Read all function names from a file.
807 Args:
808 filename: Path to file
809 comm: MPI communicator to launch IO on.
810 backend_args: Arguments to backend
812 Returns:
813 A list of function names.
814 """
815 with netCDF4.Dataset(filename, "r") as infile:
816 function_names: list[str] = []
817 for key in ["name_elem_var", "name_nod_var"]:
818 raw_names = infile.variables[key][:].data
819 decoded_names = netCDF4.chartostring(raw_names)
820 function_names.extend(decoded_names)
821 return function_names
824def write_data(
825 filename: Path | str,
826 array_data: ArrayData,
827 comm: MPI.Comm,
828 time: str | float | None,
829 mode: FileMode,
830 backend_args: dict[str, Any] | None,
831):
832 """Write a 2D-array to file (distributed across proceses with MPI).
834 Args:
835 filename: Path to file
836 array_data: Data to write to file
837 comm: MPI communicator to open the file with
838 time: Time-stamp for data.
839 mode: Append or write
840 backend_args: The backend arguments
841 """
842 raise NotImplementedError("Exodus has not implemented this yet")