/
pointset.py
2870 lines (2357 loc) · 98 KB
/
pointset.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
"""Sub-classes and wrappers for vtk.vtkPointSet."""
from collections.abc import Iterable
from functools import wraps
import logging
import numbers
import os
import pathlib
from textwrap import dedent
from typing import Sequence, Tuple, Union
import warnings
import numpy as np
import pyvista
from pyvista import _vtk
from pyvista.utilities import PyvistaDeprecationWarning, abstract_class
from pyvista.utilities.cells import (
CellArray,
create_mixed_cells,
generate_cell_offsets,
get_mixed_cells,
numpy_to_idarr,
)
from ..utilities.fileio import get_ext
from .dataset import DataSet
from .errors import DeprecationError, VTKVersionError
from .filters import PolyDataFilters, StructuredGridFilters, UnstructuredGridFilters, _get_output
log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
DEFAULT_INPLACE_WARNING = (
'You did not specify a value for `inplace` and the default value will '
'be changing to `False` in future versions for point-based meshes (e.g., '
'`PolyData`). Please make sure you are not assuming this to be an inplace '
'operation.'
)
class _PointSet(DataSet):
"""PyVista's equivalent of vtk.vtkPointSet.
This holds methods common to PolyData and UnstructuredGrid.
"""
_WRITERS = {".xyz": _vtk.vtkSimplePointsWriter}
def center_of_mass(self, scalars_weight=False):
"""Return the coordinates for the center of mass of the mesh.
Parameters
----------
scalars_weight : bool, optional
Flag for using the mesh scalars as weights. Defaults to ``False``.
Returns
-------
numpy.ndarray
Coordinates for the center of mass.
Examples
--------
>>> import pyvista
>>> mesh = pyvista.Sphere(center=(1, 1, 1))
>>> mesh.center_of_mass()
array([1., 1., 1.])
"""
alg = _vtk.vtkCenterOfMass()
alg.SetInputDataObject(self)
alg.SetUseScalarsAsWeights(scalars_weight)
alg.Update()
return np.array(alg.GetCenter())
def shallow_copy(self, to_copy):
"""Create a shallow copy from a different dataset into this one.
This method mutates this dataset and returns ``None``.
Parameters
----------
to_copy : pyvista.DataSet
Data object to perform the shallow copy from.
"""
# Set default points if needed
if not to_copy.GetPoints():
to_copy.SetPoints(_vtk.vtkPoints())
DataSet.shallow_copy(self, to_copy)
def remove_cells(self, ind, inplace=False):
"""Remove cells.
Parameters
----------
ind : sequence
Cell indices to be removed. The array can also be a
boolean array of the same size as the number of cells.
inplace : bool, optional
Whether to update the mesh in-place.
Returns
-------
pyvista.DataSet
Same type as the input, but with the specified cells
removed.
Examples
--------
Remove 20 cells from an unstructured grid.
>>> from pyvista import examples
>>> import pyvista
>>> hex_mesh = pyvista.read(examples.hexbeamfile)
>>> removed = hex_mesh.remove_cells(range(10, 20))
>>> removed.plot(color='tan', show_edges=True, line_width=3)
"""
if isinstance(ind, np.ndarray):
if ind.dtype == np.bool_ and ind.size != self.n_cells:
raise ValueError(
f'Boolean array size must match the number of cells ({self.n_cells})'
)
ghost_cells = np.zeros(self.n_cells, np.uint8)
ghost_cells[ind] = _vtk.vtkDataSetAttributes.DUPLICATECELL
if inplace:
target = self
else:
target = self.copy()
target.cell_data[_vtk.vtkDataSetAttributes.GhostArrayName()] = ghost_cells
target.RemoveGhostCells()
return target
def points_to_double(self):
"""Convert the points datatype to double precision.
Returns
-------
pyvista.PointSet
Pointset with points in double precision.
Notes
-----
This operates in place.
Examples
--------
Create a mesh that has points of the type ``float32`` and
convert the points to ``float64``.
>>> import pyvista
>>> mesh = pyvista.Sphere()
>>> mesh.points.dtype
dtype('float32')
>>> _ = mesh.points_to_double()
>>> mesh.points.dtype
dtype('float64')
"""
if self.points.dtype != np.double:
self.points = self.points.astype(np.double)
return self
# todo: `transform_all_input_vectors` is not handled when modifying inplace
def translate(
self, xyz: Union[list, tuple, np.ndarray], transform_all_input_vectors=False, inplace=None
):
"""Translate the mesh.
Parameters
----------
xyz : list or tuple or numpy.ndarray
Cartesian values to displace with. Length 3 list, tuple or array.
transform_all_input_vectors : bool, optional
When ``True``, all input vectors are transformed. Otherwise, only
the points, normals and active vectors are transformed. This is
only valid when not updating in place.
inplace : bool, optional
Updates mesh in-place.
Returns
-------
pyvista.PointSet
Translated pointset.
Examples
--------
Create a sphere and translate it by ``(2, 1, 2)``.
>>> import pyvista
>>> mesh = pyvista.Sphere()
>>> mesh.center
[0.0, 0.0, 0.0]
>>> trans = mesh.translate((2, 1, 2), inplace=True)
>>> trans.center
[2.0, 1.0, 2.0]
"""
if inplace is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
inplace = True
if inplace:
self.points += np.asarray(xyz) # type: ignore
return self
return super().translate(
xyz, transform_all_input_vectors=transform_all_input_vectors, inplace=inplace
)
def scale(
self, xyz: Union[list, tuple, np.ndarray], transform_all_input_vectors=False, inplace=None
):
"""Scale the mesh.
Parameters
----------
xyz : list or tuple or numpy.ndarray
Scale factor in x, y, and z directions. Length 3 list, tuple or
array.
transform_all_input_vectors : bool, optional
When ``True``, all input vectors are transformed. Otherwise, only
the points, normals and active vectors are transformed. This is
only valid when not updating in place.
inplace : bool, optional
Updates mesh in-place.
Returns
-------
pyvista.PointSet
Scaled pointset.
Notes
-----
``transform_all_input_vectors`` is not handled when modifying inplace.
Examples
--------
>>> import pyvista
>>> from pyvista import examples
>>> pl = pyvista.Plotter(shape=(1, 2))
>>> pl.subplot(0, 0)
>>> pl.show_axes()
>>> _ = pl.show_grid()
>>> mesh1 = examples.download_teapot()
>>> _ = pl.add_mesh(mesh1)
>>> pl.subplot(0, 1)
>>> pl.show_axes()
>>> _ = pl.show_grid()
>>> mesh2 = mesh1.scale([10.0, 10.0, 10.0], inplace=False)
>>> _ = pl.add_mesh(mesh2)
>>> pl.show(cpos="xy")
"""
if inplace is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
inplace = True
return super().scale(
xyz, transform_all_input_vectors=transform_all_input_vectors, inplace=inplace
)
@wraps(DataSet.flip_x)
def flip_x(self, *args, **kwargs):
"""Wrap ``DataSet.flip_x``."""
if kwargs.get('inplace') is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
kwargs['inplace'] = True
return super().flip_x(*args, **kwargs)
@wraps(DataSet.flip_y)
def flip_y(self, *args, **kwargs):
"""Wrap ``DataSet.flip_y``."""
if kwargs.get('inplace') is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
kwargs['inplace'] = True
return super().flip_y(*args, **kwargs)
@wraps(DataSet.flip_z)
def flip_z(self, *args, **kwargs):
"""Wrap ``DataSet.flip_z``."""
if kwargs.get('inplace') is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
kwargs['inplace'] = True
return super().flip_z(*args, **kwargs)
@wraps(DataSet.flip_normal)
def flip_normal(self, *args, **kwargs):
"""Wrap ``DataSet.flip_normal``."""
if kwargs.get('inplace') is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
kwargs['inplace'] = True
return super().flip_normal(*args, **kwargs)
@wraps(DataSet.rotate_x)
def rotate_x(self, *args, **kwargs):
"""Wrap ``DataSet.rotate_x``."""
if kwargs.get('inplace') is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
kwargs['inplace'] = True
return super().rotate_x(*args, **kwargs)
@wraps(DataSet.rotate_y)
def rotate_y(self, *args, **kwargs):
"""Wrap ``DataSet.rotate_y``."""
if kwargs.get('inplace') is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
kwargs['inplace'] = True
return super().rotate_y(*args, **kwargs)
@wraps(DataSet.rotate_z)
def rotate_z(self, *args, **kwargs):
"""Wrap ``DataSet.rotate_z``."""
if kwargs.get('inplace') is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
kwargs['inplace'] = True
return super().rotate_z(*args, **kwargs)
@wraps(DataSet.rotate_vector)
def rotate_vector(self, *args, **kwargs):
"""Wrap ``DataSet.rotate_vector``."""
if kwargs.get('inplace') is None:
# Deprecated on v0.32.0, estimated removal on v0.35.0
warnings.warn(DEFAULT_INPLACE_WARNING, PyvistaDeprecationWarning)
kwargs['inplace'] = True
return super().rotate_vector(*args, **kwargs)
class PointSet(_vtk.vtkPointSet, _PointSet):
"""Concrete class for storing a set of points.
This is a concrete class representing a set of points that specifies the
interface for datasets that explicitly use "point" arrays to represent
geometry. This class is useful for improving the performance of filters on
point clouds, but not plotting.
For further details see `VTK: vtkPointSet Details
<https://vtk.org/doc/nightly/html/classvtkPointSet.html#details>`_.
Parameters
----------
points : Sequence, optional
List, numpy array, or sequence containing point locations. Must be an
``(N, 3)`` array of points.
deep : bool, optional
Whether to copy the input ``points``, or to create a PointSet from them
without copying them. Setting ``deep=True`` ensures that the original
arrays can be modified outside the mesh without affecting the
mesh. Default is ``False``.
force_float : bool, optional
Casts the datatype to ``float32`` if points datatype is non-float.
Default ``True``. Set this to ``False`` to allow non-float types,
though this may lead to truncation of intermediate floats when
transforming datasets.
Notes
-----
This class requires ``vtk>=9.1.0``. This is an abstract class in
``vtk<9.1.0`` and cannot be instantiated.
Examples
--------
Create a simple point cloud of 10 points from a numpy array.
>>> import numpy as np
>>> import pyvista
>>> rng = np.random.default_rng()
>>> points = rng.random((10, 3))
>>> pset = pyvista.PointSet(points)
Plot the pointset. Note: this casts to a :class:`pyvista.PolyData`
internally when plotting.
>>> pset.plot(point_size=10)
"""
def __new__(cls, *args, **kwargs):
"""Construct a new PointSet object.
Wrapping this is necessary for us to show an informative error
message when the VTK version is too old, causing PointSet to be
an abstract class. Since we inherit the ``__new__()`` method of
``vtk.vtkPointSet``, we would otherwise see a generic error about
the class being abstract.
"""
if pyvista.vtk_version_info < (9, 1, 0):
raise VTKVersionError("pyvista.PointSet requires VTK >= 9.1.0")
return super().__new__(cls, *args, **kwargs)
def __init__(self, points=None, deep=False, force_float=True):
"""Initialize the pointset."""
super().__init__()
if points is not None:
self.SetPoints(pyvista.vtk_points(points, deep=deep, force_float=force_float))
def __repr__(self):
"""Return the standard representation."""
return DataSet.__repr__(self)
def __str__(self):
"""Return the standard str representation."""
return DataSet.__str__(self)
def cast_to_polydata(self, deep=True):
"""Cast this dataset to polydata.
Parameters
----------
deep : bool, optional
Whether to copy the pointset points, or to create a PolyData
without copying them. Setting ``deep=True`` ensures that the
original arrays can be modified outside the PolyData without
affecting the PolyData. Default is ``True``.
Returns
-------
pyvista.PolyData
PointSet cast to a ``pyvista.PolyData``.
"""
pdata = PolyData(self.points, deep=deep)
if deep:
pdata.point_data.update(self.point_data) # update performs deep copy
else:
for key, value in self.point_data.items():
pdata.point_data[key] = value
return pdata
@wraps(DataSet.plot) # type: ignore
def plot(self, *args, **kwargs):
"""Cast to PolyData and plot."""
pdata = self.cast_to_polydata(deep=False)
kwargs.setdefault('style', 'points')
return pdata.plot(*args, **kwargs)
class PolyData(_vtk.vtkPolyData, _PointSet, PolyDataFilters):
"""Dataset consisting of surface geometry (e.g. vertices, lines, and polygons).
Can be initialized in several ways:
- Create an empty mesh
- Initialize from a vtk.vtkPolyData
- Using vertices
- Using vertices and faces
- From a file
Parameters
----------
var_inp : vtk.vtkPolyData, str, sequence, optional
Flexible input type. Can be a ``vtk.vtkPolyData``, in which case
this PolyData object will be copied if ``deep=True`` and will
be a shallow copy if ``deep=False``.
Also accepts a path, which may be local path as in
``'my_mesh.stl'`` or global path like ``'/tmp/my_mesh.ply'``
or ``'C:/Users/user/my_mesh.ply'``.
Otherwise, this must be a points array or list containing one
or more points. Each point must have 3 dimensions.
faces : sequence, optional
Face connectivity array. Faces must contain padding
indicating the number of points in the face. For example, the
two faces ``[10, 11, 12]`` and ``[20, 21, 22, 23]`` will be
represented as ``[3, 10, 11, 12, 4, 20, 21, 22, 23]``. This
lets you have an arbitrary number of points per face.
When not including the face connectivity array, each point
will be assigned to a single vertex. This is used for point
clouds that have no connectivity.
n_faces : int, optional
Number of faces in the ``faces`` connectivity array. While
optional, setting this speeds up the creation of the
``PolyData``.
lines : sequence, optional
The line connectivity array. Like ``faces``, this array
requires padding indicating the number of points in a line
segment. For example, the two line segments ``[0, 1]`` and
``[1, 2, 3, 4]`` will be represented as
``[2, 0, 1, 4, 1, 2, 3, 4]``.
n_lines : int, optional
Number of lines in the ``lines`` connectivity array. While
optional, setting this speeds up the creation of the
``PolyData``.
deep : bool, optional
Whether to copy the inputs, or to create a mesh from them
without copying them. Setting ``deep=True`` ensures that the
original arrays can be modified outside the mesh without
affecting the mesh. Default is ``False``.
force_ext : str, optional
If initializing from a file, force the reader to treat the
file as if it had this extension as opposed to the one in the
file.
force_float : bool, optional
Casts the datatype to ``float32`` if points datatype is
non-float. Default ``True``. Set this to ``False`` to allow
non-float types, though this may lead to truncation of
intermediate floats when transforming datasets.
Examples
--------
>>> import vtk
>>> import numpy as np
>>> from pyvista import examples
>>> import pyvista
Create an empty mesh.
>>> mesh = pyvista.PolyData()
Initialize from a ``vtk.vtkPolyData`` object.
>>> vtkobj = vtk.vtkPolyData()
>>> mesh = pyvista.PolyData(vtkobj)
Initialize from just vertices.
>>> vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 0.5, 0], [0, 0.5, 0]])
>>> mesh = pyvista.PolyData(vertices)
Initialize from vertices and faces.
>>> faces = np.hstack([[3, 0, 1, 2], [3, 0, 3, 2]])
>>> mesh = pyvista.PolyData(vertices, faces)
Initialize from vertices and lines.
>>> lines = np.hstack([[2, 0, 1], [2, 1, 2]])
>>> mesh = pyvista.PolyData(vertices, lines=lines)
Initialize from a filename.
>>> mesh = pyvista.PolyData(examples.antfile)
See :ref:`ref_create_poly` for more examples.
"""
_WRITERS = {
'.ply': _vtk.vtkPLYWriter,
'.vtp': _vtk.vtkXMLPolyDataWriter,
'.stl': _vtk.vtkSTLWriter,
'.vtk': _vtk.vtkPolyDataWriter,
}
def __init__(
self,
var_inp=None,
faces=None,
n_faces=None,
lines=None,
n_lines=None,
deep=False,
force_ext=None,
force_float=True,
) -> None:
"""Initialize the polydata."""
local_parms = locals()
super().__init__()
# allow empty input
if var_inp is None:
return
# filename
opt_kwarg = ['faces', 'n_faces', 'lines', 'n_lines']
if isinstance(var_inp, (str, pathlib.Path)):
for kwarg in opt_kwarg:
if local_parms[kwarg]:
raise ValueError(
'No other arguments should be set when first parameter is a string'
)
self._from_file(var_inp, force_ext=force_ext) # is filename
return
# PolyData-like
if isinstance(var_inp, _vtk.vtkPolyData):
for kwarg in opt_kwarg:
if local_parms[kwarg]:
raise ValueError(
'No other arguments should be set when first parameter is a PolyData'
)
if deep:
self.deep_copy(var_inp)
else:
self.shallow_copy(var_inp)
return
# First parameter is points
if isinstance(var_inp, (np.ndarray, list, _vtk.vtkDataArray)):
self.SetPoints(pyvista.vtk_points(var_inp, deep=deep, force_float=force_float))
else:
msg = f"""
Invalid Input type:
Expected first argument to be either a:
- vtk.PolyData
- pyvista.PolyData
- numeric numpy.ndarray (1 or 2 dimensions)
- List (flat or nested with 3 points per vertex)
- vtk.vtkDataArray
Instead got: {type(var_inp)}"""
raise TypeError(dedent(msg.strip('\n')))
# At this point, points have been setup, add faces and/or lines
if faces is None and lines is None:
# one cell per point (point cloud case)
verts = self._make_vertex_cells(self.n_points)
self.verts = CellArray(verts, self.n_points, deep)
elif faces is not None:
# here we use CellArray since we must specify deep and n_faces
self.faces = CellArray(faces, n_faces, deep)
# can always set lines
if lines is not None:
# here we use CellArray since we must specify deep and n_lines
self.lines = CellArray(lines, n_lines, deep)
def _post_file_load_processing(self):
"""Execute after loading a PolyData from file."""
# When loading files with just point arrays, create and
# set the polydata vertices
if self.n_points > 0 and self.n_cells == 0:
verts = self._make_vertex_cells(self.n_points)
self.verts = CellArray(verts, self.n_points, deep=False)
def __repr__(self):
"""Return the standard representation."""
return DataSet.__repr__(self)
def __str__(self):
"""Return the standard str representation."""
return DataSet.__str__(self)
@staticmethod
def _make_vertex_cells(npoints):
cells = np.empty((npoints, 2), dtype=pyvista.ID_TYPE)
cells[:, 0] = 1
cells[:, 1] = np.arange(npoints, dtype=pyvista.ID_TYPE)
return cells
@property
def verts(self) -> np.ndarray:
"""Get the vertex cells.
Returns
-------
numpy.ndarray
Array of vertex cell indices.
Examples
--------
Create a point cloud polydata and return the vertex cells.
>>> import pyvista
>>> import numpy as np
>>> points = np.random.random((5, 3))
>>> pdata = pyvista.PolyData(points)
>>> pdata.verts
array([1, 0, 1, 1, 1, 2, 1, 3, 1, 4])
Set vertex cells. Note how the mesh plots both the surface
mesh and the additional vertices in a single plot.
>>> mesh = pyvista.Plane(i_resolution=3, j_resolution=3)
>>> mesh.verts = np.vstack((np.ones(mesh.n_points, dtype=np.int64),
... np.arange(mesh.n_points))).T
>>> mesh.plot(color='tan', render_points_as_spheres=True, point_size=60)
"""
return _vtk.vtk_to_numpy(self.GetVerts().GetData())
@verts.setter
def verts(self, verts):
"""Set the vertex cells."""
if isinstance(verts, CellArray):
self.SetVerts(verts)
else:
self.SetVerts(CellArray(verts))
@property
def lines(self) -> np.ndarray:
"""Return a pointer to the lines as a numpy array.
Examples
--------
Return the lines from a spline.
>>> import pyvista
>>> import numpy as np
>>> points = np.random.random((3, 3))
>>> spline = pyvista.Spline(points, 10)
>>> spline.lines
array([10, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
"""
return _vtk.vtk_to_numpy(self.GetLines().GetData()).ravel()
@lines.setter
def lines(self, lines):
"""Set the lines of the polydata."""
if isinstance(lines, CellArray):
self.SetLines(lines)
else:
self.SetLines(CellArray(lines))
@property
def faces(self) -> np.ndarray:
"""Return a pointer to the faces as a numpy array.
Returns
-------
numpy.ndarray
Array of face indices.
Examples
--------
>>> import pyvista as pv
>>> plane = pv.Plane(i_resolution=2, j_resolution=2)
>>> plane.faces
array([4, 0, 1, 4, 3, 4, 1, 2, 5, 4, 4, 3, 4, 7, 6, 4, 4, 5, 8, 7])
Note how the faces contain a "padding" indicating the number
of points per face:
>>> plane.faces.reshape(-1, 5)
array([[4, 0, 1, 4, 3],
[4, 1, 2, 5, 4],
[4, 3, 4, 7, 6],
[4, 4, 5, 8, 7]])
"""
return _vtk.vtk_to_numpy(self.GetPolys().GetData())
@faces.setter
def faces(self, faces):
"""Set the face cells."""
if isinstance(faces, CellArray):
self.SetPolys(faces)
else:
# TODO: faster to mutate in-place if array is same size?
self.SetPolys(CellArray(faces))
@property
def is_all_triangles(self):
"""Return if all the faces of the :class:`pyvista.PolyData` are triangles.
.. versionchanged:: 0.32.0
``is_all_triangles`` is now a property. Calling this value
will warn the user that this should not be called.
Additionally, the ``is`` operator will not work the return
value of this property since it is not a ``bool``
Returns
-------
CallableBool
``True`` if all the faces of the :class:`pyvista.PolyData`
are triangles and does not contain any vertices or lines.
Notes
-----
The return value is not a ``bool`` for compatibility
reasons, though this behavior will change in a future
release. Future versions will simply return a ``bool``.
Examples
--------
Show a mesh from :func:`pyvista.Plane` is not composed of all
triangles.
>>> import pyvista
>>> plane = pyvista.Plane()
>>> plane.is_all_triangles
False <CallableBool>
Show that the mesh from :func:`pyvista.Sphere` contains only
triangles.
>>> sphere = pyvista.Sphere()
>>> sphere.is_all_triangles
True <CallableBool>
"""
class CallableBool(int): # pragma: no cover
"""Boolean that can be called.
Programmer note: We must subclass int and not bool
https://stackoverflow.com/questions/2172189/why-i-cant-extend-bool-in-python
Implemented for backwards compatibility as
``is_all_triangles`` was changed to be a property in
``0.32.0``.
"""
def __new__(cls, value):
"""Use new instead of __init__.
See:
https://jfine-python-classes.readthedocs.io/en/latest/subclass-int.html#emulating-bool-using-new
"""
return int.__new__(cls, bool(value))
def __call__(self):
"""Return a ``bool`` of self."""
warnings.warn(
'``is_all_triangles`` is now property as of 0.32.0 and does not need ()',
DeprecationWarning,
)
return bool(self)
def __repr__(self):
"""Return the string of bool."""
return f'{bool(self)} <CallableBool>'
# Need to make sure there are only face cells and no lines/verts
if not self.n_faces or self.n_lines or self.n_verts:
return CallableBool(False)
# in VTK9, they use connectivity and offset rather than cell
# data. Use the new API as this is faster
if _vtk.VTK9:
# early return if not all triangular
if self._connectivity_array.size % 3:
return CallableBool(False)
# next, check if there are three points per face
return CallableBool((np.diff(self._offset_array) == 3).all())
else: # pragma: no cover
# All we have are faces, check if all faces are indeed triangles
faces = self.faces # grab once as this takes time to build
if faces.size % 4 == 0:
return CallableBool((faces[::4] == 3).all())
return CallableBool(False)
def __sub__(self, cutting_mesh):
"""Compute boolean difference of two meshes."""
return self.boolean_difference(cutting_mesh)
@property
def _offset_array(self):
"""Return the array used to store cell offsets."""
try:
return _vtk.vtk_to_numpy(self.GetPolys().GetOffsetsArray())
except AttributeError: # pragma: no cover
raise VTKVersionError('Offset array implemented in VTK 9 or newer.')
@property
def _connectivity_array(self):
"""Return the array with the point ids that define the cells connectivity."""
try:
return _vtk.vtk_to_numpy(self.GetPolys().GetConnectivityArray())
except AttributeError: # pragma: no cover
raise VTKVersionError('Connectivity array implemented in VTK 9 or newer.')
@property
def n_lines(self) -> int:
"""Return the number of lines.
Examples
--------
>>> import pyvista
>>> mesh = pyvista.Line()
>>> mesh.n_lines
1
"""
return self.GetNumberOfLines()
@property
def n_verts(self) -> int:
"""Return the number of vertices.
Examples
--------
Create a simple mesh containing just two points and return the
number of vertices.
>>> import pyvista
>>> mesh = pyvista.PolyData([[1.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
>>> mesh.n_verts
2
"""
return self.GetNumberOfVerts()
@property
def n_faces(self) -> int:
"""Return the number of cells.
Alias for ``n_cells``.
Examples
--------
>>> import pyvista
>>> plane = pyvista.Plane(i_resolution=2, j_resolution=2)
>>> plane.n_faces
4
"""
return self.n_cells
@property
def number_of_faces(self): # pragma: no cover
"""Return the number of cells."""
raise DeprecationError('``number_of_faces`` has been deprecated. Please use ``n_faces``')
def save(self, filename, binary=True, texture=None):
"""Write a surface mesh to disk.
Written file may be an ASCII or binary ply, stl, or vtk mesh
file. If ply or stl format is chosen, the face normals are
computed in place to ensure the mesh is properly saved.
Parameters
----------
filename : str
Filename of mesh to be written. File type is inferred from
the extension of the filename unless overridden with
ftype. Can be one of many of the supported the following
types (``'.ply'``, ``'.stl'``, ``'.vtk``).
binary : bool, optional
Writes the file as binary when ``True`` and ASCII when ``False``.
texture : str, numpy.ndarray, optional
Write a single texture array to file when using a PLY
file. Texture array must be a 3 or 4 component array with
the datatype ``np.uint8``. Array may be a cell array or a
point array, and may also be a string if the array already
exists in the PolyData.
If a string is provided, the texture array will be saved
to disk as that name. If an array is provided, the
texture array will be saved as ``'RGBA'`` if the array
contains an alpha channel (i.e. 4 component array), or
as ``'RGB'`` if the array is just a 3 component array.
.. note::
This feature is only available when saving PLY files.
Notes
-----
Binary files write much faster than ASCII and have a smaller
file size.
Examples
--------
Save a mesh as a STL.
>>> import pyvista
>>> sphere = pyvista.Sphere()
>>> sphere.save('my_mesh.stl') # doctest:+SKIP
Save a mesh as a PLY.
>>> sphere = pyvista.Sphere()
>>> sphere.save('my_mesh.ply') # doctest:+SKIP
Save a mesh as a PLY with a texture array. Here we also
create a simple RGB array representing the texture.
>>> import numpy as np
>>> sphere = pyvista.Sphere()
>>> texture = np.zeros((sphere.n_points, 3), np.uint8)
>>> texture[:, 1] = np.arange(sphere.n_points)[::-1] # just blue channel
>>> sphere.point_data['my_texture'] = texture
>>> sphere.save('my_mesh.ply', texture='my_texture') # doctest:+SKIP
Alternatively, provide just the texture array. This will be
written to the file as ``'RGB'`` since it does not contain an
alpha channel.