/
pylab.py
1980 lines (1720 loc) · 67.4 KB
/
pylab.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
"""The pylab module of ipvyolume."""
from __future__ import absolute_import
from __future__ import division
import pythreejs
__all__ = [
'current',
'clear',
'controls_light',
'figure',
'gcf',
'xlim',
'ylim',
'zlim',
'xyzlim',
'squarelim',
'set_box_aspect',
'set_box_aspect_data',
'plot_trisurf',
'plot_surface',
'plot_wireframe',
'plot_mesh',
'plot',
'scatter',
'quiver',
'show',
'animate_glyphs',
'animation_control',
'gcc',
'transfer_function',
'plot_isosurface',
'volshow',
'save',
'movie',
'screenshot',
'savefig',
'xlabel',
'ylabel',
'zlabel',
'xyzlabel',
'view',
'style',
'plot_plane',
'selector_default',
'light_ambient',
'light_directional',
'light_spot',
'light_point',
'light_hemisphere',
'material_physical',
'material_phong',
'material_lambert',
'material_clear',
]
import os
import time
import warnings
import tempfile
import uuid
import base64
from io import BytesIO as StringIO
import six
import numpy as np
import PIL.Image
import matplotlib.style
try:
import shapely.geometry
except:
shapely = None
try:
import skimage.measure
except:
skimage = None
import ipywidgets
import IPython
from IPython.display import display
import ipyvolume as ipv
import ipyvolume.embed
from ipyvolume import utils
from . import ui
_last_figure = None
def _docsubst(f):
"""Perform docstring substitutions."""
f.__doc__ = f.__doc__.format(**_doc_snippets)
return f
_seq_sn = "If an (S, N) array, the first dimension will be used for frames in an animation."
_seq_snm = "If an (S, N, M) array, the first dimension will be used for frames in an animation."
_doc_snippets = {}
_doc_snippets["color"] = (
"color for each point/vertex/symbol, can be string format, examples for red:'red', '#f00',"
"'#ff0000' or'rgb(1,0,0), or rgb array of shape (N, 3 or 4) or (S, N, 3 or 4)"
)
_doc_snippets[
"color2d"
] = "color for each point/vertex string format, examples for red:'red', '#f00', '#ff0000' or 'rgb(1,0,0), or rgb"
" array of shape (2, N, 3 or 4) or (S, 2, N, 3 or 4)"
_doc_snippets[
"size"
] = "float representing the size of the glyph in percentage of the viewport, where 100 is the full size of the viewport"
_doc_snippets[
"marker"
] = "name of the marker, options are: 'arrow', 'box', 'diamond', 'sphere', 'point_2d', 'square_2d', 'triangle_2d', "
"'circle_2d', 'cylinder', 'cylinder_hr' (hr means high resolution, meaning more triangles thus a performance impact)"
_doc_snippets["x"] = "numpy array of shape (N,) or (S, N) with x positions. {}".format(_seq_sn)
_doc_snippets["y"] = "idem for y"
_doc_snippets["z"] = "idem for z"
_doc_snippets["u_dir"] = "numpy array of shape (N,) or (S, N) indicating the x component of a vector. {}".format(
_seq_sn
)
_doc_snippets["v_dir"] = "idem for y"
_doc_snippets["w_dir"] = "idem for z"
_doc_snippets["u"] = "numpy array of shape (N,) or (S, N) indicating the u (x) coordinate for the texture. {}".format(
_seq_sn
)
_doc_snippets["v"] = "numpy array of shape (N,) or (S, N) indicating the v (y) coordinate for the texture. {}".format(
_seq_sn
)
_doc_snippets["x2d"] = "numpy array of shape (N,M) or (S, N, M) with x positions. {}".format(_seq_snm)
_doc_snippets["y2d"] = "idem for y"
_doc_snippets["z2d"] = "idem for z"
_doc_snippets["texture"] = "PIL.Image object or ipywebrtc.MediaStream (can be a seqence)"
_doc_snippets['cast_shadow'] = 'If this object casts a shadown on other options (default) or not. Works only with Directional, Point and Spot lights.'
_doc_snippets['receive_shadow'] = 'If this objects receives shadows (default) or not. Works only with Directional, Point and Spot lights.'
_doc_snippets['opacity'] = "Float in the range of 0.0 - 1.0 indicating how transparent the material is. A value of 0.0 indicates fully transparent, 1.0 is fully opaque."\
"If the material's transparent property is not set to true, the material will remain fully opaque and this value will only affect its color."
_doc_snippets['transparent'] = "Defines whether this material is transparent. (NOTE: might not always render correctly, see the topic of order independant transparancy)"
_doc_snippets['description'] = "Used in the legend and in popup to identify the object"
emissive_intensity_default = 0.2
class current:
figure = None
container = None
material = None
figures = {}
containers = {}
def clear():
"""Remove current figure (and container)."""
current.container = None
current.figure = None
current.material = None
def controls_light(return_widget=False):
fig = gcf()
ambient_coefficient = ipywidgets.FloatSlider(
min=0, max=1, step=0.001, value=fig.ambient_coefficient, description="ambient"
)
diffuse_coefficient = ipywidgets.FloatSlider(
min=0, max=1, step=0.001, value=fig.diffuse_coefficient, description="diffuse"
)
specular_coefficient = ipywidgets.FloatSlider(
min=0, max=1, step=0.001, value=fig.specular_coefficient, description="specular"
)
specular_exponent = ipywidgets.FloatSlider(
min=0, max=10, step=0.001, value=fig.specular_exponent, description="specular exp"
)
ipywidgets.jslink((fig, 'ambient_coefficient'), (ambient_coefficient, 'value'))
ipywidgets.jslink((fig, 'diffuse_coefficient'), (diffuse_coefficient, 'value'))
ipywidgets.jslink((fig, 'specular_coefficient'), (specular_coefficient, 'value'))
ipywidgets.jslink((fig, 'specular_exponent'), (specular_exponent, 'value'))
widgets_bottom = [
ipywidgets.HBox([ambient_coefficient, diffuse_coefficient]),
ipywidgets.HBox([specular_coefficient, specular_exponent]),
]
current.container.children = current.container.children + widgets_bottom
if return_widget:
return widgets_bottom
def figure(
key=None,
width=400,
height=500,
lighting=True,
controls=True,
controls_vr=False,
controls_light=False,
debug=False,
**kwargs
):
"""Create a new figure if no key is given, or return the figure associated with key.
:param key: Python object that identifies this figure
:param int width: pixel width of WebGL canvas
:param int height: .. height ..
:param bool lighting: use lighting or not
:param bool controls: show controls or not
:param bool controls_vr: show controls for VR or not
:param bool debug: show debug buttons or not
:return: :any:`Figure`
"""
if key is not None and key in current.figures:
current.figure = current.figures[key]
current.container = current.containers[key]
elif isinstance(key, ipv.Figure) and key in current.figures.values():
key_index = list(current.figures.values()).index(key)
key = list(current.figures.keys())[key_index]
current.figure = current.figures[key]
current.container = current.containers[key]
else:
current.figure = ipv.Figure(width=width, height=height, **kwargs)
current.material = None
legend = ui.Legend(figure=current.figure)
current.container = ui.Container(figure=current.figure, legend=legend)
current.container.children = []
if key is None:
key = uuid.uuid4().hex
current.figures[key] = current.figure
current.containers[key] = current.container
if controls:
# stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye')
# l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value'))
# current.container.children += (ipywidgets.HBox([stereo, ]),)
pass # stereo and fullscreen are now include in the js code (per view)
if controls_vr:
eye_separation = ipywidgets.FloatSlider(value=current.figure.eye_separation, min=-10, max=10, icon='eye')
ipywidgets.jslink((eye_separation, 'value'), (current.figure, 'eye_separation'))
current.container.children = current.container.children + [eye_separation]
if debug:
warnings.warn("debug=True no longer needed", DeprecationWarning, stacklevel=2)
if controls_light:
globals()['controls_light']()
return current.figure
def gcf():
"""Get current figure, or create a new one.
:return: :any:`Figure`
"""
if current.figure is None:
return figure()
else:
return current.figure
def _grow_limit(limits, values):
if isinstance(values, (tuple, list)) and len(values) == 2:
newvmin, newvmax = values
else:
try:
values[0] # test if scalar
except TypeError:
newvmin = values
newvmax = values
except IndexError:
newvmin = values
newvmax = values
else:
finites = np.isfinite(values)
newvmin = np.min(values[finites])
newvmax = np.max(values[finites])
if limits is None:
return newvmin, newvmax
else:
vmin, vmax = limits
return min(newvmin, vmin), max(newvmax, vmax)
def _grow_limits(x, y, z):
fig = gcf()
xlim(*_grow_limit(fig.xlim, x))
ylim(*_grow_limit(fig.ylim, y))
zlim(*_grow_limit(fig.zlim, z))
def xlim(xmin, xmax):
"""Set limits of x axis."""
fig = gcf()
fig.xlim = [xmin, xmax]
def ylim(ymin, ymax):
"""Set limits of y axis."""
fig = gcf()
fig.ylim = [ymin, ymax]
def zlim(zmin, zmax):
"""Set limits of zaxis."""
fig = gcf()
fig.zlim = [zmin, zmax]
def xyzlim(vmin, vmax=None):
"""Set limits or all axis the same, if vmax not given, use [-vmin, vmin]."""
if vmax is None:
vmin, vmax = -vmin, vmin
xlim(vmin, vmax)
ylim(vmin, vmax)
zlim(vmin, vmax)
def squarelim():
"""Set all axes with equal aspect ratio, such that the space is 'square'."""
fig = gcf()
xmin, xmax = fig.xlim
ymin, ymax = fig.ylim
zmin, zmax = fig.zlim
width = max([abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin)])
xc = (xmin + xmax) / 2
yc = (ymin + ymax) / 2
zc = (zmin + zmax) / 2
xlim(xc - width / 2, xc + width / 2)
ylim(yc - width / 2, yc + width / 2)
zlim(zc - width / 2, zc + width / 2)
def set_box_aspect(aspect, *, zoom=1):
'''Sets the aspects of the bounding box/axes.
Example:
>>> ipv.set_box_aspect((1, 0.5, 0.75))
:param aspect: 3 tuple defining the relative lengths of the x, y and z axis (normalized by zoom)
:param float zoom: length of the largest axis.
'''
aspect = np.array(aspect, dtype='f8')
aspect /= aspect.max()
aspect *= zoom
fig = gcf()
fig.box_size = aspect.tolist()
def set_box_aspect_data():
'''Sets the aspect of the bounding box equal to the aspects of the data
For volume rendering, this makes your voxels cubes.
'''
fig = gcf()
xmin, xmax = fig.xlim
ymin, ymax = fig.ylim
zmin, zmax = fig.zlim
size = [abs(xmax - xmin), abs(ymax - ymin), abs(zmax - zmin)]
set_box_aspect(size)
default_color = "red"
default_color_selected = "white"
default_size = 2
default_size_selected = default_size * 1.3
def material_clear():
'''Set the current material to the default'''
current.material = None
def material_physical(color="#ffffff", emissive="#000000", emissive_intensity=emissive_intensity_default, roughness=0.5, metalness=0, flat_shading=False, opacity=1, transparent=False, **kwargs):
"""Sets the current material to a :any:`pythreejs.MeshPhysicalMaterial`.
:param color color: Color of the material, by default set to white (0xffffff).
:param color emissive: Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.
:param emissive_intensity: Factor multiplied with color. Takes values between 0 and 1. Default is 0.2
:param roughness: How rough the material appears. 0.0 means a smooth mirror reflection, 1.0 means fully diffuse. Default is 0.5
:param metalness: How much the material is like a metal. Non-metallic materials such as wood or stone use 0.0, metallic use 1.0, with nothing (usually) in between
:param flat_shading: A technique for color computing where all polygons reflect as a flat surface. Default False
:param float opacity: {opacity}
:param bool transparent: {transparent}
:param kwargs: Arguments passed on the constructor of :any:`pythreejs.MeshPhysicalMaterial`
:return: :any:`pythreejs.MeshPhysicalMaterial`
"""
material = pythreejs.MeshPhysicalMaterial(
color=color,
emissive=emissive,
emissiveIntensity=emissive_intensity,
roughness=roughness,
metalness=metalness,
flat_shading=flat_shading,
opacity=opacity,
transparent=transparent,
side=pythreejs.enums.Side.DoubleSide,
**kwargs
)
current.material = material
return current.material
def material_phong(emissive="#000000", specular="#111111", shininess=30, flat_shading=False, opacity=1, transparent=False, **kwargs):
"""Sets the current material to a :any:`pythreejs.MeshPhongMaterial`.
:param color emissive: Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.
:param color specular: Specular color of the material. Default is a Color set to 0x111111 (very dark grey). This defines how shiny the material is and the color of its shine.
:param snininess: How shiny the specular highlight is; a higher value gives a sharper highlight. Default is 30.
:param flat_shading: A technique for color computing where all polygons reflect as a flat surface. Default False
:param float opacity: {opacity}
:param bool transparent: {transparent}
:param kwargs: Arguments passed on the constructor of :any:`pythreejs.MeshPhongMaterial`
:return: :any:`pythreejs.MeshPhongMaterial`
"""
material = pythreejs.MeshPhongMaterial(
emissive=emissive,
specular=specular,
shininess=shininess,
flat_shading=flat_shading,
opacity=opacity,
transparent=transparent,
side=pythreejs.enums.Side.DoubleSide,
**kwargs
)
current.material = material
return current.material
@_docsubst
def material_lambert(color="#ffffff", emissive="#000000", flat_shading=False, opacity=1, transparent=False, **kwargs):
"""Sets the current material to a :any:`pythreejs.MeshLambertMaterial`.
:param color color: Color of the material, by default set to white (0xffffff).
:param color emissive: Emissive (light) color of the material, essentially a solid color unaffected by other lighting. Default is black.
:param flat_shading: A technique for color computing where all polygons reflect as a flat surface. Default False
:param float opacity: {opacity}
:param bool transparent: {transparent}
:param kwargs: Arguments passed on the constructor of :any:`pythreejs.MeshLambertMaterial`
:return: :any:`pythreejs.MeshLambertMaterial`
"""
material = pythreejs.MeshLambertMaterial(
color=color,
emissive=emissive,
flat_shading=flat_shading,
opacity=opacity,
transparent=transparent,
side=pythreejs.enums.Side.DoubleSide,
**kwargs
)
current.material = material
return current.material
@_docsubst
def plot_trisurf(
x,
y,
z,
triangles=None,
lines=None,
color=default_color,
u=None,
v=None,
texture=None,
cast_shadow=True,
receive_shadow=True,
description=None,
**kwargs):
"""Draw a polygon/triangle mesh defined by a coordinate and triangle indices.
The following example plots a rectangle in the z==2 plane, consisting of 2 triangles:
>>> plot_trisurf([0, 0, 3., 3.], [0, 4., 0, 4.], 2,
triangles=[[0, 2, 3], [0, 3, 1]])
Note that the z value is constant, and thus not a list/array. For guidance, the triangles
refer to the vertices in this manner::
^ ydir
|
2 3
0 1 ---> x dir
Note that if you want per face/triangle colors, you need to duplicate each vertex.
:param x: {x}
:param y: {y}
:param z: {z}
:param triangles: numpy array with indices referring to the vertices, defining the triangles, with shape (M, 3)
:param lines: numpy array with indices referring to the vertices, defining the lines, with shape (K, 2)
:param color: {color} Color of the material, essentially a solid color unaffected by other lighting. Default is 'red'
:param u: {u}
:param v: {v}
:param texture: {texture}
:param cast_shadow: {cast_shadow}
:param receive_shadow: {receive_shadow}
:param description: {description}
:return: :any:`Mesh`
"""
fig = gcf()
if triangles is not None:
triangles = np.array(triangles).astype(dtype=np.uint32)
if lines is not None:
lines = np.array(lines).astype(dtype=np.uint32)
kwargs = kwargs.copy()
if current.material is not None:
kwargs['material'] = current.material
if description is None:
description = f"Mesh {len(fig.meshes)}"
mesh = ipv.Mesh(
x=x,
y=y,
z=z,
triangles=triangles,
lines=lines,
color=color,
u=u, v=v,
texture=texture,
cast_shadow=cast_shadow,
receive_shadow=receive_shadow,
description=description,
**kwargs
)
_grow_limits(np.array(x).reshape(-1), np.array(y).reshape(-1), np.array(z).reshape(-1))
fig.meshes = fig.meshes + [mesh]
return mesh
@_docsubst
def plot_surface(x, y, z, color=default_color, wrapx=False, wrapy=False, cast_shadow=True, receive_shadow=True):
"""Draws a 2d surface in 3d, defined by the 2d ordered arrays x,y,z.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points
:param bool wrapy: simular for the y coordinate
:param cast_shadow: {cast_shadow}
:param receive_shadow: {receive_shadow}
:return: :any:`Mesh`
"""
return plot_mesh(x, y, z, color=color, wrapx=wrapx, wrapy=wrapy, wireframe=False, cast_shadow=cast_shadow, receive_shadow=receive_shadow)
@_docsubst
def plot_wireframe(x, y, z, color=default_color, wrapx=False, wrapy=False, cast_shadow=True, receive_shadow=True):
"""Draws a 2d wireframe in 3d, defines by the 2d ordered arrays x,y,z.
See also :any:`ipyvolume.pylab.plot_mesh`
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the begin and end points
:param bool wrapy: idem for y
:param cast_shadow: {cast_shadow}
:param receive_shadow: {receive_shadow}
:return: :any:`Mesh`
"""
return plot_mesh(x, y, z, color=color, wrapx=wrapx, wrapy=wrapy, wireframe=True, surface=False, cast_shadow=cast_shadow, receive_shadow=receive_shadow)
@_docsubst
def plot_mesh(
x, y, z, color=default_color, wireframe=True, surface=True, wrapx=False, wrapy=False, u=None, v=None, texture=None,
cast_shadow=True, receive_shadow=True,
description=None,
):
"""Draws a 2d wireframe+surface in 3d: generalization of :any:`plot_wireframe` and :any:`plot_surface`.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param color: {color2d}
:param bool wireframe: draw lines between the vertices
:param bool surface: draw faces/triangles between the vertices
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the begin and end points
:param boool wrapy: idem for y
:param u: {u}
:param v: {v}
:param texture: {texture}
:param cast_shadow: {cast_shadow}
:param receive_shadow: {receive_shadow}
:param description: {description}
:return: :any:`Mesh`
"""
fig = gcf()
# assert len(x.shape) == 2
# assert len(y.shape) == 2
# assert len(z.shape) == 2
# if isinstance(color, np.ndarray):
# assert len(color.shape) == 3
# assert color.shape[:2] == x.shape
# color = color.reshape(-1)
def dim(x):
d = 0
el = x
while True:
try:
el = el[0]
d += 1
except:
break
return d
if dim(x) == 2:
nx, ny = x.shape
else:
nx, ny = x[0].shape
# 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."
# convert x, y, z from shape (nx, ny) to (nx * ny) or
# (frame, nx, ny) to (frame, nx*ny)
def reshape(ar):
if dim(ar) == 3:
return [k.reshape(-1) for k in ar]
else:
return ar.reshape(-1)
x = reshape(x)
y = reshape(y)
z = reshape(z)
# similar for texture coordinates
if u is not None:
u = reshape(u)
if v is not None:
v = reshape(v)
# convert color from shape (nx, ny, {3,4}) to (nx * ny, {3, 4}) or
# (frame, nx, ny, {3,4}) to (frame, nx*ny, {3,4})
def reshape_color(ar):
if dim(ar) == 4:
return [k.reshape(-1, k.shape[-1]) for k in ar]
else:
return ar.reshape(-1, ar.shape[-1])
if isinstance(color, np.ndarray):
color = reshape_color(color)
_grow_limits(np.array(x).reshape(-1), np.array(y).reshape(-1), np.array(z).reshape(-1))
triangles, lines = _make_triangles_lines((nx, ny), wrapx, wrapy)
kwargs = {}
if current.material is not None:
kwargs['material'] = current.material
mesh = ipv.Mesh(
x=x,
y=y,
z=z,
triangles=triangles if surface else None,
color=color,
lines=lines if wireframe else None,
u=u,
v=v,
texture=texture,
cast_shadow=cast_shadow,
receive_shadow=receive_shadow,
description=f"Mesh {len(fig.meshes)}" if description is None else description,
**kwargs
)
fig.meshes = fig.meshes + [mesh]
return mesh
@_docsubst
def plot(x, y, z, color=default_color, cast_shadow=True, receive_shadow=True, **kwargs):
"""Plot a line in 3d.
:param x: {x}
:param y: {y}
:param z: {z}
:param color: {color}
:param cast_shadow: {cast_shadow}
:param receive_shadow: {receive_shadow}
:param kwargs: extra arguments passed to the Scatter constructor
:return: :any:`Scatter`
"""
fig = gcf()
_grow_limits(x, y, z)
defaults = dict(
visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
)
kwargs = dict(defaults, **kwargs)
s = ipv.Scatter(x=x, y=y, z=z, color=color, cast_shadow=True, receive_shadow=True, **kwargs)
s.material.visible = False
fig.scatters = fig.scatters + [s]
return s
@_docsubst
def scatter(
x,
y,
z,
color=default_color,
size=default_size,
size_selected=default_size_selected,
color_selected=default_color_selected,
marker="diamond",
selection=None,
grow_limits=True,
cast_shadow=True,
receive_shadow=True,
description=None,
**kwargs
):
"""Plot many markers/symbols in 3d.
Due to certain shader limitations, should not use with Spot Lights and Point Lights.
Does not support shadow mapping.
:param x: {x}
:param y: {y}
:param z: {z}
:param color: {color} Color of the material, essentially a solid color unaffected by other lighting. Default is 'red'
:param size: {size}
:param size_selected: like size, but for selected glyphs
:param color_selected: like color, but for selected glyphs
:param marker: {marker}
:param selection: numpy array of shape (N,) or (S, N) with indices of x,y,z arrays of the selected markers, which
can have a different size and color
:param cast_shadow: {cast_shadow}
:param receive_shadow: {receive_shadow}
:param kwargs:
:return: :any:`Scatter`
"""
fig = gcf()
kwargs = kwargs.copy()
if current.material is not None and 'material' not in kwargs:
kwargs['material'] = current.material
s = ipv.Scatter(
x=x,
y=y,
z=z,
color=color,
size=size,
color_selected=color_selected,
size_selected=size_selected,
geo=marker,
selection=selection,
cast_shadow=cast_shadow,
receive_shadow=receive_shadow,
description=f"Scatter {len(fig.scatters)}" if description is None else description,
**kwargs
)
if grow_limits:
_grow_limits(s.x, s.y, s.z)
fig.scatters = fig.scatters + [s]
return s
@_docsubst
def quiver(
x,
y,
z,
u,
v,
w,
size=default_size * 10,
size_selected=default_size_selected * 10,
color=default_color,
color_selected=default_color_selected,
marker="arrow",
cast_shadow=True,
receive_shadow=True,
**kwargs
):
"""Create a quiver plot, which is like a scatter plot but with arrows pointing in the direction given by u, v and w.
:param x: {x}
:param y: {y}
:param z: {z}
:param u: {u_dir}
:param v: {v_dir}
:param w: {w_dir}
:param size: {size}
:param size_selected: like size, but for selected glyphs
:param color: {color}
:param color_selected: like color, but for selected glyphs
:param marker: (currently only 'arrow' would make sense)
:param cast_shadow: {cast_shadow}
:param receive_shadow: {receive_shadow}
:param kwargs: extra arguments passed on to the Scatter constructor
:return: :any:`Scatter`
"""
fig = gcf()
_grow_limits(x, y, z)
if 'vx' in kwargs or 'vy' in kwargs or 'vz' in kwargs:
raise KeyError('Please use u, v, w instead of vx, vy, vz')
kwargs = kwargs.copy()
if current.material is not None and 'material' not in kwargs:
kwargs['material'] = current.material
s = ipv.Scatter(
x=x,
y=y,
z=z,
vx=u,
vy=v,
vz=w,
color=color,
size=size,
color_selected=color_selected,
size_selected=size_selected,
geo=marker,
cast_shadow=cast_shadow,
receive_shadow=receive_shadow,
**kwargs
)
fig.scatters = fig.scatters + [s]
return s
def show(extra_widgets=[]):
"""Display (like in IPython.display.dispay(...)) the current figure."""
gcf() # make sure we have something..
display(gcc())
for widget in extra_widgets:
display(widget)
def animate_glyphs(*args, **kwargs):
"""Deprecated: please use animation_control."""
warnings.warn("Please use animation_control(...)", DeprecationWarning, stacklevel=2)
animation_control(*args, **kwargs)
def animation_control(object, sequence_length=None, add=True, interval=200):
"""Animate scatter, quiver or mesh by adding a slider and play button.
:param object: :any:`Scatter` or :any:`Mesh` object (having an sequence_index property), or a list of these to
control multiple.
:param sequence_length: If sequence_length is None we try try our best to figure out, in case we do it badly,
you can tell us what it should be. Should be equal to the S in the shape of the numpy arrays as for instance
documented in :any:`scatter` or :any:`plot_mesh`.
:param add: if True, add the widgets to the container, else return a HBox with the slider and play button. Useful when you
want to customise the layout of the widgets yourself.
:param interval: interval in msec between each frame
:return: If add is False, if returns the ipywidgets.HBox object containing the controls
"""
if isinstance(object, (list, tuple)):
objects = object
else:
objects = [object]
del object
if sequence_length is None:
# get all non-None arrays
sequence_lengths = []
for object in objects:
sequence_lengths_previous = list(sequence_lengths)
values = [getattr(object, name) for name in "x y z aux vx vy vz".split() if hasattr(object, name)]
values = [k for k in values if k is not None]
# sort them such that the higest dim is first
values.sort(key=lambda key: -len(key.shape))
try:
sequence_length = values[0].shape[0] # assume this defines the sequence length
if isinstance(object, ipv.Mesh): # for a mesh, it does not make sense to have less than 1 dimension
if len(values[0].shape) >= 2: # if just 1d, it is most likely not an animation
sequence_lengths.append(sequence_length)
else:
sequence_lengths.append(sequence_length)
except IndexError: # scalars get ignored
pass
if hasattr(object, 'color'):
color = object.color
if color is not None:
shape = color.shape
if len(shape) == 3: # would be the case for for (frame, point_index, color_index)
sequence_lengths.append(shape[0])
# TODO: maybe support arrays of string type of form (frame, point_index)
if len(sequence_lengths) == len(sequence_lengths_previous):
raise ValueError('no frame dimension found for object: {}'.format(object))
sequence_length = max(sequence_lengths)
fig = gcf()
fig.animation = interval
fig.animation_exponent = 1.0
play = ipywidgets.Play(min=0, max=sequence_length - 1, interval=interval, value=0, step=1)
slider = ipywidgets.FloatSlider(min=0, max=play.max, step=1)
ipywidgets.jslink((play, 'value'), (slider, 'value'))
for object in objects:
ipywidgets.jslink((slider, 'value'), (object, 'sequence_index'))
control = ipywidgets.HBox([play, slider])
if add:
current.container.children = current.container.children + [control]
else:
return control
def gcc():
"""Return the current container, that is the widget holding the figure and all the control widgets, buttons etc."""
gcf() # make sure we have something..
return current.container
def transfer_function(
level=[0.1, 0.5, 0.9], opacity=[0.01, 0.05, 0.1], level_width=0.1, controls=True, max_opacity=0.2
):
"""Create a transfer function, see volshow."""
tf_kwargs = {}
# level, opacity and widths can be scalars
try:
level[0]
except:
level = [level]
try:
opacity[0]
except:
opacity = [opacity] * 3
try:
level_width[0]
except:
level_width = [level_width] * 3
# clip off lists
min_length = min(len(level), len(level_width), len(opacity))
level = list(level[:min_length])
opacity = list(opacity[:min_length])
level_width = list(level_width[:min_length])
# append with zeros
while len(level) < 3:
level.append(0)
while len(opacity) < 3:
opacity.append(0)
while len(level_width) < 3:
level_width.append(0)
for i in range(1, 4):
tf_kwargs["level" + str(i)] = level[i - 1]
tf_kwargs["opacity" + str(i)] = opacity[i - 1]
tf_kwargs["width" + str(i)] = level_width[i - 1]
tf = ipv.TransferFunctionWidgetJs3(**tf_kwargs)
gcf() # make sure a current container/figure exists
if controls:
current.container.children = [tf.control(max_opacity=max_opacity)] + current.container.children
return tf
@_docsubst
def plot_isosurface(data, level=None, color=default_color, wireframe=True, surface=True, controls=True, extent=None, description=None):
"""Plot a surface at constant value (like a 2d contour).
:param data: 3d numpy array
:param float level: value where the surface should lie
:param color: color of the surface, although it can be an array, the length is difficult to predict beforehand,
if per vertex color are needed, it is better to set them on the returned mesh afterwards.
:param bool wireframe: draw lines between the vertices
:param bool surface: draw faces/triangles between the vertices
:param bool controls: add controls to change the isosurface
:param extent: list of [[xmin, xmax], [ymin, ymax], [zmin, zmax]] values that define the bounding box of the mesh,
otherwise the viewport is used
:param description: {description}
:return: :any:`Mesh`
"""
if level is None:
level = np.median(data)
if hasattr(skimage.measure, 'marching_cubes_lewiner'):
values = skimage.measure.marching_cubes_lewiner(data, level)
else:
values = skimage.measure.marching_cubes(data, level) # pylint: disable=no-member
verts, triangles = values[:2] # version 0.13 returns 4 values, normals, values
# in the future we may want to support normals and the values (with colormap)
# and require skimage >= 0.13
x, y, z = verts.T
# Rescale coordinates to given limits
if extent:
xlim, ylim, zlim = extent
x = x * np.diff(xlim) / (data.shape[0] - 1) + xlim[0]
y = y * np.diff(ylim) / (data.shape[1] - 1) + ylim[0]
z = z * np.diff(zlim) / (data.shape[2] - 1) + zlim[0]
_grow_limits(*extent)
fig = gcf()
if description is None:
description = f"Isosurface {len(fig.meshes)}"
mesh = plot_trisurf(x, y, z, triangles=triangles, color=color, description=description)
if controls:
vmin, vmax = np.percentile(data, 1), np.percentile(data, 99)
step = (vmax - vmin) / 250
level_slider = ipywidgets.FloatSlider(value=level, min=vmin, max=vmax, step=step, icon='eye')
recompute_button = ipywidgets.Button(description='update')
controls = ipywidgets.HBox(children=[level_slider, recompute_button])
current.container.children = current.container.children + [controls]
def recompute(*_ignore):
level = level_slider.value
recompute_button.description = "updating..."
if hasattr(skimage.measure, 'marching_cubes_lewiner'):
values = skimage.measure.marching_cubes_lewiner(data, level)
else:
values = skimage.measure.marching_cubes(data, level) # pylint: disable=no-member
verts, triangles = values[:2] # version 0.13 returns 4 values, normals, values
# in the future we may want to support normals and the values (with colormap)
# and require skimage >= 0.13
x, y, z = verts.T
with mesh.hold_sync():
mesh.x = x
mesh.y = y
mesh.z = z
mesh.triangles = triangles.astype(dtype=np.uint32)
recompute_button.description = "update"