Debian Codegraph @

pyvista/plotting/mapper.py

raw
1 """An internal module for wrapping the use of mappers."""
2
3 from __future__ import annotations
4
5 import sys
6 from typing import TYPE_CHECKING
7 from typing import cast
8 import weakref
9
10 import numpy as np
11
12 import pyvista as pv
13 from pyvista import _vtk
14 from pyvista._deprecate_positional_args import _deprecate_positional_args
15 from pyvista.core._typing_core import BoundsTuple
16 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
17 from pyvista.core.utilities.arrays import FieldAssociation
18 from pyvista.core.utilities.arrays import convert_array
19 from pyvista.core.utilities.arrays import convert_string_array
20 from pyvista.core.utilities.arrays import get_array_association
21 from pyvista.core.utilities.arrays import raise_not_matching
22 from pyvista.core.utilities.helpers import wrap
23 from pyvista.core.utilities.misc import _BoundsSizeMixin
24 from pyvista.core.utilities.misc import _NoNewAttrMixin
25 from pyvista.core.utilities.misc import abstract_class
26
27 from ._plotting import reduce_component_scalars
28 from .colors import Color
29 from .colors import get_cmap_safe
30 from .lookup_table import LookupTable
31 from .tools import normalize
32 from .utilities.algorithms import ActiveScalarsAlgorithm
33 from .utilities.algorithms import set_algorithm_input
34
35 if TYPE_CHECKING:
36 from pyvista import DataSet
37 from pyvista.core.utilities.arrays import CellLiteral
38 from pyvista.core.utilities.arrays import PointLiteral
39 from pyvista.themes import Theme
40
41
42 @abstract_class
43 class _BaseMapper(_NoNewAttrMixin, _BoundsSizeMixin, DisableVtkSnakeCase, _vtk.vtkAbstractMapper):
44 """Base Mapper with methods common to other mappers."""
45
46 def __init__(self, theme=None, **kwargs) -> None:
47 self._theme = pv.themes.Theme()
48 if theme is None:
49 # copy global theme to ensure local property theme is fixed
50 # after creation.
51 self._theme.load_theme(pv.global_theme)
52 else:
53 self._theme.load_theme(theme)
54 self.lookup_table = LookupTable()
55
56 self.interpolate_before_map = kwargs.get(
57 'interpolate_before_map',
58 self._theme.interpolate_before_map,
59 )
60
61 @property
62 def bounds(self) -> BoundsTuple: # numpydoc ignore=RT01
63 """Return the bounds of this mapper.
64
65 Examples
66 --------
67 >>> import pyvista as pv
68 >>> mapper = pv.DataSetMapper(dataset=pv.Cube())
69 >>> mapper.bounds
70 BoundsTuple(x_min = -0.5,
71 x_max = 0.5,
72 y_min = -0.5,
73 y_max = 0.5,
74 z_min = -0.5,
75 z_max = 0.5)
76
77 """
78 return BoundsTuple(*self.GetBounds())
79
80 @property
81 def center(self) -> tuple[float, float, float]:
82 """Return the center of mapper.
83
84 Returns
85 -------
86 tuple[float, float, float]
87 Center of the active renderer.
88
89 """
90 return self.GetCenter()
91
92 def copy(self) -> _BaseMapper:
93 """Create a copy of this mapper.
94
95 Returns
96 -------
97 pyvista.DataSetMapper
98 A copy of this dataset mapper.
99
100 Examples
101 --------
102 >>> import pyvista as pv
103 >>> mapper = pv.DataSetMapper(dataset=pv.Cube())
104 >>> mapper_copy = mapper.copy()
105
106 """
107 new_mapper = type(self)(theme=self._theme)
108 # even though this uses ShallowCopy, the new mapper no longer retains
109 # any connection with the original
110 new_mapper.ShallowCopy(self)
111 if hasattr(self, 'dataset'):
112 new_mapper.dataset = self.dataset
113 return new_mapper
114
115 @property
116 def scalar_range(self) -> tuple[float, float]: # numpydoc ignore=RT01
117 """Return or set the scalar range.
118
119 Examples
120 --------
121 Return the scalar range of a mapper.
122
123 >>> import pyvista as pv
124 >>> mesh = pv.Sphere()
125 >>> pl = pv.Plotter()
126 >>> actor = pl.add_mesh(mesh, scalars=mesh.points[:, 2])
127 >>> actor.mapper.scalar_range
128 (-0.5, 0.5)
129 >>> pl.close()
130
131 Return the scalar range of a composite dataset. In this example it's
132 set to its default value of ``(0.0, 1.0)``.
133
134 >>> import pyvista as pv
135 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
136 >>> pl = pv.Plotter()
137 >>> actor, mapper = pl.add_composite(dataset)
138 >>> mapper.scalar_range
139 (0.0, 1.0)
140 >>> pl.close()
141
142 """
143 return self.GetScalarRange()
144
145 @scalar_range.setter
146 def scalar_range(self, clim) -> None:
147 self.SetScalarRange(*clim)
148
149 @property
150 def lookup_table(self) -> LookupTable: # numpydoc ignore=RT01
151 """Return or set the lookup table.
152
153 Examples
154 --------
155 Return the lookup table of a dataset mapper.
156
157 >>> import pyvista as pv
158 >>> mesh = pv.Sphere()
159 >>> pl = pv.Plotter()
160 >>> actor = pl.add_mesh(mesh, scalars=mesh.points[:, 2], cmap='bwr')
161 >>> actor.mapper.lookup_table
162 LookupTable (...)
163 Table Range: (-0.5, 0.5)
164 N Values: 256
165 Above Range Color: None
166 Below Range Color: None
167 NAN Color: Color(name='dark_gray', hex='#a9a9a9ff', opacity=255)
168 Log Scale: False
169 Color Map: "bwr"
170
171 Return the lookup table of a composite dataset mapper.
172
173 >>> import pyvista as pv
174 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
175 >>> pl = pv.Plotter()
176 >>> actor, mapper = pl.add_composite(dataset)
177 >>> mapper.lookup_table # doctest:+SKIP
178 <vtkmodules.vtkCommonCore.vtkLookupTable(...) at ...>
179
180 """
181 return self.GetLookupTable()
182
183 @lookup_table.setter
184 def lookup_table(self, table) -> None:
185 self.SetLookupTable(table)
186
187 @property
188 def color_mode(self) -> str: # numpydoc ignore=RT01
189 """Return or set the color mode.
190
191 Either ``'direct'``, or ``'map'``.
192
193 * ``'direct'`` - All integer types are treated as colors with values in
194 the range 0-255 and floating types are treated as colors with values
195 in the range 0.0-1.0
196 * ``'map'`` - All scalar data will be mapped through the lookup table.
197
198 """
199 mode = self.GetColorModeAsString().lower()
200 if mode == 'mapscalars':
201 return 'map'
202 return 'direct'
203
204 @color_mode.setter
205 def color_mode(self, value: str):
206 if value == 'direct':
207 self.SetColorModeToDirectScalars()
208 elif value == 'map':
209 self.SetColorModeToMapScalars()
210 else:
211 msg = 'Color mode must be either "default", "direct" or "map"'
212 raise ValueError(msg)
213
214 @property
215 def interpolate_before_map(self) -> bool | None: # numpydoc ignore=RT01
216 """Return or set the interpolation of scalars before mapping.
217
218 Enabling makes for a smoother scalars display. When ``False``,
219 OpenGL will interpolate the mapped colors which can result in
220 showing colors that are not present in the color map.
221
222 Examples
223 --------
224 Disable interpolation before mapping.
225
226 >>> import pyvista as pv
227 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
228 >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
229 >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
230 >>> pl = pv.Plotter()
231 >>> actor, mapper = pl.add_composite(
232 ... dataset,
233 ... show_scalar_bar=False,
234 ... n_colors=3,
235 ... cmap='bwr',
236 ... )
237 >>> mapper.interpolate_before_map = False
238 >>> pl.show()
239
240 Enable interpolation before mapping.
241
242 >>> pl = pv.Plotter()
243 >>> actor, mapper = pl.add_composite(
244 ... dataset,
245 ... show_scalar_bar=False,
246 ... n_colors=3,
247 ... cmap='bwr',
248 ... )
249 >>> mapper.interpolate_before_map = True
250 >>> pl.show()
251
252 See :ref:`interpolate_before_map_example` for additional
253 explanation regarding this attribute.
254
255 """
256 return bool(self.GetInterpolateScalarsBeforeMapping())
257
258 @interpolate_before_map.setter
259 def interpolate_before_map(self, value: bool) -> None:
260 self.SetInterpolateScalarsBeforeMapping(value)
261
262 @property
263 def array_name(self) -> str: # numpydoc ignore=RT01
264 """Return or set the array name or number and component to color by.
265
266 Examples
267 --------
268 Show the name of the active scalars in the mapper.
269
270 >>> import pyvista as pv
271 >>> mesh = pv.Sphere()
272 >>> mesh['my_scalars'] = mesh.points[:, 2]
273 >>> pl = pv.Plotter()
274 >>> actor = pl.add_mesh(mesh, scalars='my_scalars')
275 >>> actor.mapper.array_name
276 'my_scalars'
277 >>> pl.close()
278
279 """
280 return self.GetArrayName()
281
282 @array_name.setter
283 def array_name(self, name: str) -> None:
284 """Return or set the array name or number and component to color by."""
285 self.SetArrayName(name)
286
287 @property
288 def scalar_map_mode(self) -> str: # numpydoc ignore=RT01
289 """Return or set the scalar map mode.
290
291 Examples
292 --------
293 Show that the scalar map mode is set to ``'point'`` when setting the
294 active scalars to point data.
295
296 >>> import pyvista as pv
297 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
298 >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
299 >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
300 >>> pl = pv.Plotter()
301 >>> actor, mapper = pl.add_composite(
302 ... dataset, scalars='data', show_scalar_bar=False
303 ... )
304 >>> mapper.scalar_map_mode
305 'point'
306 >>> pl.close()
307
308 """
309 # map vtk strings to more sensible strings
310 vtk_to_pv = {
311 'Default': 'default',
312 'UsePointData': 'point',
313 'UseCellData': 'cell',
314 'UsePointFieldData': 'point_field',
315 'UseCellFieldData': 'cell_field',
316 'UseFieldData': 'field',
317 }
318 return vtk_to_pv[self.GetScalarModeAsString()]
319
320 @scalar_map_mode.setter
321 def scalar_map_mode(self, scalar_mode: str | FieldAssociation):
322 if isinstance(scalar_mode, FieldAssociation):
323 scalar_mode = scalar_mode.name
324 scalar_mode = scalar_mode.lower()
325 if scalar_mode == 'default':
326 self.SetScalarModeToDefault()
327 elif scalar_mode == 'point':
328 self.SetScalarModeToUsePointData()
329 elif scalar_mode == 'cell':
330 self.SetScalarModeToUseCellData()
331 elif scalar_mode == 'point_field':
332 self.SetScalarModeToUsePointFieldData()
333 elif scalar_mode == 'cell_field':
334 self.SetScalarModeToUseCellFieldData()
335 elif scalar_mode == 'field':
336 self.SetScalarModeToUseFieldData()
337 else:
338 msg = (
339 f'Invalid `scalar_map_mode` "{scalar_mode}". Should be either '
340 '"default", "point", "cell", "point_field", "cell_field" or "field".'
341 )
342 raise ValueError(msg)
343
344 @property
345 def scalar_visibility(self) -> bool: # numpydoc ignore=RT01
346 """Return or set the scalar visibility.
347
348 Examples
349 --------
350 Show that scalar visibility is ``False``.
351
352 >>> import pyvista as pv
353 >>> mesh = pv.Sphere()
354 >>> pl = pv.Plotter()
355 >>> actor = pl.add_mesh(mesh)
356 >>> actor.mapper.scalar_visibility
357 False
358 >>> pl.close()
359
360 Show that scalar visibility is ``True``.
361
362 >>> import pyvista as pv
363 >>> dataset = pv.MultiBlock([pv.Cube(), pv.Sphere(center=(0, 0, 1))])
364 >>> dataset[0].point_data['data'] = dataset[0].points[:, 2]
365 >>> dataset[1].point_data['data'] = dataset[1].points[:, 2]
366 >>> pl = pv.Plotter()
367 >>> actor, mapper = pl.add_composite(dataset, scalars='data')
368 >>> mapper.scalar_visibility
369 True
370 >>> pl.close()
371
372 """
373 return bool(self.GetScalarVisibility())
374
375 @scalar_visibility.setter
376 def scalar_visibility(self, value: bool) -> None:
377 self.SetScalarVisibility(value)
378
379 def update(self) -> None:
380 """Update this mapper."""
381 self.Update()
382
383
384 class _DataSetMapper(_BaseMapper):
385 """Base wrapper for :vtk:`vtkDataSetMapper`.
386
387 Parameters
388 ----------
389 dataset : pyvista.DataSet, optional
390 Dataset to assign to this mapper.
391
392 theme : pyvista.plotting.themes.Theme, optional
393 Plot-specific theme.
394
395 Notes
396 -----
397 Auto scalar-range state machine. The private attribute
398 ``_use_default_scalar_range`` tracks whether the scalar range is
399 still derived from the mapped array (``True``) or has been pinned by
400 the caller (``False``). It starts ``True``. Setting ``scalar_range``
401 directly, or calling :meth:`set_scalars` with an explicit ``clim``,
402 flips it to ``False`` via :meth:`_set_scalar_range`. While ``True``,
403 the range auto-refreshes from the mapped array in
404 :meth:`_maybe_set_default_scalar_range`, which is called from
405 :meth:`set_active_scalars` and the ``dataset`` setter. Once
406 ``False``, auto-refresh is suppressed so user-supplied ``clim``
407 values are preserved.
408
409 """
410
411 _cmap = None
412
413 def __init__(
414 self,
415 dataset: DataSet | None = None,
416 theme: Theme | None = None,
417 ) -> None:
418 """Initialize this class."""
419 super().__init__(theme=theme)
420 self._use_default_scalar_range = True
421 # _BaseMapper creates a bare LookupTable() which does not honor the
422 # theme cmap. Apply it here so auto-range paths (set_active_scalars
423 # -> _maybe_set_default_scalar_range) see the theme colors before
424 # any set_scalars call.
425 self.lookup_table.apply_cmap(self._theme.cmap, self.lookup_table.n_values)
426 self._active_scalars_algo: ActiveScalarsAlgorithm | None = None
427 self._input_dataset_ref: weakref.ref[DataSet] | None = None
428 if dataset is not None:
429 self.dataset = dataset
430
431 @property
432 def dataset(self) -> DataSet | None: # numpydoc ignore=RT01
433 """Return or set the dataset assigned to this mapper."""
434 if self._input_dataset is not None:
435 return self._input_dataset
436 # Fall back to the VTK pipeline input when the mapper was wired up
437 # with a vtkAlgorithm rather than a direct DataSet assignment.
438 return cast('pv.DataSet | None', wrap(_mapper_get_data_set_input(self)))
439
440 @dataset.setter
441 def dataset(
442 self,
443 obj: DataSet | _vtk.vtkAlgorithm | _vtk.vtkAlgorithmOutput,
444 ) -> None:
445 if isinstance(obj, (_vtk.vtkAlgorithm, _vtk.vtkAlgorithmOutput)):
446 self._input_dataset = None
447 else:
448 self._input_dataset = obj
449 if self._active_scalars_algo is not None:
450 # Reconnect pipeline: new input -> algo -> mapper
451 set_algorithm_input(self._active_scalars_algo, obj)
452 set_algorithm_input(self, self._active_scalars_algo)
453 else:
454 set_algorithm_input(self, obj)
455 self._maybe_set_default_scalar_range()
456
457 @property
458 def scalar_range(self) -> tuple[float, float]: # numpydoc ignore=RT01
459 """Return or set the scalar range."""
460 return self.GetScalarRange()
461
462 @scalar_range.setter
463 def scalar_range(self, clim) -> None:
464 self._set_scalar_range(clim, use_default=False)
465
466 # Avoid ref cycles by using weakref
467 @property
468 def _input_dataset(self):
469 return None if self._input_dataset_ref is None else self._input_dataset_ref()
470
471 @_input_dataset.setter
472 def _input_dataset(self, dataset: DataSet | None):
473 self._input_dataset_ref = None if dataset is None else weakref.ref(dataset)
474
475 @property
476 def array_name(self) -> str: # numpydoc ignore=RT01
477 """Return or set the array name or number and component to color by.
478
479 Setter behavior depends on whether the array can be resolved on
480 an upstream dataset without running the pipeline:
481
482 * If ``_scalar_source_dataset`` exposes an array with the
483 given name, route through ``set_active_scalars`` so a
484 spliced ``ActiveScalarsAlgorithm`` activates the array on
485 each ``RequestData`` (and ``_maybe_set_default_scalar_range``
486 picks a default ``clim``).
487 * Otherwise fall back to the raw VTK ``SetArrayName``. This path
488 is hit when the mapper is wired to a pipeline whose output
489 topology/arrays only materialize after ``Update()``, for
490 example a ``SmoothShadingAlgorithm`` producing post-surface
491 scalars. In that case an existing active-scalars algorithm
492 (if any) is updated in place; otherwise name resolution
493 happens on the first render.
494 """
495 return self.GetArrayName()
496
497 @array_name.setter
498 def array_name(self, name: str) -> None:
499 dataset = self._scalar_source_dataset
500 if dataset is not None:
501 if self.scalar_map_mode == 'cell':
502 association = get_array_association(dataset, name, preference='cell')
503 else:
504 association = get_array_association(dataset, name, preference='point')
505 if association == FieldAssociation.POINT:
506 self.set_active_scalars(name, preference='point')
507 return
508 if association == FieldAssociation.CELL:
509 self.set_active_scalars(name, preference='cell')
510 return
511
512 self.SetArrayName(name)
513 if self._active_scalars_algo is not None:
514 # The algorithm's setter calls Modified() on change, so the
515 # next render re-runs the pipeline against the new array.
516 self._active_scalars_algo.scalars_name = name
517
518 @property
519 def _scalar_source_dataset(self) -> DataSet | None:
520 """Return a dataset suitable for resolving mapped scalar arrays.
521
522 Used by ``array_name`` and ``set_active_scalars`` to find an array
523 by name without forcing a pipeline update. Walks at most one stage
524 upstream: if the mapper's cached dataset is empty, peek at the
525 direct producer's port-0 input. For longer pipelines (e.g.
526 ``source -> callback -> active_scalars -> mapper``) this returns
527 the last stage's input, not the original source. That is enough
528 to resolve array names because each stage's ``RequestData``
529 forwards arrays via ``ShallowCopy``.
530 """
531 dataset = self.dataset
532 if dataset is not None and dataset.n_arrays > 0:
533 return dataset
534
535 input_connection = cast('_vtk.vtkAlgorithmOutput | None', self.GetInputConnection(0, 0))
536 if input_connection is not None:
537 input_algorithm = input_connection.GetProducer()
538 if input_algorithm.GetNumberOfInputPorts() == 0:
539 return dataset
540 source = input_algorithm.GetInputDataObject(0, 0)
541 if isinstance(source, _vtk.vtkDataSet):
542 return wrap(source)
543
544 return dataset
545
546 @property
547 def _mapped_scalars(self) -> pv.pyvista_ndarray | None:
548 """Return the scalars this mapper is configured to display.
549
550 When an :class:`ActiveScalarsAlgorithm` is managing the active
551 scalars, the dataset's own ``active_scalars`` may point to a
552 different array. This property always returns the correct array.
553 """
554 if self.dataset is None:
555 return None
556 if self._active_scalars_algo is not None:
557 name = self._active_scalars_algo.scalars_name
558 if self._active_scalars_algo.preference == 'cell':
559 return self.dataset.cell_data[name]
560 return self.dataset.point_data[name]
561 return self.dataset.active_scalars
562
563 def _maybe_set_default_scalar_range(self, dataset: DataSet | None = None) -> None:
564 """Set the scalar range from mapped scalars while defaults are active."""
565 if not self._use_default_scalar_range:
566 return
567
568 try:
569 scalars = self._mapped_scalars
570 except KeyError:
571 scalars = None
572 if scalars is None and self._active_scalars_algo is not None:
573 dataset = dataset or self._scalar_source_dataset
574 if dataset is None:
575 return
576 name = self._active_scalars_algo.scalars_name
577 if self._active_scalars_algo.preference == 'cell' and name in dataset.cell_data:
578 scalars = dataset.cell_data[name]
579 elif self._active_scalars_algo.preference == 'point' and name in dataset.point_data:
580 scalars = dataset.point_data[name]
581 if scalars is None:
582 return
583
584 array = np.asarray(scalars)
585 if array.size == 0:
586 return
587 if np.issubdtype(array.dtype, np.complexfloating):
588 array = array.real
589 if array.dtype == np.bool_:
590 clim = (0.0, 1.0)
591 elif np.issubdtype(array.dtype, np.number):
592 if np.isnan(array).all():
593 return
594 clim = (float(np.nanmin(array)), float(np.nanmax(array)))
595 else:
596 return
597
598 self._set_scalar_range(clim, use_default=True)
599
600 def _set_scalar_range(self, clim, *, use_default: bool) -> None:
601 """Set the scalar range and track whether it is user-defined."""
602 self.SetScalarRange(*clim)
603 self.lookup_table.scalar_range = clim
604 self._use_default_scalar_range = use_default
605
606 def as_rgba(self) -> None:
607 """Convert the active scalars to RGBA.
608
609 This method is used to convert the active scalars to a fixed RGBA array
610 and is used for certain mappers that do not support the "map" color
611 mode.
612
613 """
614 if self.color_mode == 'direct':
615 return
616
617 if self.dataset is not None:
618 self.dataset.point_data.pop('__rgba__', None)
619 self._configure_scalars_mode(
620 scalars=self.lookup_table(self._mapped_scalars),
621 scalars_name='__rgba__',
622 preference=self.scalar_map_mode,
623 direct_scalars_color_mode=True,
624 )
625
626 def set_active_scalars(
627 self,
628 name: str,
629 preference: PointLiteral | CellLiteral = 'point',
630 ) -> None:
631 """Set the active scalars for this mapper without mutating its dataset.
632
633 Inserts an :class:`ActiveScalarsAlgorithm` between the mapper's
634 current input and the mapper itself. The algorithm sets the active
635 scalars on a shallow copy of the input data, so the original
636 dataset is never mutated and the same dataset can be shared across
637 multiple mappers with different active scalars.
638
639 If an algorithm is already in place, it is updated in place.
640
641 Parameters
642 ----------
643 name : str
644 Name of the scalars array to set as active.
645
646 preference : str, default: 'point'
647 Either ``'point'`` or ``'cell'``.
648
649 See Also
650 --------
651 clear_active_scalars
652 set_scalars
653
654 """
655 source_dataset = self._scalar_source_dataset
656 if self._active_scalars_algo is None:
657 self._active_scalars_algo = ActiveScalarsAlgorithm(name=name, preference=preference)
658 # Splice the algo between the mapper and its current input.
659 # Prefer the existing pipeline connection so upstream
660 # modifications propagate on re-render. If no connection exists
661 # yet (for example on a freshly copied mapper), fall back to the
662 # cached dataset input instead of wiring a null VTK connection.
663 input_conn = cast('_vtk.vtkAlgorithmOutput | None', self.GetInputConnection(0, 0))
664 if input_conn is not None:
665 self._active_scalars_algo.SetInputConnection(0, input_conn)
666 elif self._input_dataset is not None:
667 set_algorithm_input(self._active_scalars_algo, self._input_dataset)
668 self.SetInputConnection(0, self._active_scalars_algo.GetOutputPort())
669 else:
670 self._active_scalars_algo.scalars_name = name
671 self._active_scalars_algo.preference = preference
672 # Also point the mapper at the array directly. SetInputConnection
673 # above clears the VTK-level array name, so this must come last.
674 self.SetArrayName(name)
675 self.scalar_map_mode = preference
676 self._maybe_set_default_scalar_range(source_dataset)
677
678 def clear_active_scalars(self) -> None:
679 """Detach the active scalars algorithm, if any.
680
681 Reconnects the mapper directly to its original input. This is the
682 inverse of :meth:`set_active_scalars` and is typically used when
683 switching back to solid-color rendering.
684
685 See Also
686 --------
687 set_active_scalars
688
689 """
690 if self._active_scalars_algo is None:
691 return
692 algo = self._active_scalars_algo
693 self._active_scalars_algo = None
694 if self._input_dataset is not None:
695 set_algorithm_input(self, self._input_dataset)
696 else:
697 in_conn = algo.GetInputConnection(0, 0)
698 if in_conn is not None:
699 self.SetInputConnection(0, in_conn)
700
701 def copy(self) -> _BaseMapper:
702 """Create a copy of this mapper.
703
704 Reproduces the active-scalars pipeline so the copy maps the same
705 array as the original while remaining independent of it.
706
707 Returns
708 -------
709 pyvista.DataSetMapper
710 A copy of this dataset mapper with its own active-scalars
711 pipeline.
712
713 """
714 new_mapper = cast('_DataSetMapper', super().copy())
715 new_mapper._input_dataset = self._input_dataset
716 new_mapper._use_default_scalar_range = self._use_default_scalar_range
717 if self._active_scalars_algo is not None:
718 new_mapper.set_active_scalars(
719 self._active_scalars_algo.scalars_name,
720 self._active_scalars_algo.preference,
721 )
722 return new_mapper
723
724 def _configure_scalars_mode(
725 self,
726 *,
727 scalars,
728 scalars_name,
729 preference,
730 direct_scalars_color_mode,
731 ) -> None:
732 """Configure scalar mode.
733
734 Parameters
735 ----------
736 scalars : numpy.ndarray
737 Array of scalars to assign to the mapper.
738
739 scalars_name : str
740 If the name of this array exists, scalars is ignored. Otherwise,
741 the scalars will be added to the existing dataset and this
742 parameter is the name to assign the scalars.
743
744 preference : str
745 Either ``'point'`` or ``'cell'``.
746
747 direct_scalars_color_mode : bool
748 When ``True``, scalars are treated as RGB colors. When
749 ``False``, scalars are mapped to the color table.
750
751 """
752 dataset = self.dataset
753 if dataset is not None:
754 if scalars.shape[0] == dataset.n_points and scalars.shape[0] == dataset.n_cells:
755 use_points = preference == 'point'
756 use_cells = not use_points
757 else:
758 use_points = scalars.shape[0] == dataset.n_points
759 use_cells = scalars.shape[0] == dataset.n_cells
760
761 # Set active scalars via an internal algorithm rather than mutating
762 # the dataset directly. This allows multiple mappers to share the
763 # same dataset while each independently controlling which array is
764 # active (see https://github.com/pyvista/pyvista/issues/542).
765 if use_points:
766 if (
767 scalars_name not in dataset.point_data
768 or scalars_name == pv.DEFAULT_SCALARS_NAME
769 ):
770 dataset.point_data.set_array(scalars, scalars_name, deep_copy=False)
771 self.set_active_scalars(scalars_name, 'point')
772 self.scalar_map_mode = 'point'
773 elif use_cells:
774 if (
775 scalars_name not in dataset.cell_data
776 or scalars_name == pv.DEFAULT_SCALARS_NAME
777 ):
778 dataset.cell_data.set_array(scalars, scalars_name, deep_copy=False)
779 self.set_active_scalars(scalars_name, 'cell')
780 self.scalar_map_mode = 'cell'
781 else:
782 raise_not_matching(scalars, dataset)
783
784 self.color_mode = 'direct' if direct_scalars_color_mode else 'map'
785
786 @_deprecate_positional_args(allowed=['scalars', 'scalars_name'])
787 def set_scalars( # noqa: PLR0917
788 self,
789 scalars,
790 scalars_name,
791 n_colors=256,
792 scalar_bar_args=None,
793 rgb=None,
794 component=None,
795 preference='point',
796 custom_opac: bool = False, # noqa: FBT001, FBT002
797 annotations=None,
798 log_scale: bool = False, # noqa: FBT001, FBT002
799 nan_color=None,
800 above_color=None,
801 below_color=None,
802 cmap=None,
803 flip_scalars: bool = False, # noqa: FBT001, FBT002
804 opacity=None,
805 categories: bool | int = False, # noqa: FBT001, FBT002
806 clim=None,
807 ):
808 """Set the scalars on this mapper.
809
810 Parameters
811 ----------
812 scalars : numpy.ndarray
813 Array of scalars to assign to the mapper.
814
815 scalars_name : str
816 If the name of this array exists, scalars is ignored. Otherwise,
817 the scalars will be added to the existing dataset and this
818 parameter is the name to assign the scalars.
819
820 n_colors : int, default: 256
821 Number of colors to use when displaying scalars.
822
823 scalar_bar_args : dict, optional
824 Dictionary of keyword arguments to pass when adding the
825 scalar bar to the scene. For options, see
826 :func:`pyvista.Plotter.add_scalar_bar`.
827
828 rgb : bool, default: False
829 If an 2 dimensional array is passed as the scalars, plot
830 those values as RGB(A) colors. ``rgba`` is also an
831 accepted alias for this. Opacity (the A) is optional. If
832 a scalars array ending with ``"_rgba"`` is passed, the default
833 becomes ``True``. This can be overridden by setting this
834 parameter to ``False``.
835
836 component : int, optional
837 Set component of vector valued scalars to plot. Must be
838 nonnegative, if supplied. If ``None``, the magnitude of
839 the vector is plotted.
840
841 preference : str, default: 'Point'
842 When ``dataset.n_points == dataset.n_cells`` and setting scalars,
843 this parameter sets how the scalars will be mapped to the mesh.
844 Can be either ``'point'`` or ``'cell'``.
845
846 custom_opac : bool, default: False
847 Use custom opacity.
848
849 annotations : dict, optional
850 Pass a dictionary of annotations. Keys are the float
851 values in the scalars range to annotate on the scalar bar
852 and the values are the string annotations.
853
854 log_scale : bool, default: False
855 Use log scale when mapping data to colors. Scalars less
856 than zero are mapped to the smallest representable
857 positive float.
858
859 nan_color : pyvista.ColorLike, optional
860 The color to use for all ``NaN`` values in the plotted
861 scalar array.
862
863 above_color : pyvista.ColorLike, optional
864 Solid color for values below the scalars range
865 (``clim``). This will automatically set the scalar bar
866 ``above_label`` to ``'above'``.
867
868 below_color : pyvista.ColorLike, optional
869 Solid color for values below the scalars range
870 (``clim``). This will automatically set the scalar bar
871 ``below_label`` to ``'below'``.
872
873 cmap : str, list, or pyvista.LookupTable
874 Name of the Matplotlib colormap to use when mapping the
875 ``scalars``. See available Matplotlib colormaps. Only applicable
876 for when displaying ``scalars``.
877 ``colormap`` is also an accepted alias for this. If
878 ``colorcet`` or ``cmocean`` are installed, their colormaps can be
879 specified by name.
880
881 You can also specify a list of colors to override an existing
882 colormap with a custom one. For example, to create a three color
883 colormap you might specify ``['green', 'red', 'blue']``.
884
885 This parameter also accepts a :class:`pyvista.LookupTable`. If this
886 is set, all parameters controlling the color map like ``n_colors``
887 will be ignored.
888
889 flip_scalars : bool, default: False
890 Flip direction of cmap. Most colormaps allow ``*_r`` suffix to do
891 this as well.
892
893 opacity : str or numpy.ndarray, optional
894 Opacity mapping for the scalars array.
895 A string can also be specified to map the scalars range to a
896 predefined opacity transfer function (options include: 'linear',
897 'linear_r', 'geom', 'geom_r'). Or you can pass a custom made
898 transfer function that is an array either ``n_colors`` in length or
899 shorter.
900
901 categories : bool, default: False
902 If set to ``True``, then the number of unique values in the scalar
903 array will be used as the ``n_colors`` argument.
904
905 clim : Sequence, optional
906 Color bar range for scalars. Defaults to minimum and
907 maximum of scalars array. Example: ``(-1, 2)``.
908
909 """
910 if scalar_bar_args is None:
911 scalar_bar_args = {'n_colors': n_colors}
912
913 if not isinstance(scalars, np.ndarray):
914 scalars = np.asarray(scalars)
915
916 # Set the array title for when it is added back to the mesh
917 if custom_opac:
918 scalars_name = '__custom_rgba'
919
920 if not np.issubdtype(scalars.dtype, np.number) and not isinstance(
921 cmap,
922 pv.LookupTable,
923 ):
924 # we can rapidly handle bools
925 if scalars.dtype == np.bool_:
926 cats = np.array([b'False', b'True'], dtype='|S5')
927 values = np.array([0, 1])
928 clim = [-0.5, 1.5]
929 else:
930 # If str array, digitize and annotate
931 cats, scalars = np.unique(scalars.astype('|S'), return_inverse=True)
932 values = np.unique(scalars)
933 clim = [np.min(values) - 0.5, np.max(values) + 0.5]
934 scalars_name = f'{scalars_name}-digitized'
935
936 n_colors = len(cats)
937 scalar_bar_args.setdefault('n_labels', 0)
938
939 self.lookup_table.SetAnnotations(convert_array(values), convert_string_array(cats))
940
941 # Use only the real component if an array is complex
942 if np.issubdtype(scalars.dtype, np.complexfloating):
943 scalars = scalars.astype(float)
944 scalars_name = f'{scalars_name}-real'
945
946 if scalars.ndim != 1:
947 if rgb:
948 pass
949 elif scalars.ndim == 2 and (
950 scalars.shape[0] == self.dataset.n_points # type: ignore[union-attr]
951 or scalars.shape[0] == self.dataset.n_cells # type: ignore[union-attr]
952 ):
953 scalars, scalars_name = reduce_component_scalars(scalars, scalars_name, component)
954 else:
955 scalars = scalars.ravel()
956
957 if scalars.dtype == np.bool_:
958 scalars = scalars.astype(np.float64)
959
960 # Set scalars range
961 use_default_scalar_range = clim is None
962 if clim is None:
963 clim = [np.nanmin(scalars), np.nanmax(scalars)]
964 elif isinstance(clim, (int, float)):
965 clim = [-clim, clim]
966
967 if log_scale and clim[0] <= 0:
968 clim = [sys.float_info.min, clim[1]]
969
970 if np.any(clim) and not rgb:
971 self._set_scalar_range((clim[0], clim[1]), use_default=use_default_scalar_range)
972
973 if isinstance(cmap, pv.LookupTable):
974 self.lookup_table = cmap
975 self._set_scalar_range(self.lookup_table.scalar_range, use_default=False)
976 else:
977 self.lookup_table.scalar_range = self.scalar_range
978 # Set default map
979 if cmap is None:
980 cmap = pv.global_theme.cmap if self._theme is None else self._theme.cmap
981
982 # have to add the attribute to pass it onward to some classes
983 if isinstance(cmap, str):
984 self._cmap = cmap
985 if categories:
986 if categories is True:
987 n_colors = len(np.unique(scalars))
988 elif isinstance(categories, int):
989 n_colors = categories
990
991 self.lookup_table.apply_cmap(cmap, n_colors)
992
993 # Set opactities
994 if isinstance(opacity, np.ndarray) and not custom_opac:
995 self.lookup_table.apply_opacity(opacity)
996
997 if flip_scalars:
998 self.lookup_table.values[:] = self.lookup_table.values[::-1]
999
1000 if custom_opac:
1001 # need to round the colors here since we're
1002 # directly displaying the colors
1003 hue = normalize(scalars, minimum=clim[0], maximum=clim[1])
1004 scalars = np.round(hue * n_colors) / n_colors
1005 scalars = get_cmap_safe(cmap)(scalars) * 255
1006 scalars[:, -1] *= opacity
1007 scalars = scalars.astype(np.uint8)
1008
1009 # configure the lookup table
1010 if nan_color:
1011 self.lookup_table.nan_color = nan_color
1012 if above_color:
1013 self.lookup_table.above_range_color = above_color
1014 scalar_bar_args.setdefault('above_label', 'above')
1015 if below_color:
1016 self.lookup_table.below_range_color = below_color
1017 scalar_bar_args.setdefault('below_label', 'below')
1018 if isinstance(annotations, dict):
1019 self.lookup_table.annotations = annotations
1020 self.lookup_table.log_scale = log_scale
1021
1022 self._configure_scalars_mode(
1023 scalars=scalars,
1024 scalars_name=scalars_name,
1025 preference=preference,
1026 direct_scalars_color_mode=rgb or custom_opac,
1027 )
1028
1029 if isinstance(self, PointGaussianMapper):
1030 self.as_rgba()
1031
1032 @property
1033 def cmap(self) -> str | None: # numpydoc ignore=RT01
1034 """Colormap assigned to this mapper.
1035
1036 See :ref:`named_colormaps` for supported colormaps.
1037 """
1038 return self._cmap
1039
1040 @property
1041 def resolve(self) -> str:
1042 """Set or return the global flag to avoid z-buffer resolution.
1043
1044 A global flag that controls whether the coincident topology
1045 (e.g., a line on top of a polygon) is shifted to avoid
1046 z-buffer resolution (and hence rendering problems).
1047
1048 If not off, there are two methods to choose from.
1049 `polygon_offset` uses graphics systems calls to shift polygons,
1050 lines, and points from each other.
1051 `shift_zbuffer` is a legacy method that is used to remap the z-buffer
1052 to distinguish vertices, lines, and polygons,
1053 but does not always produce acceptable results.
1054 You should only use the polygon_offset method (or none) at this point.
1055
1056 Returns
1057 -------
1058 str
1059 Global flag to avoid z-buffer resolution.
1060 Must be either `off`, `polygon_offset` or `shift_zbuffer`.
1061
1062 Examples
1063 --------
1064 >>> import pyvista as pv
1065 >>> from pyvista import examples
1066
1067 >>> mesh = examples.download_tri_quadratic_hexahedron()
1068 >>> surface_sep = mesh.separate_cells().extract_surface(
1069 ... algorithm=None, nonlinear_subdivision=4
1070 ... )
1071 >>> edges = surface_sep.extract_feature_edges()
1072 >>> surface = mesh.extract_surface(algorithm=None, nonlinear_subdivision=4)
1073
1074 >>> pl = pv.Plotter()
1075 >>> _ = pl.add_mesh(surface, smooth_shading=True, split_sharp_edges=True)
1076 >>> actor = pl.add_mesh(edges, color='k', line_width=3)
1077 >>> actor.mapper.resolve = 'polygon_offset'
1078 >>> pl.show()
1079
1080 """
1081 vtk_to_pv = {
1082 _vtk.VTK_RESOLVE_OFF: 'off',
1083 _vtk.VTK_RESOLVE_POLYGON_OFFSET: 'polygon_offset',
1084 _vtk.VTK_RESOLVE_SHIFT_ZBUFFER: 'shift_zbuffer',
1085 }
1086 return vtk_to_pv[self.GetResolveCoincidentTopology()]
1087
1088 @resolve.setter
1089 def resolve(self, resolve):
1090 if resolve == 'off':
1091 self.SetResolveCoincidentTopologyToOff()
1092 elif resolve == 'polygon_offset':
1093 self.SetResolveCoincidentTopologyToPolygonOffset()
1094 elif resolve == 'shift_zbuffer':
1095 self.SetResolveCoincidentTopologyToShiftZBuffer()
1096 else:
1097 msg = 'Resolve must be either "off", "polygon_offset" or "shift_zbuffer"'
1098 raise ValueError(msg)
1099
1100 @_deprecate_positional_args(allowed=['opacity'])
1101 def set_custom_opacity( # noqa: PLR0917
1102 self, opacity, color, n_colors, preference='point'
1103 ):
1104 """Set custom opacity.
1105
1106 Parameters
1107 ----------
1108 opacity : numpy.ndarray
1109 Opacity array to color the dataset. Array length must match either
1110 the number of points or cells.
1111
1112 color : pyvista.ColorLike
1113 The color to use with the opacity array.
1114
1115 n_colors : int
1116 Number of colors to use.
1117
1118 preference : str, default: 'point'
1119 Either ``'point'`` or ``'cell'``. Used when the number of cells
1120 matches the number of points.
1121
1122 """
1123 # Create a custom RGBA array to supply our opacity to
1124 if opacity.size == self.dataset.n_points: # type: ignore[union-attr]
1125 rgba = np.empty((self.dataset.n_points, 4), np.uint8) # type: ignore[union-attr]
1126 elif opacity.size == self.dataset.n_cells: # type: ignore[union-attr]
1127 rgba = np.empty((self.dataset.n_cells, 4), np.uint8) # type: ignore[union-attr]
1128 else: # pragma: no cover
1129 msg = (
1130 f'Opacity array size ({opacity.size}) does not equal '
1131 f'the number of points ({self.dataset.n_points}) or the ' # type: ignore[union-attr]
1132 f'number of cells ({self.dataset.n_cells}).', # type: ignore[union-attr]
1133 )
1134 raise ValueError(msg)
1135
1136 default_color = self._theme.color if self._theme is not None else pv.global_theme.color
1137
1138 rgba[:, :-1] = Color(color, default_color=default_color).int_rgb
1139 rgba[:, -1] = np.around(opacity * 255)
1140
1141 self.color_mode = 'direct'
1142 self.lookup_table.n_values = n_colors
1143 self._configure_scalars_mode(
1144 scalars=rgba, scalars_name='', preference=preference, direct_scalars_color_mode=True
1145 )
1146
1147 def __repr__(self):
1148 """Representation of the mapper."""
1149 mapper_attr = [
1150 f'{type(self).__name__} ({hex(id(self))})',
1151 f' Scalar visibility: {self.scalar_visibility}',
1152 f' Scalar range: {self.scalar_range}',
1153 f' Interpolate before mapping: {self.interpolate_before_map}',
1154 f' Scalar map mode: {self.scalar_map_mode}',
1155 f' Color mode: {self.color_mode}',
1156 '',
1157 ]
1158
1159 mapper_attr.append('Attached dataset:')
1160 mapper_attr.append(str(self.dataset))
1161
1162 return '\n'.join(mapper_attr)
1163
1164
1165 class DataSetMapper(_DataSetMapper, _vtk.vtkDataSetMapper):
1166 """Wrap :vtk:`vtkDataSetMapper`.
1167
1168 Parameters
1169 ----------
1170 dataset : pyvista.DataSet, optional
1171 Dataset to assign to this mapper.
1172
1173 theme : pyvista.plotting.themes.Theme, optional
1174 Plot-specific theme.
1175
1176 Examples
1177 --------
1178 Create a mapper outside :class:`pyvista.Plotter` and assign it to an
1179 actor.
1180
1181 >>> import pyvista as pv
1182 >>> mesh = pv.Cube()
1183 >>> mapper = pv.DataSetMapper(dataset=mesh)
1184 >>> actor = pv.Actor(mapper=mapper)
1185 >>> actor.plot()
1186
1187 """
1188
1189 def __init__(
1190 self,
1191 dataset: DataSet | None = None,
1192 theme: Theme | None = None,
1193 ) -> None:
1194 """Initialize this class."""
1195 super().__init__(dataset=dataset, theme=theme)
1196
1197
1198 class PointGaussianMapper(_DataSetMapper, _vtk.vtkPointGaussianMapper):
1199 """Wrap :vtk:`vtkPointGaussianMapper`.
1200
1201 Parameters
1202 ----------
1203 theme : pyvista.Theme, optional
1204 The theme to be used.
1205 emissive : bool, optional
1206 Whether or not the point should appear emissive. Default is set by the
1207 theme's ``lighting_params.emissive``.
1208 scale_factor : float, default: 1.0
1209 Scale factor applied to the point size.
1210
1211 """
1212
1213 def __init__(self, theme=None, emissive=None, scale_factor=1.0) -> None:
1214 super().__init__(theme=theme)
1215 if emissive is None:
1216 emissive = self._theme.lighting_params.emissive
1217 self.emissive = emissive
1218 self.scale_factor = scale_factor
1219
1220 @property
1221 def emissive(self) -> bool: # numpydoc ignore=RT01
1222 """Set or return emissive.
1223
1224 This treats points as emissive light sources. Two points that overlap
1225 will have their brightness combined.
1226 """
1227 return bool(self.GetEmissive())
1228
1229 @emissive.setter
1230 def emissive(self, value: bool) -> None:
1231 self.SetEmissive(value)
1232
1233 @property
1234 def scale_factor(self) -> float: # numpydoc ignore=RT01
1235 """Set or return the scale factor.
1236
1237 Ranges from 0 to 1. A value of 0 will cause the splats to be rendered
1238 as simple points. Defaults to 1.0.
1239
1240 """
1241 return self.GetScaleFactor()
1242
1243 @scale_factor.setter
1244 def scale_factor(self, value: float) -> None:
1245 self.SetScaleFactor(value)
1246
1247 @property
1248 def scale_array(self) -> str: # numpydoc ignore=RT01
1249 """Set or return the name of the array used to scale the splats.
1250
1251 Scalars used to scale the gaussian points. Accepts a string
1252 name of an array that is present on the mesh.
1253
1254 Notes
1255 -----
1256 Setting this automatically sets ``scale_factor = 1.0``.
1257
1258 Examples
1259 --------
1260 Plot spheres using `style='points_gaussian'` style and scale them by
1261 radius.
1262
1263 .. pyvista-plot::
1264 :force_static:
1265
1266 >>> import numpy as np
1267 >>> import pyvista as pv
1268 >>> n_spheres = 1_000
1269 >>> rng = np.random.default_rng(seed=0)
1270 >>> pos = rng.random((n_spheres, 3))
1271 >>> rad = rng.random(n_spheres) * 0.01
1272 >>> pdata = pv.PolyData(pos)
1273 >>> pdata['radius'] = rad
1274 >>> pl = pv.Plotter()
1275 >>> actor = pl.add_mesh(
1276 ... pdata,
1277 ... style='points_gaussian',
1278 ... emissive=False,
1279 ... render_points_as_spheres=True,
1280 ... )
1281 >>> actor.mapper.scale_array = 'radius'
1282 >>> pl.show()
1283
1284 """
1285 return self.GetScaleArray()
1286
1287 @scale_array.setter
1288 def scale_array(self, name: str):
1289 if not self.dataset: # pragma: no cover
1290 msg = 'Missing dataset.'
1291 raise RuntimeError(msg)
1292 if name not in self.dataset.point_data:
1293 available_arrays = ', '.join(self.dataset.point_data.keys())
1294 msg = (
1295 f'Point array "{name}" does not exist. '
1296 f'Available point arrays are: {available_arrays}'
1297 )
1298 raise KeyError(msg)
1299
1300 self.scale_factor = 1.0
1301 self.SetScaleArray(name)
1302
1303 def use_circular_splat(self, opacity: float = 1.0) -> None:
1304 """Set the fragment shader code to create a circular splat.
1305
1306 Parameters
1307 ----------
1308 opacity : float, default: 1.0
1309 Desired opacity between 0 and 1.
1310
1311 Notes
1312 -----
1313 This very close to ParaView's PointGaussianMapper, but uses opacity to
1314 modify the scale as the opacity cannot be set from the actor's property.
1315
1316 """
1317 self.SetSplatShaderCode(
1318 '//VTK::Color::Impl\n'
1319 'float dist = dot(offsetVCVSOutput.xy,offsetVCVSOutput.xy);\n'
1320 'if (dist > 1.0) {\n'
1321 ' discard;\n'
1322 '} else {\n'
1323 f' float scale = ({opacity} - dist);\n'
1324 ' ambientColor *= scale;\n'
1325 ' diffuseColor *= scale;\n'
1326 '}\n',
1327 )
1328 # maintain consistency with the default style
1329 self.scale_factor *= 1.5
1330
1331 def use_default_splat(self) -> None:
1332 """Clear the fragment shader and use the default splat."""
1333 self.SetSplatShaderCode(None) # type: ignore[arg-type]
1334 self.scale_factor /= 1.5
1335
1336 def __repr__(self):
1337 """Representation of the Gaussian mapper."""
1338 mapper_attr = [
1339 f'{type(self).__name__} ({hex(id(self))})',
1340 f' Scalar visibility: {self.scalar_visibility}',
1341 f' Scalar range: {self.scalar_range}',
1342 f' Emissive: {self.emissive}',
1343 f' Scale Factor: {self.scale_factor}',
1344 f' Using custom splat: {self.GetSplatShaderCode() is None}',
1345 '',
1346 ]
1347
1348 mapper_attr.append('Attached dataset:')
1349 mapper_attr.append(str(self.dataset))
1350
1351 return '\n'.join(mapper_attr)
1352
1353
1354 @abstract_class
1355 class _BaseVolumeMapper(_BaseMapper):
1356 """Volume mapper class to override methods and attributes for to volume mappers."""
1357
1358 def __init__(self, theme=None) -> None:
1359 """Initialize this class."""
1360 super().__init__(theme=theme)
1361 self._lut = LookupTable()
1362 self._scalar_range = (0.0, 256.0)
1363
1364 @property
1365 def interpolate_before_map(self) -> bool | None: # numpydoc ignore=RT01
1366 """Interpolate before map is not supported with volume mappers."""
1367 return None
1368
1369 @interpolate_before_map.setter
1370 def interpolate_before_map(self, *args) -> None:
1371 pass
1372
1373 @property
1374 def dataset(self): # numpydoc ignore=RT01
1375 """Return or set the dataset assigned to this mapper."""
1376 return wrap(_mapper_get_data_set_input(self))
1377
1378 @dataset.setter
1379 def dataset(
1380 self,
1381 obj: DataSet | _vtk.vtkAlgorithm | _vtk.vtkAlgorithmOutput,
1382 ) -> None:
1383 set_algorithm_input(self, obj)
1384
1385 @property
1386 def lookup_table(self): # numpydoc ignore=RT01
1387 return self._lut
1388
1389 @lookup_table.setter
1390 def lookup_table(self, lut) -> None:
1391 self._lut = lut
1392
1393 @property
1394 def scalar_range(self) -> tuple[float, float]: # numpydoc ignore=RT01
1395 """Return or set the scalar range."""
1396 return self._scalar_range
1397
1398 @scalar_range.setter
1399 def scalar_range(self, clim) -> None:
1400 if self.lookup_table is not None:
1401 self.lookup_table.SetRange(*clim)
1402 self._scalar_range = tuple(clim)
1403
1404 @property
1405 def blend_mode(self) -> str: # numpydoc ignore=RT01
1406 """Return or set the blend mode.
1407
1408 One of the following:
1409
1410 * ``"composite"``
1411 * ``"maximum"``
1412 * ``"minimum"``
1413 * ``"average"``
1414 * ``"additive"``
1415
1416 Also accepts integer values corresponding to
1417 :vtk:`vtkVolumeMapper.BlendModes`. For example
1418 :vtk:`vtkVolumeMapper.COMPOSITE_BLEND`.
1419
1420 """
1421 value = self.GetBlendMode()
1422 mode = {
1423 0: 'composite',
1424 1: 'maximum',
1425 2: 'minimum',
1426 3: 'average',
1427 4: 'additive',
1428 }.get(value)
1429 if mode is None: # pragma: no cover
1430 msg = f'Unsupported blend mode return value {value}'
1431 raise NotImplementedError(msg)
1432 return mode
1433
1434 @blend_mode.setter
1435 def blend_mode(self, value: str | int):
1436 if isinstance(value, int):
1437 self.SetBlendMode(value)
1438 elif isinstance(value, str):
1439 value = value.lower()
1440 if value in ['additive', 'add', 'sum']:
1441 self.SetBlendModeToAdditive()
1442 elif value in ['average', 'avg', 'average_intensity']:
1443 self.SetBlendModeToAverageIntensity()
1444 elif value in ['composite', 'comp']:
1445 self.SetBlendModeToComposite()
1446 elif value in ['maximum', 'max', 'maximum_intensity']:
1447 self.SetBlendModeToMaximumIntensity()
1448 elif value in ['minimum', 'min', 'minimum_intensity']:
1449 self.SetBlendModeToMinimumIntensity()
1450 else:
1451 msg = (
1452 f'Blending mode {value!r} invalid. '
1453 'Please choose either "additive", '
1454 '"composite", "minimum" or "maximum".'
1455 )
1456 raise ValueError(msg)
1457 else:
1458 msg = f'`blend_mode` should be either an int or str, not `{type(value)}`' # type: ignore[unreachable]
1459 raise TypeError(msg)
1460
1461 def __del__(self) -> None:
1462 if hasattr(self, '_lut'):
1463 del self._lut
1464
1465
1466 class FixedPointVolumeRayCastMapper(_BaseVolumeMapper, _vtk.vtkFixedPointVolumeRayCastMapper):
1467 """Wrap :vtk:`vtkFixedPointVolumeRayCastMapper`."""
1468
1469 def __init__(self, theme=None) -> None:
1470 """Initialize this class."""
1471 super().__init__(theme=theme)
1472 self.AutoAdjustSampleDistancesOff()
1473
1474
1475 class GPUVolumeRayCastMapper(_BaseVolumeMapper, _vtk.vtkGPUVolumeRayCastMapper):
1476 """Wrap :vtk:`vtkGPUVolumeRayCastMapper`."""
1477
1478 def __init__(self, theme=None) -> None:
1479 """Initialize this class."""
1480 super().__init__(theme=theme)
1481 self.AutoAdjustSampleDistancesOff()
1482
1483
1484 class OpenGLGPUVolumeRayCastMapper(_BaseVolumeMapper, _vtk.vtkOpenGLGPUVolumeRayCastMapper):
1485 """Wrap :vtk:`vtkOpenGLGPUVolumeRayCastMapper`."""
1486
1487 def __init__(self, theme=None) -> None:
1488 """Initialize this class."""
1489 super().__init__(theme=theme)
1490 self.AutoAdjustSampleDistancesOff()
1491
1492
1493 class SmartVolumeMapper(_BaseVolumeMapper, _vtk.vtkSmartVolumeMapper):
1494 """Wrap :vtk:`vtkSmartVolumeMapper`."""
1495
1496 def __init__(self, theme=None) -> None:
1497 """Initialize this class."""
1498 super().__init__(theme=theme)
1499 self.AutoAdjustSampleDistancesOff()
1500 self.InteractiveAdjustSampleDistancesOff()
1501
1502
1503 class UnstructuredGridVolumeRayCastMapper(
1504 _BaseVolumeMapper, _vtk.vtkUnstructuredGridVolumeRayCastMapper
1505 ):
1506 """Wrap :vtk:`vtkUnstructuredGridVolumeMapper`."""
1507
1508 def __init__(self, theme=None) -> None:
1509 """Initialize this class."""
1510 super().__init__(theme=theme)
1511 self.AutoAdjustSampleDistancesOff()
1512
1513
1514 def _mapper_has_data_set_input(mapper):
1515 """Check if mapper has a data set input using the appropriate method.
1516
1517 Some mappers use 'GetDataSetInput', others use 'GetInputAsDataSet'. This has
1518 been standardized to 'GetDataSetInput' in VTK >= 9.5.
1519 """
1520 return hasattr(mapper, 'GetDataSetInput') or hasattr(mapper, 'GetInputAsDataSet')
1521
1522
1523 def _mapper_get_data_set_input(mapper) -> _vtk.vtkDataSet:
1524 """Get data set input from mapper using the appropriate method.
1525
1526 Some mappers use 'GetDataSetInput', others use 'GetInputAsDataSet'. This has
1527 been standardized to 'GetDataSetInput' in VTK >= 9.5.
1528 """
1529 return (
1530 mapper.GetDataSetInput()
1531 if hasattr(mapper, 'GetDataSetInput')
1532 else mapper.GetInputAsDataSet()
1533 )