-
Notifications
You must be signed in to change notification settings - Fork 286
/
Copy pathmlab.py
1411 lines (1124 loc) · 46 KB
/
mlab.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
"""A module that provides Matlab like 3d visualization functionality.
The general idea is shamelessly stolen from the `high-level API`_
provided by Octaviz_. Some of the test cases and demos are also
translated from there!
.. _Octaviz: http://octaviz.sourceforge.net/
.. _high-level API: http://octaviz.sourceforge.net/index.php?page=manpagesq
The implementation provided here is object oriented and each
visualization capability is implemented as a class that has traits.
So each of these may be configured. Each visualization class derives
(ultimately) from MLabBase which is responsible for adding/removing
its actors into the render window. The classes all require that the
RenderWindow be a `pyface.tvtk.scene.Scene` instance (this constraint
can be relaxed if necessary later on).
This module offers the following broad class of functionality:
`Figure`
This basically manages all of the objects rendered. Just like
figure in any Matlab like environment. A convenience function
called `figure` may be used to create a nice Figure instance.
`Glyphs`
This and its subclasses let one place glyphs at points specified as
inputs. The subclasses are: `Arrows`, `Cones`, `Cubes`,
`Cylinders`, `Spheres`, and `Points`.
`Line3`
Draws lines between the points specified at initialization time.
`Outline`
Draws an outline for the contained objects.
`Title`
Draws a title for the entire figure.
`LUTBase`
Manages a lookup table and a scalar bar (legend) for it. This is
subclassed by all classes that need a LUT.
`SurfRegular`
MayaVi1's imv.surf like functionality that plots surfaces given x
(1D), y(1D) and z (or a callable) arrays.
`SurfRegularC`
Also plots contour lines.
`TriMesh`
Given triangle connectivity and points, plots a mesh of them.
`FancyTriMesh`
Plots the mesh using tubes and spheres so its fancier.
`Mesh`
Given x, y generated from numpy.mgrid, and a z to go with it. Along
with optional scalars. This class builds the triangle connectivity
(assuming that x, y are from numpy.mgrid) and builds a mesh and
shows it.
`FancyMesh`
Like mesh but shows the mesh using tubes and spheres.
`Surf`
This generates a surface mesh just like Mesh but renders the mesh as
a surface.
`Contour3`
Shows contour for a mesh.
`ImShow`
Allows one to view large numeric arrays as image data using an image
actor. This is just like MayaVi1's `mayavi.tools.imv.viewi`.
To see nice examples of all of these look at the `test_*` functions at
the end of this file. Here is a quick example that uses these test
functions::
>>> from tvtk.tools import mlab
>>> f = mlab.figure()
>>> mlab.test_surf(f) # Create a spherical harmonic.
>>> f.pop() # Remove it.
>>> mlab.test_molecule(f) # Show a caffeine molecule.
>>> f.renwin.reset_zoom() # Scale the view.
>>> f.pop() # Remove this.
>>> mlab.test_lines(f) # Show pretty lines.
>>> f.clear() # Remove all the stuff on screen.
"""
# Author: Prabhu Ramachandran <[email protected]>
# Copyright (c) 2005-2020, Enthought, Inc.
# License: BSD Style.
from distutils.version import StrictVersion
import numpy
from traits.api import HasTraits, List, Instance, Any, Float, Bool, \
Str, Trait, Int
from pyface.api import GUI
from tvtk.api import tvtk
from tvtk.tvtk_base import TVTKBase, vtk_color_trait
from tvtk.common import configure_input_data
from tvtk.tools import ivtk
# Set this to False to not use LOD Actors.
USE_LOD_ACTOR = True
VTK_VER = StrictVersion(tvtk.Version().vtk_version)
######################################################################
# Utility functions.
######################################################################
def _make_actor(**kwargs):
"""Return a TVTK actor. If `mlab.USE_LOD_ACTOR` is `True` it
returns an LODActor if not it returns a normal actor.
"""
if USE_LOD_ACTOR:
r = tvtk.LODActor(number_of_cloud_points=1500)
r.property.point_size = 2.0
r.trait_set(**kwargs)
return r
else:
return tvtk.Actor(**kwargs)
def _create_structured_points_direct(x, y, z=None):
"""Creates a StructuredPoints object given input data in the form
of numpy arrays.
Input Arguments:
x -- Array of x-coordinates. These should be regularly spaced.
y -- Array of y-coordinates. These should be regularly spaced.
z -- Array of z values for the x, y values given. The values
should be computed such that the z values are computed as x
varies fastest and y next. If z is None then no scalars are
associated with the structured points. Only the structured
points data set is created.
"""
nx = len(x)
ny = len(y)
if z is not None:
nz = numpy.size(z)
assert nx*ny == nz, "len(x)*len(y) != len(z)"\
"You passed nx=%d, ny=%d, nz=%d"%(nx, ny, nz)
xmin, ymin = x[0], y[0]
dx, dy= (x[1] - x[0]), (y[1] - y[0])
sp = tvtk.StructuredPoints(dimensions=(nx,ny,1),
origin=(xmin, ymin, 0),
spacing=(dx, dy, 1))
if z is not None:
sp.point_data.scalars = numpy.ravel(z)
sp.point_data.scalars.name = 'scalars'
return sp
def sampler(xa, ya, func, *args, **kwargs):
"""Samples a function at an array of ordered points (with equal
spacing) and returns an array of scalars as per VTK's requirements
for a structured points data set, i.e. x varying fastest and y
varying next.
Input Arguments:
xa -- Array of x points.
ya -- Array if y points.
func -- function of x, and y to sample.
args -- additional positional arguments for func()
(default is empty)
kwargs -- a dict of additional keyword arguments for func()
(default is empty)
"""
ret = func(xa[:,None] + numpy.zeros_like(ya),
numpy.transpose(ya[:,None] + numpy.zeros_like(xa)),
*args, **kwargs
)
return numpy.transpose(ret)
def _check_sanity(x, y, z):
"""Checks the given arrays to see if they are suitable for
surf."""
msg = "Only ravelled or 2D arrays can be viewed! "\
"This array has shape %s" % str(z.shape)
assert len(z.shape) <= 2, msg
if len( z.shape ) == 2:
msg = "len(x)*len(y) != len(z.flat). You passed "\
"nx=%d, ny=%d, shape of z=%s"%(len(x), len(y), z.shape)
assert z.shape[0]*z.shape[1] == len(x)*len(y), msg
msg = "length of y(%d) and x(%d) must match shape of z "\
"%s. (Maybe you need to swap x and y?)"%(len(y), len(x),
str(z.shape))
assert z.shape == (len(y), len(x)), msg
def squeeze(a):
"Returns a with any ones from the shape of a removed"
a = numpy.asarray(a)
b = numpy.asarray(a.shape)
val = numpy.reshape(a,
tuple(numpy.compress(numpy.not_equal(b, 1), b)))
return val
def make_surf_actor(x, y, z, warp=1, scale=[1.0, 1.0, 1.0],
make_actor=True, *args, **kwargs):
"""Creates a surface given regularly spaced values of x, y and the
corresponding z as arrays. Also works if z is a function.
Currently works only for regular data - can be enhanced later.
Parameters
----------
x -- Array of x points (regularly spaced)
y -- Array if y points (regularly spaced)
z -- A 2D array for the x and y points with x varying fastest
and y next. Also will work if z is a callable which supports
x and y arrays as the arguments.
warp -- If true, warp the data to show a 3D surface
(default = 1).
scale -- Scale the x, y and z axis as per passed values.
Defaults to [1.0, 1.0, 1.0].
make_actor -- also create actors suitably (default True)
args -- additional positional arguments for func()
(default is empty)
kwargs -- a dict of additional keyword arguments for func()
(default is empty)
"""
if callable(z):
zval = numpy.ravel(sampler(x, y, z, *args, **kwargs))
x, y = squeeze(x), squeeze(y)
else:
x, y = squeeze(x), squeeze(y)
_check_sanity(x, y, z)
zval = numpy.ravel(z)
assert len(zval) > 0, "z is empty - nothing to plot!"
xs = x*scale[0]
ys = y*scale[1]
data = _create_structured_points_direct(xs, ys, zval)
if not make_actor:
return data
if warp:
geom_f = tvtk.ImageDataGeometryFilter()
configure_input_data(geom_f, data)
warper = tvtk.WarpScalar(scale_factor=scale[2])
configure_input_data(warper, geom_f.output)
normals = tvtk.PolyDataNormals(feature_angle=45)
configure_input_data(normals, warper.output)
mapper = tvtk.PolyDataMapper(scalar_range=(min(zval),max(zval)))
configure_input_data(mapper, normals.output)
else:
mapper = tvtk.PolyDataMapper(scalar_range=(min(zval),max(zval)))
configure_input_data(mapper, data)
actor = _make_actor(mapper=mapper)
return data, actor
def make_triangle_polydata(triangles, points, scalars=None):
t = numpy.asarray(triangles, 'l')
assert t.shape[1] == 3, "The list of polygons must be Nx3."
if scalars is not None:
assert len(points) == len(numpy.ravel(scalars))
pd = tvtk.PolyData(points=points, polys=t)
if scalars is not None:
pd.point_data.scalars = numpy.ravel(scalars)
pd.point_data.scalars.name = 'scalars'
return pd
def make_triangles_points(x, y, z, scalars=None):
"""Given x, y, and z co-ordinates made using numpy.mgrid and
optional scalars. This function returns triangles and points
corresponding to a mesh formed by them.
Parameters
----------
- x : array
A list of x coordinate values formed using numpy.mgrid.
- y : array
A list of y coordinate values formed using numpy.mgrid.
- z : array
A list of z coordinate values formed using numpy.mgrid.
- scalars : array (optional)
Scalars to associate with the points.
"""
assert len(x.shape) == 2, "Array x must be 2 dimensional."
assert len(y.shape) == 2, "Array y must be 2 dimensional."
assert len(z.shape) == 2, "Array z must be 2 dimensional."
assert x.shape == y.shape, "Arrays x and y must have same shape."
assert y.shape == z.shape, "Arrays y and z must have same shape."
nx, ny = x.shape
i, j = numpy.mgrid[0:nx-1,0:ny-1]
i, j = numpy.ravel(i), numpy.ravel(j)
t1 = i*ny+j, (i+1)*ny+j, (i+1)*ny+(j+1)
t2 = (i+1)*ny+(j+1), i*ny+(j+1), i*ny+j
nt = len(t1[0])
triangles = numpy.zeros((nt*2, 3), 'l')
triangles[0:nt,0], triangles[0:nt,1], triangles[0:nt,2] = t1
triangles[nt:,0], triangles[nt:,1], triangles[nt:,2] = t2
points = numpy.zeros((nx, ny, 3), 'd')
points[:,:,0], points[:,:,1], points[:,:,2] = x, y, z
points = numpy.reshape(points, (nx*ny, 3))
return triangles, points
######################################################################
# `MLabBase` class.
######################################################################
class MLabBase(HasTraits):
# List of actors.
actors = List(TVTKBase)
# Renderwindow to render into.
renwin = Any
def update(self):
self.renwin.render()
def render(self):
if self.renwin:
self.renwin.render()
def _renwin_changed(self, old, new):
if old:
old.remove_actors(self.actors)
old.render()
if new:
new.add_actors(self.actors)
new.render()
def _actors_changed(self, old, new):
self._handle_actors(old, new)
def _actors_items_changed(self, list_event):
self._handle_actors(list_event.removed, list_event.added)
def _handle_actors(self, removed, added):
rw = self.renwin
if rw:
rw.remove_actors(removed)
rw.add_actors(added)
rw.render()
######################################################################
# `Glyphs` class.
######################################################################
class Glyphs(MLabBase):
# The source glyph which is placed at various locations.
glyph_source = Any
# A Glyph3D instance replicates the glyph_sources at various
# points.
glyph = Instance(tvtk.Glyph3D, (), {'vector_mode':'use_vector',
'scale_mode':'data_scaling_off'})
# Color of the glyphs.
color = vtk_color_trait((1.0, 1.0, 1.0))
def __init__(self, points, vectors=None, scalars=None, **traits):
super(Glyphs, self).__init__(**traits)
if vectors is not None:
assert len(points) == len(vectors)
if scalars is not None:
assert len(points) == len(scalars)
self.points = points
self.vectors = vectors
self.scalars = scalars
polys = numpy.arange(0, len(points), 1, 'l')
polys = numpy.reshape(polys, (len(points), 1))
pd = tvtk.PolyData(points=points, polys=polys)
if self.vectors is not None:
pd.point_data.vectors = vectors
pd.point_data.vectors.name = 'vectors'
if self.scalars is not None:
pd.point_data.scalars = scalars
pd.point_data.scalars.name = 'scalars'
self.poly_data = pd
configure_input_data(self.glyph, pd)
if self.glyph_source:
self.glyph.source = self.glyph_source.output
mapper = tvtk.PolyDataMapper(input=self.glyph.output)
actor = _make_actor(mapper=mapper)
actor.property.color = self.color
self.actors.append(actor)
def update(self):
self.poly_data.update()
self.renwin.render()
def _color_changed(self, val):
if self.actors:
self.actors[0].property.color = val
self.render()
def _glyph_source_changed(self, val):
self.glyph.source = val.output
self.render()
######################################################################
# `Arrows` class.
######################################################################
class Arrows(Glyphs):
# The arrow glyph which is placed at various locations.
glyph_source = Instance(tvtk.ArrowSource, ())
######################################################################
# `Cones` class.
######################################################################
class Cones(Glyphs):
# The cone glyph which is placed at various locations.
glyph_source = Instance(tvtk.ConeSource, ())
# Radius of the cone.
radius = Float(0.05, desc='radius of the cone')
def __init__(self, points, vectors=None, scalars=None, **traits):
super(Cones, self).__init__(points, vectors, scalars, **traits)
self._radius_changed(self.radius)
def _radius_changed(self, val):
self.glyph_source.radius = val
self.render()
######################################################################
# `Cubes` class.
######################################################################
class Cubes(Glyphs):
# The cube glyph which is placed at various locations.
glyph_source = Instance(tvtk.CubeSource, ())
# The side length of the cube.
length = Float(0.05, desc='side length of the cube')
def __init__(self, points, vectors=None, scalars=None, **traits):
super(Cubes, self).__init__(points, vectors, scalars, **traits)
self._radius_changed(self.radius)
def _length_changed(self, val):
self.glyph_source.x_length = val
self.glyph_source.y_length = val
self.glyph_source.z_length = val
self.render()
######################################################################
# `Cylinders` class.
######################################################################
class Cylinders(Glyphs):
# The cylinder glyph which is placed at various locations.
glyph_source = Instance(tvtk.CylinderSource, ())
######################################################################
# `Spheres` class.
######################################################################
class Spheres(Glyphs):
# The sphere which is placed at various locations.
glyph_source = Instance(tvtk.SphereSource, (),
{'phi_resolution':15,
'theta_resolution':30})
# Radius of the sphere.
radius = Float(0.05, desc='radius of the sphere')
def __init__(self, points, vectors=None, scalars=None, **traits):
super(Spheres, self).__init__(points, vectors, scalars, **traits)
self._radius_changed(self.radius)
def _radius_changed(self, val):
self.glyph_source.radius = val
self.render()
######################################################################
# `Points` class.
######################################################################
class Points(Glyphs):
# The point which is placed at various locations.
glyph_source = Instance(tvtk.PointSource, (),
{'radius':0, 'number_of_points':1})
######################################################################
# `Line3` class.
######################################################################
class Line3(MLabBase):
# Radius of the tube filter.
radius = Float(0.01, desc='radius of the tubes')
# Should a tube filter be used or not.
use_tubes = Bool(True,
desc='specifies if the tube filter should be used')
# The Tube filter used to generate tubes from the lines.
tube_filter = Instance(tvtk.TubeFilter, (), {'number_of_sides':6})
# Color of the actor.
color = vtk_color_trait((1.0, 1.0, 1.0))
def __init__(self, points, **traits):
super(MLabBase, self).__init__(**traits)
assert len(points[0]) == 3, "The points must be 3D"
self.points = points
np = len(points) - 1
lines = numpy.zeros((np, 2), 'l')
lines[:,0] = numpy.arange(0, np-0.5, 1, 'l')
lines[:,1] = numpy.arange(1, np+0.5, 1, 'l')
pd = tvtk.PolyData(points=points, lines=lines)
self.poly_data = pd
mapper = tvtk.PolyDataMapper()
self.mapper = mapper
tf = self.tube_filter
tf.radius = self.radius
if self.use_tubes:
configure_input_data(tf, pd)
configure_input_data(mapper, tf.output)
a = _make_actor(mapper=mapper)
a.property.color = self.color
self.actors.append(a)
def _radius_changed(self, val):
self.tube_filter.radius = val
self.render()
def _use_tubes_changed(self, val):
if val:
tf = self.tube_filter
configure_input_data(tf, self.poly_data)
configure_input_data(self.mapper, tf.output)
else:
configure_input_data(self.mapper, self.poly_data)
self.render()
def _color_changed(self, val):
if self.actors:
self.actors[0].property.color = val
self.render()
######################################################################
# `Outline` class.
######################################################################
class Outline(MLabBase):
# The axis instance to use to annotate the outline
axis = Instance(tvtk.CubeAxesActor2D, (),
{'label_format':"%4.2g", 'fly_mode':"outer_edges",
'font_factor':1.25, 'number_of_labels':5,
'corner_offset':0.0, 'scaling':0})
# The outline source.
outline = Instance(tvtk.OutlineSource, ())
def __init__(self, **traits):
super(Outline, self).__init__(**traits)
out_mapper = tvtk.PolyDataMapper(input=self.outline.output)
out_actor = _make_actor(mapper=out_mapper)
axis = self.axis
if hasattr(axis, 'view_prop'):
axis.view_prop = out_actor
else:
axis.prop = out_actor
self.actors.extend([out_actor, axis])
def update(self):
if self.renwin:
rw = self.renwin
v1, v2 = [x.visibility for x in self.actors]
self.actors[0].visibility = 0
self.actors[1].visibility = 0
rw.render()
bounds = rw.renderer.compute_visible_prop_bounds()
self.outline.bounds = bounds
rw.render()
self.actors[0].visibility = v1
self.actors[1].visibility = v2
def _renwin_changed(self, old, new):
super(Outline, self)._renwin_changed(old, new)
if old:
old.on_trait_change(self.update, 'actor_added', remove=True)
old.on_trait_change(self.update, 'actor_removed', remove=True)
if new:
self.axis.camera = new.renderer.active_camera
new.on_trait_change(self.update, 'actor_added')
new.on_trait_change(self.update, 'actor_removed')
######################################################################
# `Title` class.
######################################################################
class Title(MLabBase):
# Text of the title.
text = Str('Title', desc='text of the title')
# The text actor that renders the title.
text_actor = Instance(tvtk.TextActor, ())
def __init__(self, **traits):
super(Title, self).__init__(**traits)
ta = self.text_actor
if VTK_VER > '5.1':
ta.trait_set(text_scale_mode='prop', height=0.05, input=self.text)
else:
ta.trait_set(scaled_text=True, height=0.05, input=self.text)
pc = ta.position_coordinate
pc.coordinate_system = 'normalized_viewport'
pc.value = 0.25, 0.925, 0.0
self.actors.append(self.text_actor)
def _text_changed(self, val):
self.text_actor.input = val
self.render()
######################################################################
# `LUTBase` class.
######################################################################
class LUTBase(MLabBase):
# The choices for the lookuptable
lut_type = Trait('red-blue', 'red-blue', 'blue-red',
'black-white', 'white-black',
desc='the type of the lookup table')
# The LookupTable instance.
lut = Instance(tvtk.LookupTable, ())
# The scalar bar.
scalar_bar = Instance(tvtk.ScalarBarActor, (),
{'orientation':'horizontal',
'width':0.8, 'height':0.17})
# The scalar_bar widget.
scalar_bar_widget = Instance(tvtk.ScalarBarWidget, ())
# The legend name for the scalar bar.
legend_text = Str('Scalar', desc='the title of the legend')
# Turn on/off the visibility of the scalar bar.
show_scalar_bar = Bool(False,
desc='specifies if scalar bar is shown or not')
def __init__(self, **traits):
super(LUTBase, self).__init__(**traits)
self.lut.number_of_colors = 256
self._lut_type_changed(self.lut_type)
self.scalar_bar.trait_set(lookup_table=self.lut,
title=self.legend_text)
pc = self.scalar_bar.position_coordinate
pc.coordinate_system = 'normalized_viewport'
pc.value = 0.1, 0.01, 0.0
self.scalar_bar_widget.trait_set(scalar_bar_actor=self.scalar_bar,
key_press_activation=False)
def _lut_type_changed(self, val):
if val == 'red-blue':
hue_range = 0.0, 0.6667
saturation_range = 1.0, 1.0
value_range = 1.0, 1.0
elif val == 'blue-red':
hue_range = 0.6667, 0.0
saturation_range = 1.0, 1.0
value_range = 1.0, 1.0
elif val == 'black-white':
hue_range = 0.0, 0.0
saturation_range = 0.0, 0.0
value_range = 0.0, 1.0
elif val == 'white-black':
hue_range = 0.0, 0.0
saturation_range = 0.0, 0.0
value_range = 1.0, 0.0
lut = self.lut
lut.trait_set(hue_range=hue_range, saturation_range=saturation_range,
value_range=value_range, number_of_table_values=256,
ramp='sqrt')
lut.force_build()
self.render()
def _legend_text_changed(self, val):
self.scalar_bar.title = val
self.scalar_bar.modified()
self.render()
def _show_scalar_bar_changed(self, val):
if self.renwin:
self.scalar_bar_widget.enabled = val
self.renwin.render()
def _renwin_changed(self, old, new):
sbw = self.scalar_bar_widget
if old:
sbw.interactor = None
old.render()
if new:
sbw.interactor = new.interactor
sbw.enabled = self.show_scalar_bar
new.render()
super(LUTBase, self)._renwin_changed(old, new)
######################################################################
# `SurfRegular` class.
######################################################################
class SurfRegular(LUTBase):
def __init__(self, x, y, z, warp=1, scale=[1.0, 1.0, 1.0], f_args=(),
f_kwargs=None, **traits):
super(SurfRegular, self).__init__(**traits)
if f_kwargs is None:
f_kwargs = {}
data, actor = make_surf_actor(x, y, z, warp, scale, *f_args,
**f_kwargs)
self.data = data
mapper = actor.mapper
mapper.lookup_table = self.lut
self.lut.table_range = mapper.scalar_range
self.actors.append(actor)
######################################################################
# `SurfRegularC` class.
######################################################################
class SurfRegularC(LUTBase):
# Number of contours.
number_of_contours = Int(10, desc='number of contours values')
# The contour filter.
contour_filter = Instance(tvtk.ContourFilter, ())
def __init__(self, x, y, z, warp=1, scale=[1.0, 1.0, 1.0], f_args=(),
f_kwargs=None, **traits):
super(SurfRegularC, self).__init__(**traits)
if f_kwargs is None:
f_kwargs = {}
data, actor = make_surf_actor(x, y, z, warp, scale, *f_args,
**f_kwargs)
mapper = actor.mapper
mapper.lookup_table = self.lut
self.lut.table_range = mapper.scalar_range
self.data = data
dr = data.point_data.scalars.range
cf = self.contour_filter
configure_input_data(cf, data)
cf.generate_values(self.number_of_contours, dr[0], dr[1])
mapper = tvtk.PolyDataMapper(input=cf.output, lookup_table=self.lut)
cont_actor = _make_actor(mapper=mapper)
self.actors.extend([actor, cont_actor])
def _number_of_contours_changed(self, val):
dr = self.data.point_data.scalars.range
self.contour_filter.generate_values(val, dr[0], dr[1])
self.render()
######################################################################
# `TriMesh` class.
######################################################################
class TriMesh(LUTBase):
# Disables/enables scalar visibility.
scalar_visibility = Bool(False, desc='show scalar visibility')
# Representation of the mesh as surface or wireframe.
surface = Bool(False, desc='show as surface or wireframe')
# Color of the mesh.
color = vtk_color_trait((0.5, 1.0, 0.5))
def __init__(self, triangles, points, scalars=None, **traits):
"""
Parameters
----------
- triangles : array
This contains a list of vertex indices forming the triangles.
- points : array
Contains the list of points referred to in the triangle list.
- scalars : array (optional)
Scalars to associate with the points.
"""
super(TriMesh, self).__init__(**traits)
self.pd = make_triangle_polydata(triangles, points, scalars)
mapper = tvtk.PolyDataMapper(input=self.pd, lookup_table=self.lut,
scalar_visibility=self.scalar_visibility)
if scalars is not None:
rs = numpy.ravel(scalars)
dr = min(rs), max(rs)
mapper.scalar_range = dr
self.lut.table_range = dr
actor = _make_actor(mapper=mapper)
representation = 'w'
if self.surface:
representation = 's'
if representation == 'w':
actor.property.trait_set(diffuse=0.0, ambient=1.0, color=self.color,
representation=representation)
else:
actor.property.trait_set(diffuse=1.0, ambient=0.0, color=self.color,
representation=representation)
self.actors.append(actor)
def _scalar_visibility_changed(self, val):
if self.actors:
mapper = self.actors[0].mapper
mapper.scalar_visibility = val
self.render()
def _surface_changed(self, val):
if self.actors:
representation = 'w'
if val:
representation = 's'
actor = self.actors[0]
if representation == 'w':
actor.property.trait_set(diffuse=0.0, ambient=1.0,
representation=representation)
else:
actor.property.trait_set(diffuse=1.0, ambient=0.0,
representation=representation)
self.render()
def _color_changed(self, val):
if self.actors:
self.actors[0].property.color = val
self.render()
######################################################################
# `FancyTriMesh` class.
######################################################################
class FancyTriMesh(LUTBase):
"""Shows a mesh of triangles and draws the edges as tubes and
points as balls."""
# Disables/enables scalar visibility.
scalar_visibility = Bool(False, desc='show scalar visibility')
# Color of the mesh.
color = vtk_color_trait((0.5, 1.0, 0.5))
# The radius of the tubes.
tube_radius = Float(0.0, desc='radius of the tubes')
# The radius of the spheres.
sphere_radius = Float(0.0, desc='radius of the spheres')
# The TubeFilter used to make the tubes for the edges.
tube_filter = Instance(tvtk.TubeFilter, (),
{'vary_radius':'vary_radius_off',
'number_of_sides':6})
# The sphere source for the points.
sphere_source = Instance(tvtk.SphereSource, (),
{'theta_resolution':12,
'phi_resolution':12})
def __init__(self, triangles, points, scalars=None, **traits):
"""
Parameters
----------
- triangles : array
This contains a list of vertex indices forming the triangles.
- points : array
Contains the list of points referred to in the triangle list.
- scalars : array (optional)
Scalars to associate with the points.
"""
super(FancyTriMesh, self).__init__(**traits)
self.points = points
self.pd = make_triangle_polydata(triangles, points, scalars)
# Update the radii so the default is computed correctly.
self._tube_radius_changed(self.tube_radius)
self._sphere_radius_changed(self.sphere_radius)
scalar_vis = self.scalar_visibility
# Extract the edges and show the lines as tubes.
self.extract_filter = tvtk.ExtractEdges(input=self.pd)
extract_f = self.extract_filter
self.tube_filter.trait_set(input=extract_f.output,
radius=self.tube_radius)
edge_mapper = tvtk.PolyDataMapper(input=self.tube_filter.output,
lookup_table=self.lut,
scalar_visibility=scalar_vis)
edge_actor = _make_actor(mapper=edge_mapper)
edge_actor.property.color = self.color
# Create the spheres for the points.
self.sphere_source.radius = self.sphere_radius
spheres = tvtk.Glyph3D(scaling=0, source=self.sphere_source.output,
input=extract_f.output)
sphere_mapper = tvtk.PolyDataMapper(input=spheres.output,
lookup_table=self.lut,
scalar_visibility=scalar_vis)
sphere_actor = _make_actor(mapper=sphere_mapper)
sphere_actor.property.color = self.color
if scalars is not None:
rs = numpy.ravel(scalars)
dr = min(rs), max(rs)
self.lut.table_range = dr
edge_mapper.scalar_range = dr
sphere_mapper.scalar_range = dr
self.actors.extend([edge_actor, sphere_actor])
def _scalar_visibility_changed(self, val):
if self.actors:
for i in self.actors:
i.mapper.scalar_visibility = val
self.render()
def _tube_radius_changed(self, val):
points = self.points
if val < 1.0e-9:
val = (max(numpy.ravel(points)) -
min(numpy.ravel(points)))/250.0
self.tube_radius = val
self.tube_filter.radius = val
self.render()
def _sphere_radius_changed(self, val):
points = self.points
if val < 1.0e-9:
val = (max(numpy.ravel(points)) -
min(numpy.ravel(points)))/100.0
self.sphere_radius = val
self.sphere_source.radius = val
self.render()
def _color_changed(self, val):
if self.actors:
self.actors[0].property.color = val
self.render()
######################################################################
# `Mesh` class.
######################################################################
class Mesh(TriMesh):
def __init__(self, x, y, z, scalars=None, **traits):
"""
Parameters
----------
- x : array