Debian Codegraph @

pyvista/plotting/volume_property.py

raw
1 """Wrapper for :vtk:`vtkVolumeProperty`."""
2
3 from __future__ import annotations
4
5 from typing import TYPE_CHECKING
6 import weakref
7
8 import pyvista as pv
9 from pyvista import _vtk
10 from pyvista._deprecate_positional_args import _deprecate_positional_args
11 from pyvista.core._vtk_utilities import DisableVtkSnakeCase
12 from pyvista.core.utilities.misc import _NoNewAttrMixin
13
14 if TYPE_CHECKING:
15 from pyvista import LookupTable
16
17
18 class VolumeProperty(_NoNewAttrMixin, DisableVtkSnakeCase, _vtk.vtkVolumeProperty):
19 """Wrap the VTK class :vtk:`vtkVolumeProperty`.
20
21 This class is used to represent common properties associated with volume
22 rendering. This includes properties for determining the type of
23 interpolation to use when sampling a volume, the color of a volume, the
24 scalar opacity of a volume, the gradient opacity of a volume, and the
25 shading parameters of a volume.
26
27 Parameters
28 ----------
29 lookup_table : pyvista.LookupTable, optional
30 Lookup table to set the color and opacity transfer functions.
31
32 interpolation_type : str, optional
33 Value must be either ``'linear'`` or ``'nearest'``.
34
35 ambient : float, optional
36 When lighting is enabled, this is the amount of light in
37 the range of 0 to 1 (default 0.0) that reaches the actor
38 when not directed at the light source emitted from the
39 viewer.
40
41 diffuse : float, optional
42 The diffuse lighting coefficient.
43
44 specular : float, optional
45 The specular lighting coefficient.
46
47 specular_power : float, optional
48 The specular power. Between 0.0 and 128.0.
49
50 shade : bool, optional
51 Enable or disable volume shading. If shading is turned off, then the
52 mapper for the volume will not perform shading calculations. If shading
53 is turned on, the mapper may perform shading calculations - in some
54 cases shading does not apply (for example, in a maximum intensity
55 projection) and therefore shading will not be performed even if this
56 flag is on. For a compositing type of mapper, turning shading off is
57 generally the same as setting ``ambient=1``, ``diffuse=0``,
58 ``specular=0``. Shading can be independently turned on/off per
59 component.
60
61 opacity_unit_distance : float, optional
62 This is the unit distance on which the scalar opacity transfer function
63 is defined. By default this is 1.0, meaning that over a distance of 1.0
64 units, a given opacity (from the transfer function) is
65 accumulated. This is adjusted for the actual sampling distance during
66 rendering.
67
68 Examples
69 --------
70 Create a sample dataset from perlin noise and apply a lookup table to the
71 :class:`VolumeProperty`.
72
73 >>> import pyvista as pv
74 >>> noise = pv.perlin_noise(1, (1, 3, 5), (0, 0, 0))
75 >>> grid = pv.sample_function(
76 ... noise, bounds=[0, 3.0, -0, 1.0, 0, 1.0], dim=(40, 40, 40)
77 ... )
78 >>> pl = pv.Plotter()
79 >>> actor = pl.add_volume(grid, show_scalar_bar=False)
80 >>> lut = actor.mapper.lookup_table
81 >>> lut.cmap = 'bwr'
82 >>> lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])
83 >>> pl.show()
84
85 """
86
87 @_deprecate_positional_args
88 def __init__( # noqa: PLR0917
89 self,
90 lookup_table=None,
91 interpolation_type=None,
92 ambient=None,
93 diffuse=None,
94 specular=None,
95 specular_power=None,
96 shade=None,
97 opacity_unit_distance=None,
98 ):
99 """Initialize the :vtk:`vtkVolumeProperty` class."""
100 super().__init__()
101 self._lookup_table_ = None
102 self._lookup_table_observer_id = None
103 if lookup_table is not None:
104 self.apply_lookup_table(lookup_table)
105 if interpolation_type is not None:
106 self.interpolation_type = interpolation_type
107 if ambient is not None:
108 self.ambient = ambient
109 if diffuse is not None:
110 self.diffuse = diffuse
111 if specular is not None:
112 self.specular = specular
113 if specular_power is not None:
114 self.specular_power = specular_power
115 if shade is not None:
116 self.shade = shade
117 if opacity_unit_distance is not None:
118 self.opacity_unit_distance = opacity_unit_distance
119
120 @property
121 def _lookup_table(self) -> LookupTable | None:
122 """Get the lookup table if applied via apply_lookup_table."""
123 if self._lookup_table_ is not None:
124 return self._lookup_table_()
125 return None
126
127 @_lookup_table.setter
128 def _lookup_table(self, lookup_table: LookupTable):
129 """Set the lookup table if applied via apply_lookup_table."""
130 if self._lookup_table is not None and self._lookup_table_observer_id is not None:
131 # Clean up the old lookup table observer
132 self._lookup_table.RemoveObserver(self._lookup_table_observer_id)
133 self._lookup_table_observer_id = None
134 self._lookup_table_ = weakref.ref(lookup_table)
135 self._lookup_table_observer_id = lookup_table.AddObserver(
136 _vtk.vtkCommand.ModifiedEvent,
137 lambda *_: self.reapply_lookup_table(),
138 )
139
140 def reapply_lookup_table(self):
141 """Reapply the lookup table previously applied.
142
143 The VolumeProperty is unable to keep a dynamic link to the colors
144 and mapping laid out in the lookup table. This method allows you to
145 reapply the lookup table to the VolumeProperty. This is useful if
146 you modify the lookup table after it is applied to the
147 VolumeProperty.
148
149 We have our own modified event observer to reapply this automatically
150 when the lookup table is modified.
151
152 """
153 if self._lookup_table is not None:
154 self.apply_lookup_table(self._lookup_table)
155
156 def apply_lookup_table(self, lookup_table: LookupTable):
157 """Apply a lookup table to the volume property.
158
159 Applies both the color and opacity of the lookup table as transfer
160 functions.
161
162 Parameters
163 ----------
164 lookup_table : pyvista.LookupTable, optional
165 Lookup table to set the color and opacity transfer functions.
166
167 Examples
168 --------
169 Plot perlin noise volumetrically using a custom lookup table.
170
171 >>> import pyvista as pv
172 >>> noise = pv.perlin_noise(1, (1, 3, 5), (0, 0, 0))
173 >>> grid = pv.sample_function(
174 ... noise, bounds=[0, 3.0, -0, 1.0, 0, 1.0], dim=(40, 40, 40)
175 ... )
176 >>> pl = pv.Plotter()
177 >>> actor = pl.add_volume(grid, show_scalar_bar=False)
178 >>> lut = actor.mapper.lookup_table
179 >>> lut.cmap = 'bwr'
180 >>> lut.apply_opacity([1.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3])
181 >>> pl.show()
182
183 """
184 if not isinstance(lookup_table, pv.LookupTable):
185 msg = '`lookup_table` must be a `pyvista.LookupTable`'
186 raise TypeError(msg)
187 if self._lookup_table != lookup_table:
188 self._lookup_table = lookup_table
189 self.SetColor(lookup_table.to_color_tf())
190 self.SetScalarOpacity(lookup_table.to_opacity_tf())
191
192 def __del__(self):
193 """Clean up the lookup table observer when the object is deleted."""
194 if self._lookup_table_observer_id is not None and self._lookup_table is not None:
195 self._lookup_table.RemoveObserver(self._lookup_table_observer_id)
196 self._lookup_table_observer_id = None
197 self._lookup_table_ = None
198
199 @property
200 def interpolation_type(self) -> str: # numpydoc ignore=RT01
201 """Return or set the interpolation type.
202
203 Value must be either ``'linear'`` or ``'nearest'``.
204
205 Examples
206 --------
207 Create a sample :class:`pyvista.ImageData` dataset.
208
209 >>> import numpy as np
210 >>> import pyvista as pv
211 >>> n = 21
212 >>> c = -(n - 1) / 2
213 >>> vol = pv.ImageData(dimensions=(n, n, n), origin=(c, c, c))
214 >>> scalars = np.linalg.norm(vol.points, axis=1)
215 >>> scalars *= 255 / scalars.max()
216 >>> vol['scalars'] = scalars
217
218 Demonstrate nearest (default) interpolation.
219
220 >>> pl = pv.Plotter()
221 >>> actor = pl.add_volume(
222 ... vol,
223 ... show_scalar_bar=False,
224 ... opacity=[0.3, 0.0, 0.05, 0.0, 0.0, 0.0, 1.0, 0.0],
225 ... cmap='plasma',
226 ... )
227 >>> actor.prop.interpolation_type = 'nearest'
228 >>> pl.show()
229
230 Demonstrate linear interpolation.
231
232 >>> pl = pv.Plotter()
233 >>> actor = pl.add_volume(
234 ... vol,
235 ... show_scalar_bar=False,
236 ... opacity=[0.3, 0.0, 0.05, 0.0, 0.0, 0.0, 1.0, 0.0],
237 ... cmap='plasma',
238 ... )
239 >>> actor.prop.interpolation_type = 'linear'
240 >>> pl.show()
241
242 """
243 return self.GetInterpolationTypeAsString().split()[0].lower()
244
245 @interpolation_type.setter
246 def interpolation_type(self, value: str):
247 if value == 'linear':
248 self.SetInterpolationTypeToLinear()
249 elif value == 'nearest':
250 self.SetInterpolationTypeToNearest()
251 else:
252 msg = '`interpolation_type` must be either "linear" or "nearest"'
253 raise ValueError(msg)
254
255 @property
256 def opacity_unit_distance(self) -> float: # numpydoc ignore=RT01
257 """Return or set the opacity unit distance.
258
259 This is the unit distance on which the scalar opacity transfer function
260 is defined.
261
262 By default this is 1.0, meaning that over a distance of 1.0 units, a
263 given opacity (from the transfer function) is accumulated. This is
264 adjusted for the actual sampling distance during rendering.
265 """
266 return self.GetScalarOpacityUnitDistance()
267
268 @opacity_unit_distance.setter
269 def opacity_unit_distance(self, value: float):
270 self.SetScalarOpacityUnitDistance(value)
271
272 @property
273 def shade(self) -> bool: # numpydoc ignore=RT01
274 """Return or set shading of a volume.
275
276 If shading is turned off, then the mapper for the volume will not
277 perform shading calculations. If shading is turned on, the mapper may
278 perform shading calculations - in some cases shading does not apply
279 (for example, in a maximum intensity projection) and therefore shading
280 will not be performed even if this flag is on. For a compositing type
281 of mapper, turning shading off is generally the same as setting
282 ``ambient=1``, ``diffuse=0``, ``specular=0``. Shading can be
283 independently turned on/off per component.
284
285 """
286 return bool(self.GetShade())
287
288 @shade.setter
289 def shade(self, value: bool):
290 self.SetShade(value)
291
292 @property
293 def independent_components(self) -> bool: # numpydoc ignore=RT01
294 """Return or set independent components.
295
296 If ``False``, then you must have either 2 or 4 component data.
297 For 2 component data, the first is passed through the
298 first color transfer function and the second component is passed
299 through the first scalar opacity (and gradient opacity) transfer
300 function. Normals will be generated off of the second component. When
301 using gradient based opacity modulation, the gradients are computed off
302 of the second component.
303
304 For 4 component data, the first three will directly represent RGB (no
305 lookup table). The fourth component will be passed through the first
306 scalar opacity transfer function for opacity and first gradient opacity
307 transfer function for gradient based opacity modulation. Normals will
308 be generated from the fourth component. When using gradient based
309 opacity modulation, the gradients are computed off of the fourth
310 component.
311 """
312 return bool(self.GetIndependentComponents())
313
314 @independent_components.setter
315 def independent_components(self, value: bool):
316 self.SetIndependentComponents(value)
317
318 @property
319 def ambient(self) -> float: # numpydoc ignore=RT01
320 """Return or set ambient lighting coefficient.
321
322 This is the amount of light in the range of 0 to 1 (default 0.0) that
323 reaches the actor when not directed at the light source emitted from
324 the viewer.
325
326 Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
327 set to ``True``.
328
329 """
330 return self.GetAmbient()
331
332 @ambient.setter
333 def ambient(self, value: float):
334 self.SetAmbient(value)
335
336 @property
337 def diffuse(self) -> float: # numpydoc ignore=RT01
338 """Return or set the diffuse lighting coefficient.
339
340 This is the scattering of light by reflection or transmission. Diffuse
341 reflection results when light strikes an irregular surface such as a
342 frosted window or the surface of a frosted or coated light bulb.
343
344 Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
345 set to ``True``.
346
347 """
348 return self.GetDiffuse()
349
350 @diffuse.setter
351 def diffuse(self, value: float):
352 self.SetDiffuse(value)
353
354 @property
355 def specular(self) -> float: # numpydoc ignore=RT01
356 """Return or set specular.
357
358 Default 0.0
359
360 Specular lighting simulates the bright spot of a light that appears on
361 shiny objects.
362
363 Changing attribute has no effect unless :attr:`VolumeProperty.shade` is
364 set to ``True``.
365
366 """
367 return self.GetSpecular()
368
369 @specular.setter
370 def specular(self, value: float):
371 self.SetSpecular(value)
372
373 @property
374 def specular_power(self) -> float: # numpydoc ignore=RT01
375 """Return or set specular power.
376
377 The specular power. Between 0.0 and 128.0. Default 10.0
378
379 """
380 return self.GetSpecularPower()
381
382 @specular_power.setter
383 def specular_power(self, value: float):
384 self.SetSpecularPower(value)
385
386 def copy(self) -> VolumeProperty:
387 """Create a deep copy of this property.
388
389 Returns
390 -------
391 pyvista.plotting.volume_property.VolumeProperty
392 Deep copy of this property.
393
394 """
395 new_prop = VolumeProperty()
396 new_prop.DeepCopy(self)
397 return new_prop
398
399 def __repr__(self):
400 """Representation of this property."""
401 props = [
402 f'{type(self).__name__} ({hex(id(self))})',
403 ]
404
405 for attr in dir(self):
406 if not attr.startswith('_') and attr[0].islower():
407 name = ' '.join(attr.split('_')).capitalize() + ':'
408 try:
409 value = getattr(self, attr)
410 except AttributeError: # pragma:no cover
411 continue
412 if callable(value):
413 continue
414 if isinstance(value, str):
415 value = f'"{value}"'
416 props.append(f' {name:28s} {value}')
417
418 return '\n'.join(props)