Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/openfoam/backend.py: 94%
167 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"""
2OpenFOAM interface to io4dolfinx.
4Reads the mesh, fields, boundary patches and zones of an OpenFOAM case through the
5VTK OpenFOAM reader of `pyvista <https://pyvista.org>`_. The file is the ``.foam`` file
6in the case directory (create it with ``touch case.foam``). All file access happens on
7rank 0.
9- The cells are the cells of the internal mesh. Hexahedra, prisms, pyramids and
10 tetrahedra are supported; meshes with several of them are read as mixed meshes.
11 Polyhedra are not supported, as DOLFINx has no polyhedral cells.
12- Cell-centred fields (``vol*Field``) are read with :func:`read_cell_data`, and point
13 fields (``point*Field``) with :func:`read_point_data`. Fields are not interpolated
14 between the two.
15- Boundary patches and cell, face and point zones are read from the ``polyMesh`` files
16 by their labels, see :func:`read_meshtags_data`.
17- The regions of a multi-region case are merged into one mesh, joined where their
18 points coincide exactly, unless one region is selected with the ``region`` backend
19 argument.
21VTK reads points and fields in single precision. They are returned in the ``dtype``
22backend argument, by default :data:`dolfinx.default_real_type`.
24SPDX License identifier: MIT
26Copyright: Jørgen S. Dokken and Simula Research Laboratory
27"""
29from pathlib import Path
30from typing import Any
32from mpi4py import MPI
34import basix
35import dolfinx
36import numpy as np
37import numpy.typing as npt
39try:
40 import pyvista
41except ImportError:
42 raise ModuleNotFoundError("The openfoam-backend requires pyvista")
44from ...comm_helpers import run_on_root_and_share
45from ...structures import (
46 ArrayData,
47 FunctionData,
48 MeshData,
49 MeshTagsData,
50 ReadMeshData,
51 ReadMixedMeshData,
52)
53from ...utils import check_file_exists, codim_names
54from .. import FileMode, ReadMode
55from . import helpers
57read_mode = ReadMode.serial
60def get_default_backend_args(arguments: dict[str, Any] | None) -> dict[str, Any]:
61 """Get default backend arguments given a set of input arguments.
63 Args:
64 arguments: Input backend arguments
66 Returns:
67 The arguments, with defaults for:
68 - ``"dtype"``: Floating point type of the points and fields returned,
69 :data:`dolfinx.default_real_type`. VTK reads them in single precision.
70 - ``"region"``: Region of a multi-region case to read, ``""`` for the
71 default region. ``None`` (default) merges all regions into one mesh.
72 """
73 args: dict[str, Any] = {"dtype": dolfinx.default_real_type, "region": None}
74 args.update(arguments or {})
75 return args
78def read_mesh_data(
79 filename: Path | str,
80 comm: MPI.Comm,
81 time: str | float | None = None,
82 read_from_partition: bool = False,
83 backend_args: dict[str, Any] | None = None,
84) -> ReadMeshData | ReadMixedMeshData:
85 """Read the internal mesh of an OpenFOAM case.
87 Input node ``i`` and cell ``i`` are OpenFOAM point and cell label ``i`` for a single
88 region. Several regions are merged: their cells follow each other in region order,
89 and the points are joined where they coincide. A mesh with several cell types is read
90 as a mixed mesh, with its cells grouped by type.
92 Args:
93 filename: Path to the ``.foam`` file of the case
94 comm: MPI communicator to distribute the mesh over
95 time: Time step of the mesh, the first one if ``None``
96 read_from_partition: Read mesh with partition from file (not supported)
97 backend_args: Arguments to backend, see :func:`get_default_backend_args`
99 Returns:
100 Internal data structure for the mesh data read from file
101 """
102 if read_from_partition:
103 raise NotImplementedError("The openfoam backend cannot read partitioning data.")
104 check_file_exists(filename)
105 backend_args = get_default_backend_args(backend_args)
107 def read() -> tuple[
108 tuple[np.ndarray, list[npt.NDArray[np.int64]]], tuple[list[str], list[int], int]
109 ]:
110 case = helpers.read_case(filename, time, backend_args["region"])
111 types = case.cell_types
112 blocks = [case.cells[t] for t in types]
113 return (case.points, blocks), (types, [b.shape[1] for b in blocks], case.points.shape[1])
115 local, (cell_types, num_nodes, gdim) = run_on_root_and_share(comm, read)
116 if local is None:
117 x = np.zeros((0, gdim))
118 cells = [np.zeros((0, n), dtype=np.int64) for n in num_nodes]
119 else:
120 x, cells = local
121 x = x.astype(backend_args["dtype"])
122 lvar = int(basix.LagrangeVariant.equispaced)
123 if len(cell_types) == 1:
124 return ReadMeshData(cells=cells[0], cell_type=cell_types[0], x=x, lvar=lvar, degree=1)
125 return ReadMixedMeshData(cells=cells, cell_types=cell_types, x=x, lvar=lvar, degree=1)
128def read_point_data(
129 filename: Path | str,
130 name: str,
131 comm: MPI.Comm,
132 time: float | str | None,
133 backend_args: dict[str, Any] | None,
134) -> tuple[np.ndarray, int]:
135 """Read an OpenFOAM point field (``point*Field``).
137 Cell-centred fields are not interpolated to the points; read them with
138 :func:`read_cell_data`. Only meshes of one region and one cell type are supported.
140 Args:
141 filename: Path to the ``.foam`` file of the case
142 name: Name of the field
143 comm: Communicator to launch IO on.
144 time: The time step, the first one if ``None``
145 backend_args: The backend arguments, see :func:`get_default_backend_args`
147 Returns:
148 The values at the points, of shape ``(num_points, num_components)``, on rank 0,
149 and the global start of the data on this process, ``0``
150 """
151 check_file_exists(filename)
152 backend_args = get_default_backend_args(backend_args)
154 def read() -> tuple[np.ndarray, int]:
155 case = helpers.read_case(filename, time, backend_args["region"], point_fields=[name])
156 if len(case.regions) > 1:
157 raise NotImplementedError(
158 f"Point data of a case with several regions {case.regions} is not "
159 "supported. Select a region with backend_args={'region': name}."
160 )
161 case.get_single_type_cells("Reading point data")
162 values = case.point_data[name]
163 return values, values.shape[1]
165 values, num_components = run_on_root_and_share(comm, read)
166 if values is None:
167 values = np.zeros((0, num_components))
168 return values.astype(backend_args["dtype"]), 0
171def read_cell_data(
172 filename: Path | str,
173 name: str,
174 comm: MPI.Comm,
175 time: str | float | None,
176 backend_args: dict[str, Any] | None,
177) -> tuple[npt.NDArray[np.int64], np.ndarray]:
178 """Read a cell-centred OpenFOAM field (``vol*Field``).
180 For several regions, the field must exist in every region. Only meshes of one cell
181 type are supported.
183 Args:
184 filename: Path to the ``.foam`` file of the case
185 name: Name of the field
186 comm: Communicator to launch IO on.
187 time: The time step, the first one if ``None``
188 backend_args: The backend arguments, see :func:`get_default_backend_args`
190 Returns:
191 A tuple (topology, values), where topology holds the input node indices of each
192 cell on rank 0, and values the value of each cell
193 """
194 check_file_exists(filename)
195 backend_args = get_default_backend_args(backend_args)
197 def read() -> tuple[tuple[npt.NDArray[np.int64], np.ndarray], tuple[int, int]]:
198 case = helpers.read_case(filename, time, backend_args["region"], cell_fields=[name])
199 cells = case.get_single_type_cells("Reading cell data")
200 values = case.cell_data[name]
201 return (cells, values), (cells.shape[1], values.shape[1])
203 local, (num_nodes, num_components) = run_on_root_and_share(comm, read)
204 if local is None:
205 local = (np.zeros((0, num_nodes), dtype=np.int64), np.zeros((0, num_components)))
206 cells, values = local
207 return cells, values.astype(backend_args["dtype"])
210def read_timestamps(
211 filename: Path | str,
212 comm: MPI.Comm,
213 function_name: str,
214 backend_args: dict[str, Any] | None,
215) -> npt.NDArray[np.float64 | str]: # type: ignore[type-var]
216 """Read the time steps at which a field exists, in every region read.
218 Args:
219 filename: Path to the ``.foam`` file of the case
220 comm: MPI communicator used in storage
221 function_name: Name of the field
222 backend_args: Arguments to backend, see :func:`get_default_backend_args`
224 Returns:
225 The time steps, in increasing order
226 """
227 check_file_exists(filename)
228 backend_args = get_default_backend_args(backend_args)
230 def read() -> tuple[None, list[float]]:
231 reader = pyvista.POpenFOAMReader(str(filename))
232 time_names = reader.reader.GetTimeNames()
233 names = [time_names.GetValue(i) for i in range(time_names.GetNumberOfValues())]
234 regions = helpers.get_regions(reader, backend_args["region"])
235 case_dir = Path(filename).parent
236 times = [
237 float(t)
238 for t, n in zip(reader.time_values, names)
239 if all(helpers.field_exists(case_dir, n, r, function_name) for r in regions)
240 ]
241 return None, times
243 _, times = run_on_root_and_share(comm, read)
244 return np.array(times, dtype=np.float64)
247def read_function_names(
248 filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None
249) -> list[str]:
250 """Read the names of the cell and point fields of a case.
252 Args:
253 filename: Path to the ``.foam`` file of the case
254 comm: MPI communicator to launch IO on.
255 backend_args: Arguments to backend
257 Returns:
258 The names of the cell fields, then of the point fields
259 """
260 check_file_exists(filename)
262 def read() -> tuple[None, list[str]]:
263 reader = pyvista.POpenFOAMReader(str(filename))
264 names = list(reader.cell_array_names) + list(reader.point_array_names)
265 return None, list(dict.fromkeys(names))
267 return run_on_root_and_share(comm, read)[1]
270def _tag_sets(case: helpers.Case, dim: int) -> list[tuple[str, Any]]:
271 """The named sets of entities of a dimension, in id order: cell zones for cells, the
272 boundary patches and then face zones for facets, and point zones for vertices."""
273 tdim = dolfinx.mesh.cell_dim(dolfinx.mesh.to_type(case.cell_types[0]))
274 if dim == tdim:
275 return list(case.cell_zones.items())
276 if dim == tdim - 1:
277 return [(p.name, p.faces) for p in case.patches] + list(case.face_zones.items())
278 if dim == 0:
279 return list(case.point_zones.items())
280 return []
283def read_meshtags_data(
284 filename: Path | str,
285 comm: MPI.Comm,
286 name: str,
287 backend_args: dict[str, Any] | None = None,
288) -> MeshTagsData:
289 """Read the zones, boundary patches or regions of a case as mesh tags.
291 Zones and patches are read from the ``polyMesh`` files (``boundary``, ``faces``,
292 ``cellZones``, ``faceZones``, ``pointZones``) by their labels. In a case with several
293 regions, their names are ``"<region>/<name>"``. Ids are numbered from 1 for each
294 dimension, in the order below and of the files, and :func:`read_ids` lists them.
296 Args:
297 filename: Path to the ``.foam`` file of the case
298 comm: MPI communicator
299 name: One of:
301 - ``"cell"``: the cells of all cell zones.
302 - ``"facet"``: the facets of all boundary patches, then of all face zones.
303 - ``"peak"``: the vertices of all point zones (vertices are the peaks of a 3D
304 mesh, as in :func:`dolfinx.io.gmsh.model_to_mesh`).
305 - ``"regions"``: all cells, tagged with the region id.
306 - The name of a single patch or zone.
308 The sets combined must not overlap, as a mesh tag holds one value per entity,
309 except for the two interface patches of neighbouring regions, which hold the
310 same facets: those are tagged with the first.
312 backend_args: Arguments to backend, see :func:`get_default_backend_args`
314 Returns:
315 Internal data structure for the mesh tags read from file, on rank 0
317 Raises:
318 KeyError: For an unknown name.
319 ValueError: If the sets combined overlap.
320 NotImplementedError: On a mesh with several cell types, and for facets on a
321 mesh of prisms or pyramids, as mesh tags hold entities of one type.
322 """
323 check_file_exists(filename)
324 backend_args = get_default_backend_args(backend_args)
326 def read() -> tuple[tuple[npt.NDArray[np.int64], npt.NDArray[np.int32]], tuple[int, int]]:
327 case = helpers.read_case(filename, None, backend_args["region"])
328 cells = case.get_single_type_cells("Reading mesh tags")
329 cell_type = case.cell_types[0]
330 tdim = dolfinx.mesh.cell_dim(dolfinx.mesh.to_type(cell_type))
331 if name == "regions":
332 region_ids = np.repeat(np.arange(1, len(case.regions) + 1), np.diff(case.cell_offsets))
333 return (cells, region_ids.astype(np.int32)), (tdim, cells.shape[1])
335 # The dimension of the tags, and the sets of that dimension to tag, with their ids
336 if name in codim_names:
337 dim = tdim - codim_names[name]
338 selected = [(i + 1, n, e) for i, (n, e) in enumerate(_tag_sets(case, dim))]
339 else:
340 matches = [
341 (d, i + 1, n, e)
342 for d in (tdim, 0, tdim - 1)
343 for i, (n, e) in enumerate(_tag_sets(case, d))
344 if n == name
345 ]
346 if len(matches) == 0:
347 names = [n for d in (tdim, tdim - 1, 0) for n, _ in _tag_sets(case, d)]
348 raise KeyError(
349 f"Unknown mesh tags '{name}' in {filename}. Expected 'cell', 'facet', "
350 f"'peak', 'regions' or one of {names}."
351 )
352 if len({d for d, *_ in matches}) > 1:
353 raise ValueError(f"'{name}' names zones of several dimensions in {filename}.")
354 dim = matches[0][0]
355 selected = [(i, n, e) for _, i, n, e in matches]
356 if dim == tdim - 1 and cell_type in ("prism", "pyramid"):
357 raise NotImplementedError(
358 f"Facet tags on {cell_type} meshes are not supported, as their facets are "
359 "of two types (triangles and quadrilaterals)."
360 )
362 # Combine the sets, one value per entity. Interface patches between regions hold
363 # the same facets, which are tagged once; any other overlap is an error.
364 interfaces: set[frozenset[str]] = set()
365 if dim == tdim - 1:
366 interfaces = {frozenset(pair) for pair in case.get_interfaces(case.patches)}
367 owner: dict[Any, str] = {}
368 entities: list[npt.NDArray[np.int64]] = []
369 values: list[int] = []
370 for value, set_name, members in selected:
371 for entity in members:
372 entity = np.atleast_1d(entity)
373 key = tuple(sorted(entity.tolist()))
374 if (other := owner.get(key)) is not None:
375 if frozenset((other, set_name)) in interfaces:
376 continue
377 raise ValueError(
378 f"'{other}' and '{set_name}' share entities in {filename}, but mesh "
379 "tags hold one value per entity. Read them one at a time by name."
380 )
381 owner[key] = set_name
382 entities.append(entity)
383 values.append(value)
385 if dim == tdim:
386 indices = cells[np.array([e[0] for e in entities], dtype=np.int64)]
387 else:
388 if len({len(e) for e in entities}) > 1:
389 raise NotImplementedError(
390 f"The entities of '{name}' are of several types; mesh tags of several "
391 "entity types are not supported."
392 )
393 num_nodes = len(entities[0]) if entities else (1 if dim == 0 else dim + 1)
394 indices = np.array(entities, dtype=np.int64).reshape(-1, num_nodes)
395 return (indices, np.array(values, dtype=np.int32)), (dim, int(indices.shape[1]))
397 local, (dim, num_nodes) = run_on_root_and_share(comm, read)
398 if local is None:
399 local = (np.zeros((0, num_nodes), dtype=np.int64), np.zeros(0, dtype=np.int32))
400 return MeshTagsData(name=name, values=local[1], indices=local[0], dim=dim)
403def read_ids(
404 filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None = None
405) -> dict[str, dict[str, int]]:
406 """The ids of the zones, patches and regions of a case, as tagged by
407 :func:`read_meshtags_data`.
409 Args:
410 filename: Path to the ``.foam`` file of the case
411 comm: MPI communicator
412 backend_args: Arguments to backend, see :func:`get_default_backend_args`
414 Returns:
415 Map from ``"cell"`` (cell zones), ``"facet"`` (boundary patches, then face zones),
416 ``"peak"`` (point zones) and ``"regions"`` to a map from each name to its id
417 """
418 check_file_exists(filename)
419 backend_args = get_default_backend_args(backend_args)
421 def read() -> tuple[None, dict[str, dict[str, int]]]:
422 case = helpers.read_case(filename, None, backend_args["region"])
423 tdim = dolfinx.mesh.cell_dim(dolfinx.mesh.to_type(case.cell_types[0]))
424 ids = {
425 key: {n: i + 1 for i, (n, _) in enumerate(_tag_sets(case, tdim - codim))}
426 for key, codim in codim_names.items()
427 if tdim - codim in (tdim, tdim - 1, 0)
428 }
429 ids["regions"] = {r: i + 1 for i, r in enumerate(case.regions)}
430 return None, ids
432 return run_on_root_and_share(comm, read)[1]
435def write_attributes(
436 filename: Path | str,
437 comm: MPI.Comm,
438 name: str,
439 attributes: dict[str, np.ndarray],
440 backend_args: dict[str, Any] | None,
441):
442 """Write attributes to file.
444 Args:
445 filename: Path to file to write to
446 comm: MPI communicator used in storage
447 name: Name of the attribute group
448 attributes: Dictionary of attributes to write
449 backend_args: Arguments to backend
450 """
451 raise NotImplementedError("The openfoam backend cannot write attributes.")
454def read_attributes(
455 filename: Path | str,
456 comm: MPI.Comm,
457 name: str,
458 backend_args: dict[str, Any] | None,
459) -> dict[str, Any]:
460 """Read attributes from file.
462 Args:
463 filename: Path to file to read from
464 comm: MPI communicator used in storage
465 name: Name of the attribute group
466 backend_args: Arguments to backend
468 Returns:
469 Dictionary of attributes read from file
470 """
471 raise NotImplementedError("The openfoam backend cannot read attributes.")
474def write_mesh(
475 filename: Path | str,
476 comm: MPI.Comm,
477 mesh: MeshData,
478 backend_args: dict[str, Any] | None,
479 mode: FileMode,
480 time: float,
481):
482 """
483 Write a mesh to file.
485 Args:
486 comm: MPI communicator used in storage
487 mesh: Internal data structure for the mesh data to save to file
488 filename: Path to file to write to
489 backend_args: Arguments to backend
490 mode: File-mode to store the mesh
491 time: Time stamp associated with the mesh
492 """
493 raise NotImplementedError("The openfoam backend cannot write meshes.")
496def write_meshtags(
497 filename: str | Path,
498 comm: MPI.Comm,
499 data: MeshTagsData,
500 backend_args: dict[str, Any] | None,
501):
502 """Write mesh tags to file.
504 Args:
505 filename: Path to file to write to
506 comm: MPI communicator used in storage
507 data: Internal data structure for the mesh tags to save to file
508 backend_args: Arguments to backend
509 """
510 raise NotImplementedError("The openfoam backend cannot write meshtags.")
513def read_dofmap(
514 filename: str | Path,
515 comm: MPI.Comm,
516 name: str,
517 backend_args: dict[str, Any] | None,
518) -> dolfinx.graph.AdjacencyList:
519 """Read the dofmap of a function with a given name.
521 Args:
522 filename: Path to file to read from
523 comm: MPI communicator used in storage
524 name: Name of the function to read the dofmap for
525 backend_args: Arguments to backend
527 Returns:
528 Dofmap as an AdjacencyList
529 """
530 raise NotImplementedError("The openfoam backend cannot make checkpoints.")
533def read_dofs(
534 filename: str | Path,
535 comm: MPI.Comm,
536 name: str,
537 time: float,
538 backend_args: dict[str, Any] | None,
539) -> tuple[npt.NDArray[np.float32 | np.float64 | np.complex64 | np.complex128], int]:
540 """Read the dofs (values) of a function with a given name from a given timestep.
542 Args:
543 filename: Path to file to read from
544 comm: MPI communicator used in storage
545 name: Name of the function to read the dofs for
546 time: Time stamp associated with the function to read
547 backend_args: Arguments to backend
549 Returns:
550 Contiguous sequence of degrees of freedom (with respect to input data)
551 and the global starting point on the process.
552 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
553 """
554 raise NotImplementedError("The openfoam backend cannot make checkpoints.")
557def read_cell_perms(
558 comm: MPI.Comm, filename: Path | str, backend_args: dict[str, Any] | None
559) -> npt.NDArray[np.uint32]:
560 """
561 Read cell permutation from file with given communicator,
562 Split in continuous chunks based on number of cells in the input data.
564 Args:
565 comm: MPI communicator used in storage
566 filename: Path to file to read from
567 backend_args: Arguments to backend
569 Returns:
570 Contiguous sequence of permutations (with respect to input data)
571 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
572 """
573 raise NotImplementedError("The openfoam backend cannot make checkpoints.")
576def write_function(
577 filename: Path,
578 comm: MPI.Comm,
579 u: FunctionData,
580 time: float,
581 mode: FileMode,
582 backend_args: dict[str, Any] | None,
583):
584 """
585 Write a function to file.
587 Args:
588 comm: MPI communicator used in storage
589 u: Internal data structure for the function data to save to file
590 filename: Path to file to write to
591 time: Time stamp associated with function
592 mode: File-mode to store the function
593 backend_args: Arguments to backend
594 """
595 raise NotImplementedError("The openfoam backend cannot make checkpoints.")
598def read_legacy_mesh(
599 filename: Path | str, comm: MPI.Comm, group: str
600) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.floating], str | None]:
601 """Read in the mesh topology, geometry and (optionally) cell type from a
602 legacy DOLFIN HDF5-file.
604 Args:
605 filename: Path to file to read from
606 comm: MPI communicator used in storage
607 group: Group in HDF5 file where mesh is stored
609 Returns:
610 Tuple containing:
611 - Topology as a (num_cells, num_vertices_per_cell) array of global vertex indices
612 - Geometry as a (num_vertices, geometric_dimension) array of vertex coordinates
613 - Cell type as a string (e.g. "tetrahedron") or None if not found
614 """
615 raise NotImplementedError("The openfoam backend cannot read legacy DOLFIN meshes.")
618def snapshot_checkpoint(
619 filename: Path | str,
620 mode: FileMode,
621 u: dolfinx.fem.Function,
622 backend_args: dict[str, Any] | None,
623):
624 """Create a snapshot checkpoint of a dolfinx function.
626 Args:
627 filename: Path to file to read from
628 mode: File-mode to store the function
629 u: dolfinx function to create a snapshot checkpoint for
630 backend_args: Arguments to backend
631 """
632 raise NotImplementedError("The openfoam backend cannot make checkpoints.")
635def read_hdf5_array(
636 comm: MPI.Comm,
637 filename: Path | str,
638 group: str,
639 backend_args: dict[str, Any] | None,
640) -> tuple[np.ndarray, int]:
641 """Read an array from an HDF5 file.
643 Args:
644 comm: MPI communicator used in storage
645 filename: Path to file to read from
646 group: Group in HDF5 file where array is stored
647 backend_args: Arguments to backend
649 Returns:
650 Tuple containing:
651 - Numpy array read from file
652 - Global starting point on the process.
653 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
654 """
655 raise NotImplementedError("The openfoam backend cannot read HDF5 arrays")
658def write_data(
659 filename: Path | str,
660 array_data: ArrayData,
661 comm: MPI.Comm,
662 time: str | float | None,
663 mode: FileMode,
664 backend_args: dict[str, Any] | None,
665):
666 """Write a 2D-array to file (distributed across proceses with MPI).
668 Args:
669 filename: Path to file
670 array_data: Data to write to file
671 comm: MPI communicator to open the file with
672 time: Time stamp
673 mode: Append or write
674 backend_args: The backend arguments
675 """
676 raise NotImplementedError("The openfoam backend does not support writing point data")