-
Notifications
You must be signed in to change notification settings - Fork 440
/
poly_data.py
3730 lines (3032 loc) · 131 KB
/
poly_data.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
"""Filters module with a class to manage filters/algorithms for polydata datasets."""
import collections.abc
import warnings
import numpy as np
import pyvista
from pyvista.core import _vtk_core as _vtk
from pyvista.core.errors import (
MissingDataError,
NotAllTrianglesError,
PyVistaFutureWarning,
VTKVersionError,
)
from pyvista.core.filters import _get_output, _update_alg
from pyvista.core.filters.data_set import DataSetFilters
from pyvista.core.utilities.arrays import (
FieldAssociation,
get_array,
get_array_association,
set_default_active_scalars,
vtk_id_list_to_array,
)
from pyvista.core.utilities.geometric_objects import NORMALS
from pyvista.core.utilities.helpers import generate_plane, wrap
from pyvista.core.utilities.misc import abstract_class, assert_empty_kwargs
@abstract_class
class PolyDataFilters(DataSetFilters):
"""An internal class to manage filters/algorithms for polydata datasets."""
def edge_mask(self, angle, progress_bar=False):
"""Return a mask of the points of a surface mesh that has a surface angle greater than angle.
Parameters
----------
angle : float
Angle to consider an edge.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
numpy.ndarray
Mask of points with an angle greater than ``angle``.
Examples
--------
Plot the mask of points that exceed 45 degrees.
>>> import pyvista as pv
>>> mesh = pv.Cube().triangulate().subdivide(4)
>>> mask = mesh.edge_mask(45)
>>> mesh.plot(scalars=mask)
Show the array of masked points.
>>> mask # doctest:+SKIP
array([ True, True, True, ..., False, False, False])
"""
poly_data = self
if not isinstance(poly_data, pyvista.PolyData): # pragma: no cover
poly_data = pyvista.PolyData(poly_data)
poly_data.point_data['point_ind'] = np.arange(poly_data.n_points)
featureEdges = _vtk.vtkFeatureEdges()
featureEdges.SetInputData(poly_data)
featureEdges.FeatureEdgesOn()
featureEdges.BoundaryEdgesOff()
featureEdges.NonManifoldEdgesOff()
featureEdges.ManifoldEdgesOff()
featureEdges.SetFeatureAngle(angle)
_update_alg(featureEdges, progress_bar, 'Computing Edges')
edges = _get_output(featureEdges)
orig_id = pyvista.point_array(edges, 'point_ind')
return np.in1d(poly_data.point_data['point_ind'], orig_id, assume_unique=True)
def _boolean(self, btype, other_mesh, tolerance, progress_bar=False):
"""Perform boolean operation."""
if self.n_points == other_mesh.n_points:
if np.allclose(self.points, other_mesh.points):
raise ValueError(
"The input mesh contains identical points to the surface being operated on. Unable to perform boolean operations on an identical surface."
)
if not isinstance(other_mesh, pyvista.PolyData):
raise TypeError("Input mesh must be PolyData.")
if not self.is_all_triangles or not other_mesh.is_all_triangles:
raise NotAllTrianglesError("Make sure both the input and output are triangulated.")
bfilter = _vtk.vtkBooleanOperationPolyDataFilter()
if btype == 'union':
bfilter.SetOperationToUnion()
elif btype == 'intersection':
bfilter.SetOperationToIntersection()
elif btype == 'difference':
bfilter.SetOperationToDifference()
else: # pragma: no cover
raise ValueError(f'Invalid btype {btype}')
bfilter.SetInputData(0, self)
bfilter.SetInputData(1, other_mesh)
bfilter.ReorientDifferenceCellsOn() # this is already default
bfilter.SetTolerance(tolerance)
_update_alg(bfilter, progress_bar, 'Performing Boolean Operation')
return _get_output(bfilter)
def boolean_union(self, other_mesh, tolerance=1e-5, progress_bar=False):
"""Perform a boolean union operation on two meshes.
Essentially, boolean union, difference, and intersection are
all the same operation. Just different parts of the objects
are kept at the end.
The union of two manifold meshes ``A`` and ``B`` is the mesh
which is in ``A``, in ``B``, or in both ``A`` and ``B``.
.. note::
If your boolean operations don't react the way you think they
should (i.e. the wrong parts disappear), one of your meshes
probably has its normals pointing inward. Use
:func:`PolyDataFilters.plot_normals` to visualize the
normals.
.. note::
The behavior of this filter varies from the
:func:`PolyDataFilters.merge` filter. This filter attempts
to create a manifold mesh and will not include internal
surfaces when two meshes overlap.
.. note::
Both meshes must be composed of all triangles. Check with
:attr:`PolyData.is_all_triangles` and convert with
:func:`PolyDataFilters.triangulate`.
.. versionchanged:: 0.32.0
Behavior changed to match default VTK behavior.
Parameters
----------
other_mesh : pyvista.PolyData
Mesh operating on the source mesh.
tolerance : float, tolerance: 1e-5
Tolerance used to determine when a point's absolute
distance is considered to be zero.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
The result of the boolean operation.
Examples
--------
Demonstrate a boolean union with two spheres. Note how the
final mesh includes both spheres.
>>> import pyvista as pv
>>> sphere_a = pv.Sphere()
>>> sphere_b = pv.Sphere(center=(0.5, 0, 0))
>>> result = sphere_a.boolean_union(sphere_b)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(
... sphere_a, color='r', style='wireframe', line_width=3
... )
>>> _ = pl.add_mesh(
... sphere_b, color='b', style='wireframe', line_width=3
... )
>>> _ = pl.add_mesh(result, color='lightblue')
>>> pl.camera_position = 'xz'
>>> pl.show()
See :ref:`boolean_example` for more examples using this filter.
"""
return self._boolean('union', other_mesh, tolerance, progress_bar=progress_bar)
def boolean_intersection(self, other_mesh, tolerance=1e-5, progress_bar=False):
"""Perform a boolean intersection operation on two meshes.
Essentially, boolean union, difference, and intersection are
all the same operation. Just different parts of the objects
are kept at the end.
The intersection of two manifold meshes ``A`` and ``B`` is the mesh
which is the volume of ``A`` that is also in ``B``.
.. note::
If your boolean operations don't react the way you think they
should (i.e. the wrong parts disappear), one of your meshes
probably has its normals pointing inward. Use
:func:`PolyDataFilters.plot_normals` to visualize the
normals.
.. note::
This method returns the "volume" intersection between two
meshes whereas the :func:`PolyDataFilters.intersection`
filter returns the surface intersection between two meshes
(which often resolves as a line).
.. note::
Both meshes must be composed of all triangles. Check with
:attr:`PolyData.is_all_triangles` and convert with
:func:`PolyDataFilters.triangulate`.
.. versionadded:: 0.32.0
Parameters
----------
other_mesh : pyvista.PolyData
Mesh operating on the source mesh.
tolerance : float, default: 1e-5
Tolerance used to determine when a point's absolute
distance is considered to be zero.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
The result of the boolean operation.
Examples
--------
Demonstrate a boolean intersection with two spheres. Note how
the final mesh only includes the intersection of the two.
>>> import pyvista as pv
>>> sphere_a = pv.Sphere()
>>> sphere_b = pv.Sphere(center=(0.5, 0, 0))
>>> result = sphere_a.boolean_intersection(sphere_b)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(
... sphere_a, color='r', style='wireframe', line_width=3
... )
>>> _ = pl.add_mesh(
... sphere_b, color='b', style='wireframe', line_width=3
... )
>>> _ = pl.add_mesh(result, color='lightblue')
>>> pl.camera_position = 'xz'
>>> pl.show()
See :ref:`boolean_example` for more examples using this filter.
"""
bool_inter = self._boolean('intersection', other_mesh, tolerance, progress_bar=progress_bar)
# check if a polydata is completely contained within another
if bool_inter.n_points == 0:
inter, s1, s2 = self.intersection(other_mesh)
if inter.n_points == 0 and s1.n_points == 0 and s2.n_points == 0:
warnings.warn(
'Unable to compute boolean intersection when one PolyData is '
'contained within another and no faces intersect.',
)
return bool_inter
def boolean_difference(self, other_mesh, tolerance=1e-5, progress_bar=False):
"""Perform a boolean difference operation between two meshes.
Essentially, boolean union, difference, and intersection are
all the same operation. Just different parts of the objects
are kept at the end.
The difference of two manifold meshes ``A`` and ``B`` is the
volume of the mesh in ``A`` not belonging to ``B``.
.. note::
If your boolean operations don't react the way you think they
should (i.e. the wrong parts disappear), one of your meshes
probably has its normals pointing inward. Use
:func:`PolyDataFilters.plot_normals` to visualize the
normals.
.. note::
Both meshes must be composed of all triangles. Check with
:attr:`PolyData.is_all_triangles` and convert with
:func:`PolyDataFilters.triangulate`.
.. versionchanged:: 0.32.0
Behavior changed to match default VTK behavior.
Parameters
----------
other_mesh : pyvista.PolyData
Mesh operating on the source mesh.
tolerance : float, default: 1e-5
Tolerance used to determine when a point's absolute
distance is considered to be zero.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
The result of the boolean operation.
Examples
--------
Demonstrate a boolean difference with two spheres. Note how
the final mesh only includes ``sphere_a``.
>>> import pyvista as pv
>>> sphere_a = pv.Sphere()
>>> sphere_b = pv.Sphere(center=(0.5, 0, 0))
>>> result = sphere_a.boolean_difference(sphere_b)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(
... sphere_a, color='r', style='wireframe', line_width=3
... )
>>> _ = pl.add_mesh(
... sphere_b, color='b', style='wireframe', line_width=3
... )
>>> _ = pl.add_mesh(result, color='lightblue')
>>> pl.camera_position = 'xz'
>>> pl.show()
See :ref:`boolean_example` for more examples using this filter.
"""
return self._boolean('difference', other_mesh, tolerance, progress_bar=progress_bar)
def __add__(self, dataset):
"""Merge these two meshes."""
return self.merge(dataset)
def __iadd__(self, dataset):
"""Merge another mesh into this one if possible.
"If possible" means that ``dataset`` is also a :class:`PolyData`.
Otherwise we have to return a :class:`pyvista.UnstructuredGrid`,
so the in-place merge attempt will raise.
"""
merged = self.merge(dataset, inplace=True)
return merged
def append_polydata(
self,
*meshes,
inplace=False,
progress_bar=False,
):
"""Append one or more PolyData into this one.
Under the hood, the VTK `vtkAppendPolyDataFilter
<https://vtk.org/doc/nightly/html/classvtkAppendPolyData.html#details>`_ filter is used to perform the
append operation.
.. versionadded:: 0.40.0
.. note::
As stated in the VTK documentation of `vtkAppendPolyDataFilter
<https://vtk.org/doc/nightly/html/classvtkAppendPolyData.html#details>`_,
point and cell data are added to the output PolyData **only** if they are present across **all**
input PolyData.
.. seealso::
:func:`pyvista.PolyDataFilters.merge`
Parameters
----------
*meshes : list[pyvista.PolyData]
The PolyData(s) to append with the current one.
inplace : bool, default: False
Whether to update the mesh in-place.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Appended PolyData(s).
Examples
--------
>>> import pyvista as pv
>>> sp0 = pv.Sphere()
>>> sp1 = sp0.translate((1, 0, 0))
>>> appended = sp0.append_polydata(sp1)
>>> appended.plot()
Append more than one PolyData.
>>> sp2 = sp0.translate((-1, 0, 0))
>>> appended = sp0.append_polydata(sp1, sp2)
>>> appended.plot()
"""
if not all(isinstance(mesh, pyvista.PolyData) for mesh in meshes):
raise TypeError("All meshes need to be of PolyData type")
append_filter = _vtk.vtkAppendPolyData()
append_filter.AddInputData(self)
for mesh in meshes:
append_filter.AddInputData(mesh)
_update_alg(append_filter, progress_bar, 'Append PolyData')
merged = _get_output(append_filter)
if inplace:
self.deep_copy(merged) # type: ignore
return self
return merged
def merge(
self,
dataset,
merge_points=True,
tolerance=0.0,
inplace=False,
main_has_priority=True,
progress_bar=False,
):
"""Merge this mesh with one or more datasets.
.. note::
The behavior of this filter varies from the
:func:`PolyDataFilters.boolean_union` filter. This filter
does not attempt to create a manifold mesh and will include
internal surfaces when two meshes overlap.
.. note::
The ``+`` operator between two meshes uses this filter with
the default parameters. When the other mesh is also a
:class:`pyvista.PolyData`, in-place merging via ``+=`` is
similarly possible.
.. versionchanged:: 0.39.0
Before version ``0.39.0``, if all input datasets were of type :class:`pyvista.PolyData`,
the VTK ``vtkAppendPolyDataFilter`` and ``vtkCleanPolyData`` filters were used to perform merging.
Otherwise, :func:`DataSetFilters.merge`, which uses the VTK ``vtkAppendFilter`` filter,
was called.
To enhance performance and coherence with merging operations available for other datasets in pyvista,
the merging operation has been delegated in ``0.39.0`` to :func:`DataSetFilters.merge` only,
irrespectively of input datasets types.
This induced that points ordering can be altered compared to previous pyvista versions when
merging only PolyData together.
To obtain similar results as before ``0.39.0`` for multiple PolyData, combine
:func:`PolyDataFilters.append_polydata` and :func:`PolyDataFilters.clean`.
.. seealso::
:func:`PolyDataFilters.append_polydata`
Parameters
----------
dataset : pyvista.DataSet
PyVista dataset to merge this mesh with.
merge_points : bool, optional
Merge equivalent points when ``True``.
tolerance : float, default: 0.0
The absolute tolerance to use to find coincident points when
``merge_points=True``.
inplace : bool, default: False
Updates grid inplace when ``True`` if the input type is a
:class:`pyvista.PolyData`. For other input meshes the
result is a :class:`pyvista.UnstructuredGrid` which makes
in-place operation impossible.
main_has_priority : bool, optional
When this parameter is ``True`` and ``merge_points=True``,
the arrays of the merging grids will be overwritten
by the original main mesh.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.DataSet
:class:`pyvista.PolyData` if ``dataset`` is a
:class:`pyvista.PolyData`, otherwise a
:class:`pyvista.UnstructuredGrid`.
Examples
--------
>>> import pyvista as pv
>>> sphere_a = pv.Sphere()
>>> sphere_b = pv.Sphere(center=(0.5, 0, 0))
>>> merged = sphere_a.merge(sphere_b)
>>> merged.plot(style='wireframe', color='lightblue')
"""
# check if dataset or datasets are not polydata
if isinstance(dataset, (list, tuple, pyvista.MultiBlock)):
is_polydata = all(isinstance(data, pyvista.PolyData) for data in dataset)
else:
is_polydata = isinstance(dataset, pyvista.PolyData)
if inplace and not is_polydata:
raise TypeError("In-place merge requires both input datasets to be PolyData.")
merged = DataSetFilters.merge(
self,
dataset,
merge_points=merge_points,
tolerance=tolerance,
main_has_priority=main_has_priority,
inplace=False,
progress_bar=progress_bar,
)
# convert back to a polydata if both inputs were polydata
if is_polydata:
# if either of the input datasets contained lines or strips, we
# must use extract_geometry to ensure they get converted back
# correctly. This incurrs a performance penalty, but is needed to
# maintain data consistency.
if isinstance(dataset, (list, tuple, pyvista.MultiBlock)):
dataset_has_lines_strips = any(
[ds.n_lines or ds.n_strips or ds.n_verts for ds in dataset]
)
else:
dataset_has_lines_strips = dataset.n_lines or dataset.n_strips or dataset.n_verts
if self.n_lines or self.n_strips or self.n_verts or dataset_has_lines_strips:
merged = merged.extract_geometry()
else:
polydata_merged = pyvista.PolyData(
merged.points, faces=merged.cells, n_faces=merged.n_cells, deep=False
)
# Calling update() will modify the active scalars in this specific
# case. Store values to restore after updating.
active_point_scalars_name = merged.point_data.active_scalars_name
active_cell_scalars_name = merged.cell_data.active_scalars_name
polydata_merged.point_data.update(merged.point_data)
polydata_merged.cell_data.update(merged.cell_data)
polydata_merged.field_data.update(merged.field_data)
# restore active scalars
polydata_merged.point_data.active_scalars_name = active_point_scalars_name
polydata_merged.cell_data.active_scalars_name = active_cell_scalars_name
merged = polydata_merged
if inplace:
self.deep_copy(merged)
return self
return merged
def intersection(self, mesh, split_first=True, split_second=True, progress_bar=False):
"""Compute the intersection between two meshes.
.. note::
This method returns the surface intersection from two meshes
(which often resolves as a line), whereas the
:func:`PolyDataFilters.boolean_intersection` filter returns
the "volume" intersection between two closed (manifold)
meshes.
Parameters
----------
mesh : pyvista.PolyData
The mesh to intersect with.
split_first : bool, default: True
If ``True``, return the first input mesh split by the
intersection with the second input mesh.
split_second : bool, default: True
If ``True``, return the second input mesh split by the
intersection with the first input mesh.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
The intersection line.
pyvista.PolyData
The first mesh split along the intersection. Returns the
original first mesh if ``split_first=False``.
pyvista.PolyData
The second mesh split along the intersection. Returns the
original second mesh if ``split_second=False``.
Examples
--------
Intersect two spheres, returning the intersection and both spheres
which have new points/cells along the intersection line.
>>> import pyvista as pv
>>> import numpy as np
>>> s1 = pv.Sphere(phi_resolution=15, theta_resolution=15)
>>> s2 = s1.copy()
>>> s2.points += np.array([0.25, 0, 0])
>>> intersection, s1_split, s2_split = s1.intersection(s2)
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(s1, style='wireframe')
>>> _ = pl.add_mesh(s2, style='wireframe')
>>> _ = pl.add_mesh(intersection, color='r', line_width=10)
>>> pl.show()
The mesh splitting takes additional time and can be turned
off for either mesh individually.
>>> intersection, _, s2_split = s1.intersection(
... s2, split_first=False, split_second=True
... )
"""
intfilter = _vtk.vtkIntersectionPolyDataFilter()
intfilter.SetInputDataObject(0, self)
intfilter.SetInputDataObject(1, mesh)
intfilter.SetComputeIntersectionPointArray(True)
intfilter.SetSplitFirstOutput(split_first)
intfilter.SetSplitSecondOutput(split_second)
_update_alg(intfilter, progress_bar, 'Computing the intersection between two meshes')
intersection = _get_output(intfilter, oport=0)
first = _get_output(intfilter, oport=1)
second = _get_output(intfilter, oport=2)
return intersection, first, second
def curvature(self, curv_type='mean', progress_bar=False):
"""Return the pointwise curvature of a mesh.
See :ref:`connectivity_example` for more examples using this
filter.
Parameters
----------
curv_type : str, default: "mean"
Curvature type. One of the following:
* ``"mean"``
* ``"gaussian"``
* ``"maximum"``
* ``"minimum"``
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
numpy.ndarray
Array of curvature values.
Examples
--------
Calculate the mean curvature of the hills example mesh and plot it.
>>> from pyvista import examples
>>> hills = examples.load_random_hills()
>>> curv = hills.curvature()
>>> hills.plot(scalars=curv)
Show the curvature array.
>>> curv # doctest:+SKIP
array([0.20587616, 0.06747695, ..., 0.11781171, 0.15988467])
"""
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 ValueError(
'``curv_type`` must be either "Mean", "Gaussian", "Maximum", or "Minimum".'
)
_update_alg(curvefilter, progress_bar, 'Computing Curvature')
# Compute and return curvature
curv = _get_output(curvefilter)
return _vtk.vtk_to_numpy(curv.GetPointData().GetScalars())
def plot_curvature(self, curv_type='mean', **kwargs):
"""Plot the curvature.
Parameters
----------
curv_type : str, default: "mean"
One of the following strings indicating curvature type:
* ``'mean'``
* ``'gaussian'``
* ``'maximum'``
* ``'minimum'``
**kwargs : dict, optional
See :func:`pyvista.plot`.
Returns
-------
pyvista.CameraPosition
List of camera position, focal point, and view up.
Returned when ``return_cpos`` is ``True``.
Examples
--------
Plot the Gaussian curvature of an example mesh. Override the
default scalar bar range as the mesh edges report high
curvature.
>>> from pyvista import examples
>>> hills = examples.load_random_hills()
>>> hills.plot_curvature(
... curv_type='gaussian', smooth_shading=True, clim=[0, 1]
... )
"""
kwargs.setdefault('scalar_bar_args', {'title': f'{curv_type.capitalize()} Curvature'})
return self.plot(scalars=self.curvature(curv_type), **kwargs)
def triangulate(self, inplace=False, progress_bar=False):
"""Return an all triangle mesh.
More complex polygons will be broken down into triangles.
Parameters
----------
inplace : bool, default: False
Whether to update the mesh in-place.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Mesh containing only triangles.
Examples
--------
Generate a mesh with quadrilateral faces.
>>> import pyvista as pv
>>> plane = pv.Plane()
>>> plane.point_data.clear()
>>> plane.plot(show_edges=True, line_width=5)
Convert it to an all triangle mesh.
>>> mesh = plane.triangulate()
>>> mesh.plot(show_edges=True, line_width=5)
"""
trifilter = _vtk.vtkTriangleFilter()
trifilter.SetInputData(self)
trifilter.PassVertsOff()
trifilter.PassLinesOff()
_update_alg(trifilter, progress_bar, 'Computing Triangle Mesh')
mesh = _get_output(trifilter)
if inplace:
self.copy_from(mesh, deep=False)
return self
return mesh
def smooth(
self,
n_iter=20,
relaxation_factor=0.01,
convergence=0.0,
edge_angle=15,
feature_angle=45,
boundary_smoothing=True,
feature_smoothing=False,
inplace=False,
progress_bar=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, default: 20
Number of iterations for Laplacian smoothing.
relaxation_factor : float, default: 0.01
Relaxation factor controls the amount of displacement in a single
iteration. Generally a lower relaxation factor and higher number of
iterations is numerically more stable.
convergence : float, default: 0.0
Convergence criterion for the iteration process. Smaller numbers
result in more smoothing iterations. Range from (0 to 1).
edge_angle : float, default: 15
Edge angle to control smoothing along edges (either interior or boundary).
feature_angle : float, default: 45
Feature angle for sharp edge identification.
boundary_smoothing : bool, default: True
Flag to control smoothing of boundary edges. When ``True``,
boundary edges remain fixed.
feature_smoothing : bool, default: False
Flag to control smoothing of feature edges. When ``True``,
boundary edges remain fixed as defined by ``feature_angle`` and
``edge_angle``.
inplace : bool, default: False
Updates mesh in-place.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Smoothed mesh.
Examples
--------
Smooth the edges of an all triangular cube
>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(5)
>>> smooth_cube = cube.smooth(1000, feature_smoothing=False)
>>> n_edge_cells = cube.extract_feature_edges().n_cells
>>> n_smooth_cells = smooth_cube.extract_feature_edges().n_cells
>>> f'Sharp Edges on Cube: {n_edge_cells}'
'Sharp Edges on Cube: 384'
>>> f'Sharp Edges on Smooth Cube: {n_smooth_cells}'
'Sharp Edges on Smooth Cube: 12'
>>> smooth_cube.plot()
See :ref:`surface_smoothing_example` for more examples using this filter.
"""
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.SetRelaxationFactor(relaxation_factor)
_update_alg(alg, progress_bar, 'Smoothing Mesh')
mesh = _get_output(alg)
if inplace:
self.copy_from(mesh, deep=False)
return self
return mesh
def smooth_taubin(
self,
n_iter=20,
pass_band=0.1,
edge_angle=15.0,
feature_angle=45.0,
boundary_smoothing=True,
feature_smoothing=False,
non_manifold_smoothing=False,
normalize_coordinates=False,
inplace=False,
progress_bar=False,
):
"""Smooth a PolyData DataSet with Taubin smoothing.
This filter allows you to smooth the mesh as in the Laplacian smoothing
implementation in :func:`smooth() <PolyDataFilters.smooth>`. However,
unlike Laplacian smoothing the surface does not "shrink" since this
filter relies on an alternative approach to smoothing. This filter is
more akin to a low pass filter where undesirable high frequency features
are removed.
This PyVista filter uses the VTK `vtkWindowedSincPolyDataFilter
<https://vtk.org/doc/nightly/html/classvtkWindowedSincPolyDataFilter.html>`_
filter.
Parameters
----------
n_iter : int, default: 20
This is the degree of the polynomial used to approximate the
windowed sync function. This is generally much less than the number
needed by :func:`smooth() <PolyDataFilters.smooth>`.
pass_band : float, default: 0.1
The passband value for the windowed sinc filter. This should be
between 0 and 2, where lower values cause more smoothing.
edge_angle : float, default: 15.0
Edge angle to control smoothing along edges (either interior or
boundary).
feature_angle : float, default: 45.0
Feature angle for sharp edge identification.
boundary_smoothing : bool, default: True
Flag to control smoothing of boundary edges. When ``True``,
boundary edges remain fixed.
feature_smoothing : bool, default: False
Flag to control smoothing of feature edges. When ``True``,
boundary edges remain fixed as defined by ``feature_angle`` and
``edge_angle``.
non_manifold_smoothing : bool, default: False
Smooth non-manifold points.
normalize_coordinates : bool, default: False
Flag to control coordinate normalization. To improve the
numerical stability of the solution and minimize the scaling of the
translation effects, the algorithm can translate and scale the
position coordinates to within the unit cube ``[-1, 1]``, perform the
smoothing, and translate and scale the position coordinates back to
the original coordinate frame.
inplace : bool, default: False
Updates mesh in-place.
progress_bar : bool, default: False
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Smoothed mesh.
Notes
-----
For maximum performance, do not enable ``feature_smoothing`` or
``boundary_smoothing``. ``feature_smoothing`` is especially expensive.
References
----------
See `Optimal Surface Smoothing as Filter Design
<https://dl.acm.org/doi/pdf/10.1145/218380.218473>`_ for details
regarding the implementation of Taubin smoothing.
Examples
--------
Smooth the example bone mesh. Here, it's necessary to subdivide the
mesh to increase the number of faces as the original mesh is so coarse.
>>> import pyvista as pv
>>> from pyvista import examples
>>> mesh = examples.download_foot_bones().subdivide(2)
>>> smoothed_mesh = mesh.smooth_taubin()
>>> pl = pv.Plotter(shape=(1, 2))
>>> _ = pl.add_mesh(mesh)
>>> _ = pl.add_text('Original Mesh')
>>> pl.subplot(0, 1)
>>> _ = pl.add_mesh(smoothed_mesh)
>>> _ = pl.add_text('Smoothed Mesh')
>>> pl.show()
See :ref:`surface_smoothing_example` for more examples using this filter.
"""
alg = _vtk.vtkWindowedSincPolyDataFilter()
alg.SetInputData(self)
alg.SetNumberOfIterations(n_iter)
alg.SetFeatureEdgeSmoothing(feature_smoothing)
alg.SetNonManifoldSmoothing(non_manifold_smoothing)
alg.SetFeatureAngle(feature_angle)
alg.SetEdgeAngle(edge_angle)
alg.SetBoundarySmoothing(boundary_smoothing)
alg.SetPassBand(pass_band)
alg.SetNormalizeCoordinates(normalize_coordinates)
_update_alg(alg, progress_bar, 'Smoothing Mesh using Taubin Smoothing')
mesh = _get_output(alg)
if inplace:
self.copy_from(mesh, deep=False)
return self
return mesh
def decimate_pro(
self,
reduction,
feature_angle=45.0,