Debian Codegraph @

pyvista/core/dataset.py

raw
1 """Attributes common to PolyData and Grid Objects."""
2
3 from __future__ import annotations
4
5 from collections.abc import Iterable
6 from collections.abc import Sequence
7 from copy import deepcopy
8 from functools import partial
9 from typing import TYPE_CHECKING
10 from typing import Any
11 from typing import Literal
12 from typing import NamedTuple
13 from typing import cast
14 from typing import overload
15
16 import numpy as np
17
18 import pyvista as pv
19 from pyvista import _vtk
20 from pyvista._deprecate_positional_args import _deprecate_positional_args
21 from pyvista.typing.mypy_plugin import promote_type
22
23 from . import _validation
24 from ._typing_core import BoundsTuple
25 from .dataobject import DataObject
26 from .datasetattributes import DataSetAttributes
27 from .filters import DataSetFilters
28 from .filters import _get_output
29 from .formatting_html import _data_array_section
30 from .formatting_html import _fmt_memory
31 from .formatting_html import build_repr_html
32 from .pyvista_ndarray import pyvista_ndarray
33 from .utilities.arrays import CellLiteral
34 from .utilities.arrays import FieldAssociation
35 from .utilities.arrays import FieldLiteral
36 from .utilities.arrays import PointLiteral
37 from .utilities.arrays import _coerce_pointslike_arg
38 from .utilities.arrays import get_array
39 from .utilities.arrays import get_array_association
40 from .utilities.arrays import parse_field_choice
41 from .utilities.arrays import raise_not_matching
42 from .utilities.arrays import vtk_id_list_to_array
43 from .utilities.helpers import is_pyvista_dataset
44 from .utilities.misc import abstract_class
45 from .utilities.points import vtk_points
46
47 if TYPE_CHECKING:
48 from collections.abc import Callable
49 from collections.abc import Generator
50 from collections.abc import Iterator
51
52 import pandas
53 import pyarrow
54 from typing_extensions import Self
55
56 from pyvista import Cell
57 from pyvista import CellType
58 from pyvista import PointSet
59
60 from ._typing_core import MatrixLike
61 from ._typing_core import NumberType
62 from ._typing_core import NumpyArray
63 from ._typing_core import VectorLike
64 from ._typing_core import _ArrayLikeOrScalar
65
66 _Dimensionality = Literal[0, 1, 2, 3]
67
68 # vector array names
69 DEFAULT_VECTOR_KEY = '_vectors'
70
71
72 class ActiveArrayInfoTuple(NamedTuple):
73 """Active array info tuple.
74
75 Parameters
76 ----------
77 association : pyvista.core.utilities.arrays.FieldAssociation
78 Association of the array.
79
80 name : str
81 The name of the array.
82
83 """
84
85 association: FieldAssociation
86 name: str | None
87
88 def copy(self: ActiveArrayInfoTuple) -> ActiveArrayInfoTuple:
89 """Return a copy of this object.
90
91 Returns
92 -------
93 ActiveArrayInfo
94 A copy of this object.
95
96 """
97 return ActiveArrayInfoTuple(self.association, self.name)
98
99
100 class _ActiveArrayExistsInfoTuple(NamedTuple):
101 """Active array info tuple for arrays that exist.
102
103 This named tuple is similar to ActiveArrayInfoTuple except the
104 `name` attribute cannot be `None`.
105 """
106
107 association: FieldAssociation
108 name: str
109
110
111 @promote_type(_vtk.vtkDataSet)
112 @abstract_class
113 class DataSet(DataSetFilters, DataObject):
114 """Methods in common to spatially referenced objects.
115
116 Parameters
117 ----------
118 *args :
119 Any extra args are passed as option to spatially referenced objects.
120
121 **kwargs :
122 Any extra keyword args are passed as option to spatially referenced objects.
123
124 """
125
126 plot = pv._plot.plot
127
128 def __init__(self: Self, *args, **kwargs) -> None:
129 """Initialize the common object."""
130 super().__init__(*args, **kwargs)
131 self._last_active_scalars_name: str | None = None
132 self._active_scalars_info = ActiveArrayInfoTuple(FieldAssociation.POINT, name=None)
133 self._active_vectors_info = ActiveArrayInfoTuple(FieldAssociation.POINT, name=None)
134 self._active_tensors_info = ActiveArrayInfoTuple(FieldAssociation.POINT, name=None)
135
136 # Used by glyph filter and plotter legend
137 self._glyph_geom: Sequence[_vtk.vtkDataSet] | None = None
138
139 def __getattr__(self: Self, item: str) -> Any:
140 """Get attribute from base class if not found.
141
142 Before falling through to the VTK base class, check whether
143 ``item`` matches a pending ``pyvista.accessors`` entry point.
144 A match triggers a one-shot plugin import, after which normal
145 attribute resolution finds the newly-attached accessor
146 descriptor.
147 """
148 # Lazy import to avoid a circular dependency at module load time.
149 from pyvista.core.utilities.accessor_registry import ( # noqa: PLC0415
150 _resolve_pending_accessor,
151 )
152
153 if _resolve_pending_accessor(item):
154 return object.__getattribute__(self, item)
155 return super().__getattribute__(item)
156
157 @property
158 def active_scalars_info(self: Self) -> ActiveArrayInfoTuple:
159 """Return the active scalar's association and name.
160
161 Association refers to the data association (e.g. point, cell, or
162 field) of the active scalars.
163
164 Returns
165 -------
166 ActiveArrayInfo
167 The scalars info in an object with namedtuple semantics,
168 with attributes ``association`` and ``name``.
169
170 Notes
171 -----
172 If both cell and point scalars are present and neither have
173 been set active within at the dataset level, point scalars
174 will be made active.
175
176 Examples
177 --------
178 Create a mesh, add scalars to the mesh, and return the active
179 scalars info. Note how when the scalars are added, they
180 automatically become the active scalars.
181
182 >>> import pyvista as pv
183 >>> mesh = pv.Sphere()
184 >>> mesh['Z Height'] = mesh.points[:, 2]
185 >>> mesh.active_scalars_info
186 ActiveArrayInfoTuple(association=<FieldAssociation.POINT: 0>, name='Z Height')
187
188 """
189 field, name = self._active_scalars_info
190 exclude = {'__custom_rgba', 'Normals', 'vtkOriginalPointIds', 'TCoords'}
191 if name in exclude:
192 name = self._last_active_scalars_name
193
194 # verify this field is still valid
195 if name is not None:
196 if field is FieldAssociation.CELL:
197 if self.cell_data.active_scalars_name != name:
198 name = None
199 elif field is FieldAssociation.POINT:
200 if self.point_data.active_scalars_name != name:
201 name = None
202
203 if name is None:
204 # check for the active scalars in point or cell arrays
205 self._active_scalars_info = ActiveArrayInfoTuple(field, None)
206 for attr in [self.point_data, self.cell_data]:
207 if attr.active_scalars_name is not None:
208 self._active_scalars_info = ActiveArrayInfoTuple(
209 attr.association,
210 attr.active_scalars_name,
211 )
212 break
213
214 return self._active_scalars_info
215
216 @property
217 def active_vectors_info(self: Self) -> ActiveArrayInfoTuple:
218 """Return the active vector's association and name.
219
220 Association refers to the data association (e.g. point, cell, or
221 field) of the active vectors.
222
223 Returns
224 -------
225 ActiveArrayInfo
226 The vectors info in an object with namedtuple semantics,
227 with attributes ``association`` and ``name``.
228
229 Notes
230 -----
231 If both cell and point vectors are present and neither have
232 been set active within at the dataset level, point vectors
233 will be made active.
234
235 Examples
236 --------
237 Create a mesh, compute the normals inplace, set the active
238 vectors to the normals, and show that the active vectors are
239 the ``'Normals'`` array associated with points.
240
241 >>> import pyvista as pv
242 >>> mesh = pv.Sphere()
243 >>> _ = mesh.compute_normals(inplace=True)
244 >>> mesh.active_vectors_name = 'Normals'
245 >>> mesh.active_vectors_info
246 ActiveArrayInfoTuple(association=<FieldAssociation.POINT: 0>, name='Normals')
247
248 """
249 field, name = self._active_vectors_info
250
251 # verify this field is still valid
252 if name is not None:
253 if field is FieldAssociation.POINT:
254 if self.point_data.active_vectors_name != name:
255 name = None
256 if field is FieldAssociation.CELL:
257 if self.cell_data.active_vectors_name != name:
258 name = None
259
260 if name is None:
261 # check for the active vectors in point or cell arrays
262 self._active_vectors_info = ActiveArrayInfoTuple(field, None)
263 for attr in [self.point_data, self.cell_data]:
264 name = attr.active_vectors_name
265 if name is not None:
266 self._active_vectors_info = ActiveArrayInfoTuple(attr.association, name)
267 break
268
269 return self._active_vectors_info
270
271 @property
272 def active_tensors_info(self: Self) -> ActiveArrayInfoTuple:
273 """Return the active tensor's field and name: [field, name].
274
275 Returns
276 -------
277 ActiveArrayInfo
278 Active tensor's field and name: [field, name].
279
280 """
281 return self._active_tensors_info
282
283 @property
284 def active_vectors(self: Self) -> pyvista_ndarray | None:
285 """Return the active vectors array.
286
287 Returns
288 -------
289 Optional[pyvista_ndarray]
290 Active vectors array.
291
292 Examples
293 --------
294 Create a mesh, compute the normals inplace, and return the
295 normals vector array.
296
297 >>> import pyvista as pv
298 >>> mesh = pv.Sphere()
299 >>> _ = mesh.compute_normals(inplace=True)
300 >>> mesh.active_vectors # doctest:+SKIP
301 pyvista_ndarray([[-2.48721432e-10, -1.08815623e-09, -1.00000000e+00],
302 [-2.48721432e-10, -1.08815623e-09, 1.00000000e+00],
303 [-1.18888125e-01, 3.40539310e-03, -9.92901802e-01],
304 ...,
305 [-3.11940581e-01, -6.81432486e-02, 9.47654784e-01],
306 [-2.09880397e-01, -4.65070531e-02, 9.76620376e-01],
307 [-1.15582108e-01, -2.80492082e-02, 9.92901802e-01]],
308 dtype=float32)
309
310 """
311 field, name = self.active_vectors_info
312 if name is not None:
313 try:
314 if field is FieldAssociation.POINT:
315 return self.point_data[name]
316 if field is FieldAssociation.CELL:
317 return self.cell_data[name]
318 except KeyError:
319 return None
320 return None
321
322 @property
323 def active_tensors(self: Self) -> NumpyArray[float] | None:
324 """Return the active tensors array.
325
326 Returns
327 -------
328 Optional[np.ndarray]
329 Active tensors array.
330
331 """
332 field: FieldAssociation = self.active_tensors_info.association
333 name: str | None = self.active_tensors_info.name
334 if name is not None:
335 try:
336 if field is FieldAssociation.POINT:
337 return self.point_data[name]
338 if field is FieldAssociation.CELL:
339 return self.cell_data[name]
340 except KeyError:
341 return None
342 return None
343
344 @property
345 def active_tensors_name(self: Self) -> str | None:
346 """Return the name of the active tensor array.
347
348 Returns
349 -------
350 str
351 Name of the active tensor array.
352
353 """
354 return self.active_tensors_info.name
355
356 @active_tensors_name.setter
357 def active_tensors_name(self: Self, name: str | None) -> None:
358 """Set the name of the active tensor array.
359
360 Parameters
361 ----------
362 name : str
363 Name of the active tensor array.
364
365 """
366 self.set_active_tensors(name)
367
368 @property
369 def active_vectors_name(self: Self) -> str | None:
370 """Return the name of the active vectors array.
371
372 Returns
373 -------
374 str
375 Name of the active vectors array.
376
377 Examples
378 --------
379 Create a mesh, compute the normals, set them as active, and
380 return the name of the active vectors.
381
382 >>> import pyvista as pv
383 >>> mesh = pv.Sphere()
384 >>> mesh_w_normals = mesh.compute_normals()
385 >>> mesh_w_normals.active_vectors_name = 'Normals'
386 >>> mesh_w_normals.active_vectors_name
387 'Normals'
388
389 """
390 return self.active_vectors_info.name
391
392 @active_vectors_name.setter
393 def active_vectors_name(self: Self, name: str | None) -> None:
394 """Set the name of the active vectors array.
395
396 Parameters
397 ----------
398 name : str
399 Name of the active vectors array.
400
401 """
402 self.set_active_vectors(name)
403
404 @property
405 def active_scalars_name(self: Self) -> str | None:
406 """Return the name of the active scalars.
407
408 Returns
409 -------
410 str
411 Name of the active scalars.
412
413 Examples
414 --------
415 Create a mesh, add scalars to the mesh, and return the name of
416 the active scalars.
417
418 >>> import pyvista as pv
419 >>> mesh = pv.Sphere()
420 >>> mesh['Z Height'] = mesh.points[:, 2]
421 >>> mesh.active_scalars_name
422 'Z Height'
423
424 """
425 return self.active_scalars_info.name
426
427 @active_scalars_name.setter
428 def active_scalars_name(self: Self, name: str | None) -> None:
429 """Set the name of the active scalars.
430
431 Parameters
432 ----------
433 name : str
434 Name of the active scalars.
435
436 """
437 self.set_active_scalars(name)
438
439 @property
440 def points(self: Self) -> pyvista_ndarray:
441 """Return a reference to the points as a numpy object.
442
443 Returns
444 -------
445 pyvista_ndarray
446 Reference to the points as a numpy object.
447
448 Examples
449 --------
450 Create a mesh and return the points of the mesh as a numpy
451 array.
452
453 >>> import pyvista as pv
454 >>> cube = pv.Cube()
455 >>> points = cube.points
456 >>> points
457 pyvista_ndarray([[-0.5, -0.5, -0.5],
458 [-0.5, -0.5, 0.5],
459 [-0.5, 0.5, 0.5],
460 [-0.5, 0.5, -0.5],
461 [ 0.5, -0.5, -0.5],
462 [ 0.5, 0.5, -0.5],
463 [ 0.5, 0.5, 0.5],
464 [ 0.5, -0.5, 0.5]], dtype=float32)
465
466 Shift these points in the z direction and show that their
467 position is reflected in the mesh points.
468
469 >>> points[:, 2] += 1
470 >>> cube.points
471 pyvista_ndarray([[-0.5, -0.5, 0.5],
472 [-0.5, -0.5, 1.5],
473 [-0.5, 0.5, 1.5],
474 [-0.5, 0.5, 0.5],
475 [ 0.5, -0.5, 0.5],
476 [ 0.5, 0.5, 0.5],
477 [ 0.5, 0.5, 1.5],
478 [ 0.5, -0.5, 1.5]], dtype=float32)
479
480 You can also update the points in-place:
481
482 >>> cube.points[...] = 2 * points
483 >>> cube.points
484 pyvista_ndarray([[-1., -1., 1.],
485 [-1., -1., 3.],
486 [-1., 1., 3.],
487 [-1., 1., 1.],
488 [ 1., -1., 1.],
489 [ 1., 1., 1.],
490 [ 1., 1., 3.],
491 [ 1., -1., 3.]], dtype=float32)
492
493 """
494 _points = self.GetPoints()
495 try:
496 _points = _points.GetData()
497 except AttributeError:
498 # create an empty array
499 vtkpts = vtk_points(np.empty((0, 3)), deep=False)
500 self.SetPoints(vtkpts)
501 _points = self.GetPoints().GetData()
502 return pyvista_ndarray(_points, dataset=self)
503
504 @points.setter
505 def points(self: Self, points: MatrixLike[float] | _vtk.vtkPoints) -> None:
506 """Set a reference to the points as a numpy object.
507
508 Parameters
509 ----------
510 points : MatrixLike[float] | :vtk:`vtkPoints`
511 Points as a array object.
512
513 """
514 pdata = self.GetPoints()
515 if isinstance(points, pyvista_ndarray):
516 # simply set the underlying data
517 if points.VTKObject is not None and pdata is not None:
518 pdata.SetData(points.VTKObject)
519 pdata.Modified()
520 self.Modified()
521 return
522 # directly set the data if vtk object
523 if isinstance(points, _vtk.vtkPoints):
524 self.SetPoints(points)
525 if pdata is not None:
526 pdata.Modified()
527 self.Modified()
528 return
529 # otherwise, wrap and use the array
530 points, _ = _coerce_pointslike_arg(points, copy=False)
531 vtkpts = vtk_points(points, deep=False)
532 if not pdata:
533 self.SetPoints(vtkpts)
534 else:
535 pdata.SetData(vtkpts.GetData())
536 self.GetPoints().Modified()
537 self.Modified()
538
539 @property
540 def arrows(
541 self: Self,
542 ) -> pv.PolyData | None:
543 """Return a glyph representation of the active vector data as arrows.
544
545 Arrows will be located at the points or cells of the mesh and
546 their size will be dependent on the norm of the vector.
547 Their direction will be the "direction" of the vector.
548
549 If there are both active point and cell vectors, preference is
550 given to the point vectors.
551
552 Returns
553 -------
554 pyvista.PolyData
555 Active vectors represented as arrows.
556
557 Examples
558 --------
559 Create a mesh, compute the normals and set them active.
560
561 >>> import pyvista as pv
562 >>> mesh = pv.Cube()
563 >>> mesh_w_normals = mesh.compute_normals()
564 >>> mesh_w_normals.active_vectors_name = 'Normals'
565
566 Plot the active vectors as arrows. Show the original mesh as wireframe for
567 context.
568
569 >>> arrows = mesh_w_normals.arrows
570 >>> pl = pv.Plotter()
571 >>> _ = pl.add_mesh(mesh, style='wireframe')
572 >>> _ = pl.add_mesh(arrows, color='red')
573 >>> pl.show()
574
575 """
576 vectors = self.active_vectors
577 if vectors is None:
578 return None
579
580 if vectors.ndim != 2:
581 msg = 'Active vectors are not vectors.'
582 raise ValueError(msg)
583
584 field, vectors_name = self.active_vectors_info
585 # Cast type since we know name is not None since vectors is not None at this point
586 vectors_name = cast('str', vectors_name)
587
588 scale_name = f'{vectors_name} Magnitude'
589 scale = np.linalg.norm(vectors, axis=1)
590 if field == FieldAssociation.POINT:
591 self.point_data.set_array(scale, scale_name)
592 else:
593 self.cell_data.set_array(scale, scale_name)
594 return self.glyph(orient=vectors_name, scale=scale_name)
595
596 def set_active_scalars(
597 self: Self,
598 name: str | None,
599 preference: PointLiteral | CellLiteral = 'cell',
600 ) -> tuple[FieldAssociation, NumpyArray[float] | None]:
601 """Find the scalars by name and appropriately sets it as active.
602
603 To deactivate any active scalars, pass ``None`` as the ``name``.
604
605 Parameters
606 ----------
607 name : str, optional
608 Name of the scalars array to assign as active. If
609 ``None``, deactivates active scalars for both point and
610 cell data.
611
612 preference : str, default: "cell"
613 If there are two arrays of the same name associated with
614 points or cells, it will prioritize an array matching this
615 type. Can be either ``'cell'`` or ``'point'``.
616
617 Returns
618 -------
619 pyvista.core.utilities.arrays.FieldAssociation
620 Association of the scalars matching ``name``.
621
622 pyvista_ndarray
623 An array from the dataset matching ``name``.
624
625 """
626 if preference not in [
627 'point',
628 'cell',
629 FieldAssociation.CELL,
630 FieldAssociation.POINT,
631 ]:
632 msg = '``preference`` must be either "point" or "cell"'
633 raise ValueError(msg)
634 if name is None:
635 self.GetCellData().SetActiveScalars(None)
636 self.GetPointData().SetActiveScalars(None)
637 return FieldAssociation.NONE, np.array([])
638 field = get_array_association(self, name, preference=preference)
639 if field == FieldAssociation.NONE:
640 if name in self.field_data:
641 msg = f'Data named "{name}" is a field array which cannot be active.'
642 raise ValueError(msg)
643 else:
644 msg = f'Data named "{name}" does not exist in this dataset.'
645 raise KeyError(msg)
646 self._last_active_scalars_name = self.active_scalars_info.name
647 if field == FieldAssociation.POINT:
648 ret = self.GetPointData().SetActiveScalars(name)
649 elif field == FieldAssociation.CELL:
650 ret = self.GetCellData().SetActiveScalars(name)
651 else:
652 msg = f'Data field ({name}) with type ({field}) not usable'
653 raise ValueError(msg)
654
655 if ret < 0:
656 msg = f'Data field "{name}" with type ({field}) could not be set as the active scalars'
657 raise ValueError(msg)
658
659 self._active_scalars_info = ActiveArrayInfoTuple(field, name)
660
661 if field == FieldAssociation.POINT:
662 return field, self.point_data.active_scalars
663 else: # must be cell
664 return field, self.cell_data.active_scalars
665
666 def set_active_vectors(
667 self: Self, name: str | None, preference: PointLiteral | CellLiteral = 'point'
668 ) -> None:
669 """Find the vectors by name and appropriately sets it as active.
670
671 To deactivate any active vectors, pass ``None`` as the ``name``.
672
673 Parameters
674 ----------
675 name : str, optional
676 Name of the vectors array to assign as active.
677
678 preference : str, default: "point"
679 If there are two arrays of the same name associated with
680 points, cells, or field data, it will prioritize an array
681 matching this type. Can be either ``'cell'``,
682 ``'field'``, or ``'point'``.
683
684 """
685 if name is None:
686 self.GetCellData().SetActiveVectors(None)
687 self.GetPointData().SetActiveVectors(None)
688 field = FieldAssociation.POINT
689 else:
690 field = get_array_association(self, name, preference=preference)
691 if field == FieldAssociation.POINT:
692 ret = self.GetPointData().SetActiveVectors(name)
693 elif field == FieldAssociation.CELL:
694 ret = self.GetCellData().SetActiveVectors(name)
695 else:
696 msg = f'Data field ({name}) with type ({field}) not usable'
697 raise ValueError(msg)
698
699 if ret < 0:
700 msg = (
701 f'Data field ({name}) with type ({field}) could not be set as the '
702 f'active vectors'
703 )
704 raise ValueError(msg)
705
706 self._active_vectors_info = ActiveArrayInfoTuple(field, name)
707
708 def set_active_tensors(
709 self: Self, name: str | None, preference: PointLiteral | CellLiteral = 'point'
710 ) -> None:
711 """Find the tensors by name and appropriately sets it as active.
712
713 To deactivate any active tensors, pass ``None`` as the ``name``.
714
715 Parameters
716 ----------
717 name : str, optional
718 Name of the tensors array to assign as active.
719
720 preference : str, default: "point"
721 If there are two arrays of the same name associated with
722 points, cells, or field data, it will prioritize an array
723 matching this type. Can be either ``'cell'``,
724 ``'field'``, or ``'point'``.
725
726 """
727 if name is None:
728 self.GetCellData().SetActiveTensors(None)
729 self.GetPointData().SetActiveTensors(None)
730 field = FieldAssociation.POINT
731 else:
732 field = get_array_association(self, name, preference=preference)
733 if field == FieldAssociation.POINT:
734 ret = self.GetPointData().SetActiveTensors(name)
735 elif field == FieldAssociation.CELL:
736 ret = self.GetCellData().SetActiveTensors(name)
737 else:
738 msg = f'Data field ({name}) with type ({field}) not usable'
739 raise ValueError(msg)
740
741 if ret < 0:
742 msg = (
743 f'Data field ({name}) with type ({field}) could not be set as the '
744 f'active tensors'
745 )
746 raise ValueError(msg)
747
748 self._active_tensors_info = ActiveArrayInfoTuple(field, name)
749
750 def rename_array(
751 self: Self,
752 old_name: str,
753 new_name: str,
754 preference: PointLiteral | CellLiteral | FieldLiteral = 'cell',
755 ) -> None:
756 """Change array name by searching for the array then renaming it.
757
758 Parameters
759 ----------
760 old_name : str
761 Name of the array to rename.
762
763 new_name : str
764 Name to rename the array to.
765
766 preference : str, default: "cell"
767 If there are two arrays of the same name associated with
768 points, cells, or field data, it will prioritize an array
769 matching this type. Can be either ``'cell'``,
770 ``'field'``, or ``'point'``.
771
772 Examples
773 --------
774 Create a cube, assign a point array to the mesh named
775 ``'my_array'``, and rename it to ``'my_renamed_array'``.
776
777 >>> import pyvista as pv
778 >>> import numpy as np
779 >>> cube = pv.Cube()
780 >>> cube['my_array'] = range(cube.n_points)
781 >>> cube.rename_array('my_array', 'my_renamed_array')
782 >>> cube['my_renamed_array']
783 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
784
785 """
786 field = get_array_association(self, old_name, preference=preference)
787
788 was_active = False
789 if self.active_scalars_name == old_name:
790 was_active = True
791 if field == FieldAssociation.POINT:
792 data = self.point_data
793 elif field == FieldAssociation.CELL:
794 data = self.cell_data
795 elif field == FieldAssociation.NONE:
796 data = self.field_data
797 else:
798 msg = f'Array with name {old_name} not found.'
799 raise KeyError(msg)
800
801 arr = data.pop(old_name)
802 # Update the array's name before reassigning. This prevents taking a copy of the array in
803 # `DataSetAttributes._prepare_array` which can lead to the array being garbage collected.
804 # See issue #5244.
805 arr.VTKObject.SetName(new_name) # type: ignore[union-attr]
806 data[new_name] = arr
807
808 if was_active and field != FieldAssociation.NONE:
809 self.set_active_scalars(new_name, preference=field)
810
811 @property
812 def active_scalars(self: Self) -> pyvista_ndarray | None:
813 """Return the active scalars as an array.
814
815 Returns
816 -------
817 Optional[pyvista_ndarray]
818 Active scalars as an array.
819
820 """
821 field, name = self.active_scalars_info
822 if name is not None:
823 try:
824 if field == FieldAssociation.POINT:
825 return self.point_data[name]
826 if field == FieldAssociation.CELL:
827 return self.cell_data[name]
828 except KeyError:
829 return None
830 return None
831
832 @property
833 def active_normals(self: Self) -> pyvista_ndarray | None:
834 """Return the active normals as an array.
835
836 Returns
837 -------
838 pyvista_ndarray
839 Active normals of this dataset.
840
841 Notes
842 -----
843 If both point and cell normals exist, this returns point
844 normals by default.
845
846 Examples
847 --------
848 Compute normals on an example sphere mesh and return the
849 active normals for the dataset. Show that this is the same size
850 as the number of points.
851
852 >>> import pyvista as pv
853 >>> mesh = pv.Sphere()
854 >>> mesh = mesh.compute_normals()
855 >>> normals = mesh.active_normals
856 >>> normals.shape
857 (842, 3)
858 >>> mesh.n_points
859 842
860
861 """
862 if self.point_data.active_normals is not None:
863 return self.point_data.active_normals
864 return self.cell_data.active_normals
865
866 def get_data_range( # type: ignore[override]
867 self: Self,
868 arr_var: str | NumpyArray[float] | None = None,
869 preference: PointLiteral | CellLiteral | FieldLiteral = 'cell',
870 ) -> tuple[float, float]:
871 """Get the min and max of a named array.
872
873 Parameters
874 ----------
875 arr_var : str, np.ndarray, optional
876 The name of the array to get the range. If ``None``, the
877 active scalars is used.
878
879 preference : str, default: "cell"
880 When scalars is specified, this is the preferred array type
881 to search for in the dataset. Must be either ``'point'``,
882 ``'cell'``, or ``'field'``.
883
884 Returns
885 -------
886 tuple
887 ``(min, max)`` of the named array.
888
889 """
890 if arr_var is None: # use active scalars array
891 arr_var = self.active_scalars_info.name
892 if arr_var is None:
893 return (np.nan, np.nan)
894
895 if isinstance(arr_var, str):
896 name = arr_var
897 arr = get_array(self, name, preference=preference, err=True)
898 else:
899 arr = arr_var # type: ignore[assignment]
900
901 # If array has no tuples return a NaN range
902 if arr is None:
903 return (np.nan, np.nan)
904 if arr.size == 0 or not (arr.dtype == bool or np.issubdtype(arr.dtype, np.number)):
905 return (np.nan, np.nan)
906 # Use the array range
907 return np.nanmin(arr), np.nanmax(arr)
908
909 @_deprecate_positional_args(allowed=['ido'])
910 def copy_meta_from(self: Self, ido: DataSet, deep: bool = True) -> None: # noqa: FBT001, FBT002
911 """Copy pyvista meta data onto this object from another object.
912
913 Parameters
914 ----------
915 ido : pyvista.DataSet
916 Dataset to copy the metadata from.
917
918 deep : bool, default: True
919 Deep or shallow copy.
920
921 """
922 if deep:
923 self._association_complex_names = deepcopy(ido._association_complex_names)
924 self._association_bitarray_names = deepcopy(ido._association_bitarray_names)
925 self._active_scalars_info = ido.active_scalars_info.copy()
926 self._active_vectors_info = ido.active_vectors_info.copy()
927 self._active_tensors_info = ido.active_tensors_info.copy()
928 else:
929 # pass by reference
930 self._association_complex_names = ido._association_complex_names
931 self._association_bitarray_names = ido._association_bitarray_names
932 self._active_scalars_info = ido.active_scalars_info
933 self._active_vectors_info = ido.active_vectors_info
934 self._active_tensors_info = ido.active_tensors_info
935
936 @property
937 def point_data(self: Self) -> DataSetAttributes:
938 """Return point data as DataSetAttributes.
939
940 Returns
941 -------
942 DataSetAttributes
943 Point data as DataSetAttributes.
944
945 Examples
946 --------
947 Add point arrays to a mesh and list the available ``point_data``.
948
949 >>> import pyvista as pv
950 >>> import numpy as np
951 >>> mesh = pv.Cube()
952 >>> mesh.clear_data()
953 >>> mesh.point_data['my_array'] = np.random.default_rng().random(mesh.n_points)
954 >>> mesh.point_data['my_other_array'] = np.arange(mesh.n_points)
955 >>> mesh.point_data
956 pyvista DataSetAttributes
957 Association : POINT
958 Active Scalars : my_array
959 Active Vectors : None
960 Active Texture : None
961 Active Normals : None
962 Contains arrays :
963 my_array float64 (8,) SCALARS
964 my_other_array int64 (8,)
965
966 Access an array from ``point_data``.
967
968 >>> mesh.point_data['my_other_array']
969 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
970
971 Or access it directly from the mesh.
972
973 >>> mesh['my_array'].shape
974 (8,)
975
976 """
977 return DataSetAttributes(
978 self.GetPointData(),
979 dataset=self,
980 association=FieldAssociation.POINT,
981 )
982
983 def clear_point_data(self: Self) -> None:
984 """Remove all point arrays.
985
986 Examples
987 --------
988 Clear all point arrays from a mesh.
989
990 >>> import pyvista as pv
991 >>> import numpy as np
992 >>> mesh = pv.Sphere()
993 >>> mesh.point_data.keys()
994 ['Normals']
995 >>> mesh.clear_point_data()
996 >>> mesh.point_data.keys()
997 []
998
999 """
1000 self.point_data.clear()
1001
1002 def clear_cell_data(self: Self) -> None:
1003 """Remove all cell arrays."""
1004 self.cell_data.clear()
1005
1006 def clear_data(self: Self) -> None:
1007 """Remove all arrays from point/cell/field data.
1008
1009 Examples
1010 --------
1011 Clear all arrays from a mesh.
1012
1013 >>> import pyvista as pv
1014 >>> import numpy as np
1015 >>> mesh = pv.Sphere()
1016 >>> mesh.point_data.keys()
1017 ['Normals']
1018 >>> mesh.clear_data()
1019 >>> mesh.point_data.keys()
1020 []
1021
1022 """
1023 self.clear_point_data()
1024 self.clear_cell_data()
1025 self.clear_field_data()
1026
1027 def _attributes_for_association(
1028 self: Self, association: FieldAssociation
1029 ) -> DataSetAttributes:
1030 """Return :attr:`point_data` or :attr:`cell_data`; raise ``ValueError`` otherwise."""
1031 if association is FieldAssociation.POINT:
1032 return self.point_data
1033 if association is FieldAssociation.CELL:
1034 return self.cell_data
1035 msg = f"association must resolve to 'point' or 'cell'; got {association.name}."
1036 raise ValueError(msg)
1037
1038 def to_pandas(
1039 self: Self, association: PointLiteral | CellLiteral = 'point'
1040 ) -> pandas.DataFrame:
1041 """Return this dataset's point or cell arrays as a :class:`pandas.DataFrame`.
1042
1043 Thin wrapper around :meth:`DataSetAttributes.to_pandas`. See that
1044 method for column-expansion rules and dtype handling.
1045
1046 Requires :mod:`pandas`.
1047
1048 Parameters
1049 ----------
1050 association : str | pyvista.core.utilities.arrays.FieldAssociation, default: 'point'
1051 Which attribute set to convert. Accepts ``'point'`` or
1052 ``FieldAssociation.POINT``, which maps to :attr:`point_data`
1053 (``n_points`` rows); or ``'cell'`` or ``FieldAssociation.CELL``,
1054 which maps to :attr:`cell_data` (``n_cells`` rows). Field data is
1055 not supported because its arrays may have differing lengths.
1056
1057 Returns
1058 -------
1059 pandas.DataFrame
1060 DataFrame with one column per (expanded) array.
1061
1062 See Also
1063 --------
1064 :ref:`dataframe_export_example`
1065
1066 Examples
1067 --------
1068 >>> import pyvista as pv
1069 >>> mesh = pv.Cube()
1070 >>> mesh.clear_data()
1071 >>> mesh.point_data['scalars'] = range(mesh.n_points)
1072 >>> df = mesh.to_pandas()
1073 >>> list(df.columns)
1074 ['scalars']
1075
1076 """
1077 return self._attributes_for_association(parse_field_choice(association)).to_pandas()
1078
1079 def to_arrow(self: Self, association: PointLiteral | CellLiteral = 'point') -> pyarrow.Table:
1080 """Return this dataset's point or cell arrays as a :class:`pyarrow.Table`.
1081
1082 Thin wrapper around :meth:`DataSetAttributes.to_arrow`.
1083
1084 Requires :mod:`pyarrow`.
1085
1086 Parameters
1087 ----------
1088 association : str | pyvista.core.utilities.arrays.FieldAssociation, default: 'point'
1089 Which attribute set to convert. Accepts ``'point'`` /
1090 ``FieldAssociation.POINT`` or ``'cell'`` / ``FieldAssociation.CELL``.
1091
1092 Returns
1093 -------
1094 pyarrow.Table
1095 Table with one column per (expanded) array.
1096
1097 Examples
1098 --------
1099 >>> import pyvista as pv
1100 >>> mesh = pv.Cube()
1101 >>> mesh.clear_data()
1102 >>> mesh.point_data['scalars'] = range(mesh.n_points)
1103 >>> mesh.to_arrow().num_rows
1104 8
1105
1106 """
1107 return self._attributes_for_association(parse_field_choice(association)).to_arrow()
1108
1109 def __arrow_c_stream__(self: Self, requested_schema: object | None = None) -> object:
1110 """Export :attr:`point_data` via the Arrow PyCapsule interface.
1111
1112 Delegates to :meth:`DataSetAttributes.__arrow_c_stream__` on
1113 :attr:`point_data`. Callers wanting :attr:`cell_data` should use
1114 ``mesh.cell_data`` directly or ``mesh.to_arrow('cell')``.
1115
1116 Requires :mod:`pyarrow`.
1117 """
1118 return self.point_data.__arrow_c_stream__(requested_schema)
1119
1120 @property
1121 def cell_data(self: Self) -> DataSetAttributes:
1122 """Return cell data as DataSetAttributes.
1123
1124 Returns
1125 -------
1126 DataSetAttributes
1127 Cell data as DataSetAttributes.
1128
1129 Examples
1130 --------
1131 Add cell arrays to a mesh and list the available ``cell_data``.
1132
1133 >>> import pyvista as pv
1134 >>> import numpy as np
1135 >>> mesh = pv.Cube()
1136 >>> mesh.clear_data()
1137 >>> mesh.cell_data['my_array'] = np.random.default_rng().random(mesh.n_cells)
1138 >>> mesh.cell_data['my_other_array'] = np.arange(mesh.n_cells)
1139 >>> mesh.cell_data
1140 pyvista DataSetAttributes
1141 Association : CELL
1142 Active Scalars : my_array
1143 Active Vectors : None
1144 Active Texture : None
1145 Active Normals : None
1146 Contains arrays :
1147 my_array float64 (6,) SCALARS
1148 my_other_array int64 (6,)
1149
1150 Access an array from ``cell_data``.
1151
1152 >>> mesh.cell_data['my_other_array']
1153 pyvista_ndarray([0, 1, 2, 3, 4, 5])
1154
1155 Or access it directly from the mesh.
1156
1157 >>> mesh['my_array'].shape
1158 (6,)
1159
1160 """
1161 return DataSetAttributes(
1162 self.GetCellData(),
1163 dataset=self,
1164 association=FieldAssociation.CELL,
1165 )
1166
1167 @property
1168 def n_points(self: Self) -> int:
1169 """Return the number of points in the entire dataset.
1170
1171 Returns
1172 -------
1173 int
1174 Number of points in the entire dataset.
1175
1176 Examples
1177 --------
1178 Create a mesh and return the number of points in the
1179 mesh.
1180
1181 >>> import pyvista as pv
1182 >>> cube = pv.Cube()
1183 >>> cube.n_points
1184 8
1185
1186 """
1187 return self.GetNumberOfPoints()
1188
1189 @property
1190 def n_cells(self: Self) -> int:
1191 """Return the number of cells in the entire dataset.
1192
1193 Returns
1194 -------
1195 int :
1196 Number of cells in the entire dataset.
1197
1198 Notes
1199 -----
1200 This returns the total number of cells -- for :class:`pyvista.PolyData`
1201 this includes vertices, lines, triangle strips and polygonal faces.
1202
1203 Examples
1204 --------
1205 Create a mesh and return the number of cells in the
1206 mesh.
1207
1208 >>> import pyvista as pv
1209 >>> cube = pv.Cube()
1210 >>> cube.n_cells
1211 6
1212
1213 """
1214 return self.GetNumberOfCells()
1215
1216 @property
1217 def number_of_points(self: Self) -> int: # pragma: no cover
1218 """Return the number of points.
1219
1220 Returns
1221 -------
1222 int :
1223 Number of points.
1224
1225 """
1226 return self.GetNumberOfPoints()
1227
1228 @property
1229 def number_of_cells(self: Self) -> int: # pragma: no cover
1230 """Return the number of cells.
1231
1232 Returns
1233 -------
1234 int :
1235 Number of cells.
1236
1237 """
1238 return self.GetNumberOfCells()
1239
1240 @property
1241 def bounds(self: Self) -> BoundsTuple:
1242 """Return the bounding box of this dataset.
1243
1244 Returns
1245 -------
1246 BoundsLike
1247 Bounding box of this dataset.
1248 The form is: ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
1249
1250 Examples
1251 --------
1252 Create a cube and return the bounds of the mesh.
1253
1254 >>> import pyvista as pv
1255 >>> cube = pv.Cube()
1256 >>> cube.bounds
1257 BoundsTuple(x_min = -0.5,
1258 x_max = 0.5,
1259 y_min = -0.5,
1260 y_max = 0.5,
1261 z_min = -0.5,
1262 z_max = 0.5)
1263
1264 """
1265 return BoundsTuple(*self.GetBounds())
1266
1267 @property
1268 def length(self: Self) -> float:
1269 """Return the length of the diagonal of the bounding box.
1270
1271 Returns
1272 -------
1273 float
1274 Length of the diagonal of the bounding box.
1275
1276 Examples
1277 --------
1278 Get the length of the bounding box of a cube. This should
1279 match ``3**(1/2)`` since it is the diagonal of a cube that is
1280 ``1 x 1 x 1``.
1281
1282 >>> import pyvista as pv
1283 >>> mesh = pv.Cube()
1284 >>> mesh.length
1285 1.7320508075688772
1286
1287 """
1288 return self.GetLength()
1289
1290 @property
1291 def center(self: Self) -> tuple[float, float, float]:
1292 """Set or return the center of the bounding box.
1293
1294 .. versionchanged:: 0.47
1295 Center can now be set.
1296
1297 Returns
1298 -------
1299 tuple[float, float, float]
1300 Center of the bounding box.
1301
1302 Examples
1303 --------
1304 Get the center of a mesh.
1305
1306 >>> import pyvista as pv
1307 >>> mesh = pv.Sphere(center=(1, 2, 0))
1308 >>> mesh.center
1309 (1.0, 2.0, 0.0)
1310
1311 """
1312 return self.GetCenter()
1313
1314 @center.setter
1315 def center(self, center: VectorLike[float]) -> None:
1316 valid_center = _validation.validate_array3(center, name='center')
1317 self.translate(valid_center - self.center, inplace=True)
1318
1319 @property
1320 def volume(
1321 self: Self,
1322 ) -> float:
1323 """Return the mesh volume.
1324
1325 This will return 0 for meshes with 2D cells.
1326
1327 Returns
1328 -------
1329 float
1330 Total volume of the mesh.
1331
1332 Examples
1333 --------
1334 Get the volume of a cube of size 4x4x4.
1335 Note that there are 5 points in each direction.
1336
1337 >>> import pyvista as pv
1338 >>> mesh = pv.ImageData(dimensions=(5, 5, 5))
1339 >>> mesh.volume
1340 64.0
1341
1342 A mesh with 2D cells has no volume.
1343
1344 >>> mesh = pv.ImageData(dimensions=(5, 5, 1))
1345 >>> mesh.volume
1346 0.0
1347
1348 :class:`pyvista.PolyData` is special as a 2D surface can
1349 enclose a 3D volume. This case uses a different methodology,
1350 see :func:`pyvista.PolyData.volume`.
1351
1352 >>> mesh = pv.Sphere()
1353 >>> mesh.volume
1354 0.51825
1355
1356 """
1357 sizes = self.compute_cell_sizes(length=False, area=False, volume=True)
1358 return sizes.cell_data['Volume'].sum().item()
1359
1360 @property
1361 def area(
1362 self: Self,
1363 ) -> float:
1364 """Return the mesh area if 2D.
1365
1366 This will return 0 for meshes with 3D cells.
1367
1368 Returns
1369 -------
1370 float
1371 Total area of the mesh.
1372
1373 Examples
1374 --------
1375 Get the area of a square of size 2x2.
1376 Note 5 points in each direction.
1377
1378 >>> import pyvista as pv
1379 >>> mesh = pv.ImageData(dimensions=(5, 5, 1))
1380 >>> mesh.area
1381 16.0
1382
1383 A mesh with 3D cells does not have an area. To get
1384 the outer surface area, first extract the surface using
1385 :func:`~pyvista.DataObjectFilters.extract_surface`.
1386
1387 >>> mesh = pv.ImageData(dimensions=(5, 5, 5))
1388 >>> mesh.area
1389 0.0
1390
1391 Get the area of a sphere. Discretization error results
1392 in slight difference from ``pi``.
1393
1394 >>> mesh = pv.Sphere()
1395 >>> mesh.area
1396 3.13
1397
1398 """
1399 sizes = self.compute_cell_sizes(length=False, area=True, volume=False)
1400 return sizes.cell_data['Area'].sum().item()
1401
1402 def get_array(
1403 self: Self,
1404 name: str,
1405 preference: CellLiteral | PointLiteral | FieldLiteral = 'cell',
1406 ) -> pyvista_ndarray:
1407 """Search both point, cell and field data for an array.
1408
1409 Parameters
1410 ----------
1411 name : str
1412 Name of the array.
1413
1414 preference : str, default: "cell"
1415 When scalars is specified, this is the preferred array
1416 type to search for in the dataset. Must be either
1417 ``'point'``, ``'cell'``, or ``'field'``.
1418
1419 Returns
1420 -------
1421 pyvista.pyvista_ndarray
1422 Requested array.
1423
1424 Examples
1425 --------
1426 Create a DataSet with a variety of arrays.
1427
1428 >>> import pyvista as pv
1429 >>> mesh = pv.Cube()
1430 >>> mesh.clear_data()
1431 >>> mesh.point_data['point-data'] = range(mesh.n_points)
1432 >>> mesh.cell_data['cell-data'] = range(mesh.n_cells)
1433 >>> mesh.field_data['field-data'] = ['a', 'b', 'c']
1434 >>> mesh.array_names
1435 ['point-data', 'field-data', 'cell-data']
1436
1437 Get the point data array.
1438
1439 >>> mesh.get_array('point-data')
1440 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
1441
1442 Get the cell data array.
1443
1444 >>> mesh.get_array('cell-data')
1445 pyvista_ndarray([0, 1, 2, 3, 4, 5])
1446
1447 Get the field data array.
1448
1449 >>> mesh.get_array('field-data')
1450 pyvista_ndarray(['a', 'b', 'c'], dtype='<U1')
1451
1452 """
1453 arr = get_array(self, name, preference=preference, err=True)
1454 if arr is None: # pragma: no cover
1455 raise RuntimeError # this should never be reached with err=True
1456 return arr
1457
1458 def get_array_association(
1459 self: Self,
1460 name: str,
1461 preference: Literal['cell', 'point', 'field'] = 'cell',
1462 ) -> FieldAssociation:
1463 """Get the association of an array.
1464
1465 Parameters
1466 ----------
1467 name : str
1468 Name of the array.
1469
1470 preference : str, default: "cell"
1471 When ``name`` is specified, this is the preferred array
1472 association to search for in the dataset. Must be either
1473 ``'point'``, ``'cell'``, or ``'field'``.
1474
1475 Returns
1476 -------
1477 pyvista.core.utilities.arrays.FieldAssociation
1478 Field association of the array.
1479
1480 Examples
1481 --------
1482 Create a DataSet with a variety of arrays.
1483
1484 >>> import pyvista as pv
1485 >>> mesh = pv.Cube()
1486 >>> mesh.clear_data()
1487 >>> mesh.point_data['point-data'] = range(mesh.n_points)
1488 >>> mesh.cell_data['cell-data'] = range(mesh.n_cells)
1489 >>> mesh.field_data['field-data'] = ['a', 'b', 'c']
1490 >>> mesh.array_names
1491 ['point-data', 'field-data', 'cell-data']
1492
1493 Get the point data array association.
1494
1495 >>> mesh.get_array_association('point-data')
1496 <FieldAssociation.POINT: 0>
1497
1498 Get the cell data array association.
1499
1500 >>> mesh.get_array_association('cell-data')
1501 <FieldAssociation.CELL: 1>
1502
1503 Get the field data array association.
1504
1505 >>> mesh.get_array_association('field-data')
1506 <FieldAssociation.NONE: 2>
1507
1508 """
1509 return get_array_association(self, name, preference=preference, err=True)
1510
1511 def __getitem__(
1512 self: Self,
1513 index: tuple[str, Literal['cell', 'point', 'field']] | str,
1514 ) -> pyvista_ndarray:
1515 """Search both point, cell, and field data for an array."""
1516 if isinstance(index, tuple):
1517 name, preference = index
1518 elif isinstance(index, str):
1519 name = index
1520 preference = 'cell'
1521 else:
1522 msg = ( # type: ignore[unreachable]
1523 f'Index ({index}) not understood.'
1524 ' Index must be a string name or a tuple of string name and string preference.'
1525 )
1526 raise KeyError(msg)
1527 return self.get_array(name, preference=preference)
1528
1529 def _ipython_key_completions_(self: Self) -> list[str]:
1530 """Tab completion of IPython."""
1531 return self.array_names
1532
1533 def __setitem__(
1534 self: Self,
1535 name: str,
1536 scalars: _ArrayLikeOrScalar[NumberType],
1537 ) -> None: # numpydoc ignore=PR01,RT01
1538 """Add/set an array in the point_data, or cell_data accordingly.
1539
1540 It depends on the array's length, or specified mode.
1541
1542 """
1543 # First check points - think of case with vertex cells
1544 # there would be the same number of cells as points but we'd want
1545 # the data to be on the nodes.
1546 if scalars is None:
1547 msg = 'Empty array unable to be added.' # type: ignore[unreachable]
1548 raise TypeError(msg)
1549 else:
1550 scalars = np.asanyarray(scalars)
1551
1552 if scalars.ndim == 0:
1553 if np.issubdtype(scalars.dtype, np.str_):
1554 # Always set scalar strings as field data
1555 self.field_data[name] = scalars
1556 return
1557 # reshape single scalar values from 0D to 1D so that shape[0] can be indexed
1558 scalars = scalars.reshape((1,))
1559
1560 # Now check array size to determine which field to place array
1561 if scalars.shape[0] == self.n_points:
1562 self.point_data[name] = scalars
1563 elif scalars.shape[0] == self.n_cells:
1564 self.cell_data[name] = scalars
1565 else:
1566 # Field data must be set explicitly as it could be a point of
1567 # confusion for new users
1568 raise_not_matching(scalars, self)
1569 return
1570
1571 @property
1572 def n_arrays(self: Self) -> int:
1573 """Return the number of arrays present in the dataset.
1574
1575 Returns
1576 -------
1577 int
1578 Number of arrays present in the dataset.
1579
1580 """
1581 n = self.GetPointData().GetNumberOfArrays()
1582 n += self.GetCellData().GetNumberOfArrays()
1583 n += self.GetFieldData().GetNumberOfArrays()
1584 return n
1585
1586 @property
1587 def array_names(self: Self) -> list[str]:
1588 """Return a list of array names for the dataset.
1589
1590 This makes sure to put the active scalars' name first in the list.
1591
1592 Returns
1593 -------
1594 list[str]
1595 List of array names for the dataset.
1596
1597 Examples
1598 --------
1599 Return the array names for a mesh.
1600
1601 >>> import pyvista as pv
1602 >>> mesh = pv.Sphere()
1603 >>> mesh.point_data['my_array'] = range(mesh.n_points)
1604 >>> mesh.array_names
1605 ['my_array', 'Normals']
1606
1607 """
1608 names: list[str] = []
1609 names.extend(self.field_data.keys())
1610 names.extend(self.point_data.keys())
1611 names.extend(self.cell_data.keys())
1612 if self.active_scalars_name is not None:
1613 names.remove(self.active_scalars_name)
1614 names.insert(0, self.active_scalars_name)
1615 return names
1616
1617 def _get_attrs(self: Self) -> list[tuple[str, Any, str]]:
1618 """Return the representation methods (internal helper)."""
1619 attrs: list[tuple[str, Any, str]] = []
1620 attrs.append(('N Cells', self.GetNumberOfCells(), '{}'))
1621 attrs.append(('N Points', self.GetNumberOfPoints(), '{}'))
1622 if isinstance(self, pv.PolyData):
1623 attrs.append(('N Strips', self.n_strips, '{}'))
1624 bds = self.bounds
1625 fmt = f'{pv.FLOAT_FORMAT}, {pv.FLOAT_FORMAT}'
1626 attrs.append(('X Bounds', (bds.x_min, bds.x_max), fmt))
1627 attrs.append(('Y Bounds', (bds.y_min, bds.y_max), fmt))
1628 attrs.append(('Z Bounds', (bds.z_min, bds.z_max), fmt))
1629 # if self.n_cells <= pyvista.REPR_VOLUME_MAX_CELLS and self.n_cells > 0:
1630 # attrs.append(("Volume", (self.volume), pyvista.FLOAT_FORMAT))
1631 return attrs
1632
1633 def _repr_html_(self: Self) -> str:
1634 """Return a pretty representation for Jupyter notebooks.
1635
1636 It includes header details and information about all arrays.
1637
1638 """
1639 sections: list[str] = []
1640
1641 # Metadata rows (always-visible)
1642 meta: list[tuple[str, list[tuple[str, str]], str]] = []
1643
1644 # Bounds
1645 bds = self.bounds
1646 fmt = pv.FLOAT_FORMAT
1647 meta.append(
1648 (
1649 'Bounds',
1650 [
1651 ('X', f'[{fmt.format(bds.x_min)}, {fmt.format(bds.x_max)}]'),
1652 ('Y', f'[{fmt.format(bds.y_min)}, {fmt.format(bds.y_max)}]'),
1653 ('Z', f'[{fmt.format(bds.z_min)}, {fmt.format(bds.z_max)}]'),
1654 ],
1655 repr(tuple(bds)),
1656 )
1657 )
1658
1659 # PolyData cell-type breakdown
1660 if isinstance(self, pv.PolyData):
1661 poly_items: list[tuple[str, str]] = []
1662 if self.n_faces:
1663 poly_items.append(('faces', f'{self.n_faces:,}'))
1664 if self.n_lines:
1665 poly_items.append(('lines', f'{self.n_lines:,}'))
1666 if self.n_strips:
1667 poly_items.append(('strips', f'{self.n_strips:,}'))
1668 if self.n_verts:
1669 poly_items.append(('verts', f'{self.n_verts:,}'))
1670 if poly_items:
1671 meta.append(('Cells', poly_items, ''))
1672
1673 # Grid-specific properties
1674 if hasattr(self, 'dimensions'):
1675 dims = self.dimensions
1676 grid_items: list[tuple[str, str]] = [
1677 ('dims', f'{dims[0]} x {dims[1]} x {dims[2]}'),
1678 ]
1679 if hasattr(self, 'spacing'):
1680 sp = self.spacing
1681 grid_items.append(
1682 ('spacing', f'({fmt.format(sp[0])}, {fmt.format(sp[1])}, {fmt.format(sp[2])})')
1683 )
1684 meta.append(('Grid', grid_items, ''))
1685
1686 # Collect active array names per association
1687 pt_scalars = self.active_scalars_info
1688 active_pt_scalars = (
1689 pt_scalars.name if pt_scalars.association == FieldAssociation.POINT else None
1690 )
1691 active_cell_scalars = (
1692 pt_scalars.name if pt_scalars.association == FieldAssociation.CELL else None
1693 )
1694 active_vectors = self.active_vectors_name
1695 pt_normals = self.point_data.active_normals_name if self.point_data else None
1696 cell_normals = self.cell_data.active_normals_name if self.cell_data else None
1697 pt_tcoords = self.point_data.active_texture_coordinates_name if self.point_data else None
1698
1699 def _array_info(
1700 attrs: DataSetAttributes,
1701 *,
1702 show_shape: bool = False,
1703 show_range: bool = False,
1704 ) -> list[tuple[str, int, str, str, str]]:
1705 fmt = pv.FLOAT_FORMAT
1706 result: list[tuple[str, int, str, str, str]] = []
1707 for name, arr in attrs.items():
1708 # Field data can contain str values at runtime despite
1709 # DataSetAttributes.items() being typed as -> pyvista_ndarray.
1710 # Wrap str so .shape / .dtype are available.
1711 coerced = pv.pyvista_ndarray(arr) if isinstance(arr, str) else arr # type: ignore[redundant-expr,unreachable]
1712 ncomp = coerced.shape[1] if coerced.ndim > 1 else 1
1713 shape = str(tuple(coerced.shape)) if show_shape else ''
1714 range_str = ''
1715 if show_range and coerced.size > 0 and np.issubdtype(coerced.dtype, np.number):
1716 lo = fmt.format(np.nanmin(coerced))
1717 hi = fmt.format(np.nanmax(coerced))
1718 range_str = f'[{lo}, {hi}]'
1719 result.append((name, ncomp, str(coerced.dtype), shape, range_str))
1720 return result
1721
1722 vec_assoc = self.active_vectors_info.association
1723 pt_vectors = active_vectors if vec_assoc == FieldAssociation.POINT else None
1724 cell_vectors = active_vectors if vec_assoc == FieldAssociation.CELL else None
1725
1726 # Point Data
1727 if self.point_data:
1728 sections.append(
1729 _data_array_section(
1730 'Point Data',
1731 _array_info(self.point_data, show_range=True),
1732 active_scalars=active_pt_scalars,
1733 active_vectors=pt_vectors,
1734 active_normals=pt_normals,
1735 active_tcoords=pt_tcoords,
1736 )
1737 )
1738
1739 # Cell Data
1740 if self.cell_data:
1741 sections.append(
1742 _data_array_section(
1743 'Cell Data',
1744 _array_info(self.cell_data, show_range=True),
1745 active_scalars=active_cell_scalars,
1746 active_vectors=cell_vectors,
1747 active_normals=cell_normals,
1748 )
1749 )
1750
1751 # Field Data — show full shape since arrays are arbitrary length
1752 if self.field_data:
1753 sections.append(
1754 _data_array_section(
1755 'Field Data',
1756 _array_info(self.field_data, show_shape=True),
1757 )
1758 )
1759
1760 return build_repr_html(
1761 obj_type=type(self).__name__,
1762 mesh_type=type(self).__name__,
1763 header_badges=[
1764 f'{self.n_points:,} points',
1765 f'{self.n_cells:,} cells',
1766 _fmt_memory(self.actual_memory_size),
1767 ],
1768 metadata=meta,
1769 sections=sections,
1770 text_repr=self.head(display=False, html=False),
1771 )
1772
1773 def __repr__(self: Self) -> str:
1774 """Return the object representation."""
1775 return self.head(display=False, html=False)
1776
1777 def __str__(self: Self) -> str:
1778 """Return the object string representation."""
1779 return self.head(display=False, html=False)
1780
1781 @_deprecate_positional_args(allowed=['mesh'])
1782 def copy_from(self: Self, mesh: _vtk.vtkDataSet, deep: bool = True) -> None: # noqa: FBT001, FBT002
1783 """Overwrite this dataset inplace with the new dataset's geometries and data.
1784
1785 Parameters
1786 ----------
1787 mesh : :vtk:`vtkDataSet`
1788 The overwriting mesh.
1789
1790 deep : bool, default: True
1791 Whether to perform a deep or shallow copy.
1792
1793 Examples
1794 --------
1795 Create two meshes and overwrite ``mesh_a`` with ``mesh_b``.
1796 Show that ``mesh_a`` is equal to ``mesh_b``.
1797
1798 >>> import pyvista as pv
1799 >>> mesh_a = pv.Sphere()
1800 >>> mesh_b = pv.Cube()
1801 >>> mesh_a.copy_from(mesh_b)
1802 >>> mesh_a == mesh_b
1803 True
1804
1805 """
1806 # Allow child classes to overwrite parent classes
1807 if not isinstance(self, type(mesh)):
1808 msg = (
1809 f'The Input DataSet type {type(mesh)} must be '
1810 f'compatible with the one being overwritten {type(self)}'
1811 )
1812 raise TypeError(msg)
1813 if deep: # type: ignore[unreachable]
1814 self.deep_copy(mesh)
1815 else:
1816 self.shallow_copy(mesh)
1817 if is_pyvista_dataset(mesh):
1818 self.copy_meta_from(mesh, deep=deep)
1819
1820 def cast_to_unstructured_grid(self: Self) -> pv.UnstructuredGrid:
1821 """Get a new representation of this object as a :class:`~pyvista.UnstructuredGrid`.
1822
1823 .. note::
1824
1825 Casting preserves the cell type(s) of the input. This means that any
1826 :class:`~pyvista.CellType.PIXEL` and :class:`~pyvista.CellType.VOXEL` cells from
1827 :class:`~pyvista.ImageData` or :class:`~pyvista.RectilinearGrid` are preserved.
1828 Use ``to_quads`` or ``to_hexahedra`` instead to convert the cell
1829 type for these cases.
1830
1831 Returns
1832 -------
1833 pyvista.UnstructuredGrid
1834 Dataset cast into a :class:`pyvista.UnstructuredGrid`.
1835
1836 Examples
1837 --------
1838 Cast a :class:`pyvista.PolyData` to a
1839 :class:`pyvista.UnstructuredGrid`.
1840
1841 >>> import pyvista as pv
1842 >>> mesh = pv.Sphere()
1843 >>> type(mesh)
1844 <class 'pyvista.core.pointset.PolyData'>
1845 >>> grid = mesh.cast_to_unstructured_grid()
1846 >>> type(grid)
1847 <class 'pyvista.core.pointset.UnstructuredGrid'>
1848
1849 """
1850 alg = _vtk.vtkAppendFilter()
1851 alg.AddInputData(self)
1852 alg.Update()
1853 return _get_output(alg)
1854
1855 @_deprecate_positional_args
1856 def cast_to_pointset(self: Self, pass_cell_data: bool = False) -> PointSet: # noqa: FBT001, FBT002
1857 """Extract the points of this dataset and return a :class:`pyvista.PointSet`.
1858
1859 Parameters
1860 ----------
1861 pass_cell_data : bool, default: False
1862 Run the :func:`cell_data_to_point_data()
1863 <pyvista.DataObjectFilters.cell_data_to_point_data>` filter and pass
1864 cell data fields to the new pointset.
1865
1866 Returns
1867 -------
1868 pyvista.PointSet
1869 Dataset cast into a :class:`pyvista.PointSet`.
1870
1871 Notes
1872 -----
1873 This will produce a deep copy of the points and point/cell data of
1874 the original mesh.
1875
1876 See Also
1877 --------
1878 :ref:`create_pointset_example`
1879
1880 Examples
1881 --------
1882 >>> import pyvista as pv
1883 >>> mesh = pv.Wavelet()
1884 >>> pointset = mesh.cast_to_pointset()
1885 >>> type(pointset)
1886 <class 'pyvista.core.pointset.PointSet'>
1887
1888 """
1889 pset = pv.PointSet()
1890 pset.points = self.points.copy()
1891 out = self.cell_data_to_point_data() if pass_cell_data else self
1892 pset.GetPointData().DeepCopy(out.GetPointData())
1893 pset.active_scalars_name = out.active_scalars_name
1894 return pset
1895
1896 @_deprecate_positional_args
1897 def cast_to_poly_points(self: Self, pass_cell_data: bool = False) -> pv.PolyData: # noqa: FBT001, FBT002
1898 """Extract the points of this dataset and return a :class:`pyvista.PolyData`.
1899
1900 Parameters
1901 ----------
1902 pass_cell_data : bool, default: False
1903 Run the :func:`cell_data_to_point_data()
1904 <pyvista.DataObjectFilters.cell_data_to_point_data>` filter and pass
1905 cell data fields to the new pointset.
1906
1907 Returns
1908 -------
1909 pyvista.PolyData
1910 Dataset cast into a :class:`pyvista.PolyData`.
1911
1912 Notes
1913 -----
1914 This will produce a deep copy of the points and point/cell data of
1915 the original mesh.
1916
1917 Examples
1918 --------
1919 >>> from pyvista import examples
1920 >>> mesh = examples.load_uniform()
1921 >>> points = mesh.cast_to_poly_points(pass_cell_data=True)
1922 >>> type(points)
1923 <class 'pyvista.core.pointset.PolyData'>
1924 >>> points.n_arrays
1925 2
1926 >>> points.point_data
1927 pyvista DataSetAttributes
1928 Association : POINT
1929 Active Scalars : Spatial Point Data
1930 Active Vectors : None
1931 Active Texture : None
1932 Active Normals : None
1933 Contains arrays :
1934 Spatial Point Data float64 (1000,) SCALARS
1935 >>> points.cell_data
1936 pyvista DataSetAttributes
1937 Association : CELL
1938 Active Scalars : None
1939 Active Vectors : None
1940 Active Texture : None
1941 Active Normals : None
1942 Contains arrays :
1943 Spatial Cell Data float64 (1000,)
1944
1945 """
1946 pset = pv.PolyData(self.points.copy())
1947 if pass_cell_data:
1948 cell_data = self.copy()
1949 cell_data.clear_point_data()
1950 cell_data = cell_data.cell_data_to_point_data()
1951 pset.GetCellData().DeepCopy(cell_data.GetPointData())
1952 pset.GetPointData().DeepCopy(self.GetPointData())
1953 pset.active_scalars_name = self.active_scalars_name
1954 return pset
1955
1956 @overload
1957 def find_closest_point(self: Self, point: Iterable[float], n: Literal[1] = 1) -> int: ...
1958 @overload
1959 def find_closest_point(
1960 self: Self, point: Iterable[float], n: int = ...
1961 ) -> VectorLike[int]: ...
1962 def find_closest_point(
1963 self: Self, point: Iterable[float], n: int = 1
1964 ) -> int | VectorLike[int]:
1965 """Find index of closest point in this mesh to the given point.
1966
1967 If wanting to query many points, use a KDTree with scipy or another
1968 library as those implementations will be easier to work with.
1969
1970 See: https://github.com/pyvista/pyvista-support/issues/107
1971
1972 Parameters
1973 ----------
1974 point : sequence[float]
1975 Length 3 coordinate of the point to query.
1976
1977 n : int, optional
1978 If greater than ``1``, returns the indices of the ``n`` closest
1979 points.
1980
1981 Returns
1982 -------
1983 int
1984 The index of the point in this mesh that is closest to the given point.
1985
1986 See Also
1987 --------
1988 DataSet.find_closest_cell
1989 DataSet.find_containing_cell
1990 DataSet.find_cells_along_line
1991 DataSet.find_cells_within_bounds
1992 :ref:`point_cloud_distance_example`
1993 :ref:`point_cloud_neighbors_example`
1994
1995 Examples
1996 --------
1997 Find the index of the closest point to ``(0, 1, 0)``.
1998
1999 >>> import pyvista as pv
2000 >>> mesh = pv.Sphere()
2001 >>> index = mesh.find_closest_point((0, 1, 0))
2002 >>> index
2003 239
2004
2005 Get the coordinate of that point.
2006
2007 >>> mesh.points[index]
2008 pyvista_ndarray([-0.05218758, 0.49653167, 0.02706946], dtype=float32)
2009
2010 """
2011 if not isinstance(point, (np.ndarray, Sequence)) or len(point) != 3:
2012 msg = 'Given point must be a length three sequence.'
2013 raise TypeError(msg)
2014 if not isinstance(n, int):
2015 msg = '`n` must be a positive integer.' # type: ignore[unreachable]
2016 raise TypeError(msg)
2017 if n < 1:
2018 msg = '`n` must be a positive integer.'
2019 raise ValueError(msg)
2020
2021 locator = _vtk.vtkPointLocator()
2022 locator.SetDataSet(self)
2023 locator.BuildLocator()
2024 if n > 1:
2025 id_list = _vtk.vtkIdList()
2026 locator.FindClosestNPoints(n, point, id_list) # type: ignore[arg-type]
2027 return vtk_id_list_to_array(id_list)
2028 return locator.FindClosestPoint(point) # type: ignore[arg-type]
2029
2030 @_deprecate_positional_args(allowed=['point'])
2031 def find_closest_cell(
2032 self: Self,
2033 point: VectorLike[float] | MatrixLike[float],
2034 return_closest_point: bool = False, # noqa: FBT001, FBT002
2035 ) -> int | NumpyArray[int] | tuple[int | NumpyArray[int], NumpyArray[int]]:
2036 """Find index of closest cell in this mesh to the given point.
2037
2038 Parameters
2039 ----------
2040 point : VectorLike[float] | MatrixLike[float]
2041 Coordinates of point to query (length 3) or a
2042 :class:`numpy.ndarray` of ``n`` points with shape ``(n, 3)``.
2043
2044 return_closest_point : bool, default: False
2045 If ``True``, the closest point within a mesh cell to that point is
2046 returned. This is not necessarily the closest nodal point on the
2047 mesh. Default is ``False``.
2048
2049 Returns
2050 -------
2051 int or numpy.ndarray
2052 Index or indices of the cell in this mesh that is/are closest
2053 to the given point(s).
2054
2055 .. versionchanged:: 0.35.0
2056 Inputs of shape ``(1, 3)`` now return a :class:`numpy.ndarray`
2057 of shape ``(1,)``.
2058
2059 numpy.ndarray
2060 Point or points inside a cell of the mesh that is/are closest
2061 to the given point(s). Only returned if
2062 ``return_closest_point=True``.
2063
2064 .. versionchanged:: 0.35.0
2065 Inputs of shape ``(1, 3)`` now return a :class:`numpy.ndarray`
2066 of the same shape.
2067
2068 Warnings
2069 --------
2070 This method may still return a valid cell index even if the point
2071 contains a value like ``numpy.inf`` or ``numpy.nan``.
2072
2073 See Also
2074 --------
2075 DataSet.find_closest_point
2076 DataSet.find_containing_cell
2077 DataSet.find_cells_along_line
2078 DataSet.find_cells_within_bounds
2079 :ref:`distance_between_surfaces_example`
2080
2081 Examples
2082 --------
2083 Find nearest cell on a sphere centered on the
2084 origin to the point ``[0.1, 0.2, 0.3]``.
2085
2086 >>> import pyvista as pv
2087 >>> mesh = pv.Sphere()
2088 >>> point = [0.1, 0.2, 0.3]
2089 >>> index = mesh.find_closest_cell(point)
2090 >>> index
2091 338
2092
2093 Make sure that this cell indeed is the closest to
2094 ``[0.1, 0.2, 0.3]``.
2095
2096 >>> import numpy as np
2097 >>> cell_centers = mesh.cell_centers()
2098 >>> relative_position = cell_centers.points - point
2099 >>> distance = np.linalg.norm(relative_position, axis=1)
2100 >>> np.argmin(distance)
2101 np.int64(338)
2102
2103 Find the nearest cells to several random points that
2104 are centered on the origin.
2105
2106 >>> points = 2 * np.random.default_rng().random((5000, 3)) - 1
2107 >>> indices = mesh.find_closest_cell(points)
2108 >>> indices.shape
2109 (5000,)
2110
2111 For the closest cell, find the point inside the cell that is
2112 closest to the supplied point. The rectangle is a unit square
2113 with 1 cell and 4 nodal points at the corners in the plane with
2114 ``z`` normal and ``z=0``. The closest point inside the cell is
2115 not usually at a nodal point.
2116
2117 >>> unit_square = pv.Rectangle()
2118 >>> index, closest_point = unit_square.find_closest_cell(
2119 ... [0.25, 0.25, 0.5], return_closest_point=True
2120 ... )
2121 >>> closest_point
2122 array([0.25, 0.25, 0. ])
2123
2124 But, the closest point can be a nodal point, although the index of
2125 that point is not returned. If the closest nodal point by index is
2126 desired, see :func:`DataSet.find_closest_point`.
2127
2128 >>> index, closest_point = unit_square.find_closest_cell(
2129 ... [1.0, 1.0, 0.5], return_closest_point=True
2130 ... )
2131 >>> closest_point
2132 array([1., 1., 0.])
2133
2134 """
2135 point, singular = _coerce_pointslike_arg(point, copy=False)
2136
2137 locator = _vtk.vtkCellLocator()
2138 locator.SetDataSet(self)
2139 locator.BuildLocator()
2140
2141 cell = _vtk.vtkGenericCell()
2142
2143 closest_cells: list[int] = []
2144 closest_points: list[list[float]] = []
2145
2146 for node in point:
2147 closest_point = [0.0, 0.0, 0.0]
2148 cell_id = _vtk.mutable(0)
2149 sub_id = _vtk.mutable(0)
2150 dist2 = _vtk.mutable(0.0)
2151
2152 locator.FindClosestPoint(node, closest_point, cell, cell_id, sub_id, dist2) # type: ignore[call-overload]
2153 closest_cells.append(int(cell_id)) # type: ignore[call-overload]
2154 closest_points.append(closest_point)
2155
2156 out_cells: int | NumpyArray[int] = (
2157 closest_cells[0] if singular else np.array(closest_cells)
2158 )
2159 out_points = np.array(closest_points[0]) if singular else np.array(closest_points)
2160
2161 if return_closest_point:
2162 return out_cells, out_points
2163 return out_cells
2164
2165 def find_containing_cell(
2166 self: Self,
2167 point: VectorLike[float] | MatrixLike[float],
2168 ) -> int | NumpyArray[int]:
2169 """Find index of a cell that contains the given point.
2170
2171 Parameters
2172 ----------
2173 point : VectorLike[float] | MatrixLike[float],
2174 Coordinates of point to query (length 3) or a
2175 :class:`numpy.ndarray` of ``n`` points with shape ``(n, 3)``.
2176
2177 Returns
2178 -------
2179 output : int | numpy.ndarray
2180 Index or indices of the cell in this mesh that contains
2181 the given point.
2182
2183 .. versionchanged:: 0.35.0
2184 Inputs of shape ``(1, 3)`` now return a :class:`numpy.ndarray`
2185 of shape ``(1,)``.
2186
2187 See Also
2188 --------
2189 DataSet.find_closest_point
2190 DataSet.find_closest_cell
2191 DataSet.find_cells_along_line
2192 DataSet.find_cells_within_bounds
2193
2194 Examples
2195 --------
2196 A unit square with 16 equal sized cells is created and a cell
2197 containing the point ``[0.3, 0.3, 0.0]`` is found.
2198
2199 >>> import pyvista as pv
2200 >>> mesh = pv.ImageData(dimensions=[5, 5, 1], spacing=[1 / 4, 1 / 4, 0])
2201 >>> mesh
2202 ImageData...
2203 >>> mesh.find_containing_cell([0.3, 0.3, 0.0])
2204 5
2205
2206 A point outside the mesh domain will return ``-1``.
2207
2208 >>> mesh.find_containing_cell([0.3, 0.3, 1.0])
2209 -1
2210
2211 Find the cells that contain 1000 random points inside the mesh.
2212
2213 >>> import numpy as np
2214 >>> points = np.random.default_rng().random((1000, 3))
2215 >>> indices = mesh.find_containing_cell(points)
2216 >>> indices.shape
2217 (1000,)
2218
2219 """
2220 point, singular = _coerce_pointslike_arg(point, copy=False)
2221
2222 locator = _vtk.vtkCellLocator()
2223 locator.SetDataSet(self)
2224 locator.BuildLocator()
2225
2226 containing_cells = [locator.FindCell(node) for node in point]
2227 return containing_cells[0] if singular else np.array(containing_cells)
2228
2229 def find_cells_along_line(
2230 self: Self,
2231 pointa: VectorLike[float],
2232 pointb: VectorLike[float],
2233 tolerance: float = 0.0,
2234 ) -> NumpyArray[int]:
2235 """Find the index of cells whose bounds intersect a line.
2236
2237 Line is defined from ``pointa`` to ``pointb``.
2238
2239 Parameters
2240 ----------
2241 pointa : VectorLike
2242 Length 3 coordinate of the start of the line.
2243
2244 pointb : VectorLike
2245 Length 3 coordinate of the end of the line.
2246
2247 tolerance : float, default: 0.0
2248 The absolute tolerance to use to find cells along line.
2249
2250 Returns
2251 -------
2252 numpy.ndarray
2253 Index or indices of the cell(s) whose bounds intersect
2254 the line.
2255
2256 Warnings
2257 --------
2258 This method returns cells whose bounds intersect the line.
2259 This means that the line may not intersect the cell itself.
2260 To obtain cells that intersect the line, use
2261 :func:`pyvista.DataSet.find_cells_intersecting_line`.
2262
2263 See Also
2264 --------
2265 DataSet.find_closest_point
2266 DataSet.find_closest_cell
2267 DataSet.find_containing_cell
2268 DataSet.find_cells_within_bounds
2269 DataSet.find_cells_intersecting_line
2270
2271 Examples
2272 --------
2273 >>> import pyvista as pv
2274 >>> mesh = pv.Sphere()
2275 >>> mesh.find_cells_along_line([0.0, 0, 0], [1.0, 0, 0])
2276 array([ 86, 87, 1652, 1653])
2277
2278 """
2279 if np.array(pointa).size != 3:
2280 msg = 'Point A must be a length three tuple of floats.'
2281 raise TypeError(msg)
2282 if np.array(pointb).size != 3:
2283 msg = 'Point B must be a length three tuple of floats.'
2284 raise TypeError(msg)
2285 locator = _vtk.vtkCellLocator()
2286 locator.SetDataSet(self)
2287 locator.BuildLocator()
2288 id_list = _vtk.vtkIdList()
2289 locator.FindCellsAlongLine(
2290 cast('Sequence[float]', pointa),
2291 cast('Sequence[float]', pointb),
2292 tolerance,
2293 id_list,
2294 )
2295 return vtk_id_list_to_array(id_list)
2296
2297 def find_cells_intersecting_line(
2298 self: Self,
2299 pointa: VectorLike[float],
2300 pointb: VectorLike[float],
2301 tolerance: float = 0.0,
2302 ) -> NumpyArray[int]:
2303 """Find the index of cells that intersect a line.
2304
2305 Line is defined from ``pointa`` to ``pointb``. This
2306 method requires vtk version >=9.2.0.
2307
2308 Parameters
2309 ----------
2310 pointa : sequence[float]
2311 Length 3 coordinate of the start of the line.
2312
2313 pointb : sequence[float]
2314 Length 3 coordinate of the end of the line.
2315
2316 tolerance : float, default: 0.0
2317 The absolute tolerance to use to find cells along line.
2318
2319 Returns
2320 -------
2321 numpy.ndarray
2322 Index or indices of the cell(s) that intersect
2323 the line.
2324
2325 See Also
2326 --------
2327 DataSet.find_closest_point
2328 DataSet.find_closest_cell
2329 DataSet.find_containing_cell
2330 DataSet.find_cells_within_bounds
2331 DataSet.find_cells_along_line
2332
2333 Examples
2334 --------
2335 >>> import pyvista as pv
2336 >>> mesh = pv.Sphere()
2337 >>> mesh.find_cells_intersecting_line([0.0, 0, 0], [1.0, 0, 0])
2338 array([ 86, 1653])
2339
2340 """
2341 if np.array(pointa).size != 3:
2342 msg = 'Point A must be a length three tuple of floats.'
2343 raise TypeError(msg)
2344 if np.array(pointb).size != 3:
2345 msg = 'Point B must be a length three tuple of floats.'
2346 raise TypeError(msg)
2347 locator = _vtk.vtkCellLocator()
2348 locator.SetDataSet(cast('_vtk.vtkDataSet', self))
2349 locator.BuildLocator()
2350 id_list = _vtk.vtkIdList()
2351 points = _vtk.vtkPoints()
2352 cell = _vtk.vtkGenericCell()
2353 locator.IntersectWithLine(
2354 cast('Sequence[float]', pointa),
2355 cast('Sequence[float]', pointb),
2356 tolerance,
2357 points,
2358 id_list,
2359 cell,
2360 )
2361 return vtk_id_list_to_array(id_list)
2362
2363 def find_cells_within_bounds(self: Self, bounds: BoundsTuple) -> NumpyArray[int]:
2364 """Find the index of cells in this mesh within bounds.
2365
2366 Parameters
2367 ----------
2368 bounds : sequence[float]
2369 Bounding box. The form is: ``(x_min, x_max, y_min, y_max, z_min, z_max)``.
2370
2371 Returns
2372 -------
2373 numpy.ndarray
2374 Index or indices of the cell in this mesh that are closest
2375 to the given point.
2376
2377 See Also
2378 --------
2379 DataSet.find_closest_point
2380 DataSet.find_closest_cell
2381 DataSet.find_containing_cell
2382 DataSet.find_cells_along_line
2383
2384 Examples
2385 --------
2386 >>> import pyvista as pv
2387 >>> mesh = pv.Cube()
2388 >>> index = mesh.find_cells_within_bounds([-2.0, 2.0, -2.0, 2.0, -2.0, 2.0])
2389
2390 """
2391 if np.array(bounds).size != 6:
2392 msg = 'Bounds must be a length six tuple of floats.'
2393 raise TypeError(msg)
2394 locator = _vtk.vtkCellTreeLocator()
2395 locator.SetDataSet(cast('_vtk.vtkDataSet', self))
2396 locator.BuildLocator()
2397 id_list = _vtk.vtkIdList()
2398 locator.FindCellsWithinBounds(list(bounds), id_list)
2399 return vtk_id_list_to_array(id_list)
2400
2401 def get_cell(self: Self, index: int) -> Cell:
2402 """Return a :class:`pyvista.Cell` object.
2403
2404 Parameters
2405 ----------
2406 index : int
2407 Cell ID.
2408
2409 Returns
2410 -------
2411 pyvista.Cell
2412 The i-th pyvista.Cell.
2413
2414 Notes
2415 -----
2416 Cells returned from this method are deep copies of the original
2417 cells. Changing properties (for example, ``points``) will not affect
2418 the dataset they originated from.
2419
2420 Examples
2421 --------
2422 Get the 0-th cell.
2423
2424 >>> from pyvista import examples
2425 >>> mesh = examples.load_airplane()
2426 >>> cell = mesh.get_cell(0)
2427 >>> cell
2428 Cell ...
2429
2430 Get the point ids of the first cell
2431
2432 >>> cell.point_ids
2433 [0, 1, 2]
2434
2435 Get the point coordinates of the first cell
2436
2437 >>> cell.points
2438 array([[897.0, 48.8, 82.3],
2439 [906.6, 48.8, 80.7],
2440 [907.5, 55.5, 83.7]])
2441
2442 For the first cell, get the points associated with the first edge
2443
2444 >>> cell.edges[0].point_ids
2445 [0, 1]
2446
2447 For a Tetrahedron, get the point ids of the last face
2448
2449 >>> mesh = examples.cells.Tetrahedron()
2450 >>> cell = mesh.get_cell(0)
2451 >>> cell.faces[-1].point_ids
2452 [0, 2, 1]
2453
2454 """
2455 # must check upper bounds, otherwise segfaults (on Linux, 9.2)
2456 if index + 1 > self.n_cells:
2457 msg = f'Invalid index {index} for a dataset with {self.n_cells} cells.'
2458 raise IndexError(msg)
2459
2460 # Note: we have to use vtkGenericCell here since
2461 # GetCell(vtkIdType cellId, vtkGenericCell* cell) is thread-safe,
2462 # while GetCell(vtkIdType cellId) is not.
2463 cell = pv.Cell()
2464 self.GetCell(index, cell)
2465 cell.SetCellType(self.GetCellType(index))
2466 return cell
2467
2468 @property
2469 def cell(self: Self) -> Iterator[Cell]:
2470 """A generator that provides an easy way to loop over all cells.
2471
2472 To access a single cell, use :func:`pyvista.DataSet.get_cell`.
2473
2474 .. versionchanged:: 0.39.0
2475 Now returns a generator instead of a list.
2476 Use ``get_cell(i)`` instead of ``cell[i]``.
2477
2478 Yields
2479 ------
2480 pyvista.Cell
2481
2482 See Also
2483 --------
2484 pyvista.DataSet.get_cell
2485
2486 Examples
2487 --------
2488 Loop over the cells
2489
2490 >>> import pyvista as pv
2491 >>> # Create a grid with 9 points and 4 cells
2492 >>> mesh = pv.ImageData(dimensions=(3, 3, 1))
2493 >>> for cell in mesh.cell: # doctest: +SKIP
2494 ... cell
2495
2496 """
2497 for i in range(self.n_cells):
2498 yield self.get_cell(i)
2499
2500 def cell_neighbors(self: Self, ind: int, connections: str = 'points') -> list[int]:
2501 """Get the cell neighbors of the ind-th cell.
2502
2503 Concrete implementation of :vtk:`vtkDataSet.GetCellNeighbors`.
2504
2505 Parameters
2506 ----------
2507 ind : int
2508 Cell ID.
2509
2510 connections : str, default: "points"
2511 Describe how the neighbor cell(s) must be connected to the current
2512 cell to be considered as a neighbor.
2513 Can be either ``'points'``, ``'edges'`` or ``'faces'``.
2514
2515 Returns
2516 -------
2517 list[int]
2518 List of neighbor cells IDs for the ind-th cell.
2519
2520 Warnings
2521 --------
2522 For a :class:`pyvista.ExplicitStructuredGrid`, use
2523 :func:`pyvista.ExplicitStructuredGrid.neighbors`.
2524
2525 See Also
2526 --------
2527 pyvista.DataSet.cell_neighbors_levels
2528
2529 Examples
2530 --------
2531 >>> from pyvista import examples
2532 >>> mesh = examples.load_airplane()
2533
2534 Get the neighbor cell ids that have at least one point in common with
2535 the 0-th cell.
2536
2537 >>> mesh.cell_neighbors(0, 'points')
2538 [1, 2, 3, 388, 389, 11, 12, 395, 14, 209, 211, 212]
2539
2540 Get the neighbor cell ids that have at least one edge in common with
2541 the 0-th cell.
2542
2543 >>> mesh.cell_neighbors(0, 'edges')
2544 [1, 3, 12]
2545
2546 For unstructured grids with cells of dimension 3 (Tetrahedron for example),
2547 cell neighbors can be defined using faces.
2548
2549 >>> mesh = examples.download_tetrahedron()
2550 >>> mesh.cell_neighbors(0, 'faces')
2551 [1, 5, 7]
2552
2553 Show a visual example.
2554
2555 >>> from functools import partial
2556 >>> import pyvista as pv
2557 >>> mesh = pv.Sphere(theta_resolution=10)
2558 >>>
2559 >>> pl = pv.Plotter(shape=(1, 2))
2560 >>> pl.link_views()
2561 >>> add_point_labels = partial(
2562 ... pl.add_point_labels,
2563 ... text_color='white',
2564 ... font_size=20,
2565 ... shape=None,
2566 ... show_points=False,
2567 ... )
2568 >>>
2569 >>> for i, connection in enumerate(['points', 'edges']):
2570 ... pl.subplot(0, i)
2571 ... pl.view_xy()
2572 ... _ = pl.add_title(
2573 ... f'{connection.capitalize()} neighbors',
2574 ... color='red',
2575 ... shadow=True,
2576 ... font_size=8,
2577 ... )
2578 ...
2579 ... # Add current cell
2580 ... i_cell = 0
2581 ... current_cell = mesh.extract_cells(i_cell)
2582 ... _ = pl.add_mesh(current_cell, show_edges=True, color='blue')
2583 ... _ = add_point_labels(
2584 ... current_cell.cell_centers().points,
2585 ... labels=[f'{i_cell}'],
2586 ... )
2587 ...
2588 ... # Add neighbors
2589 ... ids = mesh.cell_neighbors(i_cell, connection)
2590 ... cells = mesh.extract_cells(ids)
2591 ... _ = pl.add_mesh(cells, color='red', show_edges=True)
2592 ... _ = add_point_labels(
2593 ... cells.cell_centers().points,
2594 ... labels=[f'{i}' for i in ids],
2595 ... )
2596 ...
2597 ... # Add other cells
2598 ... ids.append(i_cell)
2599 ... others = mesh.extract_cells(ids, invert=True)
2600 ... _ = pl.add_mesh(others, show_edges=True)
2601 >>> pl.show()
2602
2603 """
2604 if isinstance(self, _vtk.vtkExplicitStructuredGrid):
2605 msg = 'For an ExplicitStructuredGrid, use the `neighbors` method' # type: ignore[unreachable]
2606 raise TypeError(msg)
2607
2608 # Build links as recommended:
2609 # https://vtk.org/doc/nightly/html/classvtkPolyData.html#adf9caaa01f72972d9a986ba997af0ac7
2610 if hasattr(self, 'BuildLinks'):
2611 self.BuildLinks()
2612
2613 needed = ['points', 'edges', 'faces']
2614 if connections not in needed:
2615 msg = f'`connections` must be one of: {needed} (got "{connections}")'
2616 raise ValueError(msg)
2617
2618 cell = self.get_cell(ind)
2619
2620 iterators = {
2621 'points': cell.point_ids,
2622 'edges': range(cell.n_edges),
2623 'faces': range(cell.n_faces),
2624 }
2625
2626 def generate_ids(i: int, connections: str) -> _vtk.vtkIdList | None:
2627 if connections == 'points':
2628 ids = _vtk.vtkIdList()
2629 ids.InsertNextId(i)
2630 return ids
2631 elif connections == 'edges':
2632 return cell.get_edge(i).GetPointIds()
2633 elif connections == 'faces':
2634 return cell.get_face(i).GetPointIds()
2635 return None # pragma: no cover
2636
2637 neighbors = set()
2638 for i in iterators[connections]:
2639 point_ids = generate_ids(i, connections)
2640 cell_ids = _vtk.vtkIdList()
2641 self.GetCellNeighbors(ind, point_ids, cell_ids)
2642
2643 neighbors.update([cell_ids.GetId(i) for i in range(cell_ids.GetNumberOfIds())])
2644
2645 return list(neighbors)
2646
2647 def point_neighbors(self: Self, ind: int) -> list[int]:
2648 """Get the point neighbors of the ind-th point.
2649
2650 Parameters
2651 ----------
2652 ind : int
2653 Point ID.
2654
2655 Returns
2656 -------
2657 list[int]
2658 List of neighbor points IDs for the ind-th point.
2659
2660 See Also
2661 --------
2662 pyvista.DataSet.point_neighbors_levels
2663
2664 Examples
2665 --------
2666 Get the point neighbors of the 0-th point.
2667
2668 >>> import pyvista as pv
2669 >>> mesh = pv.Sphere(theta_resolution=10)
2670 >>> mesh.point_neighbors(0)
2671 [2, 226, 198, 170, 142, 114, 86, 254, 58, 30]
2672
2673 Plot them.
2674
2675 >>> pl = pv.Plotter()
2676 >>> _ = pl.add_mesh(mesh, show_edges=True)
2677 >>>
2678 >>> # Label the 0-th point
2679 >>> _ = pl.add_point_labels(
2680 ... mesh.points[0], ['0'], text_color='blue', font_size=40
2681 ... )
2682 >>>
2683 >>> # Get the point neighbors and plot them
2684 >>> neighbors = mesh.point_neighbors(0)
2685 >>> _ = pl.add_point_labels(
2686 ... mesh.points[neighbors],
2687 ... labels=[f'{i}' for i in neighbors],
2688 ... text_color='red',
2689 ... font_size=40,
2690 ... )
2691 >>> pl.camera_position = 'xy'
2692 >>> pl.camera.zoom(7.0)
2693 >>> pl.show()
2694
2695 """
2696 if ind + 1 > self.n_points:
2697 msg = f'Invalid index {ind} for a dataset with {self.n_points} points.'
2698 raise IndexError(msg)
2699
2700 out = []
2701 for cell in self.point_cell_ids(ind):
2702 out.extend([i for i in self.get_cell(cell).point_ids if i != ind])
2703 return list(set(out))
2704
2705 def point_neighbors_levels(
2706 self: Self,
2707 ind: int,
2708 n_levels: int = 1,
2709 ) -> Generator[list[int], None, None]:
2710 """Get consecutive levels of point neighbors.
2711
2712 Parameters
2713 ----------
2714 ind : int
2715 Point ID.
2716
2717 n_levels : int, default: 1
2718 Number of levels to search for point neighbors.
2719 When equal to 1, it is equivalent to :func:`pyvista.DataSet.point_neighbors`.
2720
2721 Returns
2722 -------
2723 generator[list[[int]]
2724 A generator of list of neighbor points IDs for the ind-th point.
2725
2726 See Also
2727 --------
2728 pyvista.DataSet.point_neighbors
2729
2730 Examples
2731 --------
2732 Get the point neighbors IDs starting from the 0-th point
2733 up until the third level.
2734
2735 >>> import pyvista as pv
2736 >>> mesh = pv.Sphere(theta_resolution=10)
2737 >>> pt_nbr_levels = mesh.point_neighbors_levels(0, 3)
2738 >>> pt_nbr_levels = list(pt_nbr_levels)
2739 >>> pt_nbr_levels[0]
2740 [2, 226, 198, 170, 142, 114, 86, 30, 58, 254]
2741 >>> pt_nbr_levels[1]
2742 [3, 227, 255, 199, 171, 143, 115, 87, 59, 31]
2743 >>> pt_nbr_levels[2]
2744 [256, 32, 4, 228, 200, 172, 144, 116, 88, 60]
2745
2746 Visualize these points IDs.
2747
2748 >>> from functools import partial
2749 >>> pl = pv.Plotter()
2750 >>> _ = pl.add_mesh(mesh, show_edges=True)
2751 >>>
2752 >>> # Define partial function to add point labels
2753 >>> add_point_labels = partial(
2754 ... pl.add_point_labels,
2755 ... text_color='white',
2756 ... font_size=40,
2757 ... point_size=10,
2758 ... always_visible=True,
2759 ... )
2760 >>>
2761 >>> # Add the first point label
2762 >>> _ = add_point_labels(mesh.points[0], labels=['0'], text_color='blue')
2763 >>>
2764 >>> # Add the neighbors to the plot
2765 >>> neighbors = mesh.point_neighbors_levels(0, n_levels=3)
2766 >>> for i, ids in enumerate(neighbors, start=1):
2767 ... _ = add_point_labels(
2768 ... mesh.points[ids],
2769 ... labels=[f'{i}'] * len(ids),
2770 ... text_color='red',
2771 ... )
2772 >>>
2773 >>> pl.view_xy()
2774 >>> pl.camera.zoom(4.0)
2775 >>> pl.show()
2776
2777 """
2778 method = self.point_neighbors
2779 return self._get_levels_neihgbors(ind, n_levels, method)
2780
2781 def cell_neighbors_levels(
2782 self: Self,
2783 ind: int,
2784 connections: str = 'points',
2785 n_levels: int = 1,
2786 ) -> Generator[list[int], None, None]:
2787 """Get consecutive levels of cell neighbors.
2788
2789 Parameters
2790 ----------
2791 ind : int
2792 Cell ID.
2793
2794 connections : str, default: "points"
2795 Describe how the neighbor cell(s) must be connected to the current
2796 cell to be considered as a neighbor.
2797 Can be either ``'points'``, ``'edges'`` or ``'faces'``.
2798
2799 n_levels : int, default: 1
2800 Number of levels to search for cell neighbors.
2801 When equal to 1, it is equivalent to :func:`pyvista.DataSet.cell_neighbors`.
2802
2803 Returns
2804 -------
2805 generator[list[int]]
2806 A generator of list of cell IDs for each level.
2807
2808 Warnings
2809 --------
2810 For a :class:`pyvista.ExplicitStructuredGrid`, use
2811 :func:`pyvista.ExplicitStructuredGrid.neighbors`.
2812
2813 See Also
2814 --------
2815 pyvista.DataSet.cell_neighbors
2816
2817 Examples
2818 --------
2819 Get the cell neighbors IDs starting from the 0-th cell
2820 up until the third level.
2821
2822 >>> import pyvista as pv
2823 >>> mesh = pv.Sphere(theta_resolution=10)
2824 >>> nbr_levels = mesh.cell_neighbors_levels(0, connections='edges', n_levels=3)
2825 >>> nbr_levels = list(nbr_levels)
2826 >>> nbr_levels[0]
2827 [1, 21, 9]
2828 >>> nbr_levels[1]
2829 [2, 8, 74, 75, 20, 507]
2830 >>> nbr_levels[2]
2831 [128, 129, 3, 453, 7, 77, 23, 506]
2832
2833 Visualize these cells IDs.
2834
2835 >>> from functools import partial
2836 >>> pv.global_theme.color_cycler = [
2837 ... 'red',
2838 ... 'green',
2839 ... 'blue',
2840 ... 'purple',
2841 ... ]
2842 >>> pl = pv.Plotter()
2843 >>>
2844 >>> # Define partial function to add point labels
2845 >>> add_point_labels = partial(
2846 ... pl.add_point_labels,
2847 ... text_color='white',
2848 ... font_size=40,
2849 ... shape=None,
2850 ... show_points=False,
2851 ... )
2852 >>>
2853 >>> # Add the 0-th cell to the plotter
2854 >>> cell = mesh.extract_cells(0)
2855 >>> _ = pl.add_mesh(cell, show_edges=True)
2856 >>> _ = add_point_labels(cell.cell_centers().points, labels=['0'])
2857 >>> other_ids = [0]
2858 >>>
2859 >>> # Add the neighbors to the plot
2860 >>> neighbors = mesh.cell_neighbors_levels(0, connections='edges', n_levels=3)
2861 >>> for i, ids in enumerate(neighbors, start=1):
2862 ... cells = mesh.extract_cells(ids)
2863 ... _ = pl.add_mesh(cells, show_edges=True)
2864 ... _ = add_point_labels(
2865 ... cells.cell_centers().points, labels=[f'{i}'] * len(ids)
2866 ... )
2867 ... other_ids.extend(ids)
2868 >>>
2869 >>> # Add the cell IDs that are not neighbors (ie. the rest of the sphere)
2870 >>> cells = mesh.extract_cells(other_ids, invert=True)
2871 >>> _ = pl.add_mesh(cells, color='white', show_edges=True)
2872 >>>
2873 >>> pl.view_xy()
2874 >>> pl.camera.zoom(6.0)
2875 >>> pl.show()
2876
2877 """
2878 method = partial(self.cell_neighbors, connections=connections)
2879 return self._get_levels_neihgbors(ind, n_levels, method)
2880
2881 def _get_levels_neihgbors(
2882 self: Self,
2883 ind: int,
2884 n_levels: int,
2885 method: Callable[[Any], Any],
2886 ) -> Generator[list[int], None, None]: # numpydoc ignore=PR01,RT01
2887 """Provide helper method that yields neighbors ids."""
2888 neighbors = set(method(ind))
2889 yield list(neighbors)
2890
2891 # Keep track of visited points or cells
2892 all_visited = neighbors.copy()
2893 all_visited.add(ind)
2894
2895 for _ in range(n_levels - 1):
2896 # Get the neighbors for the next level.
2897 new_visited = set()
2898 for n in neighbors:
2899 new_neighbors = method(n)
2900 new_visited.update(new_neighbors)
2901 neighbors = new_visited
2902
2903 # Only return the ones that have not been visited yet
2904 yield list(neighbors.difference(all_visited))
2905 all_visited.update(neighbors)
2906
2907 def point_cell_ids(self: Self, ind: int) -> list[int]:
2908 """Get the cell IDs that use the ind-th point.
2909
2910 Implements :vtk:`vtkDataSet.GetPointCells`.
2911
2912 Parameters
2913 ----------
2914 ind : int
2915 Point ID.
2916
2917 Returns
2918 -------
2919 list[int]
2920 List of cell IDs using the ind-th point.
2921
2922 Examples
2923 --------
2924 Get the cell ids using the 0-th point.
2925
2926 >>> import pyvista as pv
2927 >>> mesh = pv.Sphere(theta_resolution=10)
2928 >>> mesh.point_cell_ids(0)
2929 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2930
2931 Plot them.
2932
2933 >>> pl = pv.Plotter()
2934 >>> _ = pl.add_mesh(mesh, show_edges=True)
2935 >>>
2936 >>> # Label the 0-th point
2937 >>> _ = pl.add_point_labels(
2938 ... mesh.points[0], ['0'], text_color='blue', font_size=20
2939 ... )
2940 >>>
2941 >>> # Get the cells ids using the 0-th point
2942 >>> ids = mesh.point_cell_ids(0)
2943 >>> cells = mesh.extract_cells(ids)
2944 >>> _ = pl.add_mesh(cells, color='red', show_edges=True)
2945 >>> centers = cells.cell_centers().points
2946 >>> _ = pl.add_point_labels(
2947 ... centers,
2948 ... labels=[f'{i}' for i in ids],
2949 ... text_color='white',
2950 ... font_size=20,
2951 ... shape=None,
2952 ... show_points=False,
2953 ... )
2954 >>>
2955 >>> # Plot the other cells
2956 >>> others = mesh.extract_cells(
2957 ... [i for i in range(mesh.n_cells) if i not in ids]
2958 ... )
2959 >>> _ = pl.add_mesh(others, show_edges=True)
2960 >>>
2961 >>> pl.camera_position = 'xy'
2962 >>> pl.camera.zoom(7.0)
2963 >>> pl.show()
2964
2965 """
2966 # Build links as recommended:
2967 # https://vtk.org/doc/nightly/html/classvtkPolyData.html#adf9caaa01f72972d9a986ba997af0ac7
2968 if hasattr(self, 'BuildLinks'):
2969 self.BuildLinks()
2970
2971 ids = _vtk.vtkIdList()
2972 self.GetPointCells(ind, ids)
2973 out = [ids.GetId(i) for i in range(ids.GetNumberOfIds())]
2974 if (9, 4, 0) <= pv.vtk_version_info < (9, 5, 0):
2975 # Need to reverse the order
2976 return out[::-1]
2977 return out
2978
2979 def point_is_inside_cell(
2980 self: Self,
2981 ind: int,
2982 point: VectorLike[float] | MatrixLike[float],
2983 ) -> bool | NumpyArray[np.bool_]:
2984 """Return whether one or more points are inside a cell.
2985
2986 .. versionadded:: 0.35.0
2987
2988 Parameters
2989 ----------
2990 ind : int
2991 Cell ID.
2992
2993 point : VectorLike[float] | MatrixLike[float]
2994 Point or points to query if are inside a cell.
2995
2996 Returns
2997 -------
2998 output : bool | numpy.ndarray
2999 Whether point(s) is/are inside cell. A single bool is only returned if
3000 the input point has shape ``(3,)``.
3001
3002 Examples
3003 --------
3004 >>> from pyvista import examples
3005 >>> mesh = examples.load_hexbeam()
3006 >>> mesh.get_cell(0).bounds
3007 BoundsTuple(x_min = 0.0,
3008 x_max = 0.5,
3009 y_min = 0.0,
3010 y_max = 0.5,
3011 z_min = 0.0,
3012 z_max = 0.5)
3013 >>> mesh.point_is_inside_cell(0, [0.2, 0.2, 0.2])
3014 True
3015
3016 """
3017 if not isinstance(ind, (int, np.integer)):
3018 msg = f'ind must be an int, got {type(ind)}' # type: ignore[unreachable]
3019 raise TypeError(msg)
3020
3021 if not 0 <= ind < self.n_cells:
3022 msg = f'ind must be >= 0 and < {self.n_cells}, got {ind}'
3023 raise ValueError(msg)
3024
3025 co_point, singular = _coerce_pointslike_arg(point, copy=False)
3026
3027 cell = self.GetCell(ind)
3028 npoints = cell.GetPoints().GetNumberOfPoints()
3029
3030 closest_point = [0.0, 0.0, 0.0]
3031 sub_id = _vtk.mutable(0)
3032 pcoords = [0.0, 0.0, 0.0]
3033 dist2 = _vtk.mutable(0.0)
3034 weights = [0.0] * npoints
3035
3036 in_cell = np.empty(shape=co_point.shape[0], dtype=np.bool_)
3037 for i, node in enumerate(co_point):
3038 is_inside = cell.EvaluatePosition(node, closest_point, sub_id, pcoords, dist2, weights)
3039 if not 0 <= is_inside <= 1:
3040 msg = f'Computational difficulty encountered for point {node} in cell {ind}'
3041 raise RuntimeError(msg)
3042 in_cell[i] = bool(is_inside)
3043
3044 if singular:
3045 return in_cell[0].item()
3046 return in_cell
3047
3048 @property
3049 def active_texture_coordinates(self: Self) -> pyvista_ndarray | None:
3050 """Return the active texture coordinates on the points.
3051
3052 Returns
3053 -------
3054 Optional[pyvista_ndarray]
3055 Active texture coordinates on the points.
3056
3057 Examples
3058 --------
3059 Return the active texture coordinates from the globe example.
3060
3061 >>> from pyvista import examples
3062 >>> globe = examples.load_globe()
3063 >>> globe.active_texture_coordinates
3064 pyvista_ndarray([[0. , 0. ],
3065 [0. , 0.07142857],
3066 [0. , 0.14285714],
3067 ...,
3068 [1. , 0.85714286],
3069 [1. , 0.92857143],
3070 [1. , 1. ]], shape=(540, 2))
3071
3072 """
3073 return self.point_data.active_texture_coordinates
3074
3075 @active_texture_coordinates.setter
3076 def active_texture_coordinates(
3077 self: Self,
3078 texture_coordinates: NumpyArray[float],
3079 ) -> None:
3080 """Set the active texture coordinates on the points.
3081
3082 Parameters
3083 ----------
3084 texture_coordinates : np.ndarray
3085 Active texture coordinates on the points.
3086
3087 """
3088 self.point_data.active_texture_coordinates = texture_coordinates
3089
3090 @property
3091 def is_empty(self) -> bool: # numpydoc ignore=RT01
3092 """Return ``True`` if there are no points.
3093
3094 .. versionadded:: 0.45
3095
3096 Examples
3097 --------
3098 >>> import pyvista as pv
3099 >>> mesh = pv.PolyData()
3100 >>> mesh.is_empty
3101 True
3102
3103 >>> mesh = pv.Sphere()
3104 >>> mesh.is_empty
3105 False
3106
3107 """
3108 return self.n_points == 0
3109
3110 @property
3111 def dimensionality(self) -> _Dimensionality:
3112 """Return the number of spatial dimensions spanned by this dataset's points.
3113
3114 This is equivalent to computing the matrix rank of the points.
3115
3116 .. versionchanged:: 0.47
3117
3118 This property is now generalized for all datasets. Previously, it was only available
3119 for datasets with a ``dimensions`` property.
3120
3121 Notes
3122 -----
3123 :attr:`dimensionality`:
3124
3125 - ranges from ``0`` to ``3`` for all mesh types.
3126 - is equivalent to :attr:`max_cell_dimensionality` and :attr:`min_cell_dimensionality`
3127 for gridded data types :class:`~pyvista.ImageData` and :class:`~pyvista.RectilinearGrid`.
3128
3129 Returns
3130 -------
3131 int
3132 The dimensionality of the dataset.
3133
3134 See Also
3135 --------
3136 max_cell_dimensionality, min_cell_dimensionality
3137
3138 Examples
3139 --------
3140 A single point has ``0`` dimensionality.
3141
3142 >>> import pyvista as pv
3143 >>> mesh = pv.PointSet([[0.0, 0.0, 0.0]])
3144 >>> mesh.dimensionality
3145 0
3146
3147 With two points, the dimensionality is ``1``.
3148
3149 >>> mesh = pv.PointSet([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
3150 >>> mesh.dimensionality
3151 1
3152
3153 Two-dimensional :class:`~pyvista.ImageData` (i.e. where one of its dimensions is one) has
3154 a dimensionality of ``2``.
3155
3156 >>> mesh = pv.ImageData(dimensions=(100, 100, 1))
3157 >>> mesh.dimensionality
3158 2
3159
3160 A :func:`~pyvista.Plane` also has dimensionality of ``2``, even if it's arbitrarily
3161 rotated in space.
3162
3163 >>> mesh = pv.Plane().rotate_vector((1, 2, 3), 30)
3164 >>> mesh.dimensionality
3165 2
3166
3167 A :func:`~pyvista.Cube` has a dimensionality of 3.
3168
3169 >>> mesh = pv.Cube()
3170 >>> mesh.dimensionality
3171 3
3172
3173 """
3174 if self.n_points == 0:
3175 return 0
3176 elif isinstance(self, pv.Grid):
3177 # Fast path for gridded types
3178 return self.max_cell_dimensionality
3179
3180 # Align points first to make rank computation more robust
3181 aligned_points = self.align_xyz().points
3182 return int(np.linalg.matrix_rank(aligned_points)) # type: ignore[return-value]
3183
3184 @property
3185 def max_cell_dimensionality(self: Self) -> _Dimensionality:
3186 """Return the maximum spatial dimensionality of all cells in this mesh.
3187
3188 .. versionadded:: 0.47
3189
3190 Notes
3191 -----
3192 :attr:`max_cell_dimensionality`:
3193
3194 - is always ``0`` for :class:`~pyvista.PointSet`
3195 - ranges from ``0`` to ``2`` for :class:`~pyvista.PolyData`.
3196 - ranges from ``0`` to ``3`` for all other mesh types.
3197 - is equivalent to :attr:`dimensionality` for gridded data types
3198 :class:`~pyvista.ImageData` and :class:`~pyvista.RectilinearGrid`.
3199
3200 See Also
3201 --------
3202 min_cell_dimensionality, dimensionality, distinct_cell_types
3203
3204 Returns
3205 -------
3206 int
3207 The maximum dimensionality of the dataset's cells.
3208
3209 Examples
3210 --------
3211 :class:`~pyvista.PointSet` has no cells, so its :attr:`max_cell_dimensionality` is always
3212 ``0``.
3213
3214 >>> import pyvista as pv
3215 >>> from pyvista import examples
3216 >>> mesh = pv.Sphere().cast_to_pointset()
3217 >>> mesh.max_cell_dimensionality
3218 0
3219
3220 A :class:`~pyvista.PolyData` surface mesh with 2D polygonal cells such as
3221 :func:`~pyvista.Sphere` has max cell dimensionality of ``2``.
3222
3223 >>> mesh = pv.Sphere()
3224 >>> mesh.max_cell_dimensionality
3225 2
3226
3227 Since there are no 1D :attr:`~pyvista.CellType.LINE` or 0D
3228 :attr:`~pyvista.CellType.VERTEX` cells, the :attr:`min_cell_dimensionality` is also ``2``
3229 in this case.
3230
3231 >>> mesh.min_cell_dimensionality
3232 2
3233
3234 A :class:`~pyvista.UnstructuredGrid` with 3D cells such as :func:`~pyvista.SolidSphere`
3235 has max and min cell dimensionality of ``3``.
3236
3237 >>> mesh = pv.SolidSphere()
3238 >>> mesh.max_cell_dimensionality
3239 3
3240 >>> mesh.min_cell_dimensionality
3241 3
3242
3243 A :func:`~pyvista.Line` or :func:`~pyvista.Spline` with 1D cells has a max and min
3244 cell dimensionality of ``1``.
3245
3246 >>> mesh = pv.Line([0.0, 0.0, 0.0], [1.0, 1.0, 1.0])
3247 >>> mesh.max_cell_dimensionality
3248 1
3249 >>> mesh.min_cell_dimensionality
3250 1
3251
3252 A curvilinear :class:`~pyvista.StructuredGrid` such as the one from
3253 :func:`~pyvista.examples.downloads.download_wavy` has 2D cells.
3254
3255 >>> mesh = examples.download_wavy()[0]
3256 >>> mesh.max_cell_dimensionality
3257 2
3258 >>> mesh.min_cell_dimensionality
3259 2
3260
3261 But it has a spatial :attr:`dimensionality` of ``3`` since its points span three
3262 dimensions.
3263
3264 >>> mesh.dimensionality
3265 3
3266
3267 The dimensionality can vary if there are mixed cell types. E.g. load
3268 :func:`~pyvista.examples.downloads.download_prostar`.
3269
3270 >>> mesh = examples.download_prostar()
3271 >>> sorted(mesh.distinct_cell_types) # doctest:+NORMALIZE_WHITESPACE
3272 [<CellType.VERTEX: 1>, <CellType.LINE: 3>, <CellType.TRIANGLE: 5>, <CellType.POLYGON: 7>,
3273 <CellType.QUAD: 9>, <CellType.TETRA: 10>, <CellType.HEXAHEDRON: 12>, <CellType.WEDGE: 13>,
3274 <CellType.PYRAMID: 14>, <CellType.POLYHEDRON: 42>]
3275
3276 There are 3D volumetric cells, so the max dimensionality is ``3``.
3277
3278 >>> mesh.max_cell_dimensionality
3279 3
3280
3281 And since there are :attr:`~pyvista.CellType.VERTEX` cells its
3282 :attr:`min_cell_dimensionality` is ``0``.
3283
3284 >>> mesh.min_cell_dimensionality
3285 0
3286
3287 """
3288 if pv.vtk_version_info < (9, 4, 0):
3289 return max(self._distinct_cell_dimensions)
3290 return self.GetMaxSpatialDimension()
3291
3292 @property
3293 def min_cell_dimensionality(self) -> _Dimensionality:
3294 """Get the minimum spatial dimensionality of all cells in this mesh.
3295
3296 .. versionadded:: 0.47
3297
3298 Notes
3299 -----
3300 :attr:`min_cell_dimensionality`:
3301
3302 - is always ``0`` for :class:`~pyvista.PointSet`
3303 - ranges from ``0`` to ``2`` for :class:`~pyvista.PolyData`.
3304 - ranges from ``0`` to ``3`` for all other mesh types.
3305 - is equivalent to :attr:`dimensionality` for gridded data types
3306 :class:`~pyvista.ImageData` and :class:`~pyvista.RectilinearGrid`.
3307
3308 See Also
3309 --------
3310 max_cell_dimensionality, dimensionality, distinct_cell_types
3311
3312 Returns
3313 -------
3314 int
3315 The minimum dimensionality of the dataset's cells.
3316
3317 Examples
3318 --------
3319 Show the max and min cell dimensionality of a :attr:`~pyvista.CellType.LINE` cell and
3320 :attr:`~pyvista.CellType.TRIANGLE` cell.
3321
3322 >>> from pyvista.examples import cells
3323 >>> line = cells.Line()
3324 >>> line.max_cell_dimensionality
3325 1
3326 >>> line.min_cell_dimensionality
3327 1
3328
3329 >>> tri = cells.Triangle()
3330 >>> tri.max_cell_dimensionality
3331 2
3332 >>> tri.min_cell_dimensionality
3333 2
3334
3335 Merge the two cells and show the max and min cell dimensionality.
3336
3337 >>> merged = line + tri
3338 >>> merged.max_cell_dimensionality
3339 2
3340 >>> merged.min_cell_dimensionality
3341 1
3342
3343 """
3344 if self.n_cells == 0:
3345 # GetMinSpatialDimension returns 3 by default for meshes with no cells, which is odd
3346 # because then we have min_cell_dimensionality > max_cell_dimensionality
3347 return 0
3348 if pv.vtk_version_info < (9, 5, 0):
3349 return min(self._distinct_cell_dimensions)
3350 return self.GetMinSpatialDimension()
3351
3352 @property
3353 def _distinct_cell_dimensions(self) -> set[_Dimensionality]:
3354 """Compute distinct dimensions of cells. Only needed for legacy vtk < 9.5."""
3355 if self.n_cells == 0:
3356 return {0}
3357 elif hasattr(self, 'dimensions'):
3358 dims = np.array(self.dimensions)
3359 return {int(3 - (dims == 1).sum())} # type: ignore[arg-type]
3360 elif isinstance(self, pv.PolyData):
3361 distinct_dimensions = set()
3362 if self.n_faces > 0 or self.n_strips > 0:
3363 distinct_dimensions.add(2)
3364 if self.n_lines > 0:
3365 distinct_dimensions.add(1)
3366 if self.n_verts > 0:
3367 distinct_dimensions.add(0)
3368 return distinct_dimensions # type: ignore[return-value]
3369 elif isinstance(self, pv.UnstructuredGrid):
3370 distinct_dimensions = set()
3371 for cell_type in self.distinct_cell_types:
3372 distinct_dimensions.add(cell_type.dimension)
3373 return distinct_dimensions # type: ignore[return-value]
3374 msg = f'Unexpected mesh type {type(self)}'
3375 raise RuntimeError(msg)
3376
3377 @property
3378 def distinct_cell_types(self) -> set[CellType]:
3379 """Return the set of distinct cell types in this dataset.
3380
3381 The set contains :class:`~pyvista.CellType` values corresponding to the
3382 :attr:`pyvista.Cell.type` of each distinct cell in the dataset.
3383
3384 .. warning::
3385 Computing distinct cell types can be very slow for complex meshes with VTK version
3386 less than 9.6.
3387
3388 .. versionadded:: 0.47
3389
3390 Returns
3391 -------
3392 set[CellType]
3393 Set of :class:`~pyvista.CellType` values.
3394
3395 See Also
3396 --------
3397 min_cell_dimensionality
3398 max_cell_dimensionality
3399 pyvista.UnstructuredGrid.celltypes
3400
3401 Examples
3402 --------
3403 Load a mesh with linear :attr:`pyvista.CellType.HEXAHEDRON` cells.
3404
3405 >>> from pyvista import examples
3406 >>> hex_beam = examples.load_hexbeam()
3407 >>> hex_beam.distinct_cell_types
3408 {<CellType.HEXAHEDRON: 12>}
3409
3410 Load a mesh with mixed cells.
3411
3412 >>> mesh = examples.download_cow()
3413 >>> sorted(mesh.distinct_cell_types)
3414 [<CellType.TRIANGLE: 5>, <CellType.POLYGON: 7>, <CellType.QUAD: 9>]
3415
3416 Load 2D image.
3417
3418 >>> mesh = examples.load_logo()
3419 >>> mesh.distinct_cell_types
3420 {<CellType.PIXEL: 8>}
3421
3422 """
3423 if self.n_cells == 0:
3424 return set()
3425 if hasattr(self, 'dimensions'):
3426 # Fast path for dimensioned grids
3427 cell_dimension = next(iter(self._distinct_cell_dimensions))
3428 if isinstance(self, pv.Grid):
3429 mapping = {
3430 0: pv.CellType.VERTEX,
3431 1: pv.CellType.LINE,
3432 2: pv.CellType.PIXEL,
3433 3: pv.CellType.VOXEL,
3434 }
3435 else:
3436 mapping = {
3437 0: pv.CellType.VERTEX,
3438 1: pv.CellType.LINE,
3439 2: pv.CellType.QUAD,
3440 3: pv.CellType.HEXAHEDRON,
3441 }
3442 return {mapping[cell_dimension]}
3443
3444 if hasattr(self, 'GetDistinctCellTypes'):
3445 types = _vtk.vtkCellTypes()
3446 self.GetDistinctCellTypes(types)
3447 types_array = _vtk.vtk_to_numpy(types.GetCellTypesArray())
3448 elif hasattr(self, 'GetCellTypesArray'):
3449 types_array = _vtk.vtk_to_numpy(self.GetCellTypesArray())
3450 else:
3451 grid = (
3452 self if isinstance(self, pv.UnstructuredGrid) else self.cast_to_unstructured_grid()
3453 )
3454 types_array = np.unique(grid.celltypes)
3455 return {pv.CellType(cell_num) for cell_num in types_array}
3456
3457 @property
3458 def has_nonlinear_cells(self) -> bool: # numpydoc ignore=RT01
3459 """Return True if the mesh contains any non-linear cells.
3460
3461 .. note::
3462 Only :class:`~pyvista.UnstructuredGrid` can have non-linear cells. This property is
3463 therefore always False for all other dataset types.
3464
3465 .. warning::
3466 Checking for non-linear cells can be very slow for complex meshes with VTK version
3467 less than 9.6.
3468
3469 .. versionadded:: 0.47
3470
3471 Examples
3472 --------
3473 >>> from pyvista import examples
3474 >>> mesh = examples.cells.Hexahedron()
3475 >>> mesh.has_nonlinear_cells
3476 False
3477
3478 >>> mesh = examples.cells.QuadraticHexahedron()
3479 >>> mesh.has_nonlinear_cells
3480 True
3481
3482 """
3483 if not isinstance(self, pv.UnstructuredGrid):
3484 return False
3485 return not all(celltype.is_linear for celltype in self.distinct_cell_types)
3486
3487 @property
3488 def bounding_sphere(self) -> tuple[float, tuple[float, float, float]]:
3489 """Compute the radius and center of a bounding sphere.
3490
3491 The sphere is exact for meshes with 4 points or less, and is otherwise approximated
3492 using Ritter's algorithm. Returns NaN values if there are no points.
3493
3494 Uses :vtk:`vtkCell.ComputeBoundingSphere` internally for the computation.
3495
3496 .. versionadded:: 0.48
3497
3498 Returns
3499 -------
3500 float, tuple
3501 Sphere radius as a float and center as a tuple of floats.
3502
3503 Examples
3504 --------
3505 Get the bounding sphere geometry of a mesh.
3506
3507 >>> import pyvista as pv
3508 >>> from pyvista import examples
3509 >>> mesh = examples.load_airplane()
3510 >>> radius, center = mesh.bounding_sphere
3511
3512 Create a sphere and plot it along with the original mesh.
3513
3514 >>> sphere = pv.Icosphere(radius=radius, center=center)
3515 >>> pl = pv.Plotter()
3516 >>> _ = pl.add_mesh(mesh)
3517 >>> _ = pl.add_mesh(sphere, style='wireframe', color='black')
3518 >>> pl.view_xy()
3519 >>> pl.camera.zoom(1.5)
3520 >>> pl.show()
3521
3522 """
3523 # Create grid with a single POLY_VERTEX cell containing all the points
3524 n_points = self.n_points
3525 cells = np.hstack([[n_points], np.arange(n_points)])
3526 celltypes = np.array([pv.CellType.POLY_VERTEX], dtype=np.uint8)
3527 grid = pv.UnstructuredGrid(cells, celltypes, self.points)
3528
3529 # Compute radius and center of the cell
3530 center = [0.0, 0.0, 0.0]
3531 r2 = grid.GetCell(0).ComputeBoundingSphere(center)
3532 return float(r2**0.5), (center[0], center[1], center[2])