forked from pyvista/pyvista
/
pointset.py
2496 lines (1998 loc) · 78.6 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 for vtk.vtkPolyData
"""
import logging
import os
import numpy as np
import vtk
from vtk import (VTK_HEXAHEDRON, VTK_PYRAMID, VTK_QUAD,
VTK_QUADRATIC_HEXAHEDRON, VTK_QUADRATIC_PYRAMID,
VTK_QUADRATIC_QUAD, VTK_QUADRATIC_TETRA,
VTK_QUADRATIC_TRIANGLE, VTK_QUADRATIC_WEDGE, VTK_TETRA,
VTK_TRIANGLE, VTK_WEDGE, vtkPolyData, vtkStructuredGrid,
vtkUnstructuredGrid)
from vtk.util.numpy_support import (numpy_to_vtk, numpy_to_vtkIdTypeArray,
vtk_to_numpy)
import pyvista
from pyvista.filters import _get_output
from pyvista.utilities import get_scalar
log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
class PointSet(pyvista.Common):
"""PyVista's equivalant of vtk.vtkPointSet. This holds methods common to
PolyData and UnstructuredGrid.
"""
def center_of_mass(self, scalars_weight=False):
"""
Returns 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.
Return
------
center : np.ndarray, float
Coordinates for the center of mass.
"""
alg = vtk.vtkCenterOfMass()
alg.SetInputDataObject(self)
alg.SetUseScalarsAsWeights(scalars_weight)
alg.Update()
return np.array(alg.GetCenter())
class PolyData(vtkPolyData, PointSet):
"""
Extends the functionality of a vtk.vtkPolyData object
Can be initialized in several ways:
- Create an empty mesh
- Initialize from a vtk.vtkPolyData
- Using vertices
- Using vertices and faces
- From a file
Examples
--------
>>> import pyvista
>>> from pyvista import examples
>>> import vtk
>>> import numpy as np
>>> surf = pyvista.PolyData() # Create an empty mesh
>>> # Initialize from a vtk.vtkPolyData object
>>> vtkobj = vtk.vtkPolyData()
>>> surf = pyvista.PolyData(vtkobj)
>>> # initialize from just vertices
>>> vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 0.5, 0], [0, 0.5, 0],])
>>> surf = pyvista.PolyData(vertices)
>>> # initialize from vertices and faces
>>> faces = np.hstack([[3, 0, 1, 2], [3, 0, 3, 2]]).astype(np.int8)
>>> surf = pyvista.PolyData(vertices, faces)
>>> # initialize from a filename
>>> surf = pyvista.PolyData(examples.antfile)
"""
def __init__(self, *args, **kwargs):
super(PolyData, self).__init__()
deep = kwargs.pop('deep', False)
if not args:
return
elif len(args) == 1:
if isinstance(args[0], vtk.vtkPolyData):
if deep:
self.DeepCopy(args[0])
else:
self.ShallowCopy(args[0])
elif isinstance(args[0], str):
self._load_file(args[0])
elif isinstance(args[0], np.ndarray):
points = args[0]
if points.ndim != 2:
points = points.reshape((-1, 3))
cells = self._make_vertice_cells(points.shape[0])
self._from_arrays(points, cells, deep, verts=True)
else:
raise TypeError('Invalid input type')
elif len(args) == 2:
arg0_is_array = isinstance(args[0], np.ndarray)
arg1_is_array = isinstance(args[1], np.ndarray)
if arg0_is_array and arg1_is_array:
self._from_arrays(args[0], args[1], deep)
else:
raise TypeError('Invalid input type')
else:
raise TypeError('Invalid input type')
# Check if need to make vertex cells
if self.n_points > 0 and self.n_cells == 0:
# make vertex cells
self.faces = self._make_vertice_cells(self.n_points)
def __repr__(self):
return pyvista.Common.__repr__(self)
def __str__(self):
return pyvista.Common.__str__(self)
@staticmethod
def _make_vertice_cells(npoints):
cells = np.hstack((np.ones((npoints, 1)),
np.arange(npoints).reshape(-1, 1)))
cells = np.ascontiguousarray(cells, dtype=pyvista.ID_TYPE)
cells = np.reshape(cells, (2*npoints))
return cells
def _load_file(self, filename):
"""Load a surface mesh from a mesh file.
Mesh file may be an ASCII or binary ply, stl, or vtk mesh file.
Parameters
----------
filename : str
Filename of mesh to be loaded. File type is inferred from the
extension of the filename
Notes
-----
Binary files load much faster than ASCII.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# test if file exists
if not os.path.isfile(filename):
raise Exception('File %s does not exist' % filename)
# Get extension
ext = pyvista.get_ext(filename)
# Select reader
if ext == '.ply':
reader = vtk.vtkPLYReader()
elif ext == '.stl':
reader = vtk.vtkSTLReader()
elif ext == '.vtk':
reader = vtk.vtkPolyDataReader()
elif ext == '.vtp':
reader = vtk.vtkXMLPolyDataReader()
elif ext == '.obj':
reader = vtk.vtkOBJReader()
else:
raise TypeError('Filetype must be either "ply", "stl", "vtk", "vtp", or "obj".')
# Load file
reader.SetFileName(filename)
reader.Update()
self.ShallowCopy(reader.GetOutput())
# sanity check
if not np.any(self.points):
raise AssertionError('Empty or invalid file')
@property
def lines(self):
return vtk_to_numpy(self.GetLines().GetData())
@lines.setter
def lines(self, lines):
if lines.dtype != pyvista.ID_TYPE:
lines = lines.astype(pyvista.ID_TYPE)
# get number of faces
if lines.ndim == 1:
div = lines.size / 3.0
assert not div % 1, 'Invalid lines array'
nlines = int(div)
else:
nlines = lines.shape[0]
vtkcells = vtk.vtkCellArray()
vtkcells.SetCells(nlines, numpy_to_vtkIdTypeArray(lines, deep=False))
self.SetLines(vtkcells)
@property
def faces(self):
""" returns a pointer to the points as a numpy object """
return vtk_to_numpy(self.GetPolys().GetData())
@faces.setter
def faces(self, faces):
""" set faces without copying """
if faces.dtype != pyvista.ID_TYPE:
faces = faces.astype(pyvista.ID_TYPE)
# get number of faces
if faces.ndim == 1:
log.debug('efficiency warning')
c = 0
nfaces = 0
while c < faces.size:
c += faces[c] + 1
nfaces += 1
else:
nfaces = faces.shape[0]
vtkcells = vtk.vtkCellArray()
vtkcells.SetCells(nfaces, numpy_to_vtkIdTypeArray(faces, deep=False))
if faces.ndim > 1 and faces.shape[1] == 2:
self.SetVerts(vtkcells)
else:
self.SetPolys(vtkcells)
self._face_ref = faces
self.Modified()
# @property
# def lines(self):
# """ returns a copy of the indices of the lines """
# lines = vtk_to_numpy(self.GetLines().GetData()).reshape((-1, 3))
# return np.ascontiguousarray(lines[:, 1:])
def _from_arrays(self, vertices, faces, deep=True, verts=False):
"""
Set polygons and points from numpy arrays
Parameters
----------
vertices : np.ndarray of dtype=np.float32 or np.float64
Vertex array. 3D points.
faces : np.ndarray of dtype=np.int64
Face index array. Faces can contain any number of points.
Examples
--------
>>> import numpy as np
>>> import pyvista
>>> vertices = np.array([[0, 0, 0],
... [1, 0, 0],
... [1, 1, 0],
... [0, 1, 0],
... [0.5, 0.5, 1]])
>>> faces = np.hstack([[4, 0, 1, 2, 3],
... [3, 0, 1, 4],
... [3, 1, 2, 4]]) # one square and two triangles
>>> surf = pyvista.PolyData(vertices, faces)
"""
if deep or verts:
vtkpoints = vtk.vtkPoints()
vtkpoints.SetData(numpy_to_vtk(vertices, deep=deep))
self.SetPoints(vtkpoints)
# Convert to a vtk array
vtkcells = vtk.vtkCellArray()
if faces.dtype != pyvista.ID_TYPE:
faces = faces.astype(pyvista.ID_TYPE)
# get number of faces
if faces.ndim == 1:
c = 0
nfaces = 0
while c < faces.size:
c += faces[c] + 1
nfaces += 1
else:
nfaces = faces.shape[0]
idarr = numpy_to_vtkIdTypeArray(faces.ravel(), deep=deep)
vtkcells.SetCells(nfaces, idarr)
if (faces.ndim > 1 and faces.shape[1] == 2) or verts:
self.SetVerts(vtkcells)
else:
self.SetPolys(vtkcells)
else:
self.points = vertices
self.faces = faces
def edge_mask(self, angle):
"""
Returns a mask of the points of a surface mesh that have a surface
angle greater than angle
Parameters
----------
angle : float
Angle to consider an edge.
"""
self.point_arrays['point_ind'] = np.arange(self.n_points)
featureEdges = vtk.vtkFeatureEdges()
featureEdges.SetInputData(self)
featureEdges.FeatureEdgesOn()
featureEdges.BoundaryEdgesOff()
featureEdges.NonManifoldEdgesOff()
featureEdges.ManifoldEdgesOff()
featureEdges.SetFeatureAngle(angle)
featureEdges.Update()
edges = _get_output(featureEdges)
orig_id = pyvista.point_scalar(edges, 'point_ind')
return np.in1d(self.point_arrays['point_ind'], orig_id,
assume_unique=True)
def __sub__(self, cutting_mesh):
""" subtract two meshes """
return self.boolean_cut(cutting_mesh)
@property
def n_faces(self):
"""alias for ``n_cells``"""
return self.n_cells
@property
def number_of_faces(self):
""" returns the number of cells """
return self.n_cells
def boolean_cut(self, cut, tolerance=1E-5, inplace=False):
"""
Performs a Boolean cut using another mesh.
Parameters
----------
cut : pyvista.PolyData
Mesh making the cut
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : pyvista.PolyData
The cut mesh when inplace=False
"""
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToIntersection()
# bfilter.SetOperationToDifference()
bfilter.SetInputData(1, cut)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.SetTolerance(tolerance)
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh
def __add__(self, mesh):
""" adds two meshes together """
return self.boolean_add(mesh)
def boolean_add(self, mesh, inplace=False):
"""
Add a mesh to the current mesh. Does not attempt to "join"
the meshes.
Parameters
----------
mesh : pyvista.PolyData
The mesh to add.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
joinedmesh : pyvista.PolyData
Initial mesh and the new mesh when inplace=False.
"""
vtkappend = vtk.vtkAppendPolyData()
vtkappend.AddInputData(self)
vtkappend.AddInputData(mesh)
vtkappend.Update()
mesh = _get_output(vtkappend)
if inplace:
self.overwrite(mesh)
else:
return mesh
def boolean_union(self, mesh, inplace=False):
"""
Combines two meshes and attempts to create a manifold mesh.
Parameters
----------
mesh : pyvista.PolyData
The mesh to perform a union against.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
union : pyvista.PolyData
The union mesh when inplace=False.
"""
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToUnion()
bfilter.SetInputData(1, mesh)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh
def boolean_difference(self, mesh, inplace=False):
"""
Combines two meshes and retains only the volume in common
between the meshes.
Parameters
----------
mesh : pyvista.PolyData
The mesh to perform a union against.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
union : pyvista.PolyData
The union mesh when inplace=False.
"""
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToDifference()
bfilter.SetInputData(1, mesh)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh
def curvature(self, curv_type='mean'):
"""
Returns the pointwise curvature of a mesh
Parameters
----------
mesh : vtk.polydata
vtk polydata mesh
curvature string, optional
One of the following strings
Mean
Gaussian
Maximum
Minimum
Returns
-------
curvature : np.ndarray
Curvature values
"""
curv_type = curv_type.lower()
# Create curve filter and compute curvature
curvefilter = vtk.vtkCurvatures()
curvefilter.SetInputData(self)
if curv_type == 'mean':
curvefilter.SetCurvatureTypeToMean()
elif curv_type == 'gaussian':
curvefilter.SetCurvatureTypeToGaussian()
elif curv_type == 'maximum':
curvefilter.SetCurvatureTypeToMaximum()
elif curv_type == 'minimum':
curvefilter.SetCurvatureTypeToMinimum()
else:
raise Exception('Curv_Type must be either "Mean", ' +
'"Gaussian", "Maximum", or "Minimum"')
curvefilter.Update()
# Compute and return curvature
curv = _get_output(curvefilter)
return vtk_to_numpy(curv.GetPointData().GetScalars())
def save(self, filename, binary=True):
"""
Writes a surface mesh to disk.
Written file may be an ASCII or binary ply, stl, or vtk mesh file.
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 the following types (.ply, .stl,
.vtk)
binary : bool, optional
Writes the file as binary when True and ASCII when False.
Notes
-----
Binary files write much faster than ASCII and have a smaller
file size.
"""
filename = os.path.abspath(os.path.expanduser(filename))
file_mode = True
# Check filetype
ftype = filename[-3:]
if ftype == 'ply':
writer = vtk.vtkPLYWriter()
elif ftype == 'vtp':
writer = vtk.vtkXMLPolyDataWriter()
file_mode = False
if binary:
writer.SetDataModeToBinary()
else:
writer.SetDataModeToAscii()
elif ftype == 'stl':
writer = vtk.vtkSTLWriter()
elif ftype == 'vtk':
writer = vtk.vtkPolyDataWriter()
else:
raise Exception('Filetype must be either "ply", "stl", or "vtk"')
writer.SetFileName(filename)
writer.SetInputData(self)
if binary and file_mode:
writer.SetFileTypeToBinary()
elif file_mode:
writer.SetFileTypeToASCII()
writer.Write()
def plot_curvature(self, curv_type='mean', **kwargs):
"""
Plots curvature
Parameters
----------
curvtype : str, optional
One of the following strings indicating curvature type
- Mean
- Gaussian
- Maximum
- Minimum
**kwargs : optional
See help(pyvista.plot)
Returns
-------
cpos : list
List of camera position, focal point, and view up
"""
return self.plot(scalars=self.curvature(curv_type),
stitle='%s\nCurvature' % curv_type, **kwargs)
def tri_filter(self, inplace=False):
"""
Returns an all triangle mesh. More complex polygons will be broken
down into triangles.
Parameters
----------
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : pyvista.PolyData
Mesh containing only triangles. None when inplace=True
"""
trifilter = vtk.vtkTriangleFilter()
trifilter.SetInputData(self)
trifilter.PassVertsOff()
trifilter.PassLinesOff()
trifilter.Update()
mesh = _get_output(trifilter)
if inplace:
self.overwrite(mesh)
else:
return mesh
def smooth(self, n_iter=20, convergence=0.0, edge_angle=15, feature_angle=45,
boundary_smoothing=True, feature_smoothing=False, inplace=False):
"""Adjust point coordinates using Laplacian smoothing.
The effect is to "relax" the mesh, making the cells better shaped and
the vertices more evenly distributed.
Parameters
----------
n_iter : int
Number of iterations for Laplacian smoothing,
convergence : float, optional
Convergence criterion for the iteration process. Smaller numbers
result in more smoothing iterations. Range from (0 to 1).
edge_angle : float, optional
Edge angle to control smoothing along edges (either interior or boundary).
feature_angle : float, optional
Feature angle for sharp edge identification.
boundary_smoothing : bool, optional
Boolean flag to control smoothing of boundary edges.
feature_smoothing : bool, optional
Boolean flag to control smoothing of feature edges.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : pyvista.PolyData
Decimated mesh. None when inplace=True.
"""
alg = vtk.vtkSmoothPolyDataFilter()
alg.SetInputData(self)
alg.SetNumberOfIterations(n_iter)
alg.SetConvergence(convergence)
alg.SetFeatureEdgeSmoothing(feature_smoothing)
alg.SetFeatureAngle(feature_angle)
alg.SetEdgeAngle(edge_angle)
alg.SetBoundarySmoothing(boundary_smoothing)
alg.Update()
mesh = _get_output(alg)
if inplace:
self.overwrite(mesh)
else:
return mesh
def decimate_pro(self, reduction, feature_angle=45.0, split_angle=75.0, splitting=True,
pre_split_mesh=False, preserve_topology=False, inplace=False):
"""Reduce the number of triangles in a triangular mesh, forming a good
approximation to the original geometry. Based on the algorithm originally
described in "Decimation of Triangle Meshes", Proc Siggraph 92.
Parameters
----------
reduction : float
Reduction factor. A value of 0.9 will leave 10 % of the original number
of vertices.
feature_angle : float, optional
Angle used to define what an edge is (i.e., if the surface normal between
two adjacent triangles is >= feature_angle, an edge exists).
split_angle : float, optional
Angle used to control the splitting of the mesh. A split line exists
when the surface normals between two edge connected triangles are >= split_angle.
splitting : bool, optional
Controls the splitting of the mesh at corners, along edges, at non-manifold
points, or anywhere else a split is required. Turning splitting off
will better preserve the original topology of the mesh, but may not
necessarily give the exact requested decimation.
pre_split_mesh : bool, optional
Separates the mesh into semi-planar patches, which are disconnected
from each other. This can give superior results in some cases. If pre_split_mesh
is set to True, the mesh is split with the specified split_angle. Otherwise
mesh splitting is deferred as long as possible.
preserve_topology : bool, optional
Controls topology preservation. If on, mesh splitting and hole elimination
will not occur. This may limit the maximum reduction that may be achieved.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : pyvista.PolyData
Decimated mesh. None when inplace=True.
"""
alg = vtk.vtkDecimatePro()
alg.SetInputData(self)
alg.SetTargetReduction(reduction)
alg.SetPreserveTopology(preserve_topology)
alg.SetFeatureAngle(feature_angle)
alg.SetSplitting(splitting)
alg.SetSplitAngle(split_angle)
alg.SetPreSplitMesh(pre_split_mesh)
alg.Update()
mesh = _get_output(alg)
if inplace:
self.overwrite(mesh)
else:
return mesh
def tube(self, radius=None, scalars=None, capping=True, n_sides=20,
radius_factor=10, preference='point', inplace=False):
"""Generate a tube around each input line. The radius of the tube can be
set to linearly vary with a scalar value.
Parameters
----------
radius : float
Minimum tube radius (minimum because the tube radius may vary).
scalars : str, optional
Scalar array by which the radius varies
capping : bool
Turn on/off whether to cap the ends with polygons. Default True.
n_sides : int
Set the number of sides for the tube. Minimum of 3.
radius_factor : float
Maximum tube radius in terms of a multiple of the minimum radius.
preference : str
The field preference when searching for the scalar array by name
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : pyvista.PolyData
Tube-filtered mesh. None when inplace=True.
"""
if n_sides < 3:
n_sides = 3
tube = vtk.vtkTubeFilter()
tube.SetInputDataObject(self)
# User Defined Parameters
tube.SetCapping(capping)
if radius is not None:
tube.SetRadius(radius)
tube.SetNumberOfSides(n_sides)
tube.SetRadiusFactor(radius_factor)
# Check if scalar array given
if scalars is not None:
if not isinstance(scalars, str):
raise TypeError('Scalar array must be given as a string name')
_, field = self.get_scalar(scalars, preference=preference, info=True)
# args: (idx, port, connection, field, name)
tube.SetInputArrayToProcess(0, 0, 0, field, scalars)
tube.SetVaryRadiusToVaryRadiusByScalar()
# Apply the filter
tube.Update()
mesh = _get_output(tube)
if inplace:
self.overwrite(mesh)
else:
return mesh
def subdivide(self, nsub, subfilter='linear', inplace=False):
"""
Increase the number of triangles in a single, connected triangular
mesh.
Uses one of the following vtk subdivision filters to subdivide a mesh.
vtkButterflySubdivisionFilter
vtkLoopSubdivisionFilter
vtkLinearSubdivisionFilter
Linear subdivision results in the fastest mesh subdivision, but it
does not smooth mesh edges, but rather splits each triangle into 4
smaller triangles.
Butterfly and loop subdivision perform smoothing when dividing, and may
introduce artifacts into the mesh when dividing.
Subdivision filter appears to fail for multiple part meshes. Should
be one single mesh.
Parameters
----------
nsub : int
Number of subdivisions. Each subdivision creates 4 new triangles,
so the number of resulting triangles is nface*4**nsub where nface
is the current number of faces.
subfilter : string, optional
Can be one of the following: 'butterfly', 'loop', 'linear'
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : Polydata object
pyvista polydata object. None when inplace=True
Examples
--------
>>> from pyvista import examples
>>> import pyvista
>>> mesh = pyvista.PolyData(examples.planefile)
>>> submesh = mesh.subdivide(1, 'loop') # doctest:+SKIP
alternatively, update mesh in-place
>>> mesh.subdivide(1, 'loop', inplace=True) # doctest:+SKIP
"""
subfilter = subfilter.lower()
if subfilter == 'linear':
sfilter = vtk.vtkLinearSubdivisionFilter()
elif subfilter == 'butterfly':
sfilter = vtk.vtkButterflySubdivisionFilter()
elif subfilter == 'loop':
sfilter = vtk.vtkLoopSubdivisionFilter()
else:
raise Exception("Subdivision filter must be one of the following: " +
"'butterfly', 'loop', or 'linear'")
# Subdivide
sfilter.SetNumberOfSubdivisions(nsub)
sfilter.SetInputData(self)
sfilter.Update()
submesh = _get_output(sfilter)
if inplace:
self.overwrite(submesh)
else:
return submesh
def extract_edges(self, feature_angle=30, boundary_edges=True,
non_manifold_edges=True, feature_edges=True,
manifold_edges=True, inplace=False):
"""
Extracts edges from a surface. From vtk documentation, the edges are
one of the following
1) boundary (used by one polygon) or a line cell
2) non-manifold (used by three or more polygons)
3) feature edges (edges used by two triangles and whose
dihedral angle > feature_angle)
4) manifold edges (edges used by exactly two polygons).
Parameters
----------
feature_angle : float, optional
Defaults to 30 degrees.
boundary_edges : bool, optional
Defaults to True
non_manifold_edges : bool, optional
Defaults to True
feature_edges : bool, optional
Defaults to True
manifold_edges : bool, optional
Defaults to True
inplace : bool, optional
Return new mesh or overwrite input.
Returns
-------
edges : pyvista.vtkPolyData
Extracted edges. None if inplace=True.
"""
featureEdges = vtk.vtkFeatureEdges()
featureEdges.SetInputData(self)
featureEdges.SetFeatureAngle(feature_angle)
featureEdges.SetManifoldEdges(manifold_edges)
featureEdges.SetNonManifoldEdges(non_manifold_edges)
featureEdges.SetBoundaryEdges(boundary_edges)
featureEdges.SetFeatureEdges(feature_edges)
featureEdges.SetColoring(False)
featureEdges.Update()
mesh = _get_output(featureEdges)
if inplace:
self.overwrite(mesh)
else:
return mesh
def decimate(self, target_reduction, volume_preservation=False,
attribute_error=False, scalars=True, vectors=True,
normals=False, tcoords=True, tensors=True, scalars_weight=0.1,
vectors_weight=0.1, normals_weight=0.1, tcoords_weight=0.1,
tensors_weight=0.1, inplace=False):
"""
Reduces the number of triangles in a triangular mesh using
vtkQuadricDecimation.
Parameters
----------
mesh : vtk.PolyData
Mesh to decimate
target_reduction : float
Fraction of the original mesh to remove.
TargetReduction is set to 0.9, this filter will try to reduce
the data set to 10% of its original size and will remove 90%
of the input triangles.
volume_preservation : bool, optional
Decide whether to activate volume preservation which greatly reduces
errors in triangle normal direction. If off, volume preservation is
disabled and if AttributeErrorMetric is active, these errors can be
large. Defaults to False.
attribute_error : bool, optional
Decide whether to include data attributes in the error metric. If
off, then only geometric error is used to control the decimation.
Defaults to False.
scalars : bool, optional
If attribute errors are to be included in the metric (i.e.,
AttributeErrorMetric is on), then the following flags control which
attributes are to be included in the error calculation. Defaults to
True.
vectors : bool, optional
See scalars parameter. Defaults to True.
normals : bool, optional
See scalars parameter. Defaults to False.
tcoords : bool, optional
See scalars parameter. Defaults to True.
tensors : bool, optional
See scalars parameter. Defaults to True.
scalars_weight : float, optional
The scaling weight contribution of the scalar attribute. These
values are used to weight the contribution of the attributes towards
the error metric. Defaults to 0.1.
vectors_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
normals_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
tcoords_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
tensors_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
outmesh : pyvista.PolyData
Decimated mesh. None when inplace=True.
"""