Debian Codegraph @

pyvista/plotting/renderers.py

raw
1 """Organize Renderers for ``pyvista.Plotter``."""
2
3 from __future__ import annotations
4
5 from collections.abc import Sequence
6 from itertools import product
7 from weakref import proxy
8
9 import numpy as np
10
11 import pyvista as pv
12 from pyvista._deprecate_positional_args import _deprecate_positional_args
13 from pyvista.core.utilities.misc import _NoNewAttrMixin
14
15 from .background_renderer import BackgroundRenderer
16 from .renderer import Renderer
17
18
19 class Renderers(_NoNewAttrMixin):
20 """Organize Renderers for ``pyvista.Plotter``.
21
22 Parameters
23 ----------
24 plotter : str
25 The PyVista plotter.
26
27 shape : tuple[int], optional
28 The initial shape of the PyVista plotter, (rows, columns).
29
30 splitting_position : float, optional
31 The position to place the splitting line between plots.
32
33 row_weights : sequence, optional
34 The weights of the rows when the plot window is resized.
35
36 col_weights : sequence, optional
37 The weights of the columns when the plot window is resized.
38
39 groups : list, optional
40 A list of sequences that defines the grouping of the sub-datasets.
41
42 border : bool, optional
43 Whether or not a border should be added around each subplot.
44
45 border_color : str, optional
46 The color of the border around each subplot.
47
48 border_width : float, optional
49 The width of the border around each subplot.
50
51 """
52
53 @_deprecate_positional_args(allowed=['plotter'])
54 def __init__( # noqa: PLR0917
55 self,
56 plotter,
57 shape=(1, 1),
58 splitting_position=None,
59 row_weights=None,
60 col_weights=None,
61 groups=None,
62 border=None,
63 border_color='k',
64 border_width=2.0,
65 ):
66 """Initialize renderers."""
67 self._active_index = 0 # index of the active renderer
68 self._plotter = proxy(plotter)
69 self._renderers = []
70 self._shadow_renderer = None
71
72 # by default add border for multiple plots
73 if border is None:
74 border = shape != (1, 1)
75
76 self.groups = np.empty((0, 4), dtype=int)
77
78 if isinstance(shape, str):
79 if '|' in shape:
80 n = int(shape.split('|')[0])
81 m = int(shape.split('|')[1])
82 rangen = reversed(range(n))
83 rangem = reversed(range(m))
84 else:
85 m = int(shape.split('/')[0])
86 n = int(shape.split('/')[1])
87 rangen = range(n) # type: ignore[assignment]
88 rangem = range(m) # type: ignore[assignment]
89
90 if splitting_position is None:
91 splitting_position = pv.global_theme.multi_rendering_splitting_position
92
93 if splitting_position is None:
94 xsplit = m / (n + m) if n >= m else 1 - n / (n + m)
95 else:
96 xsplit = splitting_position
97
98 for i in rangen:
99 arenderer = Renderer(
100 self._plotter,
101 border=border,
102 border_color=border_color,
103 border_width=border_width,
104 )
105 if '|' in shape:
106 arenderer.viewport = (0, i / n, xsplit, (i + 1) / n)
107 else:
108 arenderer.viewport = (i / n, 0, (i + 1) / n, xsplit)
109 self._renderers.append(arenderer)
110 for i in rangem:
111 arenderer = Renderer(
112 self._plotter,
113 border=border,
114 border_color=border_color,
115 border_width=border_width,
116 )
117 if '|' in shape:
118 arenderer.viewport = (xsplit, i / m, 1, (i + 1) / m)
119 else:
120 arenderer.viewport = (i / m, xsplit, (i + 1) / m, 1)
121 self._renderers.append(arenderer)
122
123 self._shape = (n + m,)
124 self._render_idxs = np.arange(n + m)
125
126 else:
127 if not isinstance(shape, (np.ndarray, Sequence)):
128 msg = '"shape" should be a list, tuple or string descriptor'
129 raise TypeError(msg)
130 if len(shape) != 2:
131 msg = '"shape" must have length 2.'
132 raise ValueError(msg)
133 shape = np.asarray(shape)
134 if not np.issubdtype(shape.dtype, np.integer) or (shape <= 0).any():
135 msg = '"shape" must contain only positive integers.'
136 raise ValueError(msg)
137 # always assign shape as a tuple of native ints
138 self._shape = tuple(size.item() for size in shape)
139 self._render_idxs = np.empty(self._shape, dtype=int)
140 # Check if row and col weights correspond to given shape,
141 # or initialize them to defaults (equally weighted).
142
143 # and convert to normalized offsets
144 if row_weights is None:
145 row_weights = np.ones(shape[0])
146 if col_weights is None:
147 col_weights = np.ones(shape[1])
148
149 # also make flattening and abs explicit
150 row_weights = np.abs(np.asanyarray(row_weights).ravel())
151 col_weights = np.abs(np.asanyarray(col_weights).ravel())
152 if row_weights.size != shape[0]:
153 msg = (
154 f'"row_weights" must have {shape[0]} items '
155 f'for {shape[0]} rows of subplots, not '
156 f'{row_weights.size}.'
157 )
158 raise ValueError(msg)
159 if col_weights.size != shape[1]:
160 msg = (
161 f'"col_weights" must have {shape[1]} items '
162 f'for {shape[1]} columns of subplots, not '
163 f'{col_weights.size}.'
164 )
165 raise ValueError(msg)
166 row_off = np.cumsum(row_weights) / np.sum(row_weights)
167 row_off = 1 - np.concatenate(([0], row_off))
168 col_off = np.cumsum(col_weights) / np.sum(col_weights)
169 col_off = np.concatenate(([0], col_off))
170
171 # Check and convert groups to internal format (Nx4 matrix
172 # where every row contains the row and col index of the
173 # top left cell)
174
175 if groups is not None:
176 if not isinstance(groups, Sequence):
177 msg = f'"groups" should be a list or tuple, not {type(groups).__name__}.'
178 raise TypeError(msg)
179 for group in groups:
180 if not isinstance(group, Sequence):
181 msg = (
182 'Each group entry should be a list or '
183 f'tuple, not {type(group).__name__}.'
184 )
185 raise TypeError(msg)
186 if len(group) != 2:
187 msg = 'Each group entry must have length 2.'
188 raise ValueError(msg)
189
190 rows = group[0]
191 if isinstance(rows, slice):
192 rows = np.arange(self.shape[0], dtype=int)[rows]
193 cols = group[1]
194 if isinstance(cols, slice):
195 cols = np.arange(self.shape[1], dtype=int)[cols] # type: ignore[misc]
196 # Get the normalized group, i.e. extract top left corner
197 # and bottom right corner from the given rows and cols
198 norm_group = [np.min(rows), np.min(cols), np.max(rows), np.max(cols)]
199 # Check for overlap with already defined groups:
200 for i, j in product(
201 range(norm_group[0], norm_group[2] + 1),
202 range(norm_group[1], norm_group[3] + 1),
203 ):
204 if self.loc_to_group((i, j)) is not None:
205 msg = f'Groups cannot overlap. Overlap found at position {(i, j)}.'
206 raise ValueError(msg)
207 self.groups = np.concatenate(
208 (self.groups, np.array([norm_group], dtype=int)),
209 axis=0,
210 )
211 # Create subplot renderers
212 for row, col in product(range(shape[0]), range(shape[1])):
213 group = self.loc_to_group((row, col))
214 nb_rows = None
215 nb_cols = None
216 if group is not None:
217 if row == self.groups[group, 0] and col == self.groups[group, 1]:
218 # Only add renderer for first location of the group
219 nb_rows = 1 + self.groups[group, 2] - self.groups[group, 0]
220 nb_cols = 1 + self.groups[group, 3] - self.groups[group, 1]
221 else:
222 nb_rows = 1
223 nb_cols = 1
224 if nb_rows is not None:
225 renderer = Renderer(
226 self._plotter,
227 border=border,
228 border_color=border_color,
229 border_width=border_width,
230 )
231 x0 = col_off[col]
232 y0 = row_off[row + nb_rows]
233 x1 = col_off[col + nb_cols] # type: ignore[operator]
234 y1 = row_off[row]
235 renderer.viewport = (x0, y0, x1, y1)
236 self._render_idxs[row, col] = len(self)
237 self._renderers.append(renderer)
238 else:
239 self._render_idxs[row, col] = self._render_idxs[
240 self.groups[group, 0],
241 self.groups[group, 1],
242 ]
243
244 # each render will also have an associated background renderer
245 self._background_renderers: list[None | BackgroundRenderer] = [
246 None for _ in range(len(self))
247 ]
248
249 # create a shadow renderer that lives on top of all others
250 self._shadow_renderer = Renderer(
251 self._plotter, border=border, border_color=border_color, border_width=border_width
252 )
253 self._shadow_renderer.viewport = (0, 0, 1, 1)
254 self._shadow_renderer.SetDraw(False)
255
256 def loc_to_group(self, loc):
257 """Return index of the render window given a location index.
258
259 Parameters
260 ----------
261 loc : int | sequence[int]
262 Index of the renderer to add the actor to. For example, ``loc=2``
263 or ``loc=(1, 1)``.
264
265 Returns
266 -------
267 int
268 Index of the render window.
269
270 """
271 group_idxs = np.arange(self.groups.shape[0])
272 index = (
273 (loc[0] >= self.groups[:, 0])
274 & (loc[0] <= self.groups[:, 2])
275 & (loc[1] >= self.groups[:, 1])
276 & (loc[1] <= self.groups[:, 3])
277 )
278 group = group_idxs[index]
279 return None if group.size == 0 else group[0]
280
281 def loc_to_index(self, loc):
282 """Return index of the render window given a location index.
283
284 Parameters
285 ----------
286 loc : int | sequence[int]
287 Index of the renderer to add the actor to. For example, ``loc=2``
288 or ``loc=(1, 1)``.
289
290 Returns
291 -------
292 int
293 Index of the render window.
294
295 """
296 if isinstance(loc, (int, np.integer)):
297 return loc
298 elif isinstance(loc, (np.ndarray, Sequence)):
299 if len(loc) != 2:
300 msg = '"loc" must contain two items'
301 raise ValueError(msg)
302 index_row = loc[0]
303 index_column = loc[1]
304 if index_row < 0 or index_row >= self.shape[0]:
305 msg = f'Row index is out of range ({self.shape[0]})'
306 raise IndexError(msg)
307 if index_column < 0 or index_column >= self.shape[1]: # type: ignore[misc]
308 msg = f'Column index is out of range ({self.shape[1]})' # type: ignore[misc]
309 raise IndexError(msg)
310 return self._render_idxs[index_row, index_column]
311 else:
312 msg = '"loc" must be an integer or a sequence.'
313 raise TypeError(msg)
314
315 def __getitem__(self, index):
316 """Return a renderer based on an index."""
317 return self._renderers[index]
318
319 def __len__(self):
320 """Return number of renderers."""
321 return len(self._renderers)
322
323 def __iter__(self):
324 """Return a iterable of renderers."""
325 yield from self._renderers
326
327 @property
328 def active_index(self): # numpydoc ignore=RT01
329 """Return the active index.
330
331 Returns
332 -------
333 int
334 Active index.
335
336 """
337 return self._active_index
338
339 def index_to_loc(self, index):
340 """Convert a 1D index location to the 2D location on the plotting grid.
341
342 Parameters
343 ----------
344 index : int
345 A scalar integer that refers to the 1D location index.
346
347 Returns
348 -------
349 output : numpy.ndarray | numpy.int64
350 2D location on the plotting grid.
351
352 """
353 if not isinstance(index, (int, np.integer)):
354 msg = '"index" must be a scalar integer.'
355 raise TypeError(msg)
356 if len(self.shape) == 1:
357 return np.intp(index)
358 args = np.argwhere(self._render_idxs == index)
359 if len(args) < 1:
360 msg = f'Index ({index}) is out of range.'
361 raise IndexError(msg)
362 return args[0]
363
364 @property
365 def active_renderer(self): # numpydoc ignore=RT01
366 """Return the active renderer.
367
368 Returns
369 -------
370 Renderer
371 Active renderer.
372
373 """
374 return self._renderers[self._active_index]
375
376 @property
377 def shape(self) -> tuple[int] | tuple[int, int]:
378 """Return the shape of the renderers.
379
380 Returns
381 -------
382 output : tuple[int] | tuple[int, int]
383 Shape of the renderers.
384
385 """
386 return self._shape
387
388 def set_active_renderer(self, index_row, index_column=None):
389 """Set the index of the active renderer.
390
391 Parameters
392 ----------
393 index_row : int
394 Index of the subplot to activate along the rows.
395
396 index_column : int, optional
397 Index of the subplot to activate along the columns.
398
399 """
400 if len(self.shape) == 1:
401 self._active_index = index_row
402 return
403
404 if index_row < 0 or index_row >= self.shape[0]:
405 msg = f'Row index is out of range ({self.shape[0]})'
406 raise IndexError(msg)
407 if index_column < 0 or index_column >= self.shape[1]:
408 msg = f'Column index is out of range ({self.shape[1]})'
409 raise IndexError(msg)
410 self._active_index = self.loc_to_index((index_row, index_column))
411
412 @_deprecate_positional_args(allowed=['interactive'])
413 def set_chart_interaction(self, interactive, toggle: bool = False): # noqa: FBT001, FBT002
414 """Set or toggle interaction with charts for the active renderer.
415
416 Interaction with other charts in other renderers is disabled.
417 Interaction with other charts in the active renderer is only disabled
418 when ``toggle`` is ``False``.
419
420 Parameters
421 ----------
422 interactive : bool | Chart | int | sequence[Chart] | sequence[int]
423 Following parameter values are accepted:
424
425 * A boolean to enable (``True``) or disable (``False``) interaction
426 with all charts in the active renderer.
427 * The chart or its index to enable interaction with. Interaction
428 with multiple charts can be enabled by passing a list of charts
429 or indices.
430
431 toggle : bool, default: False
432 Instead of enabling interaction with the provided chart(s), interaction
433 with the provided chart(s) is toggled. Only applicable when ``interactive``
434 is not a boolean.
435
436 Returns
437 -------
438 list[Chart]
439 The list of all interactive charts for the active renderer.
440
441 """
442 interactive_scene, interactive_charts = None, []
443 if self.active_renderer.has_charts:
444 interactive_scene = self.active_renderer._charts._scene
445 interactive_charts = self.active_renderer.set_chart_interaction(
446 interactive, toggle=toggle
447 )
448 # Disable chart interaction for other renderers
449 for renderer in self:
450 if renderer is not self.active_renderer:
451 renderer.set_chart_interaction(False)
452 # Setup the context interactor style based on the resulting amount of interactive charts.
453 self._plotter.iren._set_context_style(interactive_scene if interactive_charts else None)
454 return interactive_charts
455
456 def on_plotter_render(self):
457 """Notify all renderers of explicit plotter render call."""
458 for renderer in self:
459 renderer.on_plotter_render()
460
461 def deep_clean(self):
462 """Clean all renderers."""
463 # Do not remove the renderers on the clean
464 for renderer in self:
465 renderer.deep_clean()
466 if self._shadow_renderer is not None:
467 self._shadow_renderer.deep_clean()
468 if hasattr(self, '_background_renderers'):
469 for renderer in self._background_renderers:
470 if renderer is not None:
471 renderer.deep_clean()
472
473 def add_background_renderer(self, image_path, scale, as_global):
474 """Add a background image to the renderers.
475
476 Parameters
477 ----------
478 image_path : str
479 Path to an image file.
480
481 scale : float
482 Scale the image larger or smaller relative to the size of
483 the window. For example, a scale size of 2 will make the
484 largest dimension of the image twice as large as the
485 largest dimension of the render window. Defaults to 1.
486
487 as_global : bool
488 When multiple render windows are present, setting
489 ``as_global=False`` will cause the background to only
490 appear in one window.
491
492 Returns
493 -------
494 pyvista.BackgroundRenderer
495 Newly created background renderer.
496
497 """
498 # verify no render exists
499 if as_global:
500 for renderer in self:
501 renderer.layer = 2
502 view_port = None
503 else:
504 self.active_renderer.layer = 2
505 view_port = self.active_renderer.GetViewport()
506
507 renderer = BackgroundRenderer(self._plotter, image_path, scale=scale, view_port=view_port)
508 renderer.layer = 1
509 self._background_renderers[self.active_index] = renderer
510 return renderer
511
512 @property
513 def has_active_background_renderer(self) -> bool: # numpydoc ignore=RT01
514 """Return ``True`` when Renderer has an active background renderer.
515
516 Returns
517 -------
518 bool
519 Whether or not the active renderer has a background renderer.
520
521 """
522 return self._background_renderers[self.active_index] is not None
523
524 def clear_background_renderers(self):
525 """Clear all background renderers."""
526 for renderer in self._background_renderers:
527 if renderer is not None:
528 renderer.clear()
529
530 def clear_actors(self):
531 """Clear actors from all renderers."""
532 for renderer in self:
533 renderer.clear_actors()
534
535 def clear(self):
536 """Clear all renders."""
537 for renderer in self:
538 renderer.clear()
539 self._shadow_renderer.clear() # type: ignore[union-attr]
540 self.clear_background_renderers()
541
542 def close(self):
543 """Close all renderers."""
544 for renderer in self:
545 renderer.close()
546
547 self._shadow_renderer.close() # type: ignore[union-attr]
548
549 for renderer in self._background_renderers:
550 if renderer is not None:
551 renderer.close()
552
553 def remove_all_lights(self):
554 """Remove all lights from all renderers."""
555 for renderer in self:
556 renderer.remove_all_lights()
557
558 @property
559 def shadow_renderer(self): # numpydoc ignore=RT01
560 """Shadow renderer.
561
562 Returns
563 -------
564 pyvista.plotting.renderer.Renderer
565 Shadow renderer.
566
567 """
568 return self._shadow_renderer
569
570 @_deprecate_positional_args(allowed=['color'])
571 def set_background( # noqa: PLR0917
572 self,
573 color,
574 top=None,
575 right=None,
576 side=None,
577 corner=None,
578 all_renderers: bool = True, # noqa: FBT001, FBT002
579 ):
580 """Set the background color.
581
582 Parameters
583 ----------
584 color : ColorLike, optional
585 Either a string, rgb list, or hex color string. Defaults
586 to current theme parameters. For example:
587
588 * ``color='white'``
589 * ``color='w'``
590 * ``color=[1.0, 1.0, 1.0]``
591 * ``color='#FFFFFF'``
592
593 top : ColorLike, optional
594 If given, this will enable a gradient background where the
595 ``color`` argument is at the bottom and the color given in ``top``
596 will be the color at the top of the renderer.
597
598 right : ColorLike, optional
599 If given, this will enable a gradient background where the
600 ``color`` argument is at the left and the color given in ``right``
601 will be the color at the right of the renderer.
602
603 side : ColorLike, optional
604 If given, this will enable a gradient background where the
605 ``color`` argument is at the center and the color given in ``side``
606 will be the color at the side of the renderer.
607
608 corner : ColorLike, optional
609 If given, this will enable a gradient background where the
610 ``color`` argument is at the center and the color given in ``corner``
611 will be the color at the corner of the renderer.
612
613 all_renderers : bool, default: True
614 If ``True``, applies to all renderers in subplots. If ``False``,
615 then only applies to the active renderer.
616
617 Examples
618 --------
619 Set the background color to black.
620
621 >>> import pyvista as pv
622 >>> pl = pv.Plotter()
623 >>> pl.set_background('black')
624 >>> pl.background_color
625 Color(name='black', hex='#000000ff', opacity=255)
626 >>> pl.close()
627
628 Set the background color at the bottom to black and white at
629 the top. Display a cone as well.
630
631 >>> import pyvista as pv
632 >>> pl = pv.Plotter()
633 >>> actor = pl.add_mesh(pv.Cone())
634 >>> pl.set_background('black', top='white')
635 >>> pl.show()
636
637 """
638 if all_renderers:
639 for renderer in self:
640 renderer.set_background(color, top=top, right=right, side=side, corner=corner)
641 self._shadow_renderer.set_background(color) # type: ignore[union-attr]
642 else:
643 self.active_renderer.set_background(
644 color,
645 top=top,
646 right=right,
647 side=side,
648 corner=corner,
649 )
650
651 @_deprecate_positional_args(allowed=['color_cycler'])
652 def set_color_cycler(self, color_cycler, all_renderers: bool = True): # noqa: FBT001, FBT002
653 """Set or reset the color cycler.
654
655 This color cycler is iterated over by each sequential :class:`~pyvista.Plotter.add_mesh`
656 call to set the default color of the dataset being plotted.
657
658 When setting, the value must be either a list of color-like objects,
659 or a cycler of color-like objects. If the value passed is a single
660 string, it must be one of:
661
662 * ``'default'`` - Use the default color cycler (matches matplotlib's default)
663 * ``'matplotlib`` - Dynamically get matplotlib's current theme's color cycler.
664 * ``'all'`` - Cycle through all available colors in
665 ``pyvista.plotting.colors.hexcolors``
666
667 Setting to ``None`` will disable the use of the color cycler on this
668 renderer.
669
670 .. note::
671 If a mesh has scalar data, set ``color=True`` in the call to :meth:`add_mesh`
672 to color the mesh with the next color in the cycler. Otherwise the mesh's
673 scalars are used to color the mesh by default.
674
675 Parameters
676 ----------
677 color_cycler : str | cycler.Cycler | sequence[ColorLike]
678 The colors to cycle through.
679
680 all_renderers : bool, default: True
681 If ``True``, applies to all renderers in subplots. If ``False``,
682 then only applies to the active renderer.
683
684 See Also
685 --------
686 :ref:`color_cycler_example`
687
688 Examples
689 --------
690 Set the default color cycler to iterate through red, green, and blue.
691
692 >>> import pyvista as pv
693 >>> pl = pv.Plotter()
694 >>> pl.set_color_cycler(['red', 'green', 'blue'])
695 >>> _ = pl.add_mesh(pv.Cone(center=(0, 0, 0))) # red
696 >>> _ = pl.add_mesh(pv.Cube(center=(1, 0, 0))) # green
697 >>> _ = pl.add_mesh(pv.Sphere(center=(1, 1, 0))) # blue
698 >>> _ = pl.add_mesh(pv.Cylinder(center=(0, 1, 0))) # red again
699 >>> pl.show()
700
701 """
702 if all_renderers:
703 for renderer in self:
704 renderer.set_color_cycler(color_cycler)
705 else:
706 self.active_renderer.set_color_cycler(color_cycler)
707
708 def remove_background_image(self):
709 """Remove the background image at the current renderer.
710
711 Examples
712 --------
713 >>> import pyvista as pv
714 >>> from pyvista import examples
715 >>> pl = pv.Plotter(shape=(1, 2))
716 >>> pl.subplot(0, 0)
717 >>> actor = pl.add_mesh(pv.Sphere())
718 >>> pl.add_background_image(examples.mapfile, as_global=False)
719 >>> pl.subplot(0, 1)
720 >>> actor = pl.add_mesh(pv.Cube())
721 >>> pl.add_background_image(examples.mapfile, as_global=False)
722 >>> pl.remove_background_image()
723 >>> pl.show()
724
725 """
726 renderer = self._background_renderers[self.active_index]
727 if renderer is None:
728 msg = 'No background image to remove at this subplot'
729 raise RuntimeError(msg)
730 renderer.deep_clean()
731 self._background_renderers[self.active_index] = None
732
733 def __del__(self):
734 """Destructor."""
735 self._shadow_renderer = None