forked from pyvista/pyvista
/
plotting.py
2205 lines (1786 loc) · 73.1 KB
/
plotting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
vtki plotting module
"""
import time
import logging
import ctypes
import PIL.Image
from subprocess import Popen, PIPE
import os
import colorsys
import collections
import vtk
from vtk.util import numpy_support as VN
import numpy as np
import vtki
from vtki.utilities import get_scalar, wrap, is_vtki_obj, numpy_to_texture
from vtki.export import export_plotter_vtkjs
import imageio
MAX_N_COLOR_BARS = 10
PV_BACKGROUND = [82/255., 87/255., 110/255.]
FONT_KEYS = {'arial': vtk.VTK_ARIAL,
'courier': vtk.VTK_COURIER,
'times': vtk.VTK_TIMES}
log = logging.getLogger(__name__)
log.setLevel('CRITICAL')
rcParams = {
'background' : [0.3, 0.3, 0.3],
'camera' : {
'position' : [1, 1, 1],
'viewup' : [0, 0, 1],
},
'window_size' : [1024, 768],
'font' : {
'family' : 'courier',
'size' : 12,
'title_size': None,
'label_size' : None,
'color' : [1, 1, 1],
},
'cmap' : 'jet',
'colorbar' : {
'width' : 0.60,
'height' : 0.08,
'position_x' : 0.35,
'position_y' : 0.02,
},
'show_edges' : True,
}
def set_plot_theme(theme):
"""Set the plotting parameters to a predefined theme"""
if theme.lower() in ['paraview', 'pv']:
rcParams['background'] = PV_BACKGROUND
rcParams['cmap'] = 'coolwarm'
rcParams['font']['family'] = 'arial'
rcParams['font']['label_size'] = 16
rcParams['show_edges'] = False
def run_from_ipython():
""" returns True when run from IPython """
try:
__IPYTHON__
return True
except NameError:
return False
def _raise_not_matching(scalars, mesh):
raise Exception('Number of scalars (%d) ' % scalars.size +
'must match either the number of points ' +
'(%d) ' % mesh.GetNumberOfPoints() +
'or the number of cells ' +
'(%d) ' % mesh.GetNumberOfCells())
def _remove_mapper_from_plotter(plotter, actor, reset_camera):
"""removes this actor's mapper from the given plotter's _scalar_bar_mappers"""
try:
mapper = actor.GetMapper()
except AttributeError:
return
for name in list(plotter._scalar_bar_mappers.keys()):
try:
plotter._scalar_bar_mappers[name].remove(mapper)
except ValueError:
pass
if len(plotter._scalar_bar_mappers[name]) < 1:
plotter._scalar_bar_mappers.pop(name)
plotter._scalar_bar_ranges.pop(name)
plotter.remove_actor(plotter._scalar_bar_actors.pop(name), reset_camera=reset_camera)
plotter._scalar_bar_slots.add(plotter._scalar_bar_slot_lookup.pop(name))
return
def plot(var_item, off_screen=False, full_screen=False, screenshot=None,
interactive=True, cpos=None, window_size=None,
show_bounds=False, show_axes=True, notebook=None, background=None,
text='', **kwargs):
"""
Convenience plotting function for a vtk or numpy object.
Parameters
----------
item : vtk or numpy object
VTK object or numpy array to be plotted.
off_screen : bool
Plots off screen when True. Helpful for saving screenshots
without a window popping up.
full_screen : bool, optional
Opens window in full screen. When enabled, ignores window_size.
Default False.
screenshot : str or bool, optional
Saves screenshot to file when enabled. See:
help(vtkinterface.Plotter.screenshot). Default disabled.
When True, takes screenshot and returns numpy array of image.
window_size : list, optional
Window size in pixels. Defaults to [1024, 768]
show_bounds : bool, optional
Shows mesh bounds when True. Default False.
notebook : bool, optional
When True, the resulting plot is placed inline a jupyter notebook.
Assumes a jupyter console is active.
show_axes : bool, optional
Shows a vtk axes widget. Enabled by default.
text : str, optional
Adds text at the bottom of the plot.
**kwargs : optional keyword arguments
See help(Plotter.add_mesh) for additional options.
Returns
-------
cpos : list
List of camera position, focal point, and view up.
img : numpy.ndarray
Array containing pixel RGB and alpha. Sized:
[Window height x Window width x 3] for transparent_background=False
[Window height x Window width x 4] for transparent_background=True
Returned only when screenshot enabled
"""
if notebook is None:
if run_from_ipython():
notebook = type(get_ipython()).__module__.startswith('ipykernel.')
if notebook:
off_screen = notebook
plotter = Plotter(off_screen=off_screen, notebook=notebook)
if show_axes:
plotter.add_axes()
plotter.set_background(background)
if isinstance(var_item, list):
if len(var_item) == 2: # might be arrows
isarr_0 = isinstance(var_item[0], np.ndarray)
isarr_1 = isinstance(var_item[1], np.ndarray)
if isarr_0 and isarr_1:
plotter.add_arrows(var_item[0], var_item[1])
else:
for item in var_item:
plotter.add_mesh(item, **kwargs)
else:
for item in var_item:
plotter.add_mesh(item, **kwargs)
else:
plotter.add_mesh(var_item, **kwargs)
if text:
plotter.add_text(text)
if show_bounds:
plotter.add_bounds_axes()
if cpos is None:
cpos = plotter.get_default_cam_pos()
plotter.camera_position = cpos
plotter.camera_set = False
else:
plotter.camera_position = cpos
result = plotter.show(window_size=window_size,
auto_close=False,
interactive=interactive,
full_screen=full_screen,
screenshot=screenshot)
# close and return camera position and maybe image
plotter.close()
# Result will be handled by plotter.show(): cpos or [cpos, img]
return result
def plot_arrows(cent, direction, **kwargs):
"""
Plots arrows as vectors
Parameters
----------
cent : np.ndarray
Accepts a single 3d point or array of 3d points.
directions : np.ndarray
Accepts a single 3d point or array of 3d vectors.
Must contain the same number of items as cent.
**kwargs : additional arguments, optional
See help(vtki.Plot)
Returns
-------
Same as Plot. See help(vtki.Plot)
"""
return plot([cent, direction], **kwargs)
def running_xserver():
"""
Check if x server is running
Returns
-------
running_xserver : bool
True when on Linux and running an xserver. Returns None when
on a non-linux platform.
"""
try:
p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE)
p.communicate()
return p.returncode == 0
except:
False
class BasePlotter(object):
"""
Base plotter class to be used by the Plotter and VtkInteractor
classes
"""
def __init__(self):
self.renderer = vtk.vtkRenderer()
# This is a private variable to keep track of how many colorbars exist
# This allows us to keep adding colorbars without overlapping
self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
self._scalar_bar_slot_lookup = {}
# This keeps track of scalar names already plotted and their ranges
self._scalar_bar_ranges = {}
self._scalar_bar_mappers = {}
self._scalar_bar_actors = {}
self._actors = {}
# track if the camera has been setup
self.camera_set = False
self.first_time = True
# Keep track of the scale
self.scale = [1.0, 1.0, 1.0]
self._labels = []
def update_bounds_axes(self):
"""Update the bounds axes of the render window """
# Update the bounds for the axes labels if present
if hasattr(self, 'cubeAxesActor'):
self.cubeAxesActor.SetBounds(self.bounds)
return
@property
def bounds(self):
""" Bounds of all actors present in the rendering window """
the_bounds = [np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf]
def _update_bounds(bounds):
def update_axis(ax):
if bounds[ax*2] < the_bounds[ax*2]:
the_bounds[ax*2] = bounds[ax*2]
if bounds[ax*2+1] > the_bounds[ax*2+1]:
the_bounds[ax*2+1] = bounds[ax*2+1]
for ax in range(3):
update_axis(ax)
return
for name, actor in self._actors.items():
if isinstance(actor, vtk.vtkCubeAxesActor):
continue
if hasattr(actor, 'GetBounds') and actor.GetBounds() is not None:
_update_bounds(actor.GetBounds())
return the_bounds
def clear(self):
""" Clears plot by removing all actors and properties """
self.renderer.RemoveAllViewProps()
self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
self._scalar_bar_slot_lookup = {}
self._scalar_bar_ranges = {}
self._scalar_bar_mappers = {}
self._scalar_bar_actors = {}
def enable_trackball_style(self):
""" sets the interacto style to trackball """
istyle = vtk.vtkInteractorStyleTrackballCamera()
self.iren.SetInteractorStyle(istyle)
def set_focus(self, point):
""" sets focus to a point """
if isinstance(point, np.ndarray):
if point.ndim != 1:
point = point.ravel()
self.camera.SetFocalPoint(point)
self._render()
def _render(self):
""" redraws render window if the render window exists """
if hasattr(self, 'ren_win'):
if hasattr(self, 'render_trigger'):
self.render_trigger.emit()
elif not self.first_time:
self.render()
def add_axes(self, interactive=False):
""" Add an interactive axes widget """
if hasattr(self, 'axes_widget'):
raise Exception('Plotter already has an axes widget')
self.axes_actor = vtk.vtkAxesActor()
self.axes_widget = vtk.vtkOrientationMarkerWidget()
self.axes_widget.SetOrientationMarker(self.axes_actor)
if hasattr(self, 'iren'):
self.axes_widget.SetInteractor(self.iren)
self.axes_widget.SetEnabled(1)
self.axes_widget.SetInteractive(interactive)
def get_default_cam_pos(self):
"""
Returns the default focal points and viewup. Uses ResetCamera to
make a useful view.
"""
bounds = self.bounds
x = (bounds[1] + bounds[0])/2
y = (bounds[3] + bounds[2])/2
z = (bounds[5] + bounds[4])/2
focal_pt = [x, y, z]
return [np.array(rcParams['camera']['position']) + np.array(focal_pt),
focal_pt, rcParams['camera']['viewup']]
def key_press_event(self, obj, event):
""" Listens for key press event """
key = self.iren.GetKeySym()
log.debug('Key %s pressed' % key)
if key == 'q':
self.q_pressed = True
elif key == 'b':
self.observer = self.iren.AddObserver('LeftButtonPressEvent',
self.left_button_down)
def left_button_down(self, obj, event_type):
# Get 2D click location on window
clickPos = self.iren.GetEventPosition()
# Get corresponding click location in the 3D plot
picker = vtk.vtkWorldPointPicker()
picker.Pick(clickPos[0], clickPos[1], 0, self.renderer)
self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))
if np.any(np.isnan(self.pickpoint)):
self.pickpoint[:] = 0
def update(self, stime=1, force_redraw=True):
"""
Update window, redraw, process messages query
Parameters
----------
stime : int, optional
Duration of timer that interrupt vtkRenderWindowInteractor in
milliseconds.
force_redraw : bool, optional
Call vtkRenderWindowInteractor.Render() immediately.
"""
if stime <= 0:
stime = 1
curr_time = time.time()
if Plotter.last_update_time > curr_time:
Plotter.last_update_time = curr_time
if not hasattr(self, 'iren'):
return
update_rate = self.iren.GetDesiredUpdateRate()
if (curr_time - Plotter.last_update_time) > (1.0/update_rate):
self.right_timer_id = self.iren.CreateRepeatingTimer(stime)
self.iren.Start()
self.iren.DestroyTimer(self.right_timer_id)
self._render()
Plotter.last_update_time = curr_time
else:
if force_redraw:
self.iren.Render()
def add_mesh(self, mesh, color=None, style=None,
scalars=None, rng=None, stitle=None, show_edges=None,
point_size=5.0, opacity=1, line_width=None, flip_scalars=False,
lighting=True, n_colors=256, interpolate_before_map=False,
cmap=None, label=None, reset_camera=None, scalar_bar_args=None,
multi_colors=False, name=None, texture=None,
render_points_as_spheres=False, render_lines_as_tubes=False,
edge_color='black', **kwargs):
"""
Adds a unstructured, structured, or surface mesh to the plotting object.
Also accepts a 3D numpy.ndarray
Parameters
----------
mesh : vtk unstructured, structured, polymesh, or 3D numpy.ndarray
A vtk unstructured, structured, or polymesh to plot.
color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w'
color=[1, 1, 1]
color='#FFFFFF'
Color will be overridden when scalars are input.
style : string, optional
Visualization style of the vtk mesh. One for the following:
style='surface'
style='wireframe'
style='points'
Defaults to 'surface'
scalars : numpy array, optional
Scalars used to "color" the mesh. Accepts an array equal to the
number of cells or the number of points in the mesh. Array should
be sized as a single vector. If both color and scalars are None,
then the active scalars are used
rng : 2 item list, optional
Range of mapper for scalars. Defaults to minimum and maximum of
scalars array. Example: ``[-1, 2]``
stitle : string, optional
Scalar title. By default there is no scalar legend bar. Setting
this creates the legend bar and adds a title to it. To create a
bar with no title, use an empty string (i.e. '').
show_edges : bool, optional
Shows the edges of a mesh. Does not apply to a wireframe
representation.
point_size : float, optional
Point size. Applicable when style='points'. Default 5.0
opacity : float, optional
Opacity of mesh. Should be between 0 and 1. Default 1.0
line_width : float, optional
Thickness of lines. Only valid for wireframe and surface
representations. Default None.
flip_scalars : bool, optional
Flip direction of cmap.
lighting : bool, optional
Enable or disable view direction lighting. Default False.
n_colors : int, optional
Number of colors to use when displaying scalars. Default
256.
interpolate_before_map : bool, optional
Enabling makes for a smoother scalar display. Default
False
cmap : str, optional
cmap string. See available matplotlib cmaps. Only
applicable for when displaying scalars. Defaults None
(rainbow). Requires matplotlib.
multi_colors : bool, optional
If a ``MultiBlock`` dataset is given this will color each block by
a solid color using matplotlib's color cycler.
name : str, optional
The name for the added mesh/actor so that it can be easily updated.
If an actor of this name already exists in the rendering window, it
will be replaced by the new actor.
texture : vtk.vtkTexture or np.ndarray or boolean, optional
A texture to apply if the input mesh has texture coordinates.
This will not work with MultiBlock datasets. If set to ``True``,
the first avaialble texture on the object will be used. If a string
name is given, it will pull a texture with that name associated to
the input mesh.
Returns
-------
actor: vtk.vtkActor
VTK actor of the mesh.
"""
if scalar_bar_args is None:
scalar_bar_args = {}
if isinstance(mesh, np.ndarray):
mesh = vtki.PolyData(mesh)
style = 'points'
# Convert the VTK data object to a vtki wrapped object if neccessary
if not is_vtki_obj(mesh):
mesh = wrap(mesh)
if show_edges is None:
show_edges = rcParams['show_edges']
if name is None:
name = '{}({})'.format(type(mesh).__name__, str(hex(id(mesh))))
if isinstance(mesh, vtki.MultiBlock):
self.remove_actor(name, reset_camera=reset_camera)
# frist check the scalars
if rng is None and scalars is not None:
# Get the data range across the array for all blocks if scalar specified
if isinstance(scalars, str):
rng = mesh.get_data_range(scalars)
else:
# TODO: an array was given... how do we deal with that? Possibly
# a 2D arrays or list of arrays where first index
# corresponds to the block? This could get complicated real quick.
raise RuntimeError('Scalar array must be given as a string name for multiblock datasets.')
if multi_colors:
# Compute unique colors for each index of the block
import matplotlib as mpl
from itertools import cycle
cycler = mpl.rcParams['axes.prop_cycle']
colors = cycle(cycler)
# Now iteratively plot each element of the multiblock dataset
actors = []
for idx in range(mesh.GetNumberOfBlocks()):
if mesh[idx] is None:
continue
# Get a good name to use
nm = '{}-{}'.format(name, idx)
# Get the data object
if not is_vtki_obj(mesh[idx]):
data = wrap(mesh.GetBlock(idx))
if not is_vtki_obj(mesh[idx]):
continue # move on if we can't plot it
else:
data = mesh.GetBlock(idx)
if data is None:
# Note that a block can exist but be None type
continue
# Now check that scalars is available for this dataset
if get_scalar(data, scalars) is None:
ts = None
else:
ts = scalars
if multi_colors:
color = next(colors)['color']
a = self.add_mesh(data, color=color, style=style,
scalars=ts, rng=rng, stitle=stitle, show_edges=show_edges,
point_size=point_size, opacity=opacity, line_width=line_width,
flip_scalars=flip_scalars, lighting=lighting,
n_colors=n_colors, interpolate_before_map=interpolate_before_map,
cmap=cmap, label=label,
scalar_bar_args=scalar_bar_args, reset_camera=reset_camera,
name=nm, texture=None,
render_points_as_spheres=render_points_as_spheres, render_lines_as_tubes=render_lines_as_tubes,
edge_color=edge_color, **kwargs)
actors.append(a)
if (reset_camera is None and not self.camera_set) or reset_camera:
cpos = self.get_default_cam_pos()
self.camera_position = cpos
self.camera_set = False
self.reset_camera()
return actors
# set main values
self.mesh = mesh
self.mapper = vtk.vtkDataSetMapper()
self.mapper.SetInputData(self.mesh)
if isinstance(scalars, str):
self.mapper.SetArrayName(scalars)
actor, prop = self.add_actor(self.mapper, reset_camera=reset_camera, name=name)
if texture == True or isinstance(texture, str):
texture = mesh._activate_texture(texture)
if texture:
if isinstance(texture, np.ndarray):
texture = numpy_to_texture(texture)
if not isinstance(texture, vtk.vtkTexture):
raise TypeError('Invalid texture type ({})'.format(type(texture)))
if mesh.GetPointData().GetTCoords() is None:
raise AssertionError('Input mesh does not have texture coordinates to support the texture.')
actor.SetTexture(texture)
# Attempt get the active scalars if no preference given
if scalars is None and color is None and texture is None:
scalars = mesh.active_scalar
# Make sure scalar components are not vectors/tuples
if scalars is None or scalars.ndim != 1:
scalars = None
else:
if stitle is None:
stitle = mesh.active_scalar_info[1]
# Scalar formatting ===================================================
if cmap is None:
cmap = rcParams['cmap']
title = 'Data' if stitle is None else stitle
if scalars is not None:
# if scalars is a string, then get the first array found with that name
append_scalars = True
if isinstance(scalars, str):
title = scalars
scalars = get_scalar(mesh, scalars)
if stitle is None:
stitle = title
#append_scalars = False
if not isinstance(scalars, np.ndarray):
scalars = np.asarray(scalars)
if scalars.ndim != 1:
scalars = scalars.ravel()
if scalars.dtype == np.bool:
scalars = scalars.astype(np.float)
# Scalar interpolation approach
if scalars.size == mesh.GetNumberOfPoints():
self.mesh._add_point_scalar(scalars, title, append_scalars)
self.mapper.SetScalarModeToUsePointData()
self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors)
if interpolate_before_map:
self.mapper.InterpolateScalarsBeforeMappingOn()
elif scalars.size == mesh.GetNumberOfCells():
self.mesh._add_cell_scalar(scalars, title, append_scalars)
self.mapper.SetScalarModeToUseCellData()
self.mapper.GetLookupTable().SetNumberOfTableValues(n_colors)
if interpolate_before_map:
self.mapper.InterpolateScalarsBeforeMappingOn()
else:
_raise_not_matching(scalars, mesh)
# Set scalar range
if not rng:
rng = [np.nanmin(scalars), np.nanmax(scalars)]
elif isinstance(rng, float) or isinstance(rng, int):
rng = [-rng, rng]
if np.any(rng):
self.mapper.SetScalarRange(rng[0], rng[1])
# Flip if requested
table = self.mapper.GetLookupTable()
if cmap is not None:
try:
from matplotlib.cm import get_cmap
except ImportError:
raise Exception('cmap requires matplotlib')
cmap = get_cmap(cmap)
ctable = cmap(np.linspace(0, 1, n_colors))*255
ctable = ctable.astype(np.uint8)
if flip_scalars:
ctable = np.ascontiguousarray(ctable[::-1])
table.SetTable(VN.numpy_to_vtk(ctable))
else: # no cmap specified
if flip_scalars:
self.mapper.GetLookupTable().SetHueRange(0.0, 0.66667)
else:
self.mapper.GetLookupTable().SetHueRange(0.66667, 0.0)
else:
self.mapper.SetScalarModeToUseFieldData()
# select view style
if not style:
style = 'surface'
style = style.lower()
if style == 'wireframe':
prop.SetRepresentationToWireframe()
elif style == 'points':
prop.SetRepresentationToPoints()
elif style == 'surface':
prop.SetRepresentationToSurface()
else:
raise Exception('Invalid style. Must be one of the following:\n' +
'\t"surface"\n' +
'\t"wireframe"\n' +
'\t"points"\n')
prop.SetPointSize(point_size)
# edge display style
if show_edges:
prop.EdgeVisibilityOn()
rgb_color = parse_color(color)
prop.SetColor(rgb_color)
prop.SetOpacity(opacity)
prop.SetEdgeColor(parse_color(edge_color))
if render_points_as_spheres:
prop.SetRenderPointsAsSpheres(render_points_as_spheres)
if render_lines_as_tubes:
prop.SetRenderLinesAsTubes(render_lines_as_tubes)
# legend label
if label:
assert isinstance(label, str), 'Label must be a string'
self._labels.append([single_triangle(), label, rgb_color])
# lighting display style
if lighting is False:
prop.LightingOff()
# set line thickness
if line_width:
prop.SetLineWidth(line_width)
# Add scalar bar if available
if stitle is not None:
self.add_scalar_bar(stitle, **scalar_bar_args)
return actor
def add_actor(self, uinput, reset_camera=False, name=None):
"""
Adds an actor to render window. Creates an actor if input is
a mapper.
Parameters
----------
uinput : vtk.vtkMapper or vtk.vtkActor
vtk mapper or vtk actor to be added.
reset_camera : bool, optional
Resets the camera when true.
Returns
-------
actor : vtk.vtkActor
The actor.
actor_properties : vtk.Properties
Actor properties.
"""
if isinstance(uinput, vtk.vtkMapper):
actor = vtk.vtkActor()
actor.SetMapper(uinput)
else:
actor = uinput
# Make sure scale is consistent with rest of scene
if hasattr(actor, 'SetScale'):
actor.SetScale(self.scale[0], self.scale[1], self.scale[2])
self.renderer.AddActor(actor)
if name is None:
name = str(hex(id(actor)))
# Remove actor by that name if present
rv = self.remove_actor(name, reset_camera=False)
self._actors[name] = actor
if reset_camera:
self.reset_camera()
elif not self.camera_set and reset_camera is None and not rv:
self.reset_camera()
else:
self._render()
self.update_bounds_axes()
return actor, actor.GetProperty()
@property
def camera(self):
return self.renderer.GetActiveCamera()
def remove_actor(self, actor, reset_camera=False):
"""
Removes an actor from the Plotter.
Parameters
----------
actor : vtk.vtkActor
Actor that has previously added to the Plotter.
"""
name = None
if isinstance(actor, str):
name = actor
keys = list(self._actors.keys())
names = []
for k in keys:
if k.startswith('{}-'.format(name)):
names.append(k)
if len(names) > 0:
self.remove_actor(names, reset_camera=reset_camera)
try:
actor = self._actors[name]
except KeyError:
# If actor of that name is not present then return success
return False
if isinstance(actor, collections.Iterable):
success = False
for a in actor:
rv = self.remove_actor(a, reset_camera=reset_camera)
if rv or success:
success = True
return success
if actor is None:
return False
# First remove this actor's mapper from _scalar_bar_mappers
_remove_mapper_from_plotter(self, actor, False)
self.renderer.RemoveActor(actor)
if name is None:
for k, v in self._actors.items():
if v == actor:
name = k
self._actors.pop(name, None)
self.update_bounds_axes()
if reset_camera:
self.reset_camera()
elif not self.camera_set and reset_camera is None:
self.reset_camera()
else:
self._render()
return True
def add_axes_at_origin(self):
"""
Add axes actor at origin
Returns
--------
marker_actor : vtk.vtkAxesActor
vtkAxesActor actor
"""
self.marker_actor = vtk.vtkAxesActor()
self.renderer.AddActor(self.marker_actor)
self._actors[str(hex(id(self.marker_actor)))] = self.marker_actor
return self.marker_actor
def add_bounds_axes(self, mesh=None, bounds=None, show_xaxis=True,
show_yaxis=True, show_zaxis=True, show_xlabels=True,
show_ylabels=True, show_zlabels=True, italic=False,
bold=True, shadow=False, font_size=None,
font_family=None, color='w',
xlabel='X Axis', ylabel='Y Axis', zlabel='Z Axis',
use_2d=True):
"""
Adds bounds axes. Shows the bounds of the most recent input mesh
unless mesh is specified.
Parameters
----------
mesh : vtkPolydata or unstructured grid, optional
Input mesh to draw bounds axes around
bounds : list or tuple, optional
Bounds to override mesh bounds.
[xmin, xmax, ymin, ymax, zmin, zmax]
show_xaxis : bool, optional
Makes x axis visible. Default True.
show_yaxis : bool, optional
Makes y axis visible. Default True.
show_zaxis : bool, optional
Makes z axis visible. Default True.
show_xlabels : bool, optional
Shows x labels. Default True.
show_ylabels : bool, optional
Shows y labels. Default True.
show_zlabels : bool, optional
Shows z labels. Default True.
italic : bool, optional
Italicises axis labels and numbers. Default False.
bold : bool, optional
Bolds axis labels and numbers. Default True.
shadow : bool, optional
Adds a black shadow to the text. Default False.
font_size : float, optional
Sets the size of the label font. Defaults to 16.
font_family : string, optional
Font family. Must be either courier, times, or arial.
color : string or 3 item list, optional
Color of all labels and axis titles. Default white.
Either a string, rgb list, or hex color string. For example:
color='white'
color='w'
color=[1, 1, 1]
color='#FFFFFF'
xlabel : string, optional
Title of the x axis. Default "X Axis"
ylabel : string, optional
Title of the y axis. Default "Y Axis"
zlabel : string, optional
Title of the z axis. Default "Z Axis"
use_2d : bool, optional
A bug with vtk 6.3 in Windows seems to cause this function to crash
this can be enabled for smoother plotting for other enviornments.
Returns
-------
cubeAxesActor : vtk.vtkCubeAxesActor
Bounds actor
"""
# If one is already present, just use that one
if hasattr(self, 'cubeAxesActor'):
return
if font_family is None:
font_family = rcParams['font']['family']
if font_size is None:
font_size = rcParams['font']['size']
# Use the bounds of all data in the rendering window
if not mesh and not bounds:
bounds = self.bounds
# create actor
cubeAxesActor = vtk.vtkCubeAxesActor()
cubeAxesActor.SetUse2DMode(False)
cubeAxesActor.SetScale(self.scale[0], self.scale[1], self.scale[2])
# set bounds
if not bounds:
bounds = mesh.GetBounds()
cubeAxesActor.SetBounds(bounds)
# show or hide axes
cubeAxesActor.SetXAxisVisibility(show_xaxis)
cubeAxesActor.SetYAxisVisibility(show_yaxis)
cubeAxesActor.SetZAxisVisibility(show_zaxis)
# disable minor ticks
cubeAxesActor.XAxisMinorTickVisibilityOff()
cubeAxesActor.YAxisMinorTickVisibilityOff()
cubeAxesActor.ZAxisMinorTickVisibilityOff()
cubeAxesActor.SetCamera(self.camera)
# set color
color = parse_color(color)
cubeAxesActor.GetXAxesLinesProperty().SetColor(color)
cubeAxesActor.GetYAxesLinesProperty().SetColor(color)
cubeAxesActor.GetZAxesLinesProperty().SetColor(color)