Debian Codegraph @

pyvista/core/utilities/helpers.py

raw
1 """Core helper utilities."""
2
3 from __future__ import annotations
4
5 from collections import deque
6 from collections.abc import Sequence
7 from typing import TYPE_CHECKING
8 from typing import Any
9 from typing import Literal
10 from typing import cast
11 from typing import overload
12
13 import numpy as np
14 from typing_extensions import TypeIs
15
16 import pyvista as pv
17 from pyvista import _vtk
18 from pyvista._deprecate_positional_args import _deprecate_positional_args
19 from pyvista.core import _validation
20
21 from . import transformations
22 from .fileio import from_meshio
23 from .fileio import from_trimesh
24 from .fileio import is_meshio_mesh
25 from .fileio import is_trimesh_mesh
26
27 if TYPE_CHECKING:
28 import meshio
29 import trimesh
30
31 from pyvista import DataObject
32 from pyvista import DataSet
33 from pyvista import ExplicitStructuredGrid
34 from pyvista import ImageData
35 from pyvista import MultiBlock
36 from pyvista import PartitionedDataSet
37 from pyvista import PointSet
38 from pyvista import PolyData
39 from pyvista import RectilinearGrid
40 from pyvista import StructuredGrid
41 from pyvista import Table
42 from pyvista import UnstructuredGrid
43 from pyvista import pyvista_ndarray
44 from pyvista.core._typing_core import NumpyArray
45 from pyvista.core._typing_core import VectorLike
46 from pyvista.wrappers import _WrappableVTKDataObjectType
47
48 _NORMALS = {
49 'x': [1, 0, 0],
50 'y': [0, 1, 0],
51 'z': [0, 0, 1],
52 '-x': [-1, 0, 0],
53 '-y': [0, -1, 0],
54 '-z': [0, 0, -1],
55 }
56 _NormalsLiteral = Literal['x', 'y', 'z', '-x', '-y', '-z']
57
58
59 def _dataset_array_lengths_match(obj: DataSet) -> bool:
60 """Return ``True`` when every point/cell data array length matches the geometry.
61
62 Direct Python loop over the underlying VTK arrays. Used as a fast-path
63 short-circuit by :func:`_warn_if_invalid_data`: when this returns ``True``
64 the slow :meth:`~pyvista.DataObject.validate_mesh` machinery can be skipped
65 entirely. The check is the same one performed by
66 ``validate_mesh('data', ...)`` (its ``cell_data_wrong_length`` and
67 ``point_data_wrong_length`` fields), so skipping the slow path is
68 semantically equivalent for valid datasets.
69
70 As a secondary role this loop also auto-names any unnamed array to
71 ``Unnamed_<i>``. The old ``validate_mesh`` path triggered the same rename
72 implicitly by iterating :meth:`DataSetAttributes.keys`; downstream code
73 (notably :meth:`DataSetFilters.contour`) relies on that name being present
74 after :func:`wrap`. The rename is O(1) per array and cheap, so doing it
75 here keeps the fast path observationally equivalent to the old path.
76
77 See https://github.com/pyvista/pyvista/issues/8473 for the motivating
78 benchmarks.
79
80 """
81 n_points = obj.GetNumberOfPoints()
82 n_cells = obj.GetNumberOfCells()
83 ok = True
84 for attrs, expected in (
85 (obj.GetPointData(), n_points),
86 (obj.GetCellData(), n_cells),
87 ):
88 for i in range(attrs.GetNumberOfArrays()):
89 arr = attrs.GetAbstractArray(i)
90 if arr is None:
91 continue
92 if not arr.GetName():
93 arr.SetName(f'Unnamed_{i}')
94 if arr.GetNumberOfTuples() != expected:
95 ok = False
96 return ok
97
98
99 def _warn_if_invalid_data(obj: DataObject) -> None:
100 if pv.vtk_version_info < (9, 3, 0) or not hasattr(obj, 'validate_mesh'):
101 return
102 # Fast path: for a plain DataSet, a direct Python-side array-length check
103 # avoids the ~600us setup cost of the validate_mesh machinery on the
104 # common valid case. Composite and table types fall through to
105 # validate_mesh so their warning behavior is unchanged. When the fast
106 # path detects a mismatch we still call validate_mesh to produce the
107 # detailed warning message.
108 if isinstance(obj, pv.DataSet) and _dataset_array_lengths_match(obj):
109 return
110 obj.validate_mesh('data', action='warn')
111
112
113 # vtkDataSet overloads
114 # Overload types should match the mappings in the `pyvista._wrappers` dict
115 # Overloads should be ordered from narrow types (child class) to general types (parent class)
116 @overload
117 def wrap(dataset: _vtk.vtkPolyData, *, validate: bool | None = ...) -> PolyData: ... # type: ignore[overload-overlap]
118 @overload
119 def wrap(dataset: _vtk.vtkStructuredGrid, *, validate: bool | None = ...) -> StructuredGrid: ... # type: ignore[overload-overlap]
120 @overload
121 def wrap( # type: ignore[overload-overlap]
122 dataset: _vtk.vtkExplicitStructuredGrid,
123 *,
124 validate: bool | None = ...,
125 ) -> ExplicitStructuredGrid: ...
126 @overload
127 def wrap( # type: ignore[overload-overlap]
128 dataset: _vtk.vtkUnstructuredGrid,
129 *,
130 validate: bool | None = ...,
131 ) -> UnstructuredGrid: ...
132 @overload
133 def wrap(dataset: _vtk.vtkPointSet, *, validate: bool | None = ...) -> PointSet: ...
134 @overload
135 def wrap(dataset: _vtk.vtkRectilinearGrid, *, validate: bool | None = ...) -> RectilinearGrid: ...
136 @overload
137 def wrap(dataset: _vtk.vtkStructuredPoints, *, validate: bool | None = ...) -> ImageData: ...
138 @overload
139 def wrap(dataset: _vtk.vtkImageData, *, validate: bool | None = ...) -> ImageData: ...
140 @overload
141 def wrap(dataset: _vtk.vtkMultiBlockDataSet, *, validate: bool | None = ...) -> MultiBlock: ...
142 @overload
143 def wrap(dataset: _vtk.vtkTable, *, validate: bool | None = ...) -> Table: ...
144 @overload
145 def wrap(
146 dataset: _vtk.vtkPartitionedDataSet,
147 *,
148 validate: bool | None = ...,
149 ) -> PartitionedDataSet: ...
150
151
152 # General catch-all cases
153 @overload
154 def wrap(dataset: _vtk.vtkDataSet, *, validate: bool | None = ...) -> DataSet: ...
155 @overload
156 def wrap(dataset: _vtk.vtkDataObject, *, validate: bool | None = ...) -> DataObject: ...
157
158
159 # Misc overloads
160 @overload
161 def wrap(dataset: NumpyArray[float], *, validate: bool | None = ...) -> PolyData | ImageData: ...
162 @overload
163 def wrap(dataset: _vtk.vtkAbstractArray, *, validate: bool | None = ...) -> pyvista_ndarray: ...
164 @overload
165 def wrap(dataset: None, *, validate: bool | None = ...) -> None: ...
166
167
168 # Third-party meshes
169 @overload
170 def wrap(dataset: trimesh.Trimesh, *, validate: bool | None = ...) -> PolyData: ...
171 @overload
172 def wrap(dataset: meshio.Mesh, *, validate: bool | None = ...) -> UnstructuredGrid: ...
173 def wrap( # noqa: PLR0911
174 dataset: _WrappableVTKDataObjectType
175 | DataObject
176 | trimesh.Trimesh
177 | meshio.Mesh
178 | _vtk.vtkAbstractArray
179 | NumpyArray[float]
180 | None,
181 *,
182 validate: bool | None = None,
183 ) -> DataObject | pyvista_ndarray | None:
184 """Wrap any given VTK data object to its appropriate PyVista data object.
185
186 Other formats that are supported include:
187
188 * 2D :class:`numpy.ndarray` of XYZ vertices
189 * 3D :class:`numpy.ndarray` representing a volume. Values will be scalars.
190 * 3D :class:`trimesh.Trimesh` mesh using :func:`~pyvista.from_trimesh`.
191 * 3D :class:`meshio.Mesh` mesh using :func:`~pyvista.from_meshio`.
192
193 .. versionchanged:: 0.38.0
194 If the passed object is already a wrapped PyVista object, then
195 this is no-op and will return that object directly. In previous
196 versions of PyVista, this would perform a shallow copy.
197
198 .. versionchanged:: 0.47
199
200 If wrapping a ``Trimesh`` object, any arrays are now wrapped directly
201 (no copies).
202
203 Parameters
204 ----------
205 dataset : :class:`numpy.ndarray` | :class:`trimesh.Trimesh` | vtk.DataSet
206 Dataset to wrap.
207
208 validate : bool, optional
209 When ``True``, confirm that every point and cell data array on the
210 wrapped VTK dataset has a tuple count that matches the dataset's
211 point or cell count, and emit a :class:`~pyvista.InvalidMeshWarning`
212 on any mismatch. When ``False``, skip the check entirely. When
213 ``None`` (the default), honor
214 :attr:`pyvista.core.config.Config.validate_on_wrap` (which itself
215 defaults to ``True``).
216
217 Pass ``validate=False`` in hot loops where the caller already trusts
218 the input, or set
219 ``pyvista.global_config.validate_on_wrap = False`` to disable the
220 check globally. This only affects raw VTK dataset inputs;
221 ``meshio`` and ``trimesh`` paths perform their own checks
222 independently.
223
224 .. versionadded:: 0.48
225
226 Returns
227 -------
228 pyvista.DataSet
229 The PyVista wrapped dataset.
230
231 See Also
232 --------
233 :ref:`wrap_trimesh_example`
234
235 Examples
236 --------
237 Wrap a numpy array representing a random point cloud.
238
239 >>> import numpy as np
240 >>> import pyvista as pv
241 >>> points = np.random.default_rng().random((10, 3))
242 >>> cloud = pv.wrap(points)
243 >>> cloud
244 PolyData (...)
245 N Cells: 10
246 N Points: 10
247 N Strips: 0
248 X Bounds: ...
249 Y Bounds: ...
250 Z Bounds: ...
251 N Arrays: 0
252
253 Wrap a VTK object.
254
255 >>> import pyvista as pv
256 >>> import vtk
257 >>> points = vtk.vtkPoints()
258 >>> p = [1.0, 2.0, 3.0]
259 >>> vertices = vtk.vtkCellArray()
260 >>> pid = points.InsertNextPoint(p)
261 >>> _ = vertices.InsertNextCell(1)
262 >>> _ = vertices.InsertCellPoint(pid)
263 >>> point = vtk.vtkPolyData()
264 >>> _ = point.SetPoints(points)
265 >>> _ = point.SetVerts(vertices)
266 >>> mesh = pv.wrap(point)
267 >>> mesh
268 PolyData (...)
269 N Cells: 1
270 N Points: 1
271 N Strips: 0
272 X Bounds: 1.000e+00, 1.000e+00
273 Y Bounds: 2.000e+00, 2.000e+00
274 Z Bounds: 3.000e+00, 3.000e+00
275 N Arrays: 0
276
277 Wrap a Trimesh object.
278
279 >>> import trimesh
280 >>> import pyvista as pv
281 >>> points = [[0, 0, 0], [0, 0, 1], [0, 1, 0]]
282 >>> faces = [[0, 1, 2]]
283 >>> tmesh = trimesh.Trimesh(points, faces=faces, process=False)
284 >>> mesh = pv.wrap(tmesh)
285 >>> mesh # doctest:+SKIP
286 PolyData (0x7fc55ff27ad0)
287 N Cells: 1
288 N Points: 3
289 X Bounds: 0.000e+00, 0.000e+00
290 Y Bounds: 0.000e+00, 1.000e+00
291 Z Bounds: 0.000e+00, 1.000e+00
292 N Arrays: 0
293
294 """
295 # Return if None
296 if dataset is None:
297 return None
298
299 if isinstance(dataset, tuple(pv._wrappers.values())):
300 # Return object if it is already wrapped
301 return cast('DataObject', dataset)
302
303 # Check if dataset is a numpy array. We do this first since
304 # pyvista_ndarray contains a VTK type that we don't want to
305 # directly wrap.
306 if isinstance(dataset, (np.ndarray, pv.pyvista_ndarray)):
307 if dataset.ndim == 1 and dataset.shape[0] == 3:
308 return pv.PolyData(dataset)
309 if dataset.ndim == 2 and dataset.shape[1] == 3:
310 return pv.PolyData(dataset)
311 elif dataset.ndim == 3:
312 mesh = pv.ImageData(dimensions=dataset.shape)
313 if isinstance(dataset, pv.pyvista_ndarray):
314 # this gets rid of pesky VTK reference since we're raveling this
315 dataset = np.asarray(dataset)
316 mesh['values'] = dataset.ravel(order='F')
317 mesh.active_scalars_name = 'values'
318 return mesh
319 else:
320 msg = (
321 'NumPy array could not be wrapped. `pv.wrap` only supports '
322 f'ndarray with shape (3,) or (N, 3) or (X, Y, Z). Got {dataset.shape}'
323 )
324 raise NotImplementedError(msg)
325
326 # wrap VTK arrays as pyvista_ndarray
327 if isinstance(dataset, _vtk.vtkDataArray):
328 return pv.pyvista_ndarray(dataset)
329
330 # Check if a dataset is a VTK type
331 if hasattr(dataset, 'GetClassName'):
332 key = dataset.GetClassName()
333 try:
334 wrapped_vtk: DataObject = pv._wrappers[key](dataset)
335 except KeyError:
336 msg = f'VTK data type ({key}) is not currently supported by pyvista.'
337 raise TypeError(msg)
338 else:
339 should_validate = pv.global_config.validate_on_wrap if validate is None else validate
340 if should_validate:
341 _warn_if_invalid_data(wrapped_vtk)
342 return wrapped_vtk
343
344 # wrap meshio
345 if is_meshio_mesh(dataset):
346 return from_meshio(cast('meshio.Mesh', dataset))
347
348 # wrap trimesh
349 if is_trimesh_mesh(dataset):
350 return from_trimesh(cast('trimesh.Trimesh', dataset))
351
352 # otherwise, flag tell the user we can't wrap this object
353 msg = f'Unable to wrap ({type(dataset)}) into a pyvista type.'
354 raise NotImplementedError(msg)
355
356
357 def is_pyvista_dataset(obj: Any) -> TypeIs[DataSet | MultiBlock | PartitionedDataSet]:
358 """Return ``True`` if the object is a PyVista wrapped dataset.
359
360 Parameters
361 ----------
362 obj : Any
363 Any object to test.
364
365 Returns
366 -------
367 bool
368 ``True`` when the object is a :class:`pyvista.DataSet`.
369
370 """
371 return isinstance(obj, (pv.DataSet, pv.MultiBlock, pv.PartitionedDataSet))
372
373
374 def generate_plane(normal: VectorLike[float], origin: VectorLike[float]):
375 """Return a :vtk:`vtkPlane`.
376
377 Parameters
378 ----------
379 normal : sequence[float]
380 Three item sequence representing the normal of the plane.
381
382 origin : sequence[float]
383 Three item sequence representing the origin of the plane.
384
385 Returns
386 -------
387 :vtk:`vtkPlane`
388 VTK plane.
389
390 """
391 plane = _vtk.vtkPlane()
392 # NORMAL MUST HAVE MAGNITUDE OF 1
393 normal_ = _validation.validate_array3(normal, dtype_out=float, name='normal')
394 normal_ = normal_ / np.linalg.norm(normal_)
395 plane.SetNormal(*normal_)
396 plane.SetOrigin(*origin)
397 return plane
398
399
400 def _validate_plane_origin_and_normal( # noqa: PLR0917
401 mesh: DataObject,
402 origin: VectorLike[float] | None,
403 normal: VectorLike[float] | _NormalsLiteral | None,
404 plane: PolyData | None,
405 default_normal: _NormalsLiteral,
406 ) -> tuple[NumpyArray[float], NumpyArray[float]]:
407 def _get_origin_and_normal_from_plane(
408 plane_: PolyData,
409 ) -> tuple[NumpyArray[float], NumpyArray[float]]:
410 _validation.check_instance(plane_, pv.PolyData, name='plane')
411
412 if (dimensionality := plane_.dimensionality) != 2:
413 msg = (
414 f'The plane mesh must be planar. Got a non-planar mesh with dimensionality of '
415 f'{dimensionality}.'
416 )
417 raise ValueError(msg)
418 origin = plane_.points.mean(axis=0)
419 normal = plane_.point_normals.mean(axis=0)
420 return origin, normal
421
422 if plane is not None:
423 if normal is not None or origin is not None:
424 msg = 'The `normal` and `origin` parameters cannot be set when `plane` is specified.'
425 raise ValueError(msg)
426 origin_, normal_ = _get_origin_and_normal_from_plane(plane)
427 else:
428 normal = default_normal if normal is None else normal
429 normal = _NORMALS[normal.lower()] if isinstance(normal, str) else normal
430 normal_ = _validation.validate_array3(normal, dtype_out=float, name='normal')
431
432 # find center of data if origin not specified
433 origin = mesh.center if origin is None else origin
434 origin_ = _validation.validate_array3(origin, dtype_out=float, name='origin')
435 return origin_, normal_
436
437
438 @_deprecate_positional_args(allowed=['points', 'angle'])
439 def axis_rotation( # noqa: PLR0917
440 points: NumpyArray[float],
441 angle: float,
442 inplace: bool = False, # noqa: FBT001, FBT002
443 deg: bool = True, # noqa: FBT001, FBT002
444 axis='z',
445 ):
446 """Rotate points by angle about an axis.
447
448 Parameters
449 ----------
450 points : numpy.ndarray
451 Array of points with shape ``(N, 3)``.
452
453 angle : float
454 Rotation angle.
455
456 inplace : bool, default: False
457 Updates points in-place while returning nothing.
458
459 deg : bool, default: True
460 If ``True``, the angle is interpreted as degrees instead of
461 radians.
462
463 axis : str, default: "z"
464 Name of axis to rotate about. Valid options are ``'x'``, ``'y'``,
465 and ``'z'``.
466
467 Returns
468 -------
469 numpy.ndarray
470 Rotated points.
471
472 Examples
473 --------
474 Rotate a set of points by 90 degrees about the x-axis in-place.
475
476 >>> import numpy as np
477 >>> import pyvista as pv
478 >>> from pyvista import examples
479 >>> points = examples.load_airplane().points
480 >>> points_orig = points.copy()
481 >>> pv.axis_rotation(points, 90, axis='x', deg=True, inplace=True)
482 >>> assert np.all(np.isclose(points[:, 0], points_orig[:, 0]))
483 >>> assert np.all(np.isclose(points[:, 1], -points_orig[:, 2]))
484 >>> assert np.all(np.isclose(points[:, 2], points_orig[:, 1]))
485
486 """
487 axis = axis.lower()
488 axis_to_vec = {'x': (1, 0, 0), 'y': (0, 1, 0), 'z': (0, 0, 1)}
489
490 if axis not in axis_to_vec:
491 msg = 'Invalid axis. Must be either "x", "y", or "z"'
492 raise ValueError(msg)
493
494 rot_mat = transformations.axis_angle_rotation(axis_to_vec[axis], angle, deg=deg)
495 return transformations.apply_transformation_to_points(rot_mat, points, inplace=inplace)
496
497
498 def is_inside_bounds(point, bounds):
499 """Check if a point is inside a set of bounds.
500
501 This is implemented through recursion so that this is N-dimensional.
502
503 Parameters
504 ----------
505 point : sequence[float]
506 Three item cartesian point (i.e. ``[x, y, z]``).
507
508 bounds : sequence[float]
509 Six item bounds in the form of ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
510
511 Returns
512 -------
513 bool
514 ``True`` when ``point`` is inside ``bounds``.
515
516 """
517 if isinstance(point, (int, float)):
518 point = [point]
519 if isinstance(point, (np.ndarray, Sequence)) and not isinstance(
520 point,
521 deque,
522 ):
523 if len(bounds) < 2 * len(point) or len(bounds) % 2 != 0:
524 msg = 'Bounds mismatch point dimensionality'
525 raise ValueError(msg)
526 point = deque(point)
527 bounds = deque(bounds)
528 return is_inside_bounds(point, bounds)
529 if not isinstance(point, deque):
530 msg = f'Unknown input data type ({type(point)}).'
531 raise TypeError(msg)
532 if len(point) < 1:
533 return True
534 p = point.popleft()
535 lower, upper = bounds.popleft(), bounds.popleft()
536 if lower <= p <= upper:
537 return is_inside_bounds(point, bounds)
538 return False