Debian Codegraph @

pyvista/core/utilities/cells.py

raw
1 """PyVista wrapping of :vtk:`vtkCellArray`."""
2
3 from __future__ import annotations
4
5 from collections import deque
6 from itertools import count
7 from itertools import islice
8 from typing import TYPE_CHECKING
9 from typing import Literal
10 from typing import overload
11
12 import numpy as np
13
14 import pyvista as pv
15 from pyvista import _vtk
16 from pyvista._deprecate_positional_args import _deprecate_positional_args
17
18 if TYPE_CHECKING:
19 from pyvista import CellType
20 from pyvista import UnstructuredGrid
21 from pyvista.core._typing_core import ArrayLike
22 from pyvista.core._typing_core import NumpyArray
23
24
25 def ncells_from_cells(cells: NumpyArray[int]) -> int:
26 """Get the number of cells from a VTK cell connectivity array.
27
28 Parameters
29 ----------
30 cells : numpy.ndarray
31 A VTK cell connectivity array.
32
33 Returns
34 -------
35 int
36 The number of cells extracted from the given cell connectivity array.
37
38 """
39 consumer: deque[NumpyArray[int]] = deque(maxlen=0)
40 it = cells.flat
41 for n_cells in count(): # noqa: B007
42 skip = next(it, None)
43 if skip is None:
44 break
45 consumer.extend(islice(it, skip)) # type: ignore[arg-type]
46 return n_cells
47
48
49 @overload
50 def numpy_to_idarr(
51 ind: int | ArrayLike[int],
52 deep: bool = ..., # noqa: FBT001
53 return_ind: Literal[True] = True, # noqa: FBT002
54 ) -> _vtk.vtkIdTypeArray: ...
55 @overload
56 def numpy_to_idarr(
57 ind: int | ArrayLike[int],
58 deep: bool = ..., # noqa: FBT001
59 return_ind: Literal[False] = False, # noqa: FBT002
60 ) -> tuple[_vtk.vtkIdTypeArray, NumpyArray[int]]: ...
61 @overload
62 def numpy_to_idarr(
63 ind: int | ArrayLike[int],
64 deep: bool = ..., # noqa: FBT001
65 return_ind: bool = ..., # noqa: FBT001
66 ) -> tuple[_vtk.vtkIdTypeArray, NumpyArray[int]] | _vtk.vtkIdTypeArray: ...
67 @_deprecate_positional_args(allowed=['ind'])
68 def numpy_to_idarr(
69 ind: int | ArrayLike[int],
70 deep: bool = False, # noqa: FBT001, FBT002
71 return_ind: bool = False, # noqa: FBT001, FBT002
72 ) -> tuple[_vtk.vtkIdTypeArray, NumpyArray[int]] | _vtk.vtkIdTypeArray:
73 """Safely convert a numpy array to a :vtk:`vtkIdTypeArray`.
74
75 Parameters
76 ----------
77 ind : sequence[int]
78 Input sequence to be converted to a :vtk:`vtkIdTypeArray`. Can be
79 either a mask or an integer array-like.
80 deep : bool, default: False
81 If ``True``, deep copy the input data. If ``False``, do not deep copy
82 the input data.
83 return_ind : bool, default: False
84 If ``True``, also return the input array after it has been cast to the
85 proper dtype.
86
87 Returns
88 -------
89 :vtk:`vtkIdTypeArray`
90 Converted array as a :vtk:`vtkIdTypeArray`.
91 numpy.ndarray
92 The input array after it has been cast to the proper dtype. Only
93 returned if `return_ind` is set to ``True``.
94
95 Raises
96 ------
97 TypeError
98 If the input array is not a mask or an integer array-like.
99
100 """
101 ind = np.asarray(ind)
102
103 # np.asarray will eat anything, so we have to weed out bogus inputs
104 if not (np.issubdtype(ind.dtype, np.integer) or ind.dtype == np.bool_):
105 msg = 'Indices must be either a mask or an integer array-like'
106 raise TypeError(msg)
107
108 if ind.dtype == np.bool_:
109 ind = ind.nonzero()[0].astype(pv.ID_TYPE)
110 elif ind.dtype != pv.ID_TYPE:
111 ind = ind.astype(pv.ID_TYPE)
112 elif not ind.flags['C_CONTIGUOUS']:
113 ind = np.ascontiguousarray(ind, dtype=pv.ID_TYPE)
114
115 # must ravel or segfault when saving MultiBlock
116 # but skip the ``ravel()`` allocation when the array is already
117 # 1D and contiguous (the common case), since ndarray.ravel() of
118 # a non-1D shape returns a copy.
119 ravelled = ind if ind.ndim == 1 else ind.ravel()
120 vtk_idarr = _vtk.numpy_to_vtkIdTypeArray(ravelled, deep=deep)
121 if return_ind:
122 return vtk_idarr, ind
123 return vtk_idarr
124
125
126 def create_mixed_cells(
127 mixed_cell_dict: dict[np.uint8, NumpyArray[int]], nr_points: int | None = None
128 ) -> tuple[NumpyArray[np.uint8], NumpyArray[int]]:
129 """Generate cell arrays for the creation of a pyvista.UnstructuredGrid from a cell dictionary.
130
131 This function generates all required cell arrays according to a given cell
132 dictionary. The given cell-dictionary should contain a proper
133 mapping of vtk_type -> np.ndarray (int), where the given ndarray
134 for each cell-type has to be an array of dimensions [N, D] or
135 [N*D], where N is the number of cells and D is the size of the
136 cells for the given type (e.g. 3 for triangles). Multiple
137 vtk_type keys with associated arrays can be present in one
138 dictionary. This function only accepts cell types of fixed size
139 and not dynamic sized cells like :attr:`~pyvista.CellType.POLYGON`
140
141 Parameters
142 ----------
143 mixed_cell_dict : dict
144 A dictionary that maps VTK-Enum-types (e.g. :attr:`~pyvista.CellType.TRIANGLE`) to
145 np.ndarrays of type int. The ``np.ndarrays`` describe the cell
146 connectivity.
147 nr_points : int, optional
148 Number of points of the grid. Used only to allow additional runtime
149 checks for invalid indices.
150
151 Returns
152 -------
153 cell_types : numpy.ndarray (uint8)
154 Types of each cell.
155
156 cell_arr : numpy.ndarray (int)
157 VTK-cell array.
158
159 Raises
160 ------
161 ValueError
162 If any of the cell types are not supported, have dynamic sized
163 cells, map to values with wrong size, or cell indices point
164 outside the given number of points.
165
166 Examples
167 --------
168 Create the cell arrays containing two triangles.
169
170 This will generate cell arrays to generate a mesh with two
171 disconnected triangles from 6 points.
172
173 >>> import numpy as np
174 >>> import vtk
175 >>> from pyvista.core.utilities.cells import create_mixed_cells
176 >>> cell_types, cell_arr = create_mixed_cells(
177 ... {vtk.VTK_TRIANGLE: np.array([[0, 1, 2], [3, 4, 5]])}
178 ... )
179
180 """
181 mixed_cells = {pv.CellType(k): v for k, v in mixed_cell_dict.items()} # type: ignore[arg-type]
182 if not all(k.n_points > 0 for k in mixed_cells.keys()):
183 msg = "You requested a cell type with variable length, which can't be used in this method"
184 raise ValueError(msg)
185
186 final_cell_types = []
187 final_cell_arr = []
188 for elem_t, cells_arr in mixed_cells.items():
189 nr_points_per_elem = elem_t.n_points
190 if (
191 not isinstance(cells_arr, np.ndarray) # type: ignore[redundant-expr]
192 or not np.issubdtype(cells_arr.dtype, np.integer)
193 or cells_arr.ndim not in [1, 2]
194 or (cells_arr.ndim == 1 and cells_arr.size % nr_points_per_elem != 0)
195 or (cells_arr.ndim == 2 and cells_arr.shape[-1] != nr_points_per_elem)
196 ):
197 msg = (
198 f'Expected an np.ndarray of size [N, {nr_points_per_elem}] or '
199 f'[N*{nr_points_per_elem}] with an integral type'
200 )
201 raise ValueError(msg)
202
203 if np.any(cells_arr < 0):
204 msg = f'Non-valid index (<0) given for cells of type {elem_t}'
205 raise ValueError(msg)
206
207 if nr_points is not None and np.any(cells_arr >= nr_points):
208 msg = f'Non-valid index (>={nr_points}) given for cells of type {elem_t}'
209 raise ValueError(msg)
210
211 # Ensure array is not flat
212 cells_arr_not_flat = (
213 cells_arr.reshape([-1, nr_points_per_elem]) if cells_arr.ndim == 1 else cells_arr
214 )
215
216 nr_elems = cells_arr_not_flat.shape[0]
217 final_cell_types.append(np.array([elem_t] * nr_elems, dtype=np.uint8))
218 final_cell_arr.append(
219 np.concatenate(
220 [
221 np.ones_like(cells_arr_not_flat[..., :1]) * nr_points_per_elem,
222 cells_arr_not_flat,
223 ],
224 axis=-1,
225 ).reshape([-1]),
226 )
227
228 cell_types_out = np.concatenate(final_cell_types)
229 cell_arr_out = np.concatenate(final_cell_arr)
230
231 return cell_types_out, cell_arr_out
232
233
234 def get_mixed_cells(vtkobj: UnstructuredGrid) -> dict[np.uint8, NumpyArray[int]]:
235 """Create the cells dictionary from the given pyvista.UnstructuredGrid.
236
237 This functions creates a cells dictionary (see
238 create_mixed_cells), with a mapping vtk_type -> np.ndarray (int)
239 for fixed size cell types. The returned dictionary will have
240 arrays of size [N, D], where N is the number of cells and D is the
241 size of the cells for the given type (e.g. 3 for triangles).
242
243 .. versionchanged:: 0.46
244
245 An empty dict ``{}`` is returned instead of ``None`` if the input
246 is empty.
247
248 Parameters
249 ----------
250 vtkobj : pyvista.UnstructuredGrid
251 The unstructured grid for which the cells dictionary should be computed.
252
253 Returns
254 -------
255 dict
256 Dictionary of cells.
257
258 Raises
259 ------
260 ValueError
261 If vtkobj is not a pyvista.UnstructuredGrid, any of the
262 present cells are unsupported, or have dynamic cell sizes,
263 like VTK_POLYGON.
264
265 """
266 if not isinstance(vtkobj, pv.UnstructuredGrid):
267 msg = 'Expected a pyvista object' # type: ignore[unreachable]
268 raise TypeError(msg)
269
270 nr_cells = vtkobj.n_cells
271 if nr_cells == 0:
272 return {}
273
274 return_dict: dict[CellType, NumpyArray[int]] = {}
275 cell_types = vtkobj.celltypes
276 cells = vtkobj.cells
277
278 distinct_cell_types = vtkobj.distinct_cell_types
279
280 if not all(k.n_points > 0 for k in distinct_cell_types):
281 msg = (
282 'You requested a cell-dictionary with a variable length cell, which is not supported '
283 'currently'
284 )
285 raise ValueError(msg)
286
287 cell_sizes = np.zeros_like(cell_types)
288 for cell_type in distinct_cell_types:
289 mask = cell_types == cell_type
290 cell_sizes[mask] = cell_type.n_points
291
292 cell_ends = np.cumsum(cell_sizes + 1)
293 cell_starts = np.concatenate([np.array([0], dtype=cell_ends.dtype), cell_ends[:-1]]) + 1
294
295 for cell_type in distinct_cell_types:
296 cell_size = cell_type.n_points
297 mask = cell_types == cell_type
298 current_cell_starts = cell_starts[mask]
299
300 cells_inds = current_cell_starts[..., np.newaxis] + np.arange(cell_size)[
301 np.newaxis
302 ].astype(
303 cell_starts.dtype,
304 )
305
306 return_dict[cell_type] = cells[cells_inds]
307
308 return {np.uint8(k): v for k, v in return_dict.items()}