Debian Codegraph @

pyvista/core/datasetattributes.py

raw
1 """Implements DataSetAttributes, which represents and manipulates datasets."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import copy as copylib
7 from typing import TYPE_CHECKING
8 from typing import Any
9 from typing import TypeVar
10
11 import numpy as np
12 import numpy.typing as npt
13
14 from pyvista import _vtk
15 from pyvista._deprecate_positional_args import _deprecate_positional_args
16 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
17 from pyvista.core._vtk_utilities import VTKObjectWrapperCheckSnakeCase
18
19 from .pyvista_ndarray import pyvista_ndarray
20 from .utilities.arrays import FieldAssociation
21 from .utilities.arrays import convert_array
22 from .utilities.arrays import copy_vtk_array
23 from .utilities.misc import _NoNewAttrMixin
24
25 T = TypeVar('T')
26
27 if TYPE_CHECKING:
28 from collections.abc import Iterator
29
30 import pandas
31 import pyarrow
32 from typing_extensions import Self
33
34 from pyvista import DataSet
35
36 from ._typing_core import ArrayLike
37 from ._typing_core import MatrixLike
38 from ._typing_core import NumpyArray
39
40 # from https://vtk.org/doc/nightly/html/vtkDataSetAttributes_8h_source.html
41 attr_type = [
42 'SCALARS', # 0
43 'VECTORS', # 1
44 'NORMALS', # 2
45 'TCOORDS', # 3
46 'TENSORS', # 4
47 'GLOBALIDS', # 5
48 'PEDIGREEIDS', # 6
49 'EDGEFLAG', # 7
50 'TANGENTS', # 8
51 'RATIONALWEIGHTS', # 9
52 'HIGHERORDERDEGREES', # 10
53 '', # 11 (not an attribute)
54 ]
55
56 # used to check if default args have changed in pop
57 _SENTINEL = pyvista_ndarray([])
58
59
60 class DataSetAttributes(_NoNewAttrMixin, DisableVtkSnakeCase, VTKObjectWrapperCheckSnakeCase):
61 """Python friendly wrapper of :vtk:`vtkDataSetAttributes`.
62
63 This class provides the ability to pick one of the present arrays as the
64 currently active array for each attribute type by implementing a
65 ``dict`` like interface.
66
67 When adding data arrays but not desiring to set them as active
68 scalars or vectors, use :func:`DataSetAttributes.set_array`.
69
70 When adding directional data (such as velocity vectors), use
71 :func:`DataSetAttributes.set_vectors`.
72
73 When adding non-directional data (such as temperature values or
74 multi-component scalars like RGBA values), use
75 :func:`DataSetAttributes.set_scalars`.
76
77 .. versionchanged:: 0.32.0
78 The ``[]`` operator no longer allows integers. Use
79 :func:`DataSetAttributes.get_array` to retrieve an array
80 using an index.
81
82 Parameters
83 ----------
84 vtkobject : :vtk:`vtkFieldData`
85 The vtk object to wrap as a :class:~pyvista.DataSetAttribute`,
86 usually an instance of :vtk:`vtkCellData`, :vtk:`vtkPointData`, or
87 :vtk:`vtkFieldData`.
88
89 dataset : :vtk:`vtkDataSet`
90 The :vtk:`vtkDataSet` containing the vtkobject.
91
92 association : FieldAssociation
93 The array association type of the vtkobject.
94
95 Notes
96 -----
97 When printing out the point arrays, you can see which arrays are
98 the active scalars, vectors, normals, and texture coordinates.
99 In the arrays list, ``SCALARS`` denotes that these are the active
100 scalars, ``VECTORS`` denotes that these arrays are tagged as the
101 active vectors data (i.e. data with magnitude and direction) and
102 so on.
103
104 Examples
105 --------
106 Store data with point association in a DataSet.
107
108 >>> import pyvista as pv
109 >>> mesh = pv.Cube()
110 >>> mesh.point_data['my_data'] = range(mesh.n_points)
111 >>> data = mesh.point_data['my_data']
112 >>> data
113 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
114
115 Change the data array and show that this is reflected in the DataSet.
116
117 >>> data[:] = 0
118 >>> mesh.point_data['my_data']
119 pyvista_ndarray([0, 0, 0, 0, 0, 0, 0, 0])
120
121 Remove the array.
122
123 >>> del mesh.point_data['my_data']
124 >>> 'my_data' in mesh.point_data
125 False
126
127 Print the available arrays from dataset attributes.
128
129 >>> import numpy as np
130 >>> mesh = pv.Plane(i_resolution=1, j_resolution=1)
131 >>> mesh.point_data.set_array(range(4), 'my-data')
132 >>> mesh.point_data.set_array(range(5, 9), 'my-other-data')
133 >>> vectors0 = np.random.default_rng().random((4, 3))
134 >>> mesh.point_data.set_vectors(vectors0, 'vectors0')
135 >>> vectors1 = np.random.default_rng().random((4, 3))
136 >>> mesh.point_data.set_vectors(vectors1, 'vectors1')
137 >>> mesh.point_data
138 pyvista DataSetAttributes
139 Association : POINT
140 Active Scalars : None
141 Active Vectors : vectors1
142 Active Texture : TextureCoordinates
143 Active Normals : Normals
144 Contains arrays :
145 Normals float32 (4, 3) NORMALS
146 TextureCoordinates float32 (4, 2) TCOORDS
147 my-data int64 (4,)
148 my-other-data int64 (4,)
149 vectors1 float64 (4, 3) VECTORS
150 vectors0 float64 (4, 3)
151
152 """
153
154 def __init__(
155 self: Self,
156 vtkobject: _vtk.vtkFieldData,
157 dataset: _vtk.vtkDataSet | DataSet,
158 association: FieldAssociation,
159 ) -> None: # numpydoc ignore=PR01,RT01
160 """Initialize DataSetAttributes."""
161 super().__init__(vtkobject=vtkobject)
162 self.dataset = dataset
163 self.association = association
164
165 def __repr__(self: Self) -> str:
166 """Printable representation of DataSetAttributes."""
167 info = ['pyvista DataSetAttributes']
168 array_info = ' None'
169 if self:
170 lines = []
171 for i, (name, array) in enumerate(self.items()):
172 if len(name) > 23:
173 name = f'{name[:20]}...' # noqa: PLW2901
174 try:
175 arr_type = attr_type[self.IsArrayAnAttribute(i)]
176 except (IndexError, TypeError, AttributeError): # pragma: no cover
177 arr_type = ''
178
179 # special treatment for vector data
180 if self.association in [FieldAssociation.POINT, FieldAssociation.CELL]:
181 if name == self.active_vectors_name:
182 arr_type = 'VECTORS'
183 # special treatment for string field data
184 if self.association == FieldAssociation.NONE and isinstance(array, str): # type: ignore[unreachable]
185 dtype = 'str' # type: ignore[unreachable]
186 # Show the string value itself with a max of 20 characters,
187 # 18 for string and 2 for quotes
188 val = f'{array[:15]}...' if len(array) > 18 else array
189 line = f'{name[:23]:<24}{dtype!s:<11}"{val}"'
190 else:
191 line = (
192 f'{name[:23]:<24}{array.dtype!s:<11}{array.shape!s:<20} {arr_type}'.strip()
193 )
194 lines.append(line)
195 array_info = '\n ' + '\n '.join(lines)
196
197 info.append(f'Association : {self.association.name}')
198 if self.association in [FieldAssociation.POINT, FieldAssociation.CELL]:
199 info.append(f'Active Scalars : {self.active_scalars_name}')
200 info.append(f'Active Vectors : {self.active_vectors_name}')
201 info.append(f'Active Texture : {self.active_texture_coordinates_name}')
202 info.append(f'Active Normals : {self.active_normals_name}')
203
204 info.append(f'Contains arrays :{array_info}')
205 return '\n'.join(info)
206
207 def get(self: Self, key: str, value: Any | None = None) -> pyvista_ndarray | None:
208 """Return the value of the item with the specified key.
209
210 Parameters
211 ----------
212 key : str
213 Name of the array item you want to return the value from.
214
215 value : Any, optional
216 A value to return if the key does not exist. Default
217 is ``None``.
218
219 Returns
220 -------
221 Any
222 Array if the ``key`` exists in the dataset, otherwise
223 ``value``.
224
225 Examples
226 --------
227 Show that the default return value for a non-existent key is
228 ``None``.
229
230 >>> import pyvista as pv
231 >>> mesh = pv.Cube()
232 >>> mesh.point_data['my_data'] = range(mesh.n_points)
233 >>> mesh.point_data.get('my-other-data')
234
235 """
236 if key in self:
237 return self[key]
238 return value
239
240 def __bool__(self: Self) -> bool:
241 """Return ``True`` when there are arrays present."""
242 return bool(self.GetNumberOfArrays())
243
244 def __getitem__(self: Self, key: str) -> pyvista_ndarray:
245 """Implement ``[]`` operator.
246
247 Accepts an array name.
248 """
249 if not isinstance(key, str):
250 msg = 'Only strings are valid keys for DataSetAttributes.' # type: ignore[unreachable]
251 raise TypeError(msg)
252 return self.get_array(key)
253
254 def __setitem__(
255 self: Self, key: str, value: ArrayLike[Any]
256 ) -> None: # numpydoc ignore=PR01,RT01
257 """Implement setting with the ``[]`` operator."""
258 if not isinstance(key, str):
259 msg = 'Only strings are valid keys for DataSetAttributes.' # type: ignore[unreachable]
260 raise TypeError(msg)
261
262 has_arr = key in self
263 self.set_array(value, name=key)
264
265 # do not make array active if it already exists. This covers
266 # an inplace update like self.point_data[key] += 1
267 if has_arr:
268 return
269
270 # make active if not field data and there isn't already an active scalar
271 if (
272 self.association
273 in [
274 FieldAssociation.POINT,
275 FieldAssociation.CELL,
276 ]
277 and self.active_scalars_name is None
278 ):
279 self.active_scalars_name = key
280
281 def __delitem__(self: Self, key: str) -> None:
282 """Implement del with array name or index."""
283 if not isinstance(key, str):
284 msg = 'Only strings are valid keys for DataSetAttributes.' # type: ignore[unreachable]
285 raise TypeError(msg)
286
287 self.remove(key)
288
289 def __contains__(self: Self, name: str) -> bool:
290 """Implement the ``in`` operator.
291
292 Uses VTK's native ``HasArray`` for an O(1) lookup, avoiding the
293 cost of materialising every array name into a Python list. Falls
294 back to ``self.keys()`` for the empty-name lookup so that
295 ``keys()``'s legacy auto-rename side-effect (renaming any
296 unnamed arrays to ``Unnamed_<i>``) still fires; some plotter
297 codepaths (notably ``set_custom_opacity`` for array-valued
298 ``opacity=`` arguments) inject anonymous arrays and rely on that
299 side-effect to give them a unique, lookup-able name before
300 downstream code activates them.
301 """
302 if name:
303 return bool(self.VTKObject.HasArray(name))
304 return name in self.keys()
305
306 def __iter__(self: Self) -> Iterator[str]:
307 """Implement for loop iteration."""
308 yield from self.keys()
309
310 def __len__(self: Self) -> int:
311 """Return the number of arrays."""
312 return self.VTKObject.GetNumberOfArrays()
313
314 @property
315 def active_scalars(self: Self) -> pyvista_ndarray | None:
316 """Return the active scalars.
317
318 .. versionchanged:: 0.32.0
319 Can no longer be used to set the active scalars. Either use
320 :func:`DataSetAttributes.set_scalars` or if the array
321 already exists, assign to
322 :attr:`pyvista.DataSetAttributes.active_scalars_name`.
323
324 Returns
325 -------
326 Optional[pyvista_ndarray]
327 Active scalars.
328
329 Examples
330 --------
331 Associate point data to a simple cube mesh and show that the
332 active scalars in the point array are the most recently added
333 array.
334
335 >>> import pyvista as pv
336 >>> import numpy as np
337 >>> mesh = pv.Cube()
338 >>> mesh.point_data['data0'] = np.arange(mesh.n_points)
339 >>> mesh.point_data.active_scalars
340 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
341
342 """
343 self._raise_field_data_no_scalars_vectors_normals()
344 if self.GetScalars() is not None:
345 array = pyvista_ndarray(
346 self.GetScalars(),
347 dataset=self.dataset,
348 association=self.association,
349 )
350 return self._patch_type(array)
351 return None
352
353 @property
354 def active_vectors(self: Self) -> NumpyArray[float] | None:
355 """Return the active vectors as a pyvista_ndarray.
356
357 .. versionchanged:: 0.32.0
358 Can no longer be used to set the active vectors. Either use
359 :func:`DataSetAttributes.set_vectors` or if the array
360 already exists, assign to
361 :attr:`pyvista.DataSetAttributes.active_vectors_name`.
362
363 Returns
364 -------
365 Optional[np.ndarray]
366 Active vectors as a pyvista_ndarray.
367
368 Examples
369 --------
370 Associate point data to a simple cube mesh and show that the
371 active vectors in the point array are the most recently added
372 array.
373
374 >>> import pyvista as pv
375 >>> import numpy as np
376 >>> mesh = pv.Cube()
377 >>> vectors = np.random.default_rng().random((mesh.n_points, 3))
378 >>> mesh.point_data.set_vectors(vectors, 'my-vectors')
379 >>> vectors_out = mesh.point_data.active_vectors
380 >>> vectors_out.shape
381 (8, 3)
382
383 """
384 self._raise_field_data_no_scalars_vectors_normals()
385 vectors = self.GetVectors()
386 if vectors is not None:
387 return pyvista_ndarray(vectors, dataset=self.dataset, association=self.association)
388 return None
389
390 @property
391 def valid_array_len(self: Self) -> int | None:
392 """Return the length data should be when added to the dataset.
393
394 If there are no restrictions, returns ``None``.
395
396 Returns
397 -------
398 Optional[int]
399 Length data should be when added to the dataset.
400
401 Examples
402 --------
403 Show that valid array lengths match the number of points and
404 cells for point and cell arrays, and there is no length limit
405 for field data.
406
407 >>> import pyvista as pv
408 >>> mesh = pv.Cube()
409 >>> mesh.n_points, mesh.n_cells
410 (8, 6)
411 >>> mesh.point_data.valid_array_len
412 8
413 >>> mesh.cell_data.valid_array_len
414 6
415 >>> mesh.field_data.valid_array_len is None
416 True
417
418 """
419 if self.association == FieldAssociation.POINT:
420 return self.dataset.GetNumberOfPoints()
421 if self.association == FieldAssociation.CELL:
422 return self.dataset.GetNumberOfCells()
423 return None
424
425 def get_array(self: Self, key: str | int) -> pyvista_ndarray:
426 """Get an array in this object.
427
428 Parameters
429 ----------
430 key : str | int
431 The name or index of the array to return. Arrays are
432 ordered within VTK DataSetAttributes, and this feature is
433 mirrored here.
434
435 Returns
436 -------
437 pyvista.pyvista_ndarray
438 Returns a :class:`pyvista.pyvista_ndarray`.
439
440 Raises
441 ------
442 KeyError
443 If the key does not exist.
444
445 Notes
446 -----
447 This is provided since arrays are ordered within VTK and can
448 be indexed via an int. When getting an array, you can just
449 use the key of the array with the ``[]`` operator with the
450 name of the array.
451
452 Examples
453 --------
454 Store data with point association in a DataSet.
455
456 >>> import pyvista as pv
457 >>> mesh = pv.Cube()
458 >>> mesh.clear_data()
459 >>> mesh.point_data['my_data'] = range(mesh.n_points)
460
461 Access using an index.
462
463 >>> mesh.point_data.get_array(0)
464 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
465
466 Access using a key.
467
468 >>> mesh.point_data.get_array('my_data')
469 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
470
471 """
472 self._raise_index_out_of_bounds(index=key)
473 vtk_arr = self.GetArray(key)
474 if vtk_arr is None:
475 vtk_arr = self.GetAbstractArray(key)
476 if vtk_arr is None:
477 msg = f'{key}'
478 raise KeyError(msg)
479 narray = pyvista_ndarray(vtk_arr, dataset=self.dataset, association=self.association)
480 return self._patch_type(narray)
481
482 def _patch_type(self: Self, narray: pyvista_ndarray) -> pyvista_ndarray:
483 """Check if array needs to be represented as a different type."""
484 if hasattr(narray, 'VTKObject') and isinstance(narray.VTKObject, _vtk.vtkAbstractArray):
485 name = narray.VTKObject.GetName()
486 if name in self.dataset._association_bitarray_names[self.association.name]: # type: ignore[union-attr]
487 narray = narray.view(np.bool_) # type: ignore[assignment]
488 elif name in self.dataset._association_complex_names[self.association.name]: # type: ignore[union-attr]
489 if narray.dtype == np.float32:
490 narray = narray.view(np.complex64) # type: ignore[assignment]
491 if narray.dtype == np.float64:
492 narray = narray.view(np.complex128) # type: ignore[assignment]
493 # remove singleton dimensions to match the behavior of the rest of 1D
494 # VTK arrays
495 narray = narray.squeeze() # type: ignore[assignment]
496 elif (
497 narray.association == FieldAssociation.NONE
498 and np.issubdtype(narray.dtype, np.str_)
499 and narray.ndim == 0
500 ):
501 # For field data with a string scalar, return the string
502 # itself instead of a scalar array
503 narray = narray.tolist()
504 return narray
505
506 @_deprecate_positional_args(allowed=['data', 'name'])
507 def set_array(self: Self, data: ArrayLike[float], name: str, deep_copy: bool = False) -> None: # noqa: FBT001, FBT002
508 """Add an array to this object.
509
510 Use this method when adding arrays to the DataSet. If
511 needed, these arrays can later be assigned to become the
512 active scalars, vectors, normals, or texture coordinates with:
513
514 * :attr:`active_scalars_name`
515 * :attr:`active_vectors_name`
516 * :attr:`active_normals_name`
517 * :attr:`active_texture_coordinates_name`
518
519 Parameters
520 ----------
521 data : ArrayLike[float]
522 Array of data.
523
524 name : str
525 Name to assign to the data. If this name already exists,
526 it will be overwritten.
527
528 deep_copy : bool, optional
529 When ``True`` makes a full copy of the array.
530
531 Notes
532 -----
533 You can simply use the ``[]`` operator to add an array to the
534 dataset. Note that this will automatically become the active
535 scalars.
536
537 Examples
538 --------
539 Add a point array to a mesh.
540
541 >>> import pyvista as pv
542 >>> mesh = pv.Cube()
543 >>> data = range(mesh.n_points)
544 >>> mesh.point_data.set_array(data, 'my-data')
545 >>> mesh.point_data['my-data']
546 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
547
548 Add a cell array to a mesh.
549
550 >>> cell_data = range(mesh.n_cells)
551 >>> mesh.cell_data.set_array(cell_data, 'my-data')
552 >>> mesh.cell_data['my-data']
553 pyvista_ndarray([0, 1, 2, 3, 4, 5])
554
555 Add field data to a mesh.
556
557 >>> field_data = range(3)
558 >>> mesh.field_data.set_array(field_data, 'my-data')
559 >>> mesh.field_data['my-data']
560 pyvista_ndarray([0, 1, 2])
561
562 """
563 if not isinstance(name, str):
564 msg = '`name` must be a string' # type: ignore[unreachable]
565 raise TypeError(msg)
566
567 vtk_arr = self._prepare_array(data=data, name=name, deep_copy=deep_copy)
568 self.VTKObject.AddArray(vtk_arr)
569 self.VTKObject.Modified()
570
571 @_deprecate_positional_args(allowed=['scalars', 'name'])
572 def set_scalars(
573 self: Self,
574 scalars: ArrayLike[float],
575 name: str = 'scalars',
576 deep_copy: bool = False, # noqa: FBT001, FBT002
577 ) -> None:
578 """Set the active scalars of the dataset with an array.
579
580 In VTK and PyVista, scalars are a quantity that has no
581 direction. This can include data with multiple components
582 (such as RGBA values) or just one component (such as
583 temperature data).
584
585 See :func:`DataSetAttributes.set_vectors` when adding arrays
586 that contain magnitude and direction.
587
588 Parameters
589 ----------
590 scalars : ArrayLike[float]
591 Array of data.
592
593 name : str, default: 'scalars'
594 Name to assign the scalars.
595
596 deep_copy : bool, default: False
597 When ``True`` makes a full copy of the array.
598
599 Notes
600 -----
601 When adding directional data (such as velocity vectors), use
602 :func:`DataSetAttributes.set_vectors`.
603
604 Complex arrays will be represented internally as a 2 component float64
605 array. This is due to limitations of VTK's native datatypes.
606
607 Examples
608 --------
609 >>> import pyvista as pv
610 >>> mesh = pv.Cube()
611 >>> mesh.clear_data()
612 >>> scalars = range(mesh.n_points)
613 >>> mesh.point_data.set_scalars(scalars, 'my-scalars')
614 >>> mesh.point_data
615 pyvista DataSetAttributes
616 Association : POINT
617 Active Scalars : my-scalars
618 Active Vectors : None
619 Active Texture : None
620 Active Normals : None
621 Contains arrays :
622 my-scalars int64 (8,) SCALARS
623
624 """
625 vtk_arr = self._prepare_array(data=scalars, name=name, deep_copy=deep_copy)
626 self.VTKObject.SetScalars(vtk_arr)
627 self.VTKObject.Modified()
628
629 @_deprecate_positional_args(allowed=['vectors', 'name'])
630 def set_vectors(
631 self: Self,
632 vectors: MatrixLike[float],
633 name: str,
634 deep_copy: bool = False, # noqa: FBT001, FBT002
635 ) -> None:
636 """Set the active vectors of this data attribute.
637
638 Vectors are a quantity that has magnitude and direction, such
639 as normal vectors or a velocity field.
640
641 The vectors data must contain three components per cell or point. Use
642 :func:`DataSetAttributes.set_scalars` when adding non-directional data.
643
644 Parameters
645 ----------
646 vectors : MatrixLike
647 Data shaped ``(n, 3)`` where n matches the number of points or cells.
648
649 name : str
650 Name of the vectors.
651
652 deep_copy : bool, default: False
653 When ``True`` makes a full copy of the array. When ``False``, the
654 data references the original array without copying it.
655
656 Notes
657 -----
658 PyVista and VTK treats vectors and scalars differently when performing
659 operations. Vector data, unlike scalar data, is rotated along with the
660 geometry when the DataSet is passed through a transformation filter.
661
662 When adding non-directional data (such temperature values or
663 multi-component scalars like RGBA values), you can also use
664 :func:`DataSetAttributes.set_scalars`.
665
666 Examples
667 --------
668 Add random vectors to a mesh as point data.
669
670 >>> import pyvista as pv
671 >>> import numpy as np
672 >>> mesh = pv.Cube()
673 >>> mesh.clear_data()
674 >>> vectors = np.random.default_rng().random((mesh.n_points, 3))
675 >>> mesh.point_data.set_vectors(vectors, 'my-vectors')
676 >>> mesh.point_data
677 pyvista DataSetAttributes
678 Association : POINT
679 Active Scalars : None
680 Active Vectors : my-vectors
681 Active Texture : None
682 Active Normals : None
683 Contains arrays :
684 my-vectors float64 (8, 3) VECTORS
685
686 """
687 # prepare the array and add an attribute so that we can track this as a vector
688 vtk_arr = self._prepare_array(data=vectors, name=name, deep_copy=deep_copy)
689
690 n_comp = vtk_arr.GetNumberOfComponents()
691 if n_comp != 3:
692 msg = f'Vector array should contain 3 components, got {n_comp}'
693 raise ValueError(msg)
694
695 # check if there are current vectors, if so, we need to keep
696 # this array around since setting active vectors will remove
697 # this array.
698 current_vectors = self.GetVectors()
699
700 # now we can set the active vectors and add back in the old vectors as an array
701 self.VTKObject.SetVectors(vtk_arr)
702 if current_vectors is not None:
703 self.VTKObject.AddArray(current_vectors)
704
705 self.VTKObject.Modified()
706
707 def _prepare_array(
708 self: Self,
709 *,
710 data: npt.ArrayLike,
711 name: str,
712 deep_copy: bool,
713 ) -> _vtk.vtkAbstractArray: # numpydoc ignore=PR01,RT01
714 """Prepare an array to be added to this dataset.
715
716 Notes
717 -----
718 This method also adds metadata necessary for VTK to support non-VTK
719 compatible datatypes like ``numpy.complex128`` or ``numpy.bool_`` to
720 the underlying dataset.
721
722 """
723 if data is None:
724 msg = '``data`` cannot be None.' # type: ignore[unreachable]
725 raise TypeError(msg)
726
727 # convert to numpy type if necessary
728 data = np.asanyarray(data)
729
730 if self.association == FieldAssociation.POINT:
731 array_len = self.dataset.GetNumberOfPoints()
732 elif self.association == FieldAssociation.CELL:
733 array_len = self.dataset.GetNumberOfCells()
734 else:
735 array_len = 1 if data.ndim == 0 else data.shape[0]
736
737 if np.issubdtype(data.dtype, np.str_) and data.ndim == 0:
738 pass # Do not reshape string scalars
739 else:
740 # Fixup input array length for scalar input
741 if np.ndim(data) == 0:
742 tmparray = np.empty(array_len, dtype=data.dtype)
743 tmparray.fill(data)
744 data = tmparray
745 if data.shape[0] != array_len:
746 msg = (
747 f"Invalid array shape. Array '{name}' has length ({data.shape[0]}) "
748 f'but a length of ({array_len}) was expected.'
749 )
750 raise ValueError(msg)
751 if any(data.shape) and data.size == 0:
752 msg = (
753 f'Invalid array shape. Empty arrays are not allowed. '
754 f"Array '{name}' cannot have shape {data.shape}."
755 )
756 raise ValueError(msg)
757 # attempt to reuse the existing pointer to underlying VTK data
758 if isinstance(data, pyvista_ndarray):
759 # pyvista_ndarray already contains the reference to the vtk object
760 # pyvista needs to use the copy of this object rather than wrapping
761 # the array (which leaves a C++ pointer uncollected.
762 if data.VTKObject is not None:
763 # VTK doesn't support strides, therefore we can't directly
764 # point to the underlying object
765 if data.flags.c_contiguous:
766 # no reason to return a shallow copy if the array and name
767 # are identical, just return the underlying array name
768 if not deep_copy and data.VTKObject.GetName() == name:
769 return data.VTKObject
770
771 vtk_arr = copy_vtk_array(data.VTKObject, deep=deep_copy)
772 if isinstance(name, str):
773 vtk_arr.SetName(name)
774 return vtk_arr
775
776 # reset data association
777 if name in self.dataset._association_bitarray_names[self.association.name]: # type: ignore[union-attr]
778 self.dataset._association_bitarray_names[self.association.name].remove(name) # type: ignore[union-attr]
779 if name in self.dataset._association_complex_names[self.association.name]: # type: ignore[union-attr]
780 self.dataset._association_complex_names[self.association.name].remove(name) # type: ignore[union-attr]
781
782 if data.dtype == np.bool_:
783 self.dataset._association_bitarray_names[self.association.name].add(name) # type: ignore[union-attr]
784 data = data.view(np.uint8)
785 elif np.issubdtype(data.dtype, np.complexfloating):
786 if data.dtype not in (np.complex64, np.complex128):
787 msg = (
788 'Only numpy.complex64 or numpy.complex128 is supported when '
789 'setting dataset attributes'
790 )
791 raise ValueError(msg)
792
793 if data.ndim != 1:
794 if data.shape[1] != 1:
795 msg = 'Complex data must be single dimensional.'
796 raise ValueError(msg)
797 self.dataset._association_complex_names[self.association.name].add(name) # type: ignore[union-attr]
798
799 # complex data is stored internally as a contiguous 2 component
800 # float arrays
801 if data.dtype == np.complex64:
802 data = data.view(np.float32).reshape(-1, 2)
803 else:
804 data = data.view(np.float64).reshape(-1, 2)
805
806 shape = data.shape
807 if data.ndim == 3:
808 # Array of matrices. We need to make sure the order in
809 # memory is right. If row major (C/C++),
810 # transpose. VTK wants column major (Fortran order). The deep
811 # copy later will make sure that the array is contiguous.
812 # If column order but not contiguous, transpose so that the
813 # deep copy below does not happen.
814 size = data.dtype.itemsize
815 if (data.strides[1] / size == 3 and data.strides[2] / size == 1) or (
816 data.strides[1] / size == 1
817 and data.strides[2] / size == 3
818 and not data.flags.contiguous
819 ):
820 data = data.transpose(0, 2, 1)
821
822 # If array is not contiguous, make a deep copy that is contiguous
823 if not data.flags.contiguous:
824 data = np.ascontiguousarray(data)
825
826 # Flatten array of matrices to array of vectors
827 if len(shape) == 3:
828 data = data.reshape(shape[0], shape[1] * shape[2])
829
830 # Swap bytes from big to little endian.
831 if data.dtype.byteorder == '>':
832 data = data.byteswap(inplace=True)
833
834 # this handles the case when an input array is directly added to the
835 # output. We want to make sure that the array added to the output is not
836 # referring to the input dataset.
837 copy = pyvista_ndarray(data)
838
839 return convert_array(copy, name, deep=deep_copy)
840
841 def remove(self: Self, key: str) -> None:
842 """Remove an array.
843
844 Parameters
845 ----------
846 key : str
847 The name of the array to remove.
848
849 Notes
850 -----
851 You can also use the ``del`` statement.
852
853 Examples
854 --------
855 Add a point data array to a DataSet and then remove it.
856
857 >>> import pyvista as pv
858 >>> mesh = pv.Cube()
859 >>> mesh.point_data['my_data'] = range(mesh.n_points)
860 >>> mesh.point_data.remove('my_data')
861
862 Show that the array no longer exists in ``point_data``.
863
864 >>> 'my_data' in mesh.point_data
865 False
866
867 """
868 if not isinstance(key, str):
869 msg = 'Only strings are valid keys for DataSetAttributes.' # type: ignore[unreachable]
870 raise TypeError(msg)
871
872 if key not in self:
873 msg = f'{key} not present.'
874 raise KeyError(msg)
875
876 with contextlib.suppress(KeyError):
877 self.dataset._association_bitarray_names[self.association.name].remove(key) # type: ignore[union-attr]
878 if hasattr(self.dataset, '_user_dict'):
879 del self.dataset._user_dict
880 self.VTKObject.RemoveArray(key)
881 self.VTKObject.Modified()
882
883 def pop(self: Self, key: str, default: pyvista_ndarray | T = _SENTINEL) -> pyvista_ndarray | T:
884 """Remove an array and return it.
885
886 Parameters
887 ----------
888 key : str
889 The name of the array to remove and return.
890
891 default : Any, optional
892 If default is not given and key is not in the dictionary,
893 a KeyError is raised.
894
895 Returns
896 -------
897 pyvista_ndarray
898 Requested array.
899
900 Examples
901 --------
902 Add a point data array to a DataSet and then remove it.
903
904 >>> import pyvista as pv
905 >>> mesh = pv.Cube()
906 >>> mesh.point_data['my_data'] = range(mesh.n_points)
907 >>> mesh.point_data.pop('my_data')
908 pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
909
910 Show that the array no longer exists in ``point_data``.
911
912 >>> 'my_data' in mesh.point_data
913 False
914
915 """
916 if not isinstance(key, str):
917 msg = 'Only strings are valid keys for DataSetAttributes.' # type: ignore[unreachable]
918 raise TypeError(msg)
919
920 if key not in self:
921 if default is _SENTINEL:
922 msg = f'{key} not present.'
923 raise KeyError(msg)
924 return default
925
926 narray = self.get_array(key)
927
928 self.remove(key)
929 return narray
930
931 def items(self: Self) -> list[tuple[str, pyvista_ndarray]]:
932 """Return a list of (array name, array value) tuples.
933
934 Returns
935 -------
936 list
937 List of keys and values.
938
939 Examples
940 --------
941 >>> import pyvista as pv
942 >>> mesh = pv.Cube()
943 >>> mesh.clear_data()
944 >>> mesh.cell_data['data0'] = [0] * mesh.n_cells
945 >>> mesh.cell_data['data1'] = range(mesh.n_cells)
946 >>> mesh.cell_data.items() # doctest: +NORMALIZE_WHITESPACE
947 [('data0', pyvista_ndarray([0, 0, 0, 0, 0, 0])),
948 ('data1', pyvista_ndarray([0, 1, 2, 3, 4, 5]))]
949
950 """
951 return list(zip(self.keys(), self.values(), strict=True))
952
953 def keys(self: Self) -> list[str]:
954 """Return the names of the arrays as a list.
955
956 Returns
957 -------
958 list
959 List of keys.
960
961 Examples
962 --------
963 >>> import pyvista as pv
964 >>> mesh = pv.Sphere()
965 >>> mesh.clear_data()
966 >>> mesh.point_data['data0'] = [0] * mesh.n_points
967 >>> mesh.point_data['data1'] = range(mesh.n_points)
968 >>> mesh.point_data.keys()
969 ['data0', 'data1']
970
971 """
972 keys = []
973 for i in range(self.GetNumberOfArrays()):
974 array = self.VTKObject.GetAbstractArray(i)
975 name = array.GetName()
976 if name:
977 keys.append(name)
978 else: # pragma: no cover
979 # Assign this array a name
980 name = f'Unnamed_{i}'
981 array.SetName(name)
982 keys.append(name)
983 return keys
984
985 def values(self: Self) -> list[pyvista_ndarray]:
986 """Return the arrays as a list.
987
988 Returns
989 -------
990 list
991 List of arrays.
992
993 Examples
994 --------
995 >>> import pyvista as pv
996 >>> mesh = pv.Cube()
997 >>> mesh.clear_data()
998 >>> mesh.cell_data['data0'] = [0] * mesh.n_cells
999 >>> mesh.cell_data['data1'] = range(mesh.n_cells)
1000 >>> mesh.cell_data.values()
1001 [pyvista_ndarray([0, 0, 0, 0, 0, 0]), pyvista_ndarray([0, 1, 2, 3, 4, 5])]
1002
1003 """
1004 return [self.get_array(name) for name in self.keys()]
1005
1006 def _iter_flat_columns(self: Self) -> Iterator[tuple[str, npt.NDArray[Any]]]:
1007 """Yield ``(column_name, 1d_ndarray)`` pairs with multi-component arrays expanded.
1008
1009 Shared helper for :meth:`to_arrow`, :meth:`to_pandas`, and
1010 :meth:`__arrow_c_stream__`. Raises :class:`ValueError` when the
1011 attribute set isn't row-aligned (field data), when any array's
1012 leading dimension doesn't match :attr:`valid_array_len`, or when
1013 expanding multi-component arrays would produce duplicate column
1014 names.
1015 """
1016 n_rows = self.valid_array_len
1017 if n_rows is None:
1018 msg = (
1019 'Cannot build a tabular view of field data: field arrays may have '
1020 'differing lengths and are not row-aligned. Use point_data or cell_data.'
1021 )
1022 raise ValueError(msg)
1023 seen: set[str] = set()
1024
1025 def _emit(col_name: str, values: npt.NDArray[Any]) -> tuple[str, npt.NDArray[Any]]:
1026 if col_name in seen:
1027 msg = (
1028 f'Column name collision on {col_name!r}: multiple arrays would map '
1029 f'to the same column after multi-component expansion. Rename or '
1030 f'drop an array to proceed.'
1031 )
1032 raise ValueError(msg)
1033 seen.add(col_name)
1034 return col_name, values
1035
1036 for name, array in self.items():
1037 arr = np.asarray(array)
1038 if arr.shape[0] != n_rows:
1039 msg = (
1040 f'Array {name!r} has leading dimension {arr.shape[0]}, '
1041 f'expected {n_rows}; cannot build a tabular view.'
1042 )
1043 raise ValueError(msg)
1044 if arr.ndim == 1:
1045 yield _emit(name, arr)
1046 else:
1047 flat = arr.reshape(n_rows, -1)
1048 for i in range(flat.shape[1]):
1049 yield _emit(f'{name}_{i}', flat[:, i])
1050
1051 def to_arrow(self: Self) -> pyarrow.Table:
1052 """Return this attribute set as a :class:`pyarrow.Table`.
1053
1054 Each array becomes a column. Multi-component arrays (e.g. a
1055 ``(N, 3)`` vector field) are expanded to one column per component,
1056 named ``{array_name}_{i}``. Only ``point_data`` and ``cell_data``
1057 can be converted. ``field_data`` raises :class:`ValueError`
1058 because its arrays may have differing lengths.
1059
1060 Requires :mod:`pyarrow`.
1061
1062 Returns
1063 -------
1064 pyarrow.Table
1065 Table with one column per (expanded) array and
1066 :attr:`valid_array_len` rows.
1067
1068 Notes
1069 -----
1070 Memory sharing with the underlying VTK buffers is mixed:
1071
1072 - 1D contiguous numeric columns (scalar arrays) wrap the VTK
1073 buffer zero-copy. The Arrow column and the VTK array point at
1074 the same memory.
1075 - Expanded multi-component columns (``{name}_{i}``) come from
1076 strided slices and are copied into contiguous buffers.
1077 - Booleans, complex numbers, and strings go through pyvista's
1078 existing VTK conversion and are copied.
1079
1080 Arrow buffers are immutable by contract, so consumers cannot
1081 mutate VTK memory through the returned table.
1082
1083 Examples
1084 --------
1085 >>> import pyvista as pv
1086 >>> mesh = pv.Cube()
1087 >>> mesh.clear_data()
1088 >>> mesh.point_data['scalars'] = range(mesh.n_points)
1089 >>> table = mesh.point_data.to_arrow()
1090 >>> table.num_rows
1091 8
1092
1093 """
1094 try:
1095 import pyarrow as pa # noqa: PLC0415
1096 except ImportError: # pragma: no cover
1097 msg = 'Install ``pyarrow`` to use this feature.'
1098 raise ImportError(msg) from None
1099 names: list[str] = []
1100 arrays: list[pa.Array] = []
1101 for name, col in self._iter_flat_columns():
1102 names.append(name)
1103 arrays.append(pa.array(col))
1104 return pa.table(arrays, names=names)
1105
1106 def to_pandas(self: Self) -> pandas.DataFrame:
1107 """Return this attribute set as a :class:`pandas.DataFrame`.
1108
1109 Each array becomes a column. Multi-component arrays are expanded
1110 to one column per component, named ``{array_name}_{i}``. Only
1111 ``point_data`` and ``cell_data`` can be converted.
1112 ``field_data`` raises :class:`ValueError`.
1113
1114 Requires :mod:`pandas`.
1115
1116 Returns
1117 -------
1118 pandas.DataFrame
1119 DataFrame with one column per (expanded) array and
1120 :attr:`valid_array_len` rows.
1121
1122 Notes
1123 -----
1124 Pandas consolidates the dict of columns into internal blocks
1125 during construction, which copies the data. The returned
1126 DataFrame is effectively a snapshot and does not share memory
1127 with VTK. Callers that need zero-copy access should use
1128 :meth:`to_arrow` instead.
1129
1130 Examples
1131 --------
1132 >>> import pyvista as pv
1133 >>> mesh = pv.Cube()
1134 >>> mesh.clear_data()
1135 >>> mesh.point_data['scalars'] = range(mesh.n_points)
1136 >>> df = mesh.point_data.to_pandas()
1137 >>> list(df.columns)
1138 ['scalars']
1139
1140 """
1141 try:
1142 import pandas as pd # noqa: PLC0415
1143 except ImportError: # pragma: no cover
1144 msg = 'Install ``pandas`` to use this feature.'
1145 raise ImportError(msg) from None
1146 return pd.DataFrame(dict(self._iter_flat_columns()))
1147
1148 def __arrow_c_stream__(self: Self, requested_schema: object | None = None) -> object:
1149 """Export via the Arrow PyCapsule interface.
1150
1151 Implements `the Arrow PyCapsule interface
1152 <https://arrow.apache.org/docs/format/CDataInterface/PyCapsuleInterface.html>`_
1153 so pandas, polars, DuckDB, ibis, narwhals, and other Arrow-aware
1154 consumers can ingest ``point_data`` / ``cell_data`` directly.
1155
1156 Delegates to :meth:`to_arrow`, so the same memory-sharing rules
1157 apply: scalar 1D columns are zero-copy, multi-component expanded
1158 columns are copied.
1159
1160 Requires :mod:`pyarrow`.
1161 """
1162 return self.to_arrow().__arrow_c_stream__(requested_schema)
1163
1164 def clear(self: Self) -> None:
1165 """Remove all arrays in this object.
1166
1167 Examples
1168 --------
1169 Add an array to ``point_data`` to a DataSet and then clear the
1170 point_data.
1171
1172 >>> import pyvista as pv
1173 >>> mesh = pv.Cube()
1174 >>> mesh.clear_data()
1175 >>> mesh.point_data['my_data'] = range(mesh.n_points)
1176 >>> len(mesh.point_data)
1177 1
1178 >>> mesh.point_data.clear()
1179 >>> len(mesh.point_data)
1180 0
1181
1182 """
1183 for array_name in self.keys():
1184 self.remove(key=array_name)
1185
1186 @_deprecate_positional_args(allowed=['array_dict'])
1187 def update(
1188 self: Self,
1189 array_dict: dict[str, NumpyArray[float]] | DataSetAttributes,
1190 copy: bool = True, # noqa: FBT001, FBT002
1191 ) -> None:
1192 """Update arrays in this object from another dictionary or dataset attributes.
1193
1194 For each key, value given, add the pair. If it already exists, replace
1195 it with the new array. These arrays will be copied.
1196
1197 Parameters
1198 ----------
1199 array_dict : dict, DataSetAttributes
1200 A dictionary of ``(array name, :class:`numpy.ndarray`)`` or a
1201 :class:`pyvista.DataSetAttributes`.
1202
1203 copy : bool, default: True
1204 If ``True``, arrays from ``array_dict`` are copied to this object.
1205
1206 Examples
1207 --------
1208 Add two arrays to ``point_data`` using ``update``.
1209
1210 >>> import numpy as np
1211 >>> from pyvista import examples
1212 >>> mesh = examples.load_uniform()
1213 >>> n = len(mesh.point_data)
1214 >>> arrays = {
1215 ... 'foo': np.arange(mesh.n_points),
1216 ... 'rand': np.random.default_rng().random(mesh.n_points),
1217 ... }
1218 >>> mesh.point_data.update(arrays)
1219 >>> mesh.point_data
1220 pyvista DataSetAttributes
1221 Association : POINT
1222 Active Scalars : Spatial Point Data
1223 Active Vectors : None
1224 Active Texture : None
1225 Active Normals : None
1226 Contains arrays :
1227 Spatial Point Data float64 (1000,) SCALARS
1228 foo int64 (1000,)
1229 rand float64 (1000,)
1230
1231 """
1232 for name, array in array_dict.items():
1233 self._update_array(name=name, array=array, copy=copy)
1234
1235 def _update_array(
1236 self: Self,
1237 *,
1238 name: str,
1239 array: NumpyArray[float],
1240 copy: bool,
1241 ) -> None:
1242 if copy:
1243 self[name] = array.copy() if hasattr(array, 'copy') else copylib.copy(array)
1244 else:
1245 self[name] = array
1246
1247 def _raise_index_out_of_bounds(self: Self, index: Any) -> None:
1248 """Raise a KeyError if array index is out of bounds."""
1249 if isinstance(index, int):
1250 max_index = self.VTKObject.GetNumberOfArrays()
1251 if not 0 <= index < max_index:
1252 msg = f'Array index ({index}) out of range [0, {max_index - 1}]'
1253 raise KeyError(msg)
1254
1255 def _raise_field_data_no_scalars_vectors_normals(self: Self) -> None:
1256 """Raise a ``TypeError`` if FieldData."""
1257 if self.association == FieldAssociation.NONE:
1258 msg = 'FieldData does not have active scalars or vectors or normals.'
1259 raise TypeError(msg)
1260
1261 @property
1262 def active_scalars_name(self: Self) -> str | None:
1263 """Return name of the active scalars.
1264
1265 Returns
1266 -------
1267 Optional[str]
1268 Name of the active scalars.
1269
1270 Examples
1271 --------
1272 Add two arrays to the mesh point data. Note how the first array becomes
1273 the active scalars since the ``mesh`` contained no scalars.
1274
1275 >>> import pyvista as pv
1276 >>> mesh = pv.Sphere()
1277 >>> mesh.point_data['my_data'] = range(mesh.n_points)
1278 >>> mesh.point_data['my_other_data'] = range(mesh.n_points)
1279 >>> mesh.point_data.active_scalars_name
1280 'my_data'
1281
1282 Set the name of the active scalars.
1283
1284 >>> mesh.point_data.active_scalars_name = 'my_other_data'
1285 >>> mesh.point_data.active_scalars_name
1286 'my_other_data'
1287
1288 """
1289 if self.GetScalars() is not None:
1290 name = self.GetScalars().GetName()
1291 if name is None:
1292 # Getting the keys has the side effect of naming "unnamed" arrays
1293 self.keys()
1294 name = self.GetScalars().GetName()
1295 return str(name)
1296 return None
1297
1298 @active_scalars_name.setter
1299 def active_scalars_name(self: Self, name: str | None) -> None:
1300 """Set name of the active scalars.
1301
1302 Parameters
1303 ----------
1304 name : str
1305 Name of the active scalars.
1306
1307 """
1308 # permit setting no active scalars
1309 if name is None:
1310 self.SetActiveScalars(None)
1311 return
1312 self._raise_field_data_no_scalars_vectors_normals()
1313 dtype = self[name].dtype
1314 # only vtkDataArray subclasses can be set as active attributes
1315 if np.issubdtype(dtype, np.number) or np.issubdtype(dtype, bool):
1316 self.SetActiveScalars(name)
1317
1318 @property
1319 def _active_normals_name(self: Self) -> str | None:
1320 """Return name of the active normals.
1321
1322 Returns
1323 -------
1324 Optional[str]
1325 Name of the active normals.
1326
1327 Examples
1328 --------
1329 Create a mesh add a new point array with normals.
1330
1331 >>> import pyvista as pv
1332 >>> import numpy as np
1333 >>> mesh = pv.Sphere()
1334 >>> normals = np.random.default_rng().random((mesh.n_points, 3))
1335 >>> mesh.point_data['my-normals'] = normals
1336
1337 Set the active normals.
1338
1339 >>> mesh.point_data._active_normals_name = 'my-normals'
1340 >>> mesh.point_data._active_normals_name
1341 'my-normals'
1342
1343 """
1344 if self.GetNormals() is not None:
1345 return str(self.GetNormals().GetName())
1346 return None
1347
1348 @_active_normals_name.setter
1349 def _active_normals_name(self: Self, name: str | None) -> None:
1350 """Set name of the active normals.
1351
1352 Parameters
1353 ----------
1354 name : str
1355 Name of the active normals.
1356
1357 """
1358 # permit setting no active
1359 if name is None:
1360 self.SetActiveNormals(None)
1361 return
1362 self._raise_field_data_no_scalars_vectors_normals()
1363 if name not in self:
1364 msg = f'DataSetAttribute does not contain "{name}"'
1365 raise KeyError(msg)
1366 # verify that the array has the correct number of components
1367 n_comp = self.GetArray(name).GetNumberOfComponents()
1368 if n_comp != 3:
1369 msg = f'{name} needs 3 components, has ({n_comp})'
1370 raise ValueError(msg)
1371 self.SetActiveNormals(name)
1372
1373 @property
1374 def active_vectors_name(self: Self) -> str | None:
1375 """Return name of the active vectors.
1376
1377 Returns
1378 -------
1379 Optional[str]
1380 Name of the active vectors.
1381
1382 Examples
1383 --------
1384 >>> import pyvista as pv
1385 >>> import numpy as np
1386 >>> mesh = pv.Sphere()
1387 >>> mesh.point_data.set_vectors(
1388 ... np.random.default_rng().random((mesh.n_points, 3)),
1389 ... 'my-vectors',
1390 ... )
1391 >>> mesh.point_data.active_vectors_name
1392 'my-vectors'
1393
1394 """
1395 if self.GetVectors() is not None:
1396 return str(self.GetVectors().GetName())
1397 return None
1398
1399 @active_vectors_name.setter
1400 def active_vectors_name(self: Self, name: str | None) -> None:
1401 """Set name of the active vectors.
1402
1403 Parameters
1404 ----------
1405 name : str
1406 Name of the active vectors.
1407
1408 """
1409 # permit setting no active
1410 if name is None:
1411 self.SetActiveVectors(None)
1412 return
1413 self._raise_field_data_no_scalars_vectors_normals()
1414 if name not in self:
1415 msg = f'DataSetAttribute does not contain "{name}"'
1416 raise KeyError(msg)
1417 # verify that the array has the correct number of components
1418 n_comp = self.GetArray(name).GetNumberOfComponents()
1419 if n_comp != 3:
1420 msg = f'{name} needs 3 components, has ({n_comp})'
1421 raise ValueError(msg)
1422 self.SetActiveVectors(name)
1423
1424 def __eq__(self: Self, other: object) -> bool:
1425 """Test dict-like equivalency."""
1426
1427 def array_equal_nan(array1: npt.ArrayLike, array2: npt.ArrayLike) -> bool:
1428 # Check with `equal_nan=True` but only for floats since this fails for strings
1429 # See numpy/numpy#16377
1430 return (
1431 np.issubdtype(np.asanyarray(array1).dtype, np.floating)
1432 and np.issubdtype(np.asanyarray(array2).dtype, np.floating)
1433 and np.array_equal(array1, array2, equal_nan=True)
1434 )
1435
1436 # here we check if other is the same class or a subclass of self.
1437 if not isinstance(other, type(self)):
1438 return False
1439
1440 if set(self.keys()) != set(other.keys()):
1441 return False
1442
1443 # verify the value of the arrays
1444 for key, value in other.items():
1445 if not np.array_equal(value, self[key]) and not array_equal_nan(value, self[key]):
1446 return False
1447
1448 # check the name of the active attributes
1449 if self.association != FieldAssociation.NONE:
1450 for name in ['scalars', 'vectors', 'texture_coordinates', 'normals']:
1451 attr = f'active_{name}_name'
1452 if getattr(other, attr) != getattr(self, attr):
1453 return False
1454
1455 return True
1456
1457 __hash__ = None # type: ignore[assignment] # https://github.com/pyvista/pyvista/pull/7671
1458
1459 @property
1460 def active_normals(self: Self) -> pyvista_ndarray | None:
1461 """Return the normals.
1462
1463 Returns
1464 -------
1465 pyvista_ndarray
1466 Normals of this dataset attribute. ``None`` if no normals have been
1467 set.
1468
1469 Notes
1470 -----
1471 Field data will have no normals.
1472
1473 Examples
1474 --------
1475 First, compute cell normals.
1476
1477 >>> import pyvista as pv
1478 >>> mesh = pv.Plane(i_resolution=1, j_resolution=1)
1479 >>> mesh.point_data
1480 pyvista DataSetAttributes
1481 Association : POINT
1482 Active Scalars : None
1483 Active Vectors : None
1484 Active Texture : TextureCoordinates
1485 Active Normals : Normals
1486 Contains arrays :
1487 Normals float32 (4, 3) NORMALS
1488 TextureCoordinates float32 (4, 2) TCOORDS
1489
1490 >>> mesh.point_data.active_normals
1491 pyvista_ndarray([[0., 0., 1.],
1492 [0., 0., 1.],
1493 [0., 0., 1.],
1494 [0., 0., 1.]], dtype=float32)
1495
1496 Assign normals to the cell arrays. An array will be added
1497 named ``"Normals"``.
1498
1499 >>> mesh.cell_data.active_normals = [[0.0, 0.0, 1.0]]
1500 >>> mesh.cell_data
1501 pyvista DataSetAttributes
1502 Association : CELL
1503 Active Scalars : None
1504 Active Vectors : None
1505 Active Texture : None
1506 Active Normals : Normals
1507 Contains arrays :
1508 Normals float64 (1, 3) NORMALS
1509
1510 """
1511 self._raise_no_normals()
1512 vtk_normals = self.GetNormals()
1513 if vtk_normals is not None:
1514 return pyvista_ndarray(vtk_normals, dataset=self.dataset, association=self.association)
1515 return None
1516
1517 @active_normals.setter
1518 def active_normals(self: Self, normals: MatrixLike[float]) -> None:
1519 """Set the normals.
1520
1521 Parameters
1522 ----------
1523 normals : MatrixLike
1524 Normals of this dataset attribute.
1525
1526 """
1527 self._raise_no_normals()
1528 normals = np.asarray(normals)
1529 if normals.ndim != 2:
1530 msg = 'Normals must be a 2-dimensional array'
1531 raise ValueError(msg)
1532 valid_length = self.valid_array_len
1533 if normals.shape[0] != valid_length:
1534 msg = (
1535 f'Number of normals ({normals.shape[0]}) must match '
1536 f'number of points ({valid_length})'
1537 )
1538 raise ValueError(msg)
1539 if normals.shape[1] != 3:
1540 msg = f'Normals must have exactly 3 components, not ({normals.shape[1]})'
1541 raise ValueError(msg)
1542
1543 vtkarr = _vtk.numpyTovtkDataArray(normals, name='Normals')
1544 self.SetNormals(vtkarr)
1545 self.Modified()
1546
1547 @property
1548 def active_normals_name(self: Self) -> str | None:
1549 """Return the name of the normals array.
1550
1551 Returns
1552 -------
1553 str
1554 Name of the active normals array.
1555
1556 Examples
1557 --------
1558 First, compute cell normals.
1559
1560 >>> import pyvista as pv
1561 >>> mesh = pv.Plane(i_resolution=1, j_resolution=1)
1562 >>> mesh_w_normals = mesh.compute_normals()
1563 >>> mesh_w_normals.point_data.active_normals_name
1564 'Normals'
1565
1566 """
1567 self._raise_no_normals()
1568 if self.GetNormals() is not None:
1569 return str(self.GetNormals().GetName())
1570 return None
1571
1572 @active_normals_name.setter
1573 def active_normals_name(self: Self, name: str | None) -> None:
1574 """Set the name of the normals array.
1575
1576 Parameters
1577 ----------
1578 name : str
1579 Name of the active normals array.
1580
1581 """
1582 # permit setting no active
1583 if name is None:
1584 self.SetActiveNormals(None)
1585 return
1586 self._raise_no_normals()
1587 self.SetActiveNormals(name)
1588
1589 def _raise_no_normals(self: Self) -> None:
1590 """Raise AttributeError when attempting access normals for field data."""
1591 if self.association == FieldAssociation.NONE:
1592 msg = 'FieldData does not have active normals.'
1593 raise AttributeError(msg)
1594
1595 def _raise_no_texture_coordinates(self: Self) -> None:
1596 """Raise AttributeError when attempting access texture_coordinates for field data."""
1597 if self.association == FieldAssociation.NONE:
1598 msg = 'FieldData does not have active texture coordinates.'
1599 raise AttributeError(msg)
1600
1601 @property
1602 def active_texture_coordinates(self: Self) -> pyvista_ndarray | None:
1603 """Return the active texture coordinates array.
1604
1605 Returns
1606 -------
1607 pyvista.pyvista_ndarray
1608 Array of the active texture coordinates.
1609
1610 Examples
1611 --------
1612 >>> import pyvista as pv
1613 >>> mesh = pv.Cube()
1614 >>> mesh.point_data.active_texture_coordinates
1615 pyvista_ndarray([[-0., 0.],
1616 [ 0., 0.],
1617 [ 0., 1.],
1618 [-0., 1.],
1619 [-1., 0.],
1620 [-1., 1.],
1621 [ 1., 1.],
1622 [ 1., 0.]], dtype=float32)
1623
1624 """
1625 self._raise_no_texture_coordinates()
1626 texture_coordinates = self.GetTCoords()
1627 if texture_coordinates is not None:
1628 return pyvista_ndarray(
1629 texture_coordinates,
1630 dataset=self.dataset,
1631 association=self.association,
1632 )
1633 return None
1634
1635 @active_texture_coordinates.setter
1636 def active_texture_coordinates(
1637 self: Self,
1638 texture_coordinates: NumpyArray[float],
1639 ) -> None:
1640 """Set the active texture coordinates array.
1641
1642 Parameters
1643 ----------
1644 texture_coordinates : np.ndarray
1645 Array of the active texture coordinates.
1646
1647 """
1648 self._raise_no_texture_coordinates()
1649 if not isinstance(texture_coordinates, np.ndarray):
1650 msg = 'Texture coordinates must be a numpy array' # type: ignore[unreachable]
1651 raise TypeError(msg)
1652 if texture_coordinates.ndim != 2:
1653 msg = 'Texture coordinates must be a 2-dimensional array'
1654 raise ValueError(msg)
1655 valid_length = self.valid_array_len
1656 if texture_coordinates.shape[0] != valid_length:
1657 msg = (
1658 f'Number of texture coordinates ({texture_coordinates.shape[0]}) '
1659 f'must match number of points ({valid_length})'
1660 )
1661 raise ValueError(msg)
1662 if texture_coordinates.shape[1] != 2:
1663 msg = (
1664 f'Texture coordinates must only have 2 components, '
1665 f'not ({texture_coordinates.shape[1]})'
1666 )
1667 raise ValueError(msg)
1668 vtkarr = _vtk.numpyTovtkDataArray(texture_coordinates, name='Texture Coordinates')
1669 self.SetTCoords(vtkarr)
1670 self.Modified()
1671
1672 @property
1673 def active_texture_coordinates_name(self: Self) -> str | None:
1674 """Return the name of the active texture coordinates array.
1675
1676 Returns
1677 -------
1678 Optional[str]
1679 Name of the active texture coordinates array.
1680
1681 Examples
1682 --------
1683 >>> import pyvista as pv
1684 >>> mesh = pv.Cube()
1685 >>> mesh.point_data.active_texture_coordinates_name
1686 'TCoords'
1687
1688 """
1689 self._raise_no_texture_coordinates()
1690 if self.GetTCoords() is not None:
1691 return str(self.GetTCoords().GetName())
1692 return None
1693
1694 @active_texture_coordinates_name.setter
1695 def active_texture_coordinates_name(self: Self, name: str | None) -> None:
1696 """Set the name of the active texture coordinates array.
1697
1698 Parameters
1699 ----------
1700 name : str
1701 Name of the active texture coordinates array.
1702
1703 """
1704 if name is None:
1705 self.SetActiveTCoords(None)
1706 return
1707
1708 self._raise_no_texture_coordinates()
1709 dtype = self[name].dtype
1710 # only vtkDataArray subclasses can be set as active attributes
1711 if np.issubdtype(dtype, np.number) or np.issubdtype(dtype, bool):
1712 self.SetActiveTCoords(name)