Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/pyvista/backend.py: 97%
77 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"""
2Module that uses pyvista to import grids (requires pyvista, through its helpers).
3"""
5from dataclasses import replace
6from pathlib import Path
7from typing import Any
9from mpi4py import MPI
11import basix
12import dolfinx
13import numpy as np
14import numpy.typing as npt
16from io4dolfinx.comm_helpers import run_on_root_and_share
17from io4dolfinx.structures import ArrayData, FunctionData, MeshData, MeshTagsData, ReadMeshData
18from io4dolfinx.utils import check_file_exists
20from .. import FileMode, ReadMode
21from . import helpers
23read_mode = ReadMode.serial
26def get_default_backend_args(arguments: dict[str, Any] | None) -> dict[str, Any]:
27 """Get default backend arguments given a set of input arguments.
29 Args:
30 arguments: Input backend arguments
32 Returns:
33 The arguments, with defaults for:
34 - ``"gdim"``: Geometric dimension of the mesh, ``3``. VTK points have three
35 coordinates; with a smaller ``gdim`` the others are dropped, and must be zero.
36 - ``"dtype"``: Floating point type of the mesh coordinates, ``None`` for the type
37 in the file
38 """
39 args: dict[str, Any] = {"gdim": 3, "dtype": None}
40 args.update(arguments or {})
41 return args
44def _data(grid: helpers.Grid, values: dict[str, np.ndarray], name: str, kind: str) -> np.ndarray:
45 """Point or cell data of a grid, with integer data cast to the type of the points."""
46 if name not in values:
47 raise KeyError(f"No {kind} data '{name}'. Available: {list(values)}")
48 data = values[name]
49 return data.astype(grid.mesh.x.dtype) if np.issubdtype(data.dtype, np.integer) else data
52def read_mesh_data(
53 filename: Path | str,
54 comm: MPI.Comm,
55 time: str | float | None = None,
56 read_from_partition: bool = False,
57 backend_args: dict[str, Any] | None = None,
58) -> ReadMeshData:
59 """Read mesh data from file.
61 Unstructured grids, and structured, rectilinear and image grids, are read. All data is
62 read on rank 0.
64 Args:
65 filename: Path to file to read from
66 comm: MPI communicator used in storage
67 time: Time stamp associated with the mesh to read
68 read_from_partition: Whether to read partition information
69 backend_args: Arguments to backend, see :func:`get_default_backend_args`
71 Returns:
72 Internal data structure for the mesh data read from file
73 """
74 backend_args = get_default_backend_args(backend_args)
75 check_file_exists(filename)
76 if read_from_partition:
77 raise RuntimeError("Cannot read partition data with Pyvista")
78 gdim = backend_args["gdim"]
80 def read() -> tuple[ReadMeshData, tuple[str, int, int, np.dtype]]:
81 mesh = helpers.read_grid(filename).mesh
82 if not np.allclose(mesh.x[:, gdim:], 0):
83 raise ValueError(
84 f"The points of {filename} have non-zero coordinates beyond gdim={gdim}."
85 )
86 mesh = replace(mesh, x=mesh.x[:, :gdim])
87 return mesh, (mesh.cell_type, mesh.degree, mesh.cells.shape[1], mesh.x.dtype)
89 mesh, (cell_type, degree, num_nodes, points_dtype) = run_on_root_and_share(comm, read)
90 if mesh is None:
91 mesh = ReadMeshData(
92 cells=np.zeros((0, num_nodes), dtype=np.int64),
93 cell_type=cell_type,
94 x=np.zeros((0, gdim), dtype=points_dtype),
95 lvar=int(basix.LagrangeVariant.equispaced),
96 degree=degree,
97 )
98 return replace(mesh, x=mesh.x.astype(backend_args["dtype"] or points_dtype))
101def read_point_data(
102 filename: Path | str,
103 name: str,
104 comm: MPI.Comm,
105 time: float | str | None,
106 backend_args: dict[str, Any] | None,
107) -> tuple[np.ndarray, int]:
108 """Read data from the nodes of a mesh.
110 Args:
111 filename: Path to file
112 name: Name of point data
113 comm: Communicator to launch IO on.
114 time: The time stamp
115 backend_args: The backend arguments
117 Returns:
118 The data on rank 0, of shape ``(num_points, num_components)``, and the global start
119 of the data on this process, ``0``
120 """
122 def read() -> tuple[np.ndarray, tuple[int, np.dtype]]:
123 grid = helpers.read_grid(filename)
124 data = _data(grid, grid.point_data, name, "point")
125 return data, (data.shape[1], data.dtype)
127 data, (num_components, dtype) = run_on_root_and_share(comm, read)
128 if data is None:
129 data = np.zeros((0, num_components), dtype=dtype)
130 return data, 0
133def read_cell_data(
134 filename: Path | str,
135 name: str,
136 comm: MPI.Comm,
137 time: str | float | None,
138 backend_args: dict[str, Any] | None,
139) -> tuple[npt.NDArray[np.int64], np.ndarray]:
140 """Read data from the cells of a mesh.
142 Args:
143 filename: Path to file
144 name: Name of cell data
145 comm: Communicator to launch IO on.
146 time: The time stamp
147 backend_args: The backend arguments
149 Returns:
150 A tuple (topology, data), where topology holds the input node indices of each cell
151 and data the data of each cell, on rank 0
152 """
154 def read() -> tuple[tuple[npt.NDArray[np.int64], np.ndarray], tuple[int, int, np.dtype]]:
155 grid = helpers.read_grid(filename)
156 data = _data(grid, grid.cell_data, name, "cell")
157 cells = grid.mesh.cells
158 return (cells, data), (cells.shape[1], data.shape[1], data.dtype)
160 local, (num_nodes, num_components, dtype) = run_on_root_and_share(comm, read)
161 if local is None:
162 local = (np.zeros((0, num_nodes), dtype=np.int64), np.zeros((0, num_components), dtype))
163 return local
166def write_attributes(
167 filename: Path | str,
168 comm: MPI.Comm,
169 name: str,
170 attributes: dict[str, np.ndarray],
171 backend_args: dict[str, Any] | None,
172):
173 """Write attributes to file.
175 Args:
176 filename: Path to file to write to
177 comm: MPI communicator used in storage
178 name: Name of the attribute group
179 attributes: Dictionary of attributes to write
180 backend_args: Arguments to backend
181 """
182 raise NotImplementedError("The Pyvista backend cannot write attributes.")
185def read_attributes(
186 filename: Path | str,
187 comm: MPI.Comm,
188 name: str,
189 backend_args: dict[str, Any] | None,
190) -> dict[str, Any]:
191 """Read attributes from file.
193 Args:
194 filename: Path to file to read from
195 comm: MPI communicator used in storage
196 name: Name of the attribute group
197 backend_args: Arguments to backend
199 Returns:
200 Dictionary of attributes read from file
201 """
202 raise NotImplementedError("The Pyvista backend cannot read attributes.")
205def read_timestamps(
206 filename: Path | str,
207 comm: MPI.Comm,
208 function_name: str,
209 backend_args: dict[str, Any] | None,
210) -> npt.NDArray[np.float64 | str]: # type: ignore[type-var]
211 """Read timestamps from file.
213 Args:
214 filename: Path to file to read from
215 comm: MPI communicator used in storage
216 function_name: Name of the function to read timestamps for
217 backend_args: Arguments to backend
219 Returns:
220 Numpy array of timestamps read from file
221 """
222 raise NotImplementedError("The Pyvista backend cannot read timestamps.")
225def read_function_names(
226 filename: Path | str, comm: MPI.Comm, backend_args: dict[str, Any] | None
227) -> list[str]:
228 """Read all function names from a file.
230 Args:
231 filename: Path to file
232 comm: MPI communicator to launch IO on.
233 backend_args: Arguments to backend
235 Returns:
236 The names of the point data, then of the cell data.
237 """
239 def read() -> tuple[None, list[str]]:
240 grid = helpers.read_grid(filename)
241 return None, list(grid.point_data) + list(grid.cell_data)
243 return run_on_root_and_share(comm, read)[1]
246def write_mesh(
247 filename: Path | str,
248 comm: MPI.Comm,
249 mesh: MeshData,
250 backend_args: dict[str, Any] | None,
251 mode: FileMode,
252 time: float,
253):
254 """
255 Write a mesh to file.
257 Args:
258 comm: MPI communicator used in storage
259 mesh: Internal data structure for the mesh data to save to file
260 filename: Path to file to write to
261 backend_args: Arguments to backend
262 mode: File-mode to store the mesh
263 time: Time stamp associated with the mesh
264 """
265 raise NotImplementedError("The Pyvista backend cannot write meshes.")
268def write_meshtags(
269 filename: str | Path,
270 comm: MPI.Comm,
271 data: MeshTagsData,
272 backend_args: dict[str, Any] | None,
273):
274 """Write mesh tags to file.
276 Args:
277 filename: Path to file to write to
278 comm: MPI communicator used in storage
279 data: Internal data structure for the mesh tags to save to file
280 backend_args: Arguments to backend
281 """
282 raise NotImplementedError("The Pyvista backend cannot write meshtags.")
285def read_meshtags_data(
286 filename: str | Path,
287 comm: MPI.Comm,
288 name: str,
289 backend_args: dict[str, Any] | None,
290) -> MeshTagsData:
291 """Read mesh tags from file.
293 Args:
294 filename: Path to file to read from
295 comm: MPI communicator used in storage
296 name: Name of the mesh tags to read
297 backend_args: Arguments to backend
299 Returns:
300 Internal data structure for the mesh tags read from file
301 """
302 raise NotImplementedError("The Pyvista backend cannot read meshtags.")
305def read_dofmap(
306 filename: str | Path,
307 comm: MPI.Comm,
308 name: str,
309 backend_args: dict[str, Any] | None,
310) -> dolfinx.graph.AdjacencyList:
311 """Read the dofmap of a function with a given name.
313 Args:
314 filename: Path to file to read from
315 comm: MPI communicator used in storage
316 name: Name of the function to read the dofmap for
317 backend_args: Arguments to backend
319 Returns:
320 Dofmap as an AdjacencyList
321 """
322 raise NotImplementedError("The Pyvista backend cannot make checkpoints.")
325def read_dofs(
326 filename: str | Path,
327 comm: MPI.Comm,
328 name: str,
329 time: float,
330 backend_args: dict[str, Any] | None,
331) -> tuple[npt.NDArray[np.float32 | np.float64 | np.complex64 | np.complex128], int]:
332 """Read the dofs (values) of a function with a given name from a given timestep.
334 Args:
335 filename: Path to file to read from
336 comm: MPI communicator used in storage
337 name: Name of the function to read the dofs for
338 time: Time stamp associated with the function to read
339 backend_args: Arguments to backend
341 Returns:
342 Contiguous sequence of degrees of freedom (with respect to input data)
343 and the global starting point on the process.
344 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
345 """
346 raise NotImplementedError("The Pyvista backend cannot make checkpoints.")
349def read_cell_perms(
350 comm: MPI.Comm, filename: Path | str, backend_args: dict[str, Any] | None
351) -> npt.NDArray[np.uint32]:
352 """
353 Read cell permutation from file with given communicator,
354 Split in continuous chunks based on number of cells in the input data.
356 Args:
357 comm: MPI communicator used in storage
358 filename: Path to file to read from
359 backend_args: Arguments to backend
361 Returns:
362 Contiguous sequence of permutations (with respect to input data)
363 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
364 """
365 raise NotImplementedError("The Pyvista backend cannot make checkpoints.")
368def write_function(
369 filename: Path,
370 comm: MPI.Comm,
371 u: FunctionData,
372 time: float,
373 mode: FileMode,
374 backend_args: dict[str, Any] | None,
375):
376 """
377 Write a function to file.
379 Args:
380 comm: MPI communicator used in storage
381 u: Internal data structure for the function data to save to file
382 filename: Path to file to write to
383 time: Time stamp associated with function
384 mode: File-mode to store the function
385 backend_args: Arguments to backend
386 """
387 raise NotImplementedError("The Pyvista backend cannot make checkpoints.")
390def read_legacy_mesh(
391 filename: Path | str, comm: MPI.Comm, group: str
392) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.floating], str | None]:
393 """Read in the mesh topology, geometry and (optionally) cell type from a
394 legacy DOLFIN HDF5-file.
396 Args:
397 filename: Path to file to read from
398 comm: MPI communicator used in storage
399 group: Group in HDF5 file where mesh is stored
401 Returns:
402 Tuple containing:
403 - Topology as a (num_cells, num_vertices_per_cell) array of global vertex indices
404 - Geometry as a (num_vertices, geometric_dimension) array of vertex coordinates
405 - Cell type as a string (e.g. "tetrahedron") or None if not found
406 """
407 raise NotImplementedError("The Pyvista backend cannot read legacy DOLFIN meshes.")
410def snapshot_checkpoint(
411 filename: Path | str,
412 mode: FileMode,
413 u: dolfinx.fem.Function,
414 backend_args: dict[str, Any] | None,
415):
416 """Create a snapshot checkpoint of a dolfinx function.
418 Args:
419 filename: Path to file to read from
420 mode: File-mode to store the function
421 u: dolfinx function to create a snapshot checkpoint for
422 backend_args: Arguments to backend
423 """
424 raise NotImplementedError("The Pyvista backend cannot make checkpoints.")
427def read_hdf5_array(
428 comm: MPI.Comm,
429 filename: Path | str,
430 group: str,
431 backend_args: dict[str, Any] | None,
432) -> tuple[np.ndarray, int]:
433 """Read an array from an HDF5 file.
435 Args:
436 comm: MPI communicator used in storage
437 filename: Path to file to read from
438 group: Group in HDF5 file where array is stored
439 backend_args: Arguments to backend
441 Returns:
442 Tuple containing:
443 - Numpy array read from file
444 - Global starting point on the process.
445 Process 0 has [0, M), process 1 [M, N), process 2 [N, O) etc.
446 """
447 raise NotImplementedError("The Pyvista backend cannot read HDF5 arrays")
450def write_data(
451 filename: Path | str,
452 array_data: ArrayData,
453 comm: MPI.Comm,
454 time: str | float | None,
455 mode: FileMode,
456 backend_args: dict[str, Any] | None,
457):
458 """Write a 2D-array to file (distributed across proceses with MPI).
460 Args:
461 filename: Path to file
462 array_data: Data to write to file
463 comm: MPI communicator to open the file with
464 time: Time stamp
465 mode: Append or write
466 backend_args: The backend arguments
467 """
468 raise NotImplementedError("The pyvista backend does not support writing point data")