Debian Codegraph @

pyvista/plotting/utilities/algorithms.py

raw
1 """Internal :vtk:`vtkAlgorithm` support helpers."""
2
3 from __future__ import annotations
4
5 import traceback
6 from typing import TYPE_CHECKING
7
8 import numpy as np
9
10 import pyvista as pv
11 from pyvista import _vtk
12 from pyvista._deprecate_positional_args import _deprecate_positional_args
13 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
14 from pyvista.core.errors import PyVistaPipelineError
15 from pyvista.core.utilities.helpers import wrap
16 from pyvista.core.utilities.misc import _NoNewAttrMixin
17
18 if TYPE_CHECKING:
19 from collections.abc import Callable
20
21 from pyvista import DataSet
22 from pyvista.core.utilities.arrays import CellLiteral
23 from pyvista.core.utilities.arrays import PointLiteral
24
25
26 def algorithm_to_mesh_handler(
27 mesh_or_algo, port=0
28 ) -> tuple[DataSet, _vtk.vtkAlgorithm | _vtk.vtkAlgorithmOutput | None]:
29 """Handle :vtk:`vtkAlgorithm` where mesh objects are expected.
30
31 This is a convenience method to handle :vtk:`vtkAlgorithm` when passed to methods
32 that expect a :class:`~pyvista.DataSet`. This method will check if the passed
33 object is a :vtk:`vtkAlgorithm` or :vtk:`vtkAlgorithmOutput` and if so,
34 return that algorithm's output dataset (mesh) as the mesh to be used by the
35 calling function.
36
37 Parameters
38 ----------
39 mesh_or_algo : DataSet | :vtk:`vtkAlgorithm` | :vtk:`vtkAlgorithmOutput`
40 The input to be used as a data set (mesh) or :vtk:`vtkAlgorithm` object.
41
42 port : int, default: 0
43 If the input (``mesh_or_algo``) is an algorithm, this specifies which output
44 port to use on that algorithm for the returned mesh.
45
46 Returns
47 -------
48 mesh : pyvista.DataSet
49 The resulting mesh data set from the input.
50
51 algorithm : :vtk:`vtkAlgorithm` | :vtk:`vtkAlgorithmOutput` | None
52 If an algorithm is passed, it will be returned. Otherwise returns ``None``.
53
54 """
55 if isinstance(mesh_or_algo, (_vtk.vtkAlgorithm, _vtk.vtkAlgorithmOutput)):
56 if isinstance(mesh_or_algo, _vtk.vtkAlgorithmOutput):
57 algo = mesh_or_algo.GetProducer()
58 # If vtkAlgorithmOutput, override port argument
59 port = mesh_or_algo.GetIndex()
60 output = mesh_or_algo
61 else:
62 algo = mesh_or_algo
63 output = algo.GetOutputPort(port)
64 algo.Update() # NOTE: this could be expensive... but we need it to get the mesh
65 # for legacy implementation. This can be refactored.
66 mesh = wrap(algo.GetOutputDataObject(port))
67 if mesh is None:
68 # This is known to happen with vtkPointSet and VTKPythonAlgorithmBase
69 # see workaround in PreserveTypeAlgorithmBase.
70 # This check remains as a fail-safe.
71 msg = 'The passed algorithm is failing to produce an output.' # type: ignore[unreachable]
72 raise PyVistaPipelineError(msg)
73 # NOTE: Return the vtkAlgorithmOutput only if port is non-zero. Segfaults can sometimes
74 # happen with vtkAlgorithmOutput. This logic will mostly avoid those issues.
75 # See https://gitlab.kitware.com/vtk/vtk/-/issues/18776
76 return mesh, output if port != 0 else algo
77 return mesh_or_algo, None
78
79
80 def set_algorithm_input(alg, inp, port=0):
81 """Set the input to a :vtk:`vtkAlgorithm`.
82
83 Parameters
84 ----------
85 alg : :vtk:`vtkAlgorithm`
86 The algorithm whose input is being set.
87
88 inp : :vtk:`vtkAlgorithm` | :vtk:`vtkAlgorithmOutput` | :vtk:`vtkDataObject`
89 The input to the algorithm.
90
91 port : int, default: 0
92 The input port.
93
94 """
95 if isinstance(inp, _vtk.vtkAlgorithm):
96 alg.SetInputConnection(port, inp.GetOutputPort())
97 elif isinstance(inp, _vtk.vtkAlgorithmOutput):
98 alg.SetInputConnection(port, inp)
99 else:
100 alg.SetInputDataObject(port, inp)
101
102
103 class PreserveTypeAlgorithmBase(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.VTKPythonAlgorithmBase):
104 """Base algorithm to preserve type.
105
106 Parameters
107 ----------
108 nInputPorts : int, default: 1
109 Number of input ports for the algorithm.
110
111 nOutputPorts : int, default: 1
112 Number of output ports for the algorithm.
113
114 """
115
116 def __init__(self, nInputPorts=1, nOutputPorts=1):
117 """Initialize algorithm."""
118 _vtk.VTKPythonAlgorithmBase.__init__(
119 self,
120 nInputPorts=nInputPorts,
121 nOutputPorts=nOutputPorts,
122 )
123
124 def GetInputData(self, inInfo, port, idx):
125 """Get input data object.
126
127 This will convert :vtk:`vtkPointSet` to :vtk:`vtkPolyData`.
128
129 Parameters
130 ----------
131 inInfo : :vtk:`vtkInformation`
132 The information object associated with the input port.
133
134 port : int
135 The index of the input port.
136
137 idx : int
138 The index of the data object within the input port.
139
140 Returns
141 -------
142 :vtk:`vtkDataObject`
143 The input data object.
144
145 """
146 inp = wrap(_vtk.VTKPythonAlgorithmBase.GetInputData(self, inInfo, port, idx))
147 if isinstance(inp, pv.PointSet):
148 return inp.cast_to_polydata()
149 return inp
150
151 # THIS IS CRUCIAL to preserve data type through filter
152 def RequestDataObject(self, _request, inInfo, outInfo) -> int:
153 """Preserve data type.
154
155 Parameters
156 ----------
157 _request : :vtk:`vtkInformation`
158 The request object for the filter.
159
160 inInfo : :vtk:`vtkInformationVector`
161 The input information vector for the filter.
162
163 outInfo : :vtk:`vtkInformationVector`
164 The output information vector for the filter.
165
166 Returns
167 -------
168 int
169 Returns 1 if successful.
170
171 """
172 class_name = self.GetInputData(inInfo, 0, 0).GetClassName()
173 if class_name == 'vtkPointSet':
174 # See https://gitlab.kitware.com/vtk/vtk/-/issues/18771
175 self.OutputType = 'vtkPolyData'
176 else:
177 self.OutputType = class_name
178 self.FillOutputPortInformation(0, outInfo.GetInformationObject(0))
179 return 1
180
181
182 class SourceAlgorithm(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.VTKPythonAlgorithmBase):
183 """Algorithm that generates data from a callable with no input.
184
185 The callable is invoked on each :meth:`RequestData` and must return a
186 :class:`~pyvista.DataSet`.
187
188 Parameters
189 ----------
190 generator : callable
191 ``generator() -> dataset``. Called each time the pipeline requests
192 data.
193
194 output_type : str | type[pyvista.DataSet], default: :class:`pyvista.UnstructuredGrid`
195 Output type. Accepts a VTK class name string (e.g.
196 ``'vtkPolyData'``) or a PyVista :class:`~pyvista.DataSet` subclass
197 (e.g. :class:`pyvista.PolyData`).
198
199 """
200
201 def __init__(
202 self,
203 generator: Callable[[], DataSet],
204 output_type: str | type = pv.UnstructuredGrid,
205 ):
206 """Initialize algorithm."""
207 _vtk.VTKPythonAlgorithmBase.__init__(
208 self,
209 nInputPorts=0,
210 nOutputPorts=1,
211 outputType=(
212 output_type if isinstance(output_type, str) else output_type().GetClassName()
213 ),
214 )
215 self._generator = generator
216
217 def RequestData(self, _request, _inInfo, outInfo) -> int:
218 """Perform algorithm execution.
219
220 Parameters
221 ----------
222 _request : :vtk:`vtkInformation`
223 The request object.
224 _inInfo : :vtk:`vtkInformationVector`
225 Information about the input data. Unused; this algorithm has no input ports.
226 outInfo : :vtk:`vtkInformationVector`
227 Information about the output data.
228
229 Returns
230 -------
231 int
232 1 on success.
233
234 """
235 try:
236 out = self.GetOutputData(outInfo, 0)
237 out.ShallowCopy(self._generator())
238 except Exception: # pragma: no cover
239 traceback.print_exc()
240 raise
241 return 1
242
243
244 class CallbackFilterAlgorithm(PreserveTypeAlgorithmBase):
245 """Algorithm that delegates processing to a user-supplied callable.
246
247 The callable receives a :class:`~pyvista.DataSet` (the wrapped input) and
248 must return a :class:`~pyvista.DataSet` of the appropriate type.
249
250 By default the output type is preserved from the input (via
251 :class:`PreserveTypeAlgorithmBase`). Pass ``output_type`` to override.
252
253 Parameters
254 ----------
255 callback : callable
256 ``callback(dataset) -> dataset``. Called on each
257 :meth:`RequestData` invocation with the wrapped input.
258
259 output_type : str | type[pyvista.DataSet] | None, default: ``None``
260 Fixed output type. Accepts a VTK class name string (e.g.
261 ``'vtkPolyData'``) or a PyVista :class:`~pyvista.DataSet` subclass
262 (e.g. :class:`pyvista.PolyData`). When ``None``, the output type is
263 inferred from the input.
264
265 nInputPorts : int, default: 1
266 Number of input ports.
267
268 nOutputPorts : int, default: 1
269 Number of output ports.
270
271 """
272
273 def __init__( # noqa: PLR0917
274 self,
275 callback: Callable[[DataSet], DataSet],
276 output_type: str | type | None = None,
277 nInputPorts: int = 1,
278 nOutputPorts: int = 1,
279 ):
280 """Initialize algorithm."""
281 self._fixed_output_type: str | None = (
282 None
283 if output_type is None
284 else output_type
285 if isinstance(output_type, str)
286 else output_type().GetClassName()
287 )
288 if self._fixed_output_type is not None:
289 _vtk.VTKPythonAlgorithmBase.__init__(
290 self,
291 nInputPorts=nInputPorts,
292 nOutputPorts=nOutputPorts,
293 outputType=self._fixed_output_type,
294 )
295 else:
296 super().__init__(nInputPorts=nInputPorts, nOutputPorts=nOutputPorts)
297 self._callback = callback
298
299 def RequestDataObject(self, _request, inInfo, outInfo) -> int:
300 """Preserve or override data type.
301
302 Parameters
303 ----------
304 _request : :vtk:`vtkInformation`
305 The request object for the filter.
306 inInfo : :vtk:`vtkInformationVector`
307 The input information vector for the filter.
308 outInfo : :vtk:`vtkInformationVector`
309 The output information vector for the filter.
310
311 Returns
312 -------
313 int
314 Returns 1 if successful.
315
316 """
317 if self._fixed_output_type is not None:
318 return 1
319 return super().RequestDataObject(_request, inInfo, outInfo)
320
321 def RequestData(self, _request, inInfo, outInfo) -> int:
322 """Perform algorithm execution.
323
324 Parameters
325 ----------
326 _request : :vtk:`vtkInformation`
327 The request object.
328 inInfo : :vtk:`vtkInformationVector`
329 Information about the input data.
330 outInfo : :vtk:`vtkInformationVector`
331 Information about the output data.
332
333 Returns
334 -------
335 int
336 1 on success.
337
338 """
339 try:
340 inp = self.GetInputData(inInfo, 0, 0)
341 out = self.GetOutputData(outInfo, 0)
342 result = self._callback(wrap(inp))
343 out.ShallowCopy(result)
344 except Exception: # pragma: no cover
345 traceback.print_exc()
346 raise
347 return 1
348
349
350 class ActiveScalarsAlgorithm(PreserveTypeAlgorithmBase):
351 """Algorithm to control active scalars.
352
353 The output of this filter is a shallow copy of the input data
354 set with the active scalars set as specified.
355
356 Parameters
357 ----------
358 name : str
359 Name of scalars used to set as active on the output mesh.
360 Accepts a string name of an array that is present on the mesh.
361 Array should be sized as a single vector.
362
363 preference : str, default: 'point'
364 When ``mesh.n_points == mesh.n_cells`` and setting
365 scalars, this parameter sets how the scalars will be
366 mapped to the mesh. The default, ``'point'``, causes the
367 scalars to be associated with the mesh points. Can be
368 either ``'point'`` or ``'cell'``.
369
370 """
371
372 def __init__(self, name: str, preference: PointLiteral | CellLiteral = 'point'):
373 """Initialize algorithm."""
374 super().__init__()
375 self._scalars_name = name
376 self._preference: PointLiteral | CellLiteral = preference
377
378 @property
379 def scalars_name(self) -> str: # numpydoc ignore=RT01
380 """Return or set the name of the active scalars array."""
381 return self._scalars_name
382
383 @scalars_name.setter
384 def scalars_name(self, name: str) -> None:
385 if name != self._scalars_name:
386 self._scalars_name = name
387 self.Modified()
388
389 @property
390 def preference(self) -> PointLiteral | CellLiteral: # numpydoc ignore=RT01
391 """Return or set the preferred field association (``'point'`` or ``'cell'``)."""
392 return self._preference
393
394 @preference.setter
395 def preference(self, preference: PointLiteral | CellLiteral) -> None:
396 if preference != self._preference:
397 self._preference = preference
398 self.Modified()
399
400 def RequestData(self, _request, inInfo, outInfo) -> int:
401 """Perform algorithm execution.
402
403 Parameters
404 ----------
405 _request : :vtk:`vtkInformation`
406 The request object.
407 inInfo : :vtk:`vtkInformationVector`
408 Information about the input data.
409 outInfo : :vtk:`vtkInformationVector`
410 Information about the output data.
411
412 Returns
413 -------
414 int
415 1 on success.
416
417 """
418 try:
419 inp = self.GetInputData(inInfo, 0, 0)
420 out = self.GetOutputData(outInfo, 0)
421 out.ShallowCopy(inp)
422 # Set active scalars directly via VTK API on the output object.
423 # Using wrap(out) would create a new VTK object rather than
424 # wrapping the existing one, so changes would be lost.
425 if self.preference == 'cell':
426 out.GetCellData().SetActiveScalars(self.scalars_name)
427 else:
428 out.GetPointData().SetActiveScalars(self.scalars_name)
429 except Exception: # pragma: no cover
430 traceback.print_exc()
431 raise
432 return 1
433
434
435 class SmoothShadingAlgorithm(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.VTKPythonAlgorithmBase):
436 """Algorithm to compute point normals for smooth shading.
437
438 The output is always a :vtk:`vtkPolyData`. Non-polydata inputs have their
439 external surface extracted first. Normals are computed via
440 :meth:`~pyvista.PolyDataFilters.compute_normals`, with ``split_vertices``
441 controlled by ``split_sharp_edges`` to get crisp edges at feature-angle
442 boundaries.
443
444 The output carries a ``vtkOriginalPointIds`` point-data array that maps
445 each output point back to its index in the original input mesh. Callers
446 that need to remap input-length arrays onto the (potentially longer)
447 output topology (for example raw numpy scalars passed to ``add_mesh``)
448 can do so via this tracker.
449
450 Parameters
451 ----------
452 split_sharp_edges : bool, default: False
453 Whether to use feature-angle splitting when computing normals.
454 When ``True``, shared vertices on sharp edges are duplicated so
455 each face has its own normal, producing crisp feature lines.
456
457 feature_angle : float, default: 30.0
458 Angle (in degrees) above which an edge is considered sharp. Only
459 used when ``split_sharp_edges`` is ``True``.
460
461 """
462
463 ORIGINAL_POINT_IDS_NAME = 'vtkOriginalPointIds'
464
465 @_deprecate_positional_args
466 def __init__(
467 self,
468 split_sharp_edges: bool = False, # noqa: FBT001, FBT002
469 feature_angle: float = 30.0,
470 ):
471 """Initialize algorithm."""
472 _vtk.VTKPythonAlgorithmBase.__init__(
473 self,
474 nInputPorts=1,
475 nOutputPorts=1,
476 outputType='vtkPolyData',
477 )
478 self._split_sharp_edges = split_sharp_edges
479 self._feature_angle = feature_angle
480
481 @property
482 def split_sharp_edges(self) -> bool: # numpydoc ignore=RT01
483 """Return or set whether to split sharp edges when computing normals."""
484 return self._split_sharp_edges
485
486 @split_sharp_edges.setter
487 def split_sharp_edges(self, value: bool) -> None:
488 if value != self._split_sharp_edges:
489 self._split_sharp_edges = value
490 self.Modified()
491
492 @property
493 def feature_angle(self) -> float: # numpydoc ignore=RT01
494 """Return or set the feature angle (degrees) for splitting sharp edges."""
495 return self._feature_angle
496
497 @feature_angle.setter
498 def feature_angle(self, value: float) -> None:
499 if value != self._feature_angle:
500 self._feature_angle = value
501 self.Modified()
502
503 def RequestData(self, _request, inInfo, outInfo) -> int:
504 """Perform algorithm execution.
505
506 Parameters
507 ----------
508 _request : :vtk:`vtkInformation`
509 The request object.
510 inInfo : :vtk:`vtkInformationVector`
511 Information about the input data.
512 outInfo : :vtk:`vtkInformationVector`
513 Information about the output data.
514
515 Returns
516 -------
517 int
518 1 on success.
519
520 """
521 try:
522 inp = self.GetInputData(inInfo, 0, 0)
523 out = self.GetOutputData(outInfo, 0)
524
525 wrapped = wrap(inp)
526 if isinstance(wrapped, pv.PointSet):
527 wrapped = wrapped.cast_to_polydata()
528
529 if not isinstance(wrapped, pv.DataSet) or wrapped.n_points == 0:
530 return 1
531
532 # Respect user-provided point normals on a polydata input when no
533 # splitting is requested: pass the input through unchanged so the
534 # custom normals survive. Splitting always re-runs compute_normals
535 # because it needs to know which points to duplicate.
536 # No ``vtkOriginalPointIds`` tracker is needed here because the
537 # topology is unchanged (n_points stays the same).
538 if (
539 isinstance(wrapped, pv.PolyData)
540 and not self._split_sharp_edges
541 and wrapped.point_data.active_normals is not None
542 ):
543 out.ShallowCopy(wrapped)
544 return 1
545
546 # Extract the external surface when the input is not polydata.
547 # ``pass_pointid=True`` attaches ``vtkOriginalPointIds`` that maps
548 # each surface point back to its index in the input mesh. For
549 # polydata inputs we install an identity tracker on a shallow
550 # copy so that compute_normals(split_vertices=True) will split
551 # it alongside the points, giving us a chained mapping for free.
552 if isinstance(wrapped, pv.PolyData):
553 surface = wrapped.copy(deep=False)
554 surface.point_data[self.ORIGINAL_POINT_IDS_NAME] = np.arange(
555 surface.n_points, dtype=pv.ID_TYPE
556 )
557 else:
558 surface = wrapped.extract_surface(
559 algorithm=None,
560 pass_pointid=True,
561 pass_cellid=True,
562 )
563 if surface.n_points == 0:
564 out.ShallowCopy(surface)
565 return 1
566
567 # ``compute_normals`` raises TypeError when the surface has no
568 # polygonal cells (point clouds, lines). Pre-check and pass the
569 # surface through so downstream stages still see a valid
570 # polydata, without coupling to the upstream error message.
571 if surface.n_verts + surface.n_lines == surface.n_cells:
572 out.ShallowCopy(surface)
573 return 1
574
575 result = surface.compute_normals(
576 cell_normals=False,
577 split_vertices=self._split_sharp_edges,
578 feature_angle=self._feature_angle,
579 )
580
581 # ``compute_normals(split_vertices=True)`` leaves behind a
582 # ``pyvistaOriginalPointIds`` helper array that mirrors our own
583 # ``vtkOriginalPointIds``. Drop it so downstream code isn't
584 # surprised by the duplicate tracker.
585 if 'pyvistaOriginalPointIds' in result.point_data:
586 del result.point_data['pyvistaOriginalPointIds']
587
588 out.ShallowCopy(result)
589 except Exception: # pragma: no cover
590 traceback.print_exc()
591 raise
592 return 1
593
594
595 class PointSetToPolyDataAlgorithm(
596 _NoNewAttrMixin, DisableVtkSnakeCase, _vtk.VTKPythonAlgorithmBase
597 ):
598 """Algorithm to cast PointSet to PolyData.
599
600 This is implemented with :func:`pyvista.PointSet.cast_to_polydata`.
601
602 """
603
604 def __init__(self):
605 """Initialize algorithm."""
606 _vtk.VTKPythonAlgorithmBase.__init__(
607 self,
608 nInputPorts=1,
609 nOutputPorts=1,
610 inputType='vtkPointSet',
611 outputType='vtkPolyData',
612 )
613
614 def RequestData(self, _request, inInfo, outInfo) -> int:
615 """Perform algorithm execution.
616
617 Parameters
618 ----------
619 _request : :vtk:`vtkInformation`
620 Information associated with the request.
621 inInfo : :vtk:`vtkInformationVector`
622 Information about the input data.
623 outInfo : :vtk:`vtkInformationVector`
624 Information about the output data.
625
626 Returns
627 -------
628 int
629 1 when successful.
630
631 """
632 try:
633 inp = wrap(self.GetInputData(inInfo, 0, 0))
634 out = self.GetOutputData(outInfo, 0)
635 output = inp.cast_to_polydata(deep=False)
636 out.ShallowCopy(output)
637 except Exception: # pragma: no cover
638 traceback.print_exc()
639 raise
640 return 1
641
642
643 class AddIDsAlgorithm(PreserveTypeAlgorithmBase):
644 """Algorithm to add point or cell IDs.
645
646 Output of this filter is a shallow copy of the input with
647 point and/or cell ID arrays added.
648
649 Parameters
650 ----------
651 point_ids : bool, default: True
652 Whether to add point IDs.
653
654 cell_ids : bool, default: True
655 Whether to add cell IDs.
656
657 Raises
658 ------
659 ValueError
660 If neither point IDs nor cell IDs are set.
661
662 """
663
664 @_deprecate_positional_args
665 def __init__(self, point_ids: bool = True, cell_ids: bool = True): # noqa: FBT001, FBT002
666 """Initialize algorithm."""
667 super().__init__()
668 if not point_ids and not cell_ids: # pragma: no cover
669 msg = 'IDs must be set for points or cells or both.'
670 raise ValueError(msg)
671 self.point_ids = point_ids
672 self.cell_ids = cell_ids
673
674 def RequestData(self, _request, inInfo, outInfo) -> int:
675 """Perform algorithm execution.
676
677 Parameters
678 ----------
679 _request : :vtk:`vtkInformation`
680 Information associated with the request.
681 inInfo : :vtk:`vtkInformationVector`
682 Information about the input data.
683 outInfo : :vtk:`vtkInformationVector`
684 Information about the output data.
685
686 Returns
687 -------
688 int
689 Returns 1 if the algorithm was successful.
690
691 Raises
692 ------
693 Exception
694 If the algorithm fails to execute properly.
695
696 """
697 try:
698 inp = self.GetInputData(inInfo, 0, 0)
699 out = self.GetOutputData(outInfo, 0)
700 out.ShallowCopy(inp)
701 # AddArray does not modify active scalars (unlike PyVista's
702 # __setitem__), so no fixup is needed after insertion.
703 if self.point_ids:
704 n = out.GetNumberOfPoints()
705 arr = _vtk.numpy_to_vtk(np.arange(n, dtype=int))
706 arr.SetName('point_ids')
707 out.GetPointData().AddArray(arr)
708 if self.cell_ids:
709 n = out.GetNumberOfCells()
710 arr = _vtk.numpy_to_vtk(np.arange(n, dtype=int))
711 arr.SetName('cell_ids')
712 out.GetCellData().AddArray(arr)
713 except Exception: # pragma: no cover
714 traceback.print_exc()
715 raise
716 return 1
717
718
719 class CrinkleAlgorithm(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.VTKPythonAlgorithmBase):
720 """Algorithm to crinkle cell IDs."""
721
722 def __init__(self):
723 """Initialize algorithm."""
724 super().__init__(
725 nInputPorts=2,
726 outputType='vtkUnstructuredGrid',
727 )
728
729 def RequestData(self, _request, inInfo, outInfo) -> int:
730 """Perform algorithm execution based on the input data and produce the output.
731
732 Parameters
733 ----------
734 _request : :vtk:`vtkInformation`
735 The request information associated with the algorithm.
736 inInfo : :vtk:`vtkInformationVector`
737 Information vector describing the input data.
738 outInfo : :vtk:`vtkInformationVector`
739 Information vector where the output data should be placed.
740
741 Returns
742 -------
743 int
744 Status of the execution. Returns 1 on successful completion.
745
746 """
747 try:
748 clipped = wrap(self.GetInputData(inInfo, 0, 0))
749 source = wrap(self.GetInputData(inInfo, 1, 0))
750 out = self.GetOutputData(outInfo, 0)
751 output = source.extract_cells(np.unique(clipped.cell_data['cell_ids']))
752 out.ShallowCopy(output)
753 except Exception: # pragma: no cover
754 traceback.print_exc()
755 raise
756 return 1
757
758
759 @_deprecate_positional_args(allowed=['inp'])
760 def outline_algorithm(inp, generate_faces: bool = False): # noqa: FBT001, FBT002
761 """Add :vtk:`vtkOutlineFilter` to pipeline.
762
763 Parameters
764 ----------
765 inp : pyvista.DataSet
766 Input data to be filtered.
767 generate_faces : bool, default: False
768 Whether to generate faces for the outline.
769
770 Returns
771 -------
772 :vtk:`vtkOutlineFilter`
773 Outline filter applied to the input data.
774
775 """
776 alg = _vtk.vtkOutlineFilter()
777 set_algorithm_input(alg, inp)
778 alg.SetGenerateFaces(generate_faces)
779 return alg
780
781
782 @_deprecate_positional_args(allowed=['generator'])
783 def source_algorithm(
784 generator: Callable[[], DataSet],
785 output_type: str | type = pv.UnstructuredGrid,
786 ) -> SourceAlgorithm:
787 """Create a source algorithm that generates data from a callable.
788
789 A source has no input port. It produces data from scratch via
790 *generator*.
791
792 Parameters
793 ----------
794 generator : callable
795 ``generator() -> dataset``.
796
797 output_type : str | type[pyvista.DataSet], default: :class:`pyvista.UnstructuredGrid`
798 Output type. Accepts a VTK class name string or a PyVista
799 :class:`~pyvista.DataSet` subclass.
800
801 Returns
802 -------
803 SourceAlgorithm
804 The source algorithm.
805
806 """
807 return SourceAlgorithm(generator=generator, output_type=output_type)
808
809
810 @_deprecate_positional_args(allowed=['inp', 'callback'])
811 def callback_algorithm(
812 inp,
813 callback: Callable[[DataSet], DataSet],
814 output_type: str | type | None = None,
815 ) -> CallbackFilterAlgorithm:
816 """Add a filter that delegates to a user-supplied callable.
817
818 Parameters
819 ----------
820 inp : pyvista.DataSet | :vtk:`vtkAlgorithm`
821 Input data or algorithm.
822
823 callback : callable
824 ``callback(dataset) -> dataset``.
825
826 output_type : str | type[pyvista.DataSet] | None, default: ``None``
827 Fixed output type. Accepts a VTK class name string or a PyVista
828 :class:`~pyvista.DataSet` subclass. When ``None``, the output
829 type matches the input type.
830
831 Returns
832 -------
833 CallbackFilterAlgorithm
834 The callback filter wired to *inp*.
835
836 """
837 alg = CallbackFilterAlgorithm(callback=callback, output_type=output_type)
838 set_algorithm_input(alg, inp)
839 return alg
840
841
842 @_deprecate_positional_args(allowed=['inp'])
843 def extract_surface_algorithm( # noqa: PLR0917
844 inp,
845 pass_pointid: bool = False, # noqa: FBT001, FBT002
846 pass_cellid: bool = False, # noqa: FBT001, FBT002
847 nonlinear_subdivision=1,
848 ):
849 """Add :vtk:`vtkDataSetSurfaceFilter` to pipeline.
850
851 Parameters
852 ----------
853 inp : pyvista.DataSet
854 Input data to be filtered.
855 pass_pointid : bool, default: False
856 If ``True``, pass point IDs to the output.
857 pass_cellid : bool, default: False
858 If ``True``, pass cell IDs to the output.
859 nonlinear_subdivision : int, default: 1
860 Level of nonlinear subdivision.
861
862 Returns
863 -------
864 :vtk:`vtkDataSetSurfaceFilter`
865 Surface filter applied to the input data.
866
867 """
868 surf_filter = _vtk.vtkDataSetSurfaceFilter()
869 surf_filter.SetPassThroughPointIds(pass_pointid)
870 surf_filter.SetPassThroughCellIds(pass_cellid)
871 if nonlinear_subdivision != 1:
872 surf_filter.SetNonlinearSubdivisionLevel(nonlinear_subdivision)
873 set_algorithm_input(surf_filter, inp)
874 return surf_filter
875
876
877 @_deprecate_positional_args(allowed=['inp', 'name'])
878 def active_scalars_algorithm(
879 inp,
880 name: str,
881 preference: PointLiteral | CellLiteral = 'point',
882 ) -> ActiveScalarsAlgorithm:
883 """Add a filter that sets the active scalars.
884
885 Parameters
886 ----------
887 inp : pyvista.DataSet | :vtk:`vtkAlgorithm`
888 Input data or algorithm.
889
890 name : str
891 Name of the scalars to set as active.
892
893 preference : str, default: 'point'
894 Either ``'point'`` or ``'cell'``. Determines the field
895 association when the same array name exists on both.
896
897 Returns
898 -------
899 ActiveScalarsAlgorithm
900 Active scalars filter applied to the input data.
901
902 """
903 alg = ActiveScalarsAlgorithm(
904 name=name,
905 preference=preference,
906 )
907 set_algorithm_input(alg, inp)
908 return alg
909
910
911 @_deprecate_positional_args(allowed=['inp'])
912 def smooth_shading_algorithm(
913 inp,
914 split_sharp_edges: bool = False, # noqa: FBT001, FBT002
915 feature_angle: float = 30.0,
916 ) -> SmoothShadingAlgorithm:
917 """Add a filter that computes point normals for smooth shading.
918
919 Parameters
920 ----------
921 inp : pyvista.DataSet | :vtk:`vtkAlgorithm`
922 Input data or algorithm.
923
924 split_sharp_edges : bool, default: False
925 Whether to split sharp edges when computing normals.
926
927 feature_angle : float, default: 30.0
928 Angle (in degrees) above which an edge is considered sharp. Only
929 used when ``split_sharp_edges`` is ``True``.
930
931 Returns
932 -------
933 SmoothShadingAlgorithm
934 Smooth shading filter applied to the input data.
935
936 """
937 alg = SmoothShadingAlgorithm(
938 split_sharp_edges=split_sharp_edges,
939 feature_angle=feature_angle,
940 )
941 set_algorithm_input(alg, inp)
942 return alg
943
944
945 def pointset_to_polydata_algorithm(inp) -> PointSetToPolyDataAlgorithm:
946 """Add a filter that casts PointSet to PolyData.
947
948 Parameters
949 ----------
950 inp : pyvista.PointSet
951 Input point set to be cast to PolyData.
952
953 Returns
954 -------
955 :vtk:`vtkAlgorithm`
956 Filter that casts the input PointSet to PolyData.
957
958 """
959 alg = PointSetToPolyDataAlgorithm()
960 set_algorithm_input(alg, inp)
961 return alg
962
963
964 @_deprecate_positional_args(allowed=['inp'])
965 def add_ids_algorithm(inp, point_ids: bool = True, cell_ids: bool = True): # noqa: FBT001, FBT002
966 """Add a filter that adds point and/or cell IDs.
967
968 Parameters
969 ----------
970 inp : pyvista.DataSet
971 The input data to which the IDs will be added.
972 point_ids : bool, default: True
973 If ``True``, point IDs will be added to the input data.
974 cell_ids : bool, default: True
975 If ``True``, cell IDs will be added to the input data.
976
977 Returns
978 -------
979 AddIDsAlgorithm
980 AddIDsAlgorithm filter.
981
982 """
983 alg = AddIDsAlgorithm(point_ids=point_ids, cell_ids=cell_ids)
984 set_algorithm_input(alg, inp)
985 return alg
986
987
988 def crinkle_algorithm(clip, source):
989 """Add a filter that crinkles a clip.
990
991 Parameters
992 ----------
993 clip : pyvista.DataSet
994 The input data to be crinkled.
995 source : pyvista.DataSet
996 The source of the crinkle.
997
998 Returns
999 -------
1000 CrinkleAlgorithm
1001 CrinkleAlgorithm filter.
1002
1003 """
1004 alg = CrinkleAlgorithm()
1005 set_algorithm_input(alg, clip, 0)
1006 set_algorithm_input(alg, source, 1)
1007 return alg
1008
1009
1010 @_deprecate_positional_args(allowed=['inp'])
1011 def cell_data_to_point_data_algorithm(inp, pass_cell_data: bool = False): # noqa: FBT001, FBT002
1012 """Add a filter that converts cell data to point data.
1013
1014 Parameters
1015 ----------
1016 inp : pyvista.DataSet
1017 The input data whose cell data will be converted to point data.
1018 pass_cell_data : bool, default: False
1019 If ``True``, the original cell data will be passed to the output.
1020
1021 Returns
1022 -------
1023 :vtk:`vtkCellDataToPointData`
1024 The :vtk:`vtkCellDataToPointData` filter.
1025
1026 """
1027 alg = _vtk.vtkCellDataToPointData()
1028 alg.SetPassCellData(pass_cell_data)
1029 set_algorithm_input(alg, inp)
1030 return alg
1031
1032
1033 @_deprecate_positional_args(allowed=['inp'])
1034 def point_data_to_cell_data_algorithm(inp, pass_point_data: bool = False): # noqa: FBT001, FBT002
1035 """Add a filter that converts point data to cell data.
1036
1037 Parameters
1038 ----------
1039 inp : pyvista.DataSet
1040 The input data whose point data will be converted to cell data.
1041 pass_point_data : bool, default: False
1042 If ``True``, the original point data will be passed to the output.
1043
1044 Returns
1045 -------
1046 :vtk:`vtkPointDataToCellData`
1047 :vtk:`vtkPointDataToCellData` algorithm.
1048
1049 """
1050 alg = _vtk.vtkPointDataToCellData()
1051 alg.SetPassPointData(pass_point_data)
1052 set_algorithm_input(alg, inp)
1053 return alg
1054
1055
1056 def triangulate_algorithm(inp):
1057 """Triangulate the input data.
1058
1059 Parameters
1060 ----------
1061 inp : :vtk:`vtkDataObject`
1062 The input data to be triangulated.
1063
1064 Returns
1065 -------
1066 :vtk:`vtkTriangleFilter`
1067 The triangle filter that has been applied to the input data.
1068
1069 """
1070 trifilter = _vtk.vtkTriangleFilter()
1071 trifilter.PassVertsOff()
1072 trifilter.PassLinesOff()
1073 set_algorithm_input(trifilter, inp)
1074 return trifilter
1075
1076
1077 def decimation_algorithm(inp, target_reduction):
1078 """Decimate the input data to the target reduction.
1079
1080 Parameters
1081 ----------
1082 inp : :vtk:`vtkDataObject`
1083 The input data to be decimated.
1084 target_reduction : float
1085 The target reduction amount, as a fraction of the original data.
1086
1087 Returns
1088 -------
1089 :vtk:`vtkQuadricDecimation`
1090 The decimation algorithm that has been applied to the input data.
1091
1092 """
1093 alg = _vtk.vtkQuadricDecimation()
1094 alg.SetTargetReduction(target_reduction)
1095 set_algorithm_input(alg, inp)
1096 return alg