Coverage for /dolfinx-env/lib/python3.14/site-packages/io4dolfinx/backends/pyvista/helpers.py: 84%
49 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"""
2Helpers for the PyVista backend: reading a VTK grid with pyvista as arrays.
4SPDX License identifier: MIT
6Copyright: Jørgen S. Dokken and Simula Research Laboratory
7"""
9from __future__ import annotations
11from dataclasses import dataclass
12from pathlib import Path
14import basix
15import dolfinx
16import fenicsx_compat
17import numpy as np
19try:
20 import pyvista
21except ImportError:
22 raise ModuleNotFoundError("The PyVista-backend requires pyvista")
24from ...structures import ReadMeshData
25from ...utils import as_rows
26from ..vtk_cell_types import _arbitrary_lagrange_vtk, _cell_degree, _first_order_vtk
28__all__ = ["Grid", "read_grid"]
30# Cell types can be found at https://vtk.org/doc/nightly/html/vtkCellType_8h_source.html
31_quadratic_vtk = {
32 21: "interval",
33 22: "triangle",
34 23: "quadrilateral",
35 24: "tetrahedron",
36 25: "hexahedron",
37}
39#: VTK pixels and voxels, the cells of image and rectilinear grids. They number their nodes
40#: x fastest, as DOLFINx numbers the vertices of quadrilaterals and hexahedra.
41_lexicographic_vtk = {8: "quadrilateral", 11: "hexahedron"}
44@dataclass
45class Grid:
46 """A VTK grid of one cell type, as arrays."""
48 #: The mesh, with the points of each cell in DOLFINx order. VTK points have three
49 #: coordinates.
50 mesh: ReadMeshData
51 #: Point data, each of shape ``(num_points, num_components)``
52 point_data: dict[str, np.ndarray]
53 #: Cell data, each of shape ``(num_cells, num_components)``
54 cell_data: dict[str, np.ndarray]
57def read_grid(filename: Path | str) -> Grid:
58 """Read a VTK grid with pyvista.
60 Unstructured grids, and structured, rectilinear and image grids, are read, also as the
61 single block of a multiblock data set (e.g. from a ``.pvd`` file).
63 Args:
64 filename: Path to the file
66 Returns:
67 The grid, as arrays
69 Raises:
70 NotImplementedError: For several blocks, several cell types, or an unsupported cell
71 type.
72 """
73 data: pyvista.DataSet | pyvista.MultiBlock | None = pyvista.read(filename)
74 if isinstance(data, pyvista.MultiBlock):
75 fenicsx_compat.pyvista_allow_snake_case(pyvista)
76 if data.number_of_blocks != 1:
77 raise NotImplementedError(
78 f"{filename} has {data.number_of_blocks} blocks; only one is supported."
79 )
80 data = data.get_block(0)
81 if not isinstance(data, pyvista.DataSet):
82 raise TypeError(f"Unknown data type {type(data)} in {filename}.")
83 # Structured grids are cast to unstructured ones, keeping the order of points and cells
84 if isinstance(data, pyvista.UnstructuredGrid):
85 grid = data
86 else:
87 grid = data.cast_to_unstructured_grid()
89 if len(vtk_types := np.unique(grid.celltypes)) != 1:
90 raise NotImplementedError(f"{filename} has several cell types {vtk_types.tolist()}.")
91 vtk_type = int(vtk_types[0])
92 nodes = np.asarray(grid.cells_dict[vtk_types[0]], dtype=np.int64)
93 if vtk_type in _lexicographic_vtk:
94 cell_type, degree = _lexicographic_vtk[vtk_type], 1
95 cells = nodes
96 else:
97 if vtk_type in _first_order_vtk:
98 cell_type, degree = _first_order_vtk[vtk_type], 1
99 elif vtk_type in _quadratic_vtk:
100 cell_type, degree = _quadratic_vtk[vtk_type], 2
101 elif vtk_type in _arbitrary_lagrange_vtk:
102 cell_type = _arbitrary_lagrange_vtk[vtk_type]
103 degree = _cell_degree(cell_type, nodes.shape[1])
104 else:
105 raise NotImplementedError(f"VTK cell type {vtk_type} is not supported.")
106 cells = nodes[:, dolfinx.cpp.io.perm_vtk(dolfinx.mesh.to_type(cell_type), nodes.shape[1])]
108 mesh = ReadMeshData(
109 cells=cells,
110 cell_type=cell_type,
111 x=np.asarray(grid.points),
112 lvar=int(basix.LagrangeVariant.equispaced),
113 degree=degree,
114 )
115 return Grid(
116 mesh=mesh,
117 point_data={name: as_rows(grid.point_data[name]) for name in grid.point_data.keys()},
118 cell_data={name: as_rows(grid.cell_data[name]) for name in grid.cell_data.keys()},
119 )