-
Notifications
You must be signed in to change notification settings - Fork 2
/
coplot.py
executable file
·1863 lines (1693 loc) · 47.2 KB
/
coplot.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import matplotlib as mpl
#from coplot import *
from coroutine import coroutine
from read import read
import argparse
import itertools as it
from scipy.optimize import curve_fit
import itertools
from matplotlib.colors import LogNorm,SymLogNorm
from FunctionNorm import FunctionNorm,ArcsinhNorm
from centercmap import centercmap
stdcmap = plt.cm.viridis
try:
from tqdm import tqdm
except ImportError:
tqdm = lambda a: a
from matplotlib import rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
#rc('text', usetex=False)
#rc('text.latex', preamble=r"\usepackage{wasysym}")
#rc('text.latex', unicode=True)
# overwrite some standard keymapings, so they don't collide with our
# own.
# See: http://matplotlib.github.com/users/navigation_toolbar.html
rc('keymap',back='c',forward='v',zoom='z',home='h')
# Add Keypress to plot coroutine
def connectKey(fig,key,action):
def press(event):
if(event.key == key):
action()
fig.canvas.draw()
fig.canvas.mpl_connect('key_press_event', press)
@coroutine
def once(send,data):
first = True
while True:
d = (yield)
if first:
send(data)
send(d)
@coroutine
def sum(send, axis=None):
while True:
d = (yield)
send(np.sum(d,axis))
@coroutine
def gaussian_filter(send,*args,**kwargs):
from scipy.ndimage.filters import gaussian_filter
while True:
d = (yield)
a = gaussian_filter(d,*args,**kwargs)
send(a)
@coroutine
def gaussiankernel_filter(send,stddev,*args,**kwargs):
from astropy.convolution import Gaussian1DKernel, convolve
#http://docs.astropy.org/en/stable/convolution/
g = Gaussian1DKernel(stddev=stddev)
kwargs.setdefault("boundary","extend")
while True:
d = (yield)
a = convolve(d, g, *args,**kwargs)
send(a)
@coroutine
def median_filter(send,*args,**kwargs):
from scipy.signal import medfilt
while True:
d = (yield)
a = medfilt(d,*args,**kwargs)
send(a)
@coroutine
def uniform_filter(send,*args,**kwargs):
from scipy.ndimage.filters import uniform_filter
while True:
d = (yield)
a = uniform_filter(d,*args,**kwargs)
send(a)
@coroutine
def mean(send, axis=None):
while True:
d = (yield)
send(np.mean(d,axis))
@coroutine
def customfilter(send,fn):
while True:
d = (yield)
if fn(d):
send(d)
@coroutine
def min(send, axis=None):
while True:
d = (yield)
send(np.min(d,axis))
@coroutine
def max(send, axis=None):
while True:
d = (yield)
send(np.max(d,axis))
minmaxmean = lambda d: (np.min(d),np.mean(d),np.max(d))
@coroutine
def minmax(send, axis=None):
while True:
d = (yield)
send((np.min(d,axis),np.max(d,axis)))
@coroutine
def clip(send, min, max):
while True:
d = (yield)
send(np.clip(d, min, max))
@coroutine
def symclip(send):
while True:
d = (yield)
l = np.min([np.abs(np.min(d)),np.max(d)])
send(np.clip(d, -l, l))
@coroutine
def printer(send,fn=lambda d: d):
while True:
d = (yield)
if 'f' in send:
f = send['f']
print fn(d)
send(d)
@coroutine
def produce(send,d):
while True:
(yield)
send(d)
@coroutine
def generate(send,d=None):
while True:
r = (yield)
if d is None:
d = r
for i in d:
send(i)
def getval(p,*args):
@coroutine
def exitandraise(send):
d = (yield)
raise StopIteration(d)
try:
(p | exitandraise()).send(*args)
except StopIteration as inst:
if(len(inst.args)==1):
return inst.args[0]
else:
return inst.args
@coroutine
def pipe(send,p=None):
if p is None:
while True:
send((yield))
else:
@coroutine
def helper(send2):
while True:
d2 = (yield)
send(d2)
subpipe = p | helper()
while True:
d = (yield)
subpipe.send(d)
def inject(send,p):
@coroutine
def helper(send2):
while True:
d2 = (yield)
send(d2)
subpipe = p | helper()
return subpipe
@coroutine
def call(send,f,*args,**kwargs):
while True:
d = (yield)
f(*args,**kwargs)
send(d)
@coroutine
def iterate(send):
while True:
d = (yield)
for i in d:
send(i)
@coroutine
def select(send,frame=None):
f = send['f']
while True:
d = (yield)
if frame is None:
if isinstance(d,str):
i = int(d.rstrip(".bin").split("_")[-1])
else:
i = d
else:
i = frame
if isinstance(f,tuple) or isinstance(f,list):
for file in f:
file.select(i)
else:
f.select(i)
send(d)
@coroutine
def imshow(send,aspect=1,cmap=stdcmap,cax=plt,clim=None,cscale=None,norm=None,xscale=None,yscale=None,xlabel='x',ylabel='y',clabel=None,*args,**kwargs):
from matplotlib.colors import LogNorm
kwargs.setdefault("rasterized",True)
p = None
fig,sub = send['fig'],send['sub']
if clim==None:
rescale = lambda p: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
else:
rescale = lambda p: p.set_clim(clim[0],clim[1])
ex = kwargs.get('extent')
if ex is not None:
print ex
f = send['f']
try:
kwargs['extent'] = ex(f)
except:
pass
while True:
d = (yield)
if p==None:
if cscale=='log':
norm=LogNorm()
elif cscale=='symlog':
norm=SymLogNorm(0.01)
elif cscale=='arcsinh':
norm=ArcsinhNorm()
p = sub.imshow(d.T,
interpolation='none',
cmap=cmap,
clim=clim,
norm=norm,
origin='lower',
*args,
**kwargs)
ax = p.axes
if aspect is not None:
ax.set_aspect(aspect)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if xscale is not None:
ax.set_xscale(xscale)
if yscale is not None:
ax.set_yscale(yscale)
cbar = cax.colorbar(p)
if clabel!=None and cbar is not None:
cbar.set_label(clabel)
if clim==None:
rescale2 = lambda: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
else:
rescale2 = lambda: p.set_clim(clim[0],clim[1])
connectKey(fig,'backspace',rescale2)
rescale2()
else:
p.set_array(d.T)
rescale(p)
send(d)
@coroutine
def surface(send,f,fig,sub,aspect=1,cmap=stdcmap,cax=plt,clim=None,cscale=None,norm=None,xscale=None,yscale=None,*args,**kwargs):
from matplotlib.colors import LogNorm
p = None
while True:
d = (yield)
if p==None:
if cscale=='log':
norm=LogNorm()
bccart = f['/mesh/bary_centers']
X = bccart[:,:,0]
Y = bccart[:,:,1]
#p = sub.plot_surface(
p = sub.plot_trisurf(
X.flatten(), Y.flatten(),
d.flatten(),
linewidth=0.,
# rstride = 1,
# cstride = 1,
norm=norm,
cmap=cmap,
*args,
**kwargs)
ax = p.axes
ax.set_aspect(aspect)
if xscale is not None:
ax.set_xscale(xscale)
if yscale is not None:
ax.set_yscale(yscale)
cax.colorbar(p)
if clim==None:
rescale = lambda: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
else:
rescale = lambda: p.set_clim(clim[0],clim[1])
connectKey(fig,'backspace',rescale)
rescale()
else:
#p.set_array(d.T)
p.set_array(d.flatten())
send(d)
@coroutine
def plot(send,xdata=None,xlabel='x',ylabel='y',fmt='',xscale=None,yscale=None,xlim=None,ylim=None,aspect=None,text = lambda f:'n = %i\nt = %.2e' % (f.frame, f['/timedisc/time']),**kwargs):
f = send.get('f')
fig,sub = send['fig'],send['sub']
p, = sub.plot([],[],fmt,**kwargs)
ax = p.axes
ax.grid(True)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if aspect is not None:
ax.set_aspect(aspect)
title = ax.text(0.95,0.9,'',transform=ax.transAxes,ha='right')
def rescale():
minmax = lambda data: (np.min(data), np.max(data))
x, y = p.get_data()
if(xlim==None):
sub.set_xlim(*minmax(x))
else:
sub.set_xlim(xlim)
if(ylim==None):
sub.set_ylim(*minmax(y))
else:
sub.set_ylim(ylim)
connectKey(fig,"backspace",rescale)
first = True
while True:
d = (yield)
try:
p.set_data(*d)
except:
if xdata is None:
p.set_data(np.arange(len(d)),d)
else:
p.set_data(xdata,d)
if f is not None:
title.set_text(text(f))
if first:
if xscale is not None:
sub.set_xscale(xscale)
if yscale is not None:
sub.set_yscale(yscale)
rescale()
first = not first
send(d)
@coroutine
def multiplot(send,xlabel='x',ylabel='y',xlim=(None,None),ylim=(None,None),fmts=(),labels=(),repeat=0,xscale=None,yscale=None,loc='best',ncol=1,ltitle=None,rtitle=None,color='rgbcmykw',marker=None,linestyle='-',**kwargs):
#marker='xo+ps*'
fig,sub = send['fig'],send['sub']
minmax = lambda d: (np.min(d),np.max(d))
ax = None
p = []
def rescale():
xl = minmax(np.concatenate([l.get_xdata() for l in p]))
yl = minmax(np.concatenate([l.get_ydata() for l in p]))
ax.set_xlim(xl)
ax.set_ylim(yl)
# sub.set_xlim(auto=True)
# sub.set_ylim(auto=True)
def press(event):
print 'press', event.key
if(event.key in keys):
keys[event.key]()
fig.canvas.draw()
keys = dict(backspace = lambda: rescale())
fig.canvas.mpl_connect('key_press_event', press)
for i,fmt,label in it.izip_longest(it.count(0),fmts,labels,fillvalue=None):
x,y = (yield)
if repeat==0 or i<repeat:
c = color[len(p) % len(color)]
ls = linestyle[len(p) % len(linestyle)]
if marker is not None:
m = marker[len(p) % len(marker)]
#print marker,len(p),len(marker),len(p) % len(marker),m
#kwargs.setdefault('marker',m)
else:
m= None
kwargs.setdefault('markevery',int(len(y)/10.))
if fmt != None:
p.append(sub.plot(x,y,fmt,label=label,color=c,marker=m,linestyle=ls,**kwargs)[0])
else:
p.append(sub.plot(x,y,label=label,color=c,marker=m,linestyle=ls,**kwargs)[0])
if len(p)==1:
ax = p[0].axes
ax.grid(True)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if xscale is not None:
ax.set_xscale(xscale)
if yscale is not None:
ax.set_yscale(yscale)
ax.legend(loc=loc,ncol=ncol)
rescale()
if ltitle is not None:
ax.set_title(ltitle(),loc='left')
if rtitle is not None:
ax.set_title(rtitle(),loc='right')
ax.set_xlim(*xlim)
ax.set_ylim(*ylim)
else:
p[i%repeat].set_ydata(y)
send((x,y))
@coroutine
def makelist(send,n=lambda f: len(f),l=None):
f = send.get('f')
l = None
i = 0
nolist=False
while True:
d = (yield)
if not isinstance(d, (list,tuple)):
d = (d,)
nolist=True
i += 1
if l==None:
l = tuple([e] for e in d)
else:
for a,e in zip(l,d):
a.append(e)
if(i%n(f)==0):
if nolist:
l, = l
send(l)
l=None
@coroutine
def cut(send,s):
sel = tuple()
for i in s:
if i==None:
sel += (slice(None,None),)
else:
sel += (i,)
while True:
d = (yield)
send(d[sel])
#with interpolation
@coroutine
def streamplot2(send,res=50,clabel=None,xlim=None,ylim=None,scale=1.,cmap=stdcmap,color=lambda u,v: np.sqrt(u**2+v**2),lw=lambda c: 4*c/np.nanmax(c),*args,**kwargs):
import streamplot as sp
from scipy.interpolate import griddata
f,fig,sub = send['f'],send['fig'],send['sub']
minmax = lambda d: [np.min(d),np.max(d)]
bc = f['/mesh/bary_centers']/scale
bx,by = bc[:,:,0].flatten(),bc[:,:,1].flatten()
if xlim is None:
xlim = minmax(bx)
if ylim is None:
ylim = minmax(by)
x,y = np.linspace(xlim[0],xlim[1],res),np.linspace(ylim[0],ylim[1],res)
xi,yi = np.meshgrid(x,y)
#mask for inner hole
minr2 = np.min(bx**2+by**2)
mask = xi**2+yi**2 < minr2
minmax = lambda d: [np.nanmin(d),np.nanmax(d)]
interpolate = lambda d: griddata(zip(bx,by),d.flatten(),(xi,yi))
firsttime = True
p = None
while True:
u,v = (yield)
speed = color(u,v,f)
gu,gv=interpolate(u),interpolate(v)
gu[mask] = np.nan
gspeed=interpolate(speed)
if p!=None:
p.lines.remove()
##p.arrows.remove() # does not work: not implemented for this collection!
#workaŕound from http://stackoverflow.com/questions/19621521/deleting-streamplots-matplotlib-without-clearing-the-graph
keep = lambda x: not isinstance(x, mpl.patches.FancyArrowPatch)
ax = sub.axes
ax.patches = [patch for patch in ax.patches if keep(patch)]
#sub.cla() # only available method at the moment
#firsttime=True
#p = sub.streamplot(x,y,gu,gv,color=gspeed,linewidth=lw,cmap=cmap,*args,**kwargs)
#try:
# p = sp.streamplot(sub,x,y,gu,gv,color=gspeed,linewidth=lw(gspeed),cmap=cmap,*args,**kwargs)
#except sp.InvalidIndexError:
if True:
print "Could not start at index point. Disabling start points for now"
kw = kwargs
kw['start_points'] = None
kw['density'] = 0.5
kw['maxlength'] = 4.
kw['integration_direction'] = 'both'
p = sp.streamplot(sub,x,y,gu,gv,color=gspeed,linewidth=lw(gspeed),cmap=cmap,*args,**kw)
ax = sub.axes
if p is not None and firsttime:
#from mpl_toolkits.axes_grid1 import make_axes_locatable
## create an axes on the right side of ax. The width of cax will be 5%
## of ax and the padding between cax and ax will be fixed at 0.05 inch.
#divider = make_axes_locatable(ax)
#cax = divider.append_axes("right", size="5%", pad=0.05)
#cbar = plt.colorbar(p.lines,cax=cax)
cbar = plt.colorbar(p.lines,use_gridspec=True)
if clabel is not None:
cbar.set_label(clabel)
firsttime=False
ax.set_aspect('equal')
ax.set_xlim(xlim)
ax.set_ylim(ylim)
#else:
#cbar = plt.colorbar(p.lines)
#cbar.update_normal(p.lines)
#cbar.remove()
#cbar = plt.colorbar(p.lines)
send((u,v))
@coroutine
def streamplot(send,scale=1.,*args,**kwargs):
f,fig,sub = send['f'],send['fig'],send['sub']
bc = f['/mesh/bary_centers']/scale
x,y = bc[:,0,0],bc[0,:,1]
p = None
while True:
u,v = (yield)
if p!=None:
# p.lines.remove()
# p.arrows.remove() # does not work: not implemented for this collection!
sub.cla() # only available method at the moment
p = sub.streamplot(x,y,u.T,v.T,*args,**kwargs)
send((u,v))
@coroutine
def contour(send,*args,**kwargs):
from matplotlib.colors import LogNorm
f,sub = send['f'],send['sub']
bary = f['/mesh/bary_centers']
x = bary[:,:,0].T
y = bary[:,:,1].T
p = None
cscale=kwargs.get('cscale')
if cscale=='log':
norm=LogNorm()
else:
norm=None
while True:
d = (yield)
if p==None:
p = sub.contour(x,y,d.T,*args,norm=norm,**kwargs)
#plt.clabel(p,inline=1)
else:
p.set_array(d.T)
send(d)
@coroutine
def nextsub(send):
subs = send['subs']
send['sub'] = subs.next()
while True:
d = (yield)
send(d)
@coroutine
def selectsub(send,i):
grid = send['grid']
send['sub'] = grid[i]
while True:
d = (yield)
send(d)
@coroutine
def pcolormesh(send,cmap=stdcmap,clim=None,xlabel='x',ylabel='y',aspect='equal',scale=1.,clabel=None,xlim=None,ylim=None,text=None,X=None,Y=None,xscale=None,yscale=None,cscale=None,xticks=None,yticks=None,norm=None,ltitle=None,rtitle=None,cax=None,autoscale=False,edgecolors='None',linewidth=0,tcolor='k',zoom=None,nbins=None,*args,**kwargs):
kwargs.setdefault("rasterized",True)
p = None
d = None
fig,sub = send['fig'],send['sub']
minmax = lambda d: (np.min(d),np.max(d))
rescale = lambda: p.set_clim(*minmax(d))
def press(event):
#print 'press', event.key
if(event.key in keys):
keys[event.key]()
fig.canvas.draw()
keys = dict(backspace = lambda: rescale())
fig.canvas.mpl_connect('key_press_event', press)
f=send.get('files')
if f is not None:
f = f[0]
while True:
d = (yield)
if p==None:
if cscale=='log':
norm=LogNorm()
elif cscale=='symlog':
norm=SymLogNorm(0.01)
elif cscale=='arcsinh':
norm=ArcsinhNorm()
if X is None: X=send.get('X')
if Y is None: Y=send.get('Y')
if X is None:
X=f['/mesh/grid_x']/scale
else:
X=X(f)
if Y is None:
Y=f['/mesh/grid_y']/scale
else:
Y=Y(f)
# Squeeze any additional dimensions with extent=1 from the grid,
# e.g. in case of 3D->2D data:
X = np.squeeze(X)
Y = np.squeeze(Y)
p = sub.pcolormesh(X,Y,
d,cmap=cmap,
edgecolors=edgecolors,
linewidth=linewidth,
norm=norm,
*args,**kwargs)#,
#picker=True)
plist = send.get('p')
if plist is None:
plist = [p]
else:
plist.append(p)
send['p'] = plist
ax = p.axes
ax.set_aspect(aspect)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.autoscale(tight=True)
if xscale is not None:
ax.set_xscale(xscale)
if yscale is not None:
ax.set_yscale(yscale)
if xlim!=None:
ax.set_xlim(*xlim)
if ylim!=None:
ax.set_ylim(*ylim)
if yticks is not None:
ax.set_yticks(yticks[0])
ax.set_yticklabels(yticks[1])
if zoom is not None:
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
axins = zoomed_inset_axes(sub, 4, loc=2) # zoom = 6
pz = axins.pcolormesh(X,Y,
d,cmap=cmap,
edgecolors=edgecolors,
linewidth=linewidth,
norm=norm,
*args,**kwargs)
pz.set_clim(*clim)
axins.set_xlim(*zoom[0])
axins.set_ylim(*zoom[1])
plt.xticks(visible=False)
plt.yticks(visible=False)
# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(sub, axins, loc1=3, loc2=1, fc="none", ec="0.5")
#fix cax
from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(sub)
cax = divider.append_axes("right", size="5%", pad=0.05)
if nbins is not None:
#sub.locator_params(nbins=nbins)
#from matplotlib.ticker import MaxNLocator
ax.locator_params(nbins=nbins)
#ax.xaxis.set_major_locator(MaxNLocator(nbins=nbins,prune='both'))
#ax.yaxis.set_major_locator(MaxNLocator(nbins=nbins,prune='both'))
textbox = ax.text(0.95,0.90,'',color=tcolor,transform=ax.transAxes,ha='right')
if isinstance(cax,(int,long)):
grid = send['grid']
cax = grid.cbar_axes[cax]
if cax is None:
#from mpl_toolkits.axes_grid1 import make_axes_locatable
## create an axes on the right side of ax. The width of cax will be 5%
## of ax and the padding between cax and ax will be fixed at 0.05 inch.
#divider = make_axes_locatable(ax)
#cax = divider.append_axes("right", size="5%", pad=0.05)
#cbar = fig.colorbar(p,cax=cax)
cbar = fig.colorbar(p,use_gridspec=True)
elif cax!='' and cax!=None:
cbar = plt.colorbar(p,cax=cax)
#try:
# #cbar = cax.colorbar(p,rasterized=True)
# cbar = plt.colorbar(p,cax=cax,rasterized=True)
#except:
# cbar = None
# pass
else:
cbar = None
if cbar is not None:
cbar.update_ticks()
# to use scaling factor
if norm is None:
cbar.formatter.set_scientific(True)
cbar.formatter.set_powerlimits((0,0))
cbar.update_ticks()
if clabel!=None and cbar is not None:
cbar.set_label(clabel)
if clim is not None:
p.set_clim(*clim)
p.set_clim(*clim)
else:
p.set_array(d.ravel())
if autoscale:
if clim is None:
# Yes, two times is correct here.
# There seems to be a bug? feature? in mpl,
# and therefore the colorbar is only updated
# after the second call
# Its the same, when calling "rescale" per
# hand, but it doesn't matter there too much.
p.set_clim(*minmax(d))
p.set_clim(*minmax(d))
fig.canvas.draw()
if ltitle is not None:
ax.set_title(ltitle(),loc='left')
if rtitle is not None:
ax.set_title(rtitle(),loc='right')
if text is not None:
textbox.set_text(text(f))
else:
time = send['files'][0]['/timedisc/time']
textbox.set_text('n = %i\nt = %.2e' % (f.getNumber(), time))
send(d)
@coroutine
def text(send,x,y,label,*args,**kwargs):
first = True
while True:
d = (yield)
if first:
sub,f = send['sub'],send.get('f')
kwargs.setdefault('transform',sub.transAxes)
kwargs.setdefault('ha','right')
sub.text(x,y,label(f),*args,**kwargs)
first = False
send(d)
@coroutine
def annotate(send,label,xy,xytext,*args,**kwargs):
first = True
while True:
d = (yield)
if first:
sub,f = send['sub'],send.get('f')
kwargs.setdefault('xycoords','axes fraction')
sub.annotate(label(f),xy=xy,xytext=xytext,*args,**kwargs)
first = False
send(d)
@coroutine
def colorbar(send,i=0,label="",*args,**kwargs):
fig = send.get('fig')
p = send.get('p')
grid = send['grid']
try:
cax = grid.cbar_axes[i]
except:
import matplotlib as mpl
cax,kw = mpl.colorbar.make_axes([ax for ax in grid.flat])
#cbar = cax.colorbar(p[i],*args,**kwargs)
cbar = fig.colorbar(p[i],cax=cax)
try:
cax.toggle_label(True)
cax.axis[cax.orientation].set_label(label)
except:
cbar.set_label(label)
#print cbar
#cbar.update_ticks()
# to use scaling factor
#if norm is None:
#cbar.formatter.set_scientific(True)
#cbar.formatter.set_powerlimits((0,0))
while True:
d = (yield)
send(d)
@coroutine
def addtitle(send,i=0,label="",*args,**kwargs):
grid = send['grid']
grid[i].set_title(label,*args,**kwargs)
while True:
d = (yield)
send(d)
def pcolorflat(*args,**kwargs):
scale=1.
if 'scale' in kwargs:
scale = kwargs['scale']
#get = lambda f,i: f['/mesh/bary_centers'][:,:,i]
def get(f,i):
if i==0:
return f['/mesh/grid_x']
elif i==1:
return f['/mesh/grid_y']
else:
raise "not allowed"
X = lambda f: np.sqrt(get(f,0)**2+get(f,1)**2)/scale
def Y(f):
d = np.arctan2(get(f,1),get(f,0))
if d[0,-1]<0.:
d[:,-1] += 2.*np.pi
d /= np.pi
return d
kwargs.update({'X':X,'Y':Y})
return pcolormesh(*args,**kwargs)
@coroutine
def timelistgrid(send,scale=1.,tscale=1.):
first=True
def get(f,i):
if i==0:
return f['/mesh/grid_x']
elif i==1:
return f['/mesh/grid_y']
else:
raise "not allowed"
while True:
time,radius,data = (yield)
if first:
#t = []
#for f in tqdm(file):
# t.append(file['/timedisc/time'])
t = np.zeros(len(time)+1)
t[0:-1] = time
t[-1] = (time[-1] + (time[-1]-time[-2]))
send['X'] = lambda d: np.array(t) / tscale
send['Y'] = lambda d: radius/scale
#send['Y'] = lambda d: np.sqrt(get(f,0)**2+get(f,1)**2)[:,0] / scale
first = not first
send(data)
@coroutine
def moviesave(send,filename,fps=60,ffmpeg_params=['-preset','slow','-crf','4'],*args,**kwargs):
from moviepy.editor import VideoClip
from moviepy.video.io.bindings import mplfig_to_npimage
fig = send['fig']
f = send['f']
#duration = int(len(f)/fps)
duration = len(f)/fps
while True:
d = (yield)
def make_frame(t):
i = int(t*fps)
f.select(i)
send(d)
# hack! probably not always right..
#fig.canvas.draw()
return mplfig_to_npimage(fig)
anim = VideoClip(make_frame, duration=duration)
#ani = animation.FuncAnimation(fig, anifn, frames=frames)#, blit=True, repeat=False)
#ani.save(filename,*args,**kwargs)
anim.write_videofile(filename,fps,ffmpeg_params=ffmpeg_params,*args,**kwargs)
@coroutine
def anisave(send,filename,frames,*args,**kwargs):
fig = send['fig']
f = send['f']
while True:
d = (yield)
def anifn(i):
f.select(i)
send(d)
# hack! probably not always right..
#fig.canvas.draw()
return fig.axes[0],
ani = animation.FuncAnimation(fig, anifn, frames=frames)#, blit=True, repeat=False)
ani.save(filename,*args,**kwargs)
@coroutine
def animate(send,*args,**kwargs):
while True:
names = (yield)
def anifn(a):
send(names)
# hack! probably not always right..
fig.canvas.draw()
return fig.axes[0],
ani = animation.FuncAnimation(fig, anifn, f, interval=interval, blit=True, repeat=False)
@coroutine
def timeseries(send):
f = send['f']
# it = range(len(f))
while True:
names = (yield)
for i in tqdm(f): #it:
#f.select(i)
send(names)
@coroutine
def series(send,it):
f = send['f']
while True:
names = (yield)
try:
for i in tqdm(it(f)):
f.select(i)
send(names)
except:
for i in tqdm(it):
f.select(i)
send(names)
def getData(f, names):
if(isinstance(names,list)):
return list([f[name] for name in names])
elif(isinstance(names,tuple)):
return tuple((f[name] for name in names))
else:
return f[names]
@coroutine
def get(send):
f = send['f']
while True:
names = (yield)
send(getData(f,names))
@coroutine
def savetxt(send,name,*args,**kwargs):
while True:
d = (yield)
np.savetxt(name,np.transpose(d),*args,**kwargs)
send(d)
@coroutine
def loadtxt(send,*args,**kwargs):
kwargs.setdefault('unpack',True)
while True:
d = (yield)
try:
d = np.loadtxt(d,*args,**kwargs)
except:
d = np.loadtxt(d[0],*args,**kwargs)
send(d)
@coroutine
def savefig(send,name,*args,**kwargs):
fig = send['fig']
kwargs.setdefault("bbox_inches","tight")
while True:
d = (yield)
if isinstance(name,list):
n = name.pop(0)
elif(hasattr(name, '__call__')):
n = name(send['f'])
else:
n = name
#print "Save: %s" % n
fig.savefig(n,*args,**kwargs)
send(d)
def savepng(name,*args,**kwargs):