/
data_set.py
5548 lines (4621 loc) · 201 KB
/
data_set.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 of common filters that can be applied to any vtkDataSet."""
import collections.abc
from typing import Optional, Sequence, Union
import warnings
import numpy as np
import pyvista
from pyvista import FieldAssociation, _vtk
from pyvista.core.errors import VTKVersionError
from pyvista.core.filters import _get_output, _update_alg
from pyvista.errors import AmbiguousDataError, MissingDataError
from pyvista.utilities import (
NORMALS,
abstract_class,
assert_empty_kwargs,
generate_plane,
get_array,
get_array_association,
transformations,
wrap,
)
from pyvista.utilities.cells import numpy_to_idarr
@abstract_class
class DataSetFilters:
"""A set of common filters that can be applied to any vtkDataSet."""
def _clip_with_function(
self,
function,
invert=True,
value=0.0,
return_clipped=False,
progress_bar=False,
crinkle=False,
):
"""Clip using an implicit function (internal helper)."""
if crinkle:
# Add Cell IDs
self.cell_data['cell_ids'] = np.arange(self.n_cells)
if isinstance(self, _vtk.vtkPolyData):
alg = _vtk.vtkClipPolyData()
# elif isinstance(self, vtk.vtkImageData):
# alg = vtk.vtkClipVolume()
# alg.SetMixed3DCellGeneration(True)
else:
alg = _vtk.vtkTableBasedClipDataSet()
alg.SetInputDataObject(self) # Use the grid as the data we desire to cut
alg.SetValue(value)
alg.SetClipFunction(function) # the implicit function
alg.SetInsideOut(invert) # invert the clip if needed
alg.SetGenerateClippedOutput(return_clipped)
_update_alg(alg, progress_bar, 'Clipping with Function')
if return_clipped:
a = _get_output(alg, oport=0)
b = _get_output(alg, oport=1)
if crinkle:
a = self.extract_cells(np.unique(a.cell_data['cell_ids']))
b = self.extract_cells(np.unique(b.cell_data['cell_ids']))
return a, b
clipped = _get_output(alg)
if crinkle:
clipped = self.extract_cells(np.unique(clipped.cell_data['cell_ids']))
return clipped
def clip(
self,
normal='x',
origin=None,
invert=True,
value=0.0,
inplace=False,
return_clipped=False,
progress_bar=False,
crinkle=False,
):
"""Clip a dataset by a plane by specifying the origin and normal.
If no parameters are given the clip will occur in the center
of that dataset.
Parameters
----------
normal : tuple(float) or str, default: 'x'
Length 3 tuple for the normal vector direction. Can also
be specified as a string conventional direction such as
``'x'`` for ``(1,0,0)`` or ``'-x'`` for ``(-1,0,0)``, etc.
origin : tuple(float), optional
The center ``(x,y,z)`` coordinate of the plane on which the clip
occurs. The default is the center of the dataset.
invert : bool, optional
Flag on whether to flip/invert the clip.
value : float, optional
Set the clipping value along the normal direction.
The default value is 0.0.
inplace : bool, optional
Updates mesh in-place.
return_clipped : bool, optional
Return both unclipped and clipped parts of the dataset.
progress_bar : bool, optional
Display a progress bar to indicate progress.
crinkle : bool, optional
Crinkle the clip by extracting the entire cells along the
clip. This adds the ``"cell_ids"`` array to the ``cell_data``
attribute that tracks the original cell IDs of the original
dataset.
Returns
-------
pyvista.PolyData or tuple(pyvista.PolyData)
Clipped mesh when ``return_clipped=False``,
otherwise a tuple containing the unclipped and clipped datasets.
Examples
--------
Clip a cube along the +X direction. ``triangulate`` is used as
the cube is initially composed of quadrilateral faces and
subdivide only works on triangles.
>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip()
>>> clipped_cube.plot()
Clip a cube in the +Z direction. This leaves half a cube
below the XY plane.
>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip('z')
>>> clipped_cube.plot()
See :ref:`clip_with_surface_example` for more examples using this filter.
"""
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = self.center
# create the plane for clipping
function = generate_plane(normal, origin)
# run the clip
result = DataSetFilters._clip_with_function(
self,
function,
invert=invert,
value=value,
return_clipped=return_clipped,
progress_bar=progress_bar,
crinkle=crinkle,
)
if inplace:
if return_clipped:
self.copy_from(result[0], deep=False)
return self, result[1]
else:
self.copy_from(result, deep=False)
return self
return result
def clip_box(
self,
bounds=None,
invert=True,
factor=0.35,
progress_bar=False,
merge_points=True,
crinkle=False,
):
"""Clip a dataset by a bounding box defined by the bounds.
If no bounds are given, a corner of the dataset bounds will be removed.
Parameters
----------
bounds : tuple(float), optional
Length 6 sequence of floats: (xmin, xmax, ymin, ymax, zmin, zmax).
Length 3 sequence of floats: distances from the min coordinate of
of the input mesh. Single float value: uniform distance from the
min coordinate. Length 12 sequence of length 3 sequence of floats:
a plane collection (normal, center, ...).
:class:`pyvista.PolyData`: if a poly mesh is passed that represents
a box with 6 faces that all form a standard box, then planes will
be extracted from the box to define the clipping region.
invert : bool, optional
Flag on whether to flip/invert the clip.
factor : float, optional
If bounds are not given this is the factor along each axis to
extract the default box.
progress_bar : bool, optional
Display a progress bar to indicate progress.
merge_points : bool, optional
If ``True`` (default), coinciding points of independently
defined mesh elements will be merged.
crinkle : bool, optional
Crinkle the clip by extracting the entire cells along the
clip. This adds the ``"cell_ids"`` array to the ``cell_data``
attribute that tracks the original cell IDs of the original
dataset.
Returns
-------
pyvista.UnstructuredGrid
Clipped dataset.
Examples
--------
Clip a corner of a cube. The bounds of a cube are normally
``[-0.5, 0.5, -0.5, 0.5, -0.5, 0.5]``, and this removes 1/8 of
the cube's surface.
>>> import pyvista as pv
>>> cube = pv.Cube().triangulate().subdivide(3)
>>> clipped_cube = cube.clip_box([0, 1, 0, 1, 0, 1])
>>> clipped_cube.plot()
See :ref:`clip_with_plane_box_example` for more examples using this filter.
"""
if bounds is None:
def _get_quarter(dmin, dmax):
"""Get a section of the given range (internal helper)."""
return dmax - ((dmax - dmin) * factor)
xmin, xmax, ymin, ymax, zmin, zmax = self.bounds
xmin = _get_quarter(xmin, xmax)
ymin = _get_quarter(ymin, ymax)
zmin = _get_quarter(zmin, zmax)
bounds = [xmin, xmax, ymin, ymax, zmin, zmax]
if isinstance(bounds, (float, int)):
bounds = [bounds, bounds, bounds]
elif isinstance(bounds, pyvista.PolyData):
poly = bounds
if poly.n_cells != 6:
raise ValueError("The bounds mesh must have only 6 faces.")
bounds = []
poly.compute_normals(inplace=True)
for cid in range(6):
cell = poly.extract_cells(cid)
normal = cell["Normals"][0]
bounds.append(normal)
bounds.append(cell.center)
if not isinstance(bounds, (np.ndarray, collections.abc.Sequence)):
raise TypeError('Bounds must be a sequence of floats with length 3, 6 or 12.')
if len(bounds) not in [3, 6, 12]:
raise ValueError('Bounds must be a sequence of floats with length 3, 6 or 12.')
if len(bounds) == 3:
xmin, xmax, ymin, ymax, zmin, zmax = self.bounds
bounds = (xmin, xmin + bounds[0], ymin, ymin + bounds[1], zmin, zmin + bounds[2])
if crinkle:
self.cell_data['cell_ids'] = np.arange(self.n_cells)
alg = _vtk.vtkBoxClipDataSet()
if not merge_points:
# vtkBoxClipDataSet uses vtkMergePoints by default
alg.SetLocator(_vtk.vtkNonMergingPointLocator())
alg.SetInputDataObject(self)
alg.SetBoxClip(*bounds)
port = 0
if invert:
# invert the clip if needed
port = 1
alg.GenerateClippedOutputOn()
_update_alg(alg, progress_bar, 'Clipping a Dataset by a Bounding Box')
clipped = _get_output(alg, oport=port)
if crinkle:
clipped = self.extract_cells(np.unique(clipped.cell_data['cell_ids']))
return clipped
def compute_implicit_distance(self, surface, inplace=False):
"""Compute the implicit distance from the points to a surface.
This filter will compute the implicit distance from all of the
nodes of this mesh to a given surface. This distance will be
added as a point array called ``'implicit_distance'``.
Parameters
----------
surface : pyvista.DataSet
The surface used to compute the distance.
inplace : bool, optional
If ``True``, a new scalar array will be added to the
``point_data`` of this mesh and the modified mesh will
be returned. Otherwise a copy of this mesh is returned
with that scalar field added.
Returns
-------
pyvista.DataSet
Dataset containing the ``'implicit_distance'`` array in
``point_data``.
Examples
--------
Compute the distance between all the points on a sphere and a
plane.
>>> import pyvista as pv
>>> sphere = pv.Sphere()
>>> plane = pv.Plane()
>>> _ = sphere.compute_implicit_distance(plane, inplace=True)
>>> dist = sphere['implicit_distance']
>>> type(dist)
<class 'pyvista.core.pyvista_ndarray.pyvista_ndarray'>
Plot these distances as a heatmap
>>> pl = pv.Plotter()
>>> _ = pl.add_mesh(sphere, scalars='implicit_distance', cmap='bwr')
>>> _ = pl.add_mesh(plane, color='w', style='wireframe')
>>> pl.show()
See :ref:`clip_with_surface_example` and
:ref:`voxelize_surface_mesh_example` for more examples using
this filter.
"""
function = _vtk.vtkImplicitPolyDataDistance()
function.SetInput(surface)
points = pyvista.convert_array(self.points)
dists = _vtk.vtkDoubleArray()
function.FunctionValue(points, dists)
if inplace:
self.point_data['implicit_distance'] = pyvista.convert_array(dists)
return self
result = self.copy()
result.point_data['implicit_distance'] = pyvista.convert_array(dists)
return result
def clip_scalar(
self, scalars=None, invert=True, value=0.0, inplace=False, progress_bar=False, both=False
):
"""Clip a dataset by a scalar.
Parameters
----------
scalars : str, optional
Name of scalars to clip on. Defaults to currently active scalars.
invert : bool, optional
Flag on whether to flip/invert the clip. When ``True``,
only the mesh below ``value`` will be kept. When
``False``, only values above ``value`` will be kept.
value : float, optional
Set the clipping value. The default value is 0.0.
inplace : bool, optional
Update mesh in-place.
progress_bar : bool, optional
Display a progress bar to indicate progress.
both : bool, optional
If ``True``, also returns the complementary clipped mesh.
Returns
-------
pyvista.PolyData or tuple
Clipped dataset if ``both=False``. If ``both=True`` then
returns a tuple of both clipped datasets.
Examples
--------
Remove the part of the mesh with "sample_point_scalars" above 100.
>>> import pyvista as pv
>>> from pyvista import examples
>>> dataset = examples.load_hexbeam()
>>> clipped = dataset.clip_scalar(scalars="sample_point_scalars", value=100)
>>> clipped.plot()
Get clipped meshes corresponding to the portions of the mesh above and below 100.
>>> import pyvista as pv
>>> from pyvista import examples
>>> dataset = examples.load_hexbeam()
>>> _below, _above = dataset.clip_scalar(scalars="sample_point_scalars", value=100, both=True)
Remove the part of the mesh with "sample_point_scalars" below 100.
>>> import pyvista as pv
>>> from pyvista import examples
>>> dataset = examples.load_hexbeam()
>>> clipped = dataset.clip_scalar(scalars="sample_point_scalars", value=100, invert=False)
>>> clipped.plot()
"""
if isinstance(self, _vtk.vtkPolyData):
alg = _vtk.vtkClipPolyData()
else:
alg = _vtk.vtkTableBasedClipDataSet()
alg.SetInputDataObject(self)
alg.SetValue(value)
if scalars is None:
pyvista.set_default_active_scalars(self)
else:
self.set_active_scalars(scalars)
alg.SetInsideOut(invert) # invert the clip if needed
alg.SetGenerateClippedOutput(both)
_update_alg(alg, progress_bar, 'Clipping by a Scalar')
result0 = _get_output(alg)
if inplace:
self.copy_from(result0, deep=False)
result0 = self
if both:
result1 = _get_output(alg, oport=1)
if isinstance(self, _vtk.vtkPolyData):
# For some reason vtkClipPolyData with SetGenerateClippedOutput on leaves unreferenced vertices
result0, result1 = (r.clean() for r in (result0, result1))
return result0, result1
return result0
def clip_surface(
self,
surface,
invert=True,
value=0.0,
compute_distance=False,
progress_bar=False,
crinkle=False,
):
"""Clip any mesh type using a :class:`pyvista.PolyData` surface mesh.
This will return a :class:`pyvista.UnstructuredGrid` of the clipped
mesh. Geometry of the input dataset will be preserved where possible.
Geometries near the clip intersection will be triangulated/tessellated.
Parameters
----------
surface : pyvista.PolyData
The ``PolyData`` surface mesh to use as a clipping
function. If this input mesh is not a :class`pyvista.PolyData`,
the external surface will be extracted.
invert : bool, optional
Flag on whether to flip/invert the clip.
value : float, optional
Set the clipping value of the implicit function (if
clipping with implicit function) or scalar value (if
clipping with scalars). The default value is 0.0.
compute_distance : bool, optional
Compute the implicit distance from the mesh onto the input
dataset. A new array called ``'implicit_distance'`` will
be added to the output clipped mesh.
progress_bar : bool, optional
Display a progress bar to indicate progress.
crinkle : bool, optional
Crinkle the clip by extracting the entire cells along the
clip. This adds the ``"cell_ids"`` array to the ``cell_data``
attribute that tracks the original cell IDs of the original
dataset.
Returns
-------
pyvista.PolyData
Clipped surface.
Examples
--------
Clip a cube with a sphere.
>>> import pyvista
>>> sphere = pyvista.Sphere(center=(-0.4, -0.4, -0.4))
>>> cube = pyvista.Cube().triangulate().subdivide(3)
>>> clipped = cube.clip_surface(sphere)
>>> clipped.plot(show_edges=True, cpos='xy', line_width=3)
See :ref:`clip_with_surface_example` for more examples using
this filter.
"""
if not isinstance(surface, _vtk.vtkPolyData):
surface = DataSetFilters.extract_geometry(surface)
function = _vtk.vtkImplicitPolyDataDistance()
function.SetInput(surface)
if compute_distance:
points = pyvista.convert_array(self.points)
dists = _vtk.vtkDoubleArray()
function.FunctionValue(points, dists)
self['implicit_distance'] = pyvista.convert_array(dists)
# run the clip
result = DataSetFilters._clip_with_function(
self,
function,
invert=invert,
value=value,
progress_bar=progress_bar,
crinkle=crinkle,
)
return result
def slice_implicit(
self, implicit_function, generate_triangles=False, contour=False, progress_bar=False
):
"""Slice a dataset by a VTK implicit function.
Parameters
----------
implicit_function : vtk.vtkImplicitFunction
Specify the implicit function to perform the cutting.
generate_triangles : bool, default: False
If this is enabled (``False`` by default), the output will
be triangles. Otherwise the output will be the intersection
polygons. If the cutting function is not a plane, the
output will be 3D polygons, which might be nice to look at
but hard to compute with downstream.
contour : bool, default: False
If ``True``, apply a ``contour`` filter after slicing.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Sliced dataset.
Examples
--------
Slice the surface of a sphere.
>>> import pyvista as pv
>>> import vtk
>>> sphere = vtk.vtkSphere()
>>> sphere.SetRadius(10)
>>> mesh = pv.Wavelet()
>>> slice = mesh.slice_implicit(sphere)
>>> slice.plot(show_edges=True, line_width=5)
>>> sphere = vtk.vtkCylinder()
>>> sphere.SetRadius(10)
>>> mesh = pv.Wavelet()
>>> slice = mesh.slice_implicit(sphere)
>>> slice.plot(show_edges=True, line_width=5)
"""
alg = _vtk.vtkCutter() # Construct the cutter object
alg.SetInputDataObject(self) # Use the grid as the data we desire to cut
alg.SetCutFunction(implicit_function) # the cutter to use the function
alg.SetGenerateTriangles(generate_triangles)
_update_alg(alg, progress_bar, 'Slicing')
output = _get_output(alg)
if contour:
return output.contour()
return output
def slice(
self, normal='x', origin=None, generate_triangles=False, contour=False, progress_bar=False
):
"""Slice a dataset by a plane at the specified origin and normal vector orientation.
If no origin is specified, the center of the input dataset will be used.
Parameters
----------
normal : tuple(float) or str, default: 'x'
Length 3 tuple for the normal vector direction. Can also be
specified as a string conventional direction such as ``'x'`` for
``(1, 0, 0)`` or ``'-x'`` for ``(-1, 0, 0)``, etc.
origin : tuple(float), optional
The center ``(x, y, z)`` coordinate of the plane on which
the slice occurs.
generate_triangles : bool, optional
If this is enabled (``False`` by default), the output will
be triangles. Otherwise the output will be the intersection
polygons.
contour : bool, optional
If ``True``, apply a ``contour`` filter after slicing.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Sliced dataset.
Examples
--------
Slice the surface of a sphere.
>>> import pyvista
>>> sphere = pyvista.Sphere()
>>> slice_x = sphere.slice(normal='x')
>>> slice_y = sphere.slice(normal='y')
>>> slice_z = sphere.slice(normal='z')
>>> slices = slice_x + slice_y + slice_z
>>> slices.plot(line_width=5)
See :ref:`slice_example` for more examples using this filter.
"""
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = self.center
# create the plane for clipping
plane = generate_plane(normal, origin)
return DataSetFilters.slice_implicit(
self,
plane,
generate_triangles=generate_triangles,
contour=contour,
progress_bar=progress_bar,
)
def slice_orthogonal(
self, x=None, y=None, z=None, generate_triangles=False, contour=False, progress_bar=False
):
"""Create three orthogonal slices through the dataset on the three cartesian planes.
Yields a MutliBlock dataset of the three slices.
Parameters
----------
x : float, optional
The X location of the YZ slice.
y : float, optional
The Y location of the XZ slice.
z : float, optional
The Z location of the XY slice.
generate_triangles : bool, optional
If this is enabled (``False`` by default), the output will
be triangles. Otherwise the output will be the intersection
polygons.
contour : bool, optional
If ``True``, apply a ``contour`` filter after slicing.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Sliced dataset.
Examples
--------
Slice the random hills dataset with three orthogonal planes.
>>> from pyvista import examples
>>> hills = examples.load_random_hills()
>>> slices = hills.slice_orthogonal(contour=False)
>>> slices.plot(line_width=5)
See :ref:`slice_example` for more examples using this filter.
"""
# Create the three slices
if x is None:
x = self.center[0]
if y is None:
y = self.center[1]
if z is None:
z = self.center[2]
output = pyvista.MultiBlock()
if isinstance(self, pyvista.MultiBlock):
for i in range(self.n_blocks):
output.append(
self[i].slice_orthogonal(
x=x, y=y, z=z, generate_triangles=generate_triangles, contour=contour
)
)
return output
output.append(
self.slice(
normal='x',
origin=[x, y, z],
generate_triangles=generate_triangles,
progress_bar=progress_bar,
),
'YZ',
)
output.append(
self.slice(
normal='y',
origin=[x, y, z],
generate_triangles=generate_triangles,
progress_bar=progress_bar,
),
'XZ',
)
output.append(
self.slice(
normal='z',
origin=[x, y, z],
generate_triangles=generate_triangles,
progress_bar=progress_bar,
),
'XY',
)
return output
def slice_along_axis(
self,
n=5,
axis='x',
tolerance=None,
generate_triangles=False,
contour=False,
bounds=None,
center=None,
progress_bar=False,
):
"""Create many slices of the input dataset along a specified axis.
Parameters
----------
n : int, optional
The number of slices to create.
axis : str or int, default: 'x'
The axis to generate the slices along. Perpendicular to the
slices. Can be string name (``'x'``, ``'y'``, or ``'z'``) or
axis index (``0``, ``1``, or ``2``).
tolerance : float, optional
The tolerance to the edge of the dataset bounds to create
the slices. The ``n`` slices are placed equidistantly with
an absolute padding of ``tolerance`` inside each side of the
``bounds`` along the specified axis. Defaults to 1% of the
``bounds`` along the specified axis.
generate_triangles : bool, optional
If this is enabled (``False`` by default), the output will
be triangles. Otherwise the output will be the intersection
polygons.
contour : bool, optional
If ``True``, apply a ``contour`` filter after slicing.
bounds : sequence, optional
A 6-length sequence overriding the bounds of the mesh.
The bounds along the specified axis define the extent
where slices are taken.
center : sequence, optional
A 3-length sequence specifying the position of the line
along which slices are taken. Defaults to the center of
the mesh.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Sliced dataset.
Examples
--------
Slice the random hills dataset in the X direction.
>>> from pyvista import examples
>>> hills = examples.load_random_hills()
>>> slices = hills.slice_along_axis(n=10)
>>> slices.plot(line_width=5)
Slice the random hills dataset in the Z direction.
>>> from pyvista import examples
>>> hills = examples.load_random_hills()
>>> slices = hills.slice_along_axis(n=10, axis='z')
>>> slices.plot(line_width=5)
See :ref:`slice_example` for more examples using this filter.
"""
# parse axis input
labels = ['x', 'y', 'z']
label_to_index = {label: index for index, label in enumerate(labels)}
if isinstance(axis, int):
ax_index = axis
ax_label = labels[ax_index]
elif isinstance(axis, str):
try:
ax_index = label_to_index[axis.lower()]
except KeyError:
raise ValueError(
f'Axis ({axis!r}) not understood. Choose one of {labels}.'
) from None
ax_label = axis
# get the locations along that axis
if bounds is None:
bounds = self.bounds
if center is None:
center = self.center
if tolerance is None:
tolerance = (bounds[ax_index * 2 + 1] - bounds[ax_index * 2]) * 0.01
rng = np.linspace(bounds[ax_index * 2] + tolerance, bounds[ax_index * 2 + 1] - tolerance, n)
center = list(center)
# Make each of the slices
output = pyvista.MultiBlock()
if isinstance(self, pyvista.MultiBlock):
for i in range(self.n_blocks):
output.append(
self[i].slice_along_axis(
n=n,
axis=ax_label,
tolerance=tolerance,
generate_triangles=generate_triangles,
contour=contour,
bounds=bounds,
center=center,
)
)
return output
for i in range(n):
center[ax_index] = rng[i]
slc = DataSetFilters.slice(
self,
normal=ax_label,
origin=center,
generate_triangles=generate_triangles,
contour=contour,
progress_bar=progress_bar,
)
output.append(slc, f'slice{i}')
return output
def slice_along_line(self, line, generate_triangles=False, contour=False, progress_bar=False):
"""Slice a dataset using a polyline/spline as the path.
This also works for lines generated with :func:`pyvista.Line`.
Parameters
----------
line : pyvista.PolyData
A PolyData object containing one single PolyLine cell.
generate_triangles : bool, optional
If this is enabled (``False`` by default), the output will
be triangles. Otherwise the output will be the intersection
polygons.
contour : bool, optional
If ``True``, apply a ``contour`` filter after slicing.
progress_bar : bool, optional
Display a progress bar to indicate progress.
Returns
-------
pyvista.PolyData
Sliced dataset.
Examples
--------
Slice the random hills dataset along a circular arc.
>>> import numpy as np
>>> import pyvista
>>> from pyvista import examples
>>> hills = examples.load_random_hills()
>>> center = np.array(hills.center)
>>> point_a = center + np.array([5, 0, 0])
>>> point_b = center + np.array([-5, 0, 0])
>>> arc = pyvista.CircularArc(point_a, point_b, center, resolution=100)
>>> line_slice = hills.slice_along_line(arc)
Plot the circular arc and the hills mesh.
>>> pl = pyvista.Plotter()
>>> _ = pl.add_mesh(hills, smooth_shading=True, style='wireframe')
>>> _ = pl.add_mesh(line_slice, line_width=10, render_lines_as_tubes=True,
... color='k')
>>> _ = pl.add_mesh(arc, line_width=10, color='grey')
>>> pl.show()
See :ref:`slice_example` for more examples using this filter.
"""
# check that we have a PolyLine cell in the input line
if line.GetNumberOfCells() != 1:
raise ValueError('Input line must have only one cell.')
polyline = line.GetCell(0)
if not isinstance(polyline, _vtk.vtkPolyLine):
raise TypeError(f'Input line must have a PolyLine cell, not ({type(polyline)})')
# Generate PolyPlane
polyplane = _vtk.vtkPolyPlane()
polyplane.SetPolyLine(polyline)
# Create slice
alg = _vtk.vtkCutter() # Construct the cutter object
alg.SetInputDataObject(self) # Use the grid as the data we desire to cut
alg.SetCutFunction(polyplane) # the cutter to use the poly planes
if not generate_triangles:
alg.GenerateTrianglesOff()
_update_alg(alg, progress_bar, 'Slicing along Line')
output = _get_output(alg)
if contour:
return output.contour()
return output
def threshold(
self,
value=None,
scalars=None,
invert=False,
continuous=False,
preference='cell',
all_scalars=False,
component_mode='all',
component=0,
method='upper',
progress_bar=False,
):
"""Apply a ``vtkThreshold`` filter to the input dataset.
This filter will apply a ``vtkThreshold`` filter to the input
dataset and return the resulting object. This extracts cells
where the scalar value in each cell satisfies the threshold
criterion. If ``scalars`` is ``None``, the input's active
scalars array is used.
.. warning::
Thresholding is inherently a cell operation, even though it can use
associated point data for determining whether to keep a cell. In
other words, whether or not a given point is included after
thresholding depends on whether that point is part of a cell that
is kept after thresholding.
Please also note the default ``preference`` choice for CELL data
over POINT data. This is contrary to most other places in PyVista's
API where the preference typically defaults to POINT data. We chose
to prefer CELL data here so that if thresholding by a named array
that exists for both the POINT and CELL data, this filter will
default to the CELL data array while performing the CELL-wise
operation.
Parameters
----------
value : float or sequence, optional
Single value or (min, max) to be used for the data threshold. If
a sequence, then length must be 2. If no value is specified, the
non-NaN data range will be used to remove any NaN values.
Please reference the ``method`` parameter for how single values
are handled.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
invert : bool, default: False
Invert the threshold results. That is, cells that would have been
in the output with this option off are excluded, while cells that
would have been excluded from the output are included.
.. warning::
This option is only supported for VTK version 9+
continuous : bool, default: False
When True, the continuous interval [minimum cell scalar,
maximum cell scalar] will be used to intersect the threshold bound,
rather than the set of discrete scalar values from the vertices.
preference : str, default: 'cell'
When ``scalars`` is specified, this is the preferred array
type to search for in the dataset. Must be either
``'point'`` or ``'cell'``. Throughout PyVista, the preference
is typically ``'point'`` but since the threshold filter is a
cell-wise operation, we prefer cell data for thresholding
operations.