/
dataset.py
3424 lines (2816 loc) · 106 KB
/
dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Attributes common to PolyData and Grid Objects."""
from __future__ import annotations
import collections.abc
from copy import deepcopy
from functools import partial
from typing import (
Any,
Callable,
Generator,
Iterable,
Iterator,
List,
Literal,
NamedTuple,
Optional,
Sequence,
Tuple,
Union,
cast,
)
import warnings
import numpy as np
import pyvista
from . import _vtk_core as _vtk
from ._typing_core import BoundsLike, MatrixLike, Number, NumpyArray, VectorLike
from .dataobject import DataObject
from .datasetattributes import DataSetAttributes
from .errors import PyVistaDeprecationWarning, VTKVersionError
from .filters import DataSetFilters, _get_output
from .pyvista_ndarray import pyvista_ndarray
from .utilities import transformations
from .utilities.arrays import (
FieldAssociation,
_coerce_pointslike_arg,
get_array,
get_array_association,
raise_not_matching,
vtk_id_list_to_array,
)
from .utilities.helpers import is_pyvista_dataset
from .utilities.misc import abstract_class, check_valid_vector
from .utilities.points import vtk_points
# vector array names
DEFAULT_VECTOR_KEY = '_vectors'
class ActiveArrayInfoTuple(NamedTuple):
"""Active array info tuple to provide legacy support."""
association: FieldAssociation
name: str
class ActiveArrayInfo:
"""Active array info class with support for pickling.
Parameters
----------
association : pyvista.core.utilities.arrays.FieldAssociation
Array association.
Association of the array.
name : str
The name of the array.
"""
def __init__(self, association, name):
"""Initialize."""
self.association = association
self.name = name
def copy(self) -> ActiveArrayInfo:
"""Return a copy of this object.
Returns
-------
ActiveArrayInfo
A copy of this object.
"""
return ActiveArrayInfo(self.association, self.name)
def __getstate__(self):
"""Support pickling."""
state = self.__dict__.copy()
state['association'] = int(self.association.value)
return state
def __setstate__(self, state):
"""Support unpickling."""
self.__dict__ = state.copy()
self.association = FieldAssociation(state['association'])
@property
def _namedtuple(self):
"""Build a namedtuple on the fly to provide legacy support."""
return ActiveArrayInfoTuple(self.association, self.name)
def __iter__(self):
"""Provide namedtuple-like __iter__."""
return self._namedtuple.__iter__()
def __repr__(self):
"""Provide namedtuple-like __repr__."""
return self._namedtuple.__repr__()
def __getitem__(self, item):
"""Provide namedtuple-like __getitem__."""
return self._namedtuple.__getitem__(item)
def __setitem__(self, key, value):
"""Provide namedtuple-like __setitem__."""
self._namedtuple.__setitem__(key, value)
def __getattr__(self, item):
"""Provide namedtuple-like __getattr__."""
self._namedtuple.__getattr__(item)
def __eq__(self, other):
"""Check equivalence (useful for serialize/deserialize tests)."""
same_association = int(self.association.value) == int(other.association.value)
return self.name == other.name and same_association
@abstract_class
class DataSet(DataSetFilters, DataObject):
"""Methods in common to spatially referenced objects.
Parameters
----------
*args :
Any extra args are passed as option to spatially referenced objects.
**kwargs :
Any extra keyword args are passed as option to spatially referenced objects.
"""
plot = pyvista._plot.plot
def __init__(self, *args, **kwargs) -> None:
"""Initialize the common object."""
super().__init__()
self._last_active_scalars_name: Optional[str] = None
self._active_scalars_info = ActiveArrayInfo(FieldAssociation.POINT, name=None)
self._active_vectors_info = ActiveArrayInfo(FieldAssociation.POINT, name=None)
self._active_tensors_info = ActiveArrayInfo(FieldAssociation.POINT, name=None)
def __getattr__(self, item) -> Any:
"""Get attribute from base class if not found."""
return super().__getattribute__(item)
@property
def active_scalars_info(self) -> ActiveArrayInfo: # numpydoc ignore=RT01
"""Return the active scalar's association and name.
Association refers to the data association (e.g. point, cell, or
field) of the active scalars.
Returns
-------
ActiveArrayInfo
The scalars info in an object with namedtuple semantics,
with attributes ``association`` and ``name``.
Notes
-----
If both cell and point scalars are present and neither have
been set active within at the dataset level, point scalars
will be made active.
Examples
--------
Create a mesh, add scalars to the mesh, and return the active
scalars info. Note how when the scalars are added, they
automatically become the active scalars.
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> mesh['Z Height'] = mesh.points[:, 2]
>>> mesh.active_scalars_info
ActiveArrayInfoTuple(association=<FieldAssociation.POINT: 0>, name='Z Height')
"""
field, name = self._active_scalars_info
exclude = {'__custom_rgba', 'Normals', 'vtkOriginalPointIds', 'TCoords'}
if name in exclude:
name = self._last_active_scalars_name
# verify this field is still valid
if name is not None:
if field is FieldAssociation.CELL:
if self.cell_data.active_scalars_name != name:
name = None
elif field is FieldAssociation.POINT:
if self.point_data.active_scalars_name != name:
name = None
if name is None:
# check for the active scalars in point or cell arrays
self._active_scalars_info = ActiveArrayInfo(field, None)
for attr in [self.point_data, self.cell_data]:
if attr.active_scalars_name is not None:
self._active_scalars_info = ActiveArrayInfo(
attr.association,
attr.active_scalars_name,
)
break
return self._active_scalars_info
@property
def active_vectors_info(self) -> ActiveArrayInfo: # numpydoc ignore=RT01
"""Return the active vector's association and name.
Association refers to the data association (e.g. point, cell, or
field) of the active vectors.
Returns
-------
ActiveArrayInfo
The vectors info in an object with namedtuple semantics,
with attributes ``association`` and ``name``.
Notes
-----
If both cell and point vectors are present and neither have
been set active within at the dataset level, point vectors
will be made active.
Examples
--------
Create a mesh, compute the normals inplace, set the active
vectors to the normals, and show that the active vectors are
the ``'Normals'`` array associated with points.
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> _ = mesh.compute_normals(inplace=True)
>>> mesh.active_vectors_name = 'Normals'
>>> mesh.active_vectors_info
ActiveArrayInfoTuple(association=<FieldAssociation.POINT: 0>, name='Normals')
"""
field, name = self._active_vectors_info
# verify this field is still valid
if name is not None:
if field is FieldAssociation.POINT:
if self.point_data.active_vectors_name != name:
name = None
if field is FieldAssociation.CELL:
if self.cell_data.active_vectors_name != name:
name = None
if name is None:
# check for the active vectors in point or cell arrays
self._active_vectors_info = ActiveArrayInfo(field, None)
for attr in [self.point_data, self.cell_data]:
name = attr.active_vectors_name
if name is not None:
self._active_vectors_info = ActiveArrayInfo(attr.association, name)
break
return self._active_vectors_info
@property
def active_tensors_info(self) -> ActiveArrayInfo: # numpydoc ignore=RT01
"""Return the active tensor's field and name: [field, name].
Returns
-------
ActiveArrayInfo
Active tensor's field and name: [field, name].
"""
return self._active_tensors_info
@property
def active_vectors(self) -> Optional[pyvista_ndarray]: # numpydoc ignore=RT01
"""Return the active vectors array.
Returns
-------
Optional[pyvista_ndarray]
Active vectors array.
Examples
--------
Create a mesh, compute the normals inplace, and return the
normals vector array.
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> _ = mesh.compute_normals(inplace=True)
>>> mesh.active_vectors # doctest:+SKIP
pyvista_ndarray([[-2.48721432e-10, -1.08815623e-09, -1.00000000e+00],
[-2.48721432e-10, -1.08815623e-09, 1.00000000e+00],
[-1.18888125e-01, 3.40539310e-03, -9.92901802e-01],
...,
[-3.11940581e-01, -6.81432486e-02, 9.47654784e-01],
[-2.09880397e-01, -4.65070531e-02, 9.76620376e-01],
[-1.15582108e-01, -2.80492082e-02, 9.92901802e-01]],
dtype=float32)
"""
field, name = self.active_vectors_info
if name is not None:
try:
if field is FieldAssociation.POINT:
return self.point_data[name]
if field is FieldAssociation.CELL:
return self.cell_data[name]
except KeyError:
return None
return None
@property
def active_tensors(self) -> Optional[NumpyArray[float]]: # numpydoc ignore=RT01
"""Return the active tensors array.
Returns
-------
Optional[np.ndarray]
Active tensors array.
"""
field, name = self.active_tensors_info
if name is not None:
try:
if field is FieldAssociation.POINT:
return self.point_data[name]
if field is FieldAssociation.CELL:
return self.cell_data[name]
except KeyError:
return None
return None
@property
def active_tensors_name(self) -> str: # numpydoc ignore=RT01
"""Return the name of the active tensor array.
Returns
-------
str
Name of the active tensor array.
"""
return self.active_tensors_info.name
@active_tensors_name.setter
def active_tensors_name(self, name: str): # numpydoc ignore=GL08
"""Set the name of the active tensor array.
Parameters
----------
name : str
Name of the active tensor array.
"""
self.set_active_tensors(name)
@property
def active_vectors_name(self) -> str: # numpydoc ignore=RT01
"""Return the name of the active vectors array.
Returns
-------
str
Name of the active vectors array.
Examples
--------
Create a mesh, compute the normals, set them as active, and
return the name of the active vectors.
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> mesh_w_normals = mesh.compute_normals()
>>> mesh_w_normals.active_vectors_name = 'Normals'
>>> mesh_w_normals.active_vectors_name
'Normals'
"""
return self.active_vectors_info.name
@active_vectors_name.setter
def active_vectors_name(self, name: str): # numpydoc ignore=GL08
"""Set the name of the active vectors array.
Parameters
----------
name : str
Name of the active vectors array.
"""
self.set_active_vectors(name)
@property # type: ignore[explicit-override, override]
def active_scalars_name(self) -> str: # numpydoc ignore=RT01
"""Return the name of the active scalars.
Returns
-------
str
Name of the active scalars.
Examples
--------
Create a mesh, add scalars to the mesh, and return the name of
the active scalars.
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> mesh['Z Height'] = mesh.points[:, 2]
>>> mesh.active_scalars_name
'Z Height'
"""
return self.active_scalars_info.name
@active_scalars_name.setter
def active_scalars_name(self, name: str): # numpydoc ignore=GL08
"""Set the name of the active scalars.
Parameters
----------
name : str
Name of the active scalars.
"""
self.set_active_scalars(name)
@property
def points(self) -> pyvista_ndarray: # numpydoc ignore=RT01
"""Return a reference to the points as a numpy object.
Returns
-------
pyvista_ndarray
Reference to the points as a numpy object.
Examples
--------
Create a mesh and return the points of the mesh as a numpy
array.
>>> import pyvista as pv
>>> cube = pv.Cube()
>>> points = cube.points
>>> points
pyvista_ndarray([[-0.5, -0.5, -0.5],
[-0.5, -0.5, 0.5],
[-0.5, 0.5, 0.5],
[-0.5, 0.5, -0.5],
[ 0.5, -0.5, -0.5],
[ 0.5, 0.5, -0.5],
[ 0.5, 0.5, 0.5],
[ 0.5, -0.5, 0.5]], dtype=float32)
Shift these points in the z direction and show that their
position is reflected in the mesh points.
>>> points[:, 2] += 1
>>> cube.points
pyvista_ndarray([[-0.5, -0.5, 0.5],
[-0.5, -0.5, 1.5],
[-0.5, 0.5, 1.5],
[-0.5, 0.5, 0.5],
[ 0.5, -0.5, 0.5],
[ 0.5, 0.5, 0.5],
[ 0.5, 0.5, 1.5],
[ 0.5, -0.5, 1.5]], dtype=float32)
You can also update the points in-place:
>>> cube.points[...] = 2 * points
>>> cube.points
pyvista_ndarray([[-1., -1., 1.],
[-1., -1., 3.],
[-1., 1., 3.],
[-1., 1., 1.],
[ 1., -1., 1.],
[ 1., 1., 1.],
[ 1., 1., 3.],
[ 1., -1., 3.]], dtype=float32)
"""
_points = self.GetPoints()
try:
_points = _points.GetData()
except AttributeError:
# create an empty array
vtkpts = vtk_points(np.empty((0, 3)), False)
self.SetPoints(vtkpts)
_points = self.GetPoints().GetData()
return pyvista_ndarray(_points, dataset=self)
@points.setter
def points(self, points: Union[MatrixLike[float], _vtk.vtkPoints]): # numpydoc ignore=GL08
"""Set a reference to the points as a numpy object.
Parameters
----------
points : MatrixLike[float] | vtk.vtkPoints
Points as a array object.
"""
pdata = self.GetPoints()
if isinstance(points, pyvista_ndarray):
# simply set the underlying data
if points.VTKObject is not None and pdata is not None:
pdata.SetData(points.VTKObject)
pdata.Modified()
self.Modified()
return
# directly set the data if vtk object
if isinstance(points, _vtk.vtkPoints):
self.SetPoints(points)
if pdata is not None:
pdata.Modified()
self.Modified()
return
# otherwise, wrap and use the array
points, _ = _coerce_pointslike_arg(points, copy=False)
vtkpts = vtk_points(points, False)
if not pdata:
self.SetPoints(vtkpts)
else:
pdata.SetData(vtkpts.GetData())
self.GetPoints().Modified()
self.Modified()
@property
def arrows(self) -> Optional[pyvista.PolyData]: # numpydoc ignore=RT01
"""Return a glyph representation of the active vector data as arrows.
Arrows will be located at the points of the mesh and
their size will be dependent on the norm of the vector.
Their direction will be the "direction" of the vector
Returns
-------
pyvista.PolyData
Active vectors represented as arrows.
Examples
--------
Create a mesh, compute the normals and set them active, and
plot the active vectors.
>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> mesh_w_normals = mesh.compute_normals()
>>> mesh_w_normals.active_vectors_name = 'Normals'
>>> arrows = mesh_w_normals.arrows
>>> arrows.plot(show_scalar_bar=False)
"""
vectors, vectors_name = self.active_vectors, self.active_vectors_name
if vectors is None or vectors_name is None:
return None
if vectors.ndim != 2:
raise ValueError('Active vectors are not vectors.')
scale_name = f'{vectors_name} Magnitude'
scale = np.linalg.norm(vectors, axis=1)
self.point_data.set_array(scale, scale_name)
return self.glyph(orient=vectors_name, scale=scale_name)
@property
def active_t_coords(self) -> Optional[pyvista_ndarray]: # numpydoc ignore=RT01
"""Return the active texture coordinates on the points.
Returns
-------
Optional[pyvista_ndarray]
Active texture coordinates on the points.
"""
warnings.warn(
"Use of `DataSet.active_t_coords` is deprecated. Use `DataSet.active_texture_coordinates` instead.",
PyVistaDeprecationWarning,
)
return self.active_texture_coordinates
@active_t_coords.setter
def active_t_coords(self, t_coords: NumpyArray[float]): # numpydoc ignore=GL08
"""Set the active texture coordinates on the points.
Parameters
----------
t_coords : np.ndarray
Active texture coordinates on the points.
"""
warnings.warn(
"Use of `DataSet.active_t_coords` is deprecated. Use `DataSet.active_texture_coordinates` instead.",
PyVistaDeprecationWarning,
)
self.active_texture_coordinates = t_coords # type: ignore[assignment]
def set_active_scalars(
self,
name: Optional[str],
preference='cell',
) -> Tuple[FieldAssociation, Optional[NumpyArray[float]]]:
"""Find the scalars by name and appropriately sets it as active.
To deactivate any active scalars, pass ``None`` as the ``name``.
Parameters
----------
name : str, optional
Name of the scalars array to assign as active. If
``None``, deactivates active scalars for both point and
cell data.
preference : str, default: "cell"
If there are two arrays of the same name associated with
points or cells, it will prioritize an array matching this
type. Can be either ``'cell'`` or ``'point'``.
Returns
-------
pyvista.core.utilities.arrays.FieldAssociation
Association of the scalars matching ``name``.
pyvista_ndarray
An array from the dataset matching ``name``.
"""
if preference not in ['point', 'cell', FieldAssociation.CELL, FieldAssociation.POINT]:
raise ValueError('``preference`` must be either "point" or "cell"')
if name is None:
self.GetCellData().SetActiveScalars(None)
self.GetPointData().SetActiveScalars(None)
return FieldAssociation.NONE, np.array([])
field = get_array_association(self, name, preference=preference)
if field == FieldAssociation.NONE:
if name in self.field_data:
raise ValueError(f'Data named "{name}" is a field array which cannot be active.')
else:
raise KeyError(f'Data named "{name}" does not exist in this dataset.')
self._last_active_scalars_name = self.active_scalars_info.name
if field == FieldAssociation.POINT:
ret = self.GetPointData().SetActiveScalars(name)
elif field == FieldAssociation.CELL:
ret = self.GetCellData().SetActiveScalars(name)
else:
raise ValueError(f'Data field ({name}) with type ({field}) not usable')
if ret < 0:
raise ValueError(
f'Data field "{name}" with type ({field}) could not be set as the active scalars',
)
self._active_scalars_info = ActiveArrayInfo(field, name)
if field == FieldAssociation.POINT:
return field, self.point_data.active_scalars
else: # must be cell
return field, self.cell_data.active_scalars
def set_active_vectors(self, name: Optional[str], preference: str = 'point') -> None:
"""Find the vectors by name and appropriately sets it as active.
To deactivate any active vectors, pass ``None`` as the ``name``.
Parameters
----------
name : str, optional
Name of the vectors array to assign as active.
preference : str, default: "point"
If there are two arrays of the same name associated with
points, cells, or field data, it will prioritize an array
matching this type. Can be either ``'cell'``,
``'field'``, or ``'point'``.
"""
if name is None:
self.GetCellData().SetActiveVectors(None)
self.GetPointData().SetActiveVectors(None)
field = FieldAssociation.POINT
else:
field = get_array_association(self, name, preference=preference)
if field == FieldAssociation.POINT:
ret = self.GetPointData().SetActiveVectors(name)
elif field == FieldAssociation.CELL:
ret = self.GetCellData().SetActiveVectors(name)
else:
raise ValueError(f'Data field ({name}) with type ({field}) not usable')
if ret < 0:
raise ValueError(
f'Data field ({name}) with type ({field}) could not be set as the active vectors',
)
self._active_vectors_info = ActiveArrayInfo(field, name)
def set_active_tensors(self, name: Optional[str], preference: str = 'point') -> None:
"""Find the tensors by name and appropriately sets it as active.
To deactivate any active tensors, pass ``None`` as the ``name``.
Parameters
----------
name : str, optional
Name of the tensors array to assign as active.
preference : str, default: "point"
If there are two arrays of the same name associated with
points, cells, or field data, it will prioritize an array
matching this type. Can be either ``'cell'``,
``'field'``, or ``'point'``.
"""
if name is None:
self.GetCellData().SetActiveTensors(None)
self.GetPointData().SetActiveTensors(None)
field = FieldAssociation.POINT
else:
field = get_array_association(self, name, preference=preference)
if field == FieldAssociation.POINT:
ret = self.GetPointData().SetActiveTensors(name)
elif field == FieldAssociation.CELL:
ret = self.GetCellData().SetActiveTensors(name)
else:
raise ValueError(f'Data field ({name}) with type ({field}) not usable')
if ret < 0:
raise ValueError(
f'Data field ({name}) with type ({field}) could not be set as the active tensors',
)
self._active_tensors_info = ActiveArrayInfo(field, name)
def rename_array(self, old_name: str, new_name: str, preference='cell') -> None:
"""Change array name by searching for the array then renaming it.
Parameters
----------
old_name : str
Name of the array to rename.
new_name : str
Name to rename the array to.
preference : str, default: "cell"
If there are two arrays of the same name associated with
points, cells, or field data, it will prioritize an array
matching this type. Can be either ``'cell'``,
``'field'``, or ``'point'``.
Examples
--------
Create a cube, assign a point array to the mesh named
``'my_array'``, and rename it to ``'my_renamed_array'``.
>>> import pyvista as pv
>>> import numpy as np
>>> cube = pv.Cube()
>>> cube['my_array'] = range(cube.n_points)
>>> cube.rename_array('my_array', 'my_renamed_array')
>>> cube['my_renamed_array']
pyvista_ndarray([0, 1, 2, 3, 4, 5, 6, 7])
"""
field = get_array_association(self, old_name, preference=preference)
was_active = False
if self.active_scalars_name == old_name:
was_active = True
if field == FieldAssociation.POINT:
data = self.point_data
elif field == FieldAssociation.CELL:
data = self.cell_data
elif field == FieldAssociation.NONE:
data = self.field_data
else:
raise KeyError(f'Array with name {old_name} not found.')
arr = data.pop(old_name)
# Update the array's name before reassigning. This prevents taking a copy of the array
# in `DataSetAttributes._prepare_array` which can lead to the array being garbage collected.
# See issue #5244.
arr.VTKObject.SetName(new_name)
data[new_name] = arr
if was_active and field != FieldAssociation.NONE:
self.set_active_scalars(new_name, preference=field)
@property
def active_scalars(self) -> Optional[pyvista_ndarray]: # numpydoc ignore=RT01
"""Return the active scalars as an array.
Returns
-------
Optional[pyvista_ndarray]
Active scalars as an array.
"""
field, name = self.active_scalars_info
if name is not None:
try:
if field == FieldAssociation.POINT:
return self.point_data[name]
if field == FieldAssociation.CELL:
return self.cell_data[name]
except KeyError:
return None
return None
@property
def active_normals(self) -> Optional[pyvista_ndarray]: # numpydoc ignore=RT01
"""Return the active normals as an array.
Returns
-------
pyvista_ndarray
Active normals of this dataset.
Notes
-----
If both point and cell normals exist, this returns point
normals by default.
Examples
--------
Compute normals on an example sphere mesh and return the
active normals for the dataset. Show that this is the same size
as the number of points.
>>> import pyvista as pv
>>> mesh = pv.Sphere()
>>> mesh = mesh.compute_normals()
>>> normals = mesh.active_normals
>>> normals.shape
(842, 3)
>>> mesh.n_points
842
"""
if self.point_data.active_normals is not None:
return self.point_data.active_normals
return self.cell_data.active_normals
def get_data_range(
self,
arr_var: Optional[Union[str, NumpyArray[float]]] = None,
preference='cell',
) -> Tuple[float, float]:
"""Get the min and max of a named array.
Parameters
----------
arr_var : str, np.ndarray, optional
The name of the array to get the range. If ``None``, the
active scalars is used.
preference : str, default: "cell"
When scalars is specified, this is the preferred array type
to search for in the dataset. Must be either ``'point'``,
``'cell'``, or ``'field'``.
Returns
-------
tuple
``(min, max)`` of the named array.
"""
if arr_var is None: # use active scalars array
_, arr_var = self.active_scalars_info
if arr_var is None:
return (np.nan, np.nan)
if isinstance(arr_var, str):
name = arr_var
arr = get_array(self, name, preference=preference, err=True)
else:
arr = arr_var
# If array has no tuples return a NaN range
if arr is None:
return (np.nan, np.nan)
if arr.size == 0 or not np.issubdtype(arr.dtype, np.number):
return (np.nan, np.nan)
# Use the array range
return np.nanmin(arr), np.nanmax(arr)
def rotate_x(
self,
angle: float,
point: VectorLike[float] = (0.0, 0.0, 0.0),
transform_all_input_vectors: bool = False,
inplace: bool = False,
):
"""Rotate mesh about the x-axis.
.. note::
See also the notes at :func:`transform()
<DataSetFilters.transform>` which is used by this filter
under the hood.
Parameters
----------
angle : float
Angle in degrees to rotate about the x-axis.
point : Vector, default: (0.0, 0.0, 0.0)
Point to rotate about. Defaults to origin.
transform_all_input_vectors : bool, default: False
When ``True``, all input vectors are
transformed. Otherwise, only the points, normals and
active vectors are transformed.
inplace : bool, default: False
Updates mesh in-place.
Returns
-------
pyvista.DataSet
Rotated dataset.
Examples
--------
Rotate a mesh 30 degrees about the x-axis.
>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> rot = mesh.rotate_x(30, inplace=False)
Plot the rotated mesh.
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(rot)
>>> _ = pl.add_mesh(mesh, style='wireframe', line_width=3)
>>> _ = pl.add_axes_at_origin()
>>> pl.show()
"""
check_valid_vector(point, "point")
t = transformations.axis_angle_rotation((1, 0, 0), angle, point=point, deg=True)
return self.transform(
t,
transform_all_input_vectors=transform_all_input_vectors,
inplace=inplace,
)
def rotate_y(
self,
angle: float,
point: VectorLike[float] = (0.0, 0.0, 0.0),
transform_all_input_vectors: bool = False,
inplace: bool = False,
):
"""Rotate mesh about the y-axis.
.. note::
See also the notes at :func:`transform()
<DataSetFilters.transform>` which is used by this filter
under the hood.
Parameters
----------
angle : float
Angle in degrees to rotate about the y-axis.
point : Vector, default: (0.0, 0.0, 0.0)
Point to rotate about.
transform_all_input_vectors : bool, default: False
When ``True``, all input vectors are transformed. Otherwise, only
the points, normals and active vectors are transformed.
inplace : bool, default: False
Updates mesh in-place.
Returns
-------
pyvista.DataSet
Rotated dataset.
Examples
--------
Rotate a cube 30 degrees about the y-axis.
>>> import pyvista as pv
>>> mesh = pv.Cube()
>>> rot = mesh.rotate_y(30, inplace=False)
Plot the rotated mesh.