coplot.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 from __future__ import division
4 
5 import numpy as np
6 from mpl_toolkits.mplot3d import Axes3D
7 import matplotlib.animation as animation
8 import matplotlib.pyplot as plt
9 import matplotlib as mpl
10 #from coplot import *
11 from coroutine import coroutine
12 from read import read
13 import argparse
14 import itertools as it
15 from scipy.optimize import curve_fit
16 import itertools
17 
18 from matplotlib.colors import LogNorm,SymLogNorm
19 from FunctionNorm import FunctionNorm,ArcsinhNorm
20 
21 from centercmap import centercmap
22 stdcmap = plt.cm.viridis
23 
24 try:
25  from tqdm import tqdm
26 except ImportError:
27  tqdm = lambda a: a
28 
29 
30 from matplotlib import rc
31 #rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
32 
40 rc('keymap',back='c',forward='v',zoom='z',home='h')
41 
42 # Add Keypress to plot coroutine
43 def connectKey(fig,key,action):
44  def press(event):
45  if(event.key == key):
46  action()
47  fig.canvas.draw()
48  fig.canvas.mpl_connect('key_press_event', press)
49 
50 @coroutine
51 def once(send,data):
52  first = True
53  while True:
54  d = (yield)
55  if first:
56  send(data)
57  send(d)
58 
59 @coroutine
60 def sum(send, axis=None):
61  while True:
62  d = (yield)
63  send(np.sum(d,axis))
64 
65 @coroutine
66 def gaussian_filter(send,*args,**kwargs):
67  from scipy.ndimage.filters import gaussian_filter
68  while True:
69  d = (yield)
70  a = gaussian_filter(d,*args,**kwargs)
71  send(a)
72 
73 @coroutine
74 def gaussiankernel_filter(send,stddev,*args,**kwargs):
75  from astropy.convolution import Gaussian1DKernel, convolve
76  #http://docs.astropy.org/en/stable/convolution/
77  g = Gaussian1DKernel(stddev=stddev)
78  kwargs.setdefault("boundary","extend")
79  while True:
80  d = (yield)
81  a = convolve(d, g, *args,**kwargs)
82  send(a)
83 
84 @coroutine
85 def median_filter(send,*args,**kwargs):
86  from scipy.signal import medfilt
87  while True:
88  d = (yield)
89  a = medfilt(d,*args,**kwargs)
90  send(a)
91 
92 @coroutine
93 def uniform_filter(send,*args,**kwargs):
94  from scipy.ndimage.filters import uniform_filter
95  while True:
96  d = (yield)
97  a = uniform_filter(d,*args,**kwargs)
98  send(a)
99 
100 @coroutine
101 def mean(send, axis=None):
102  while True:
103  d = (yield)
104  send(np.mean(d,axis))
105 
106 @coroutine
107 def customfilter(send,fn):
108  while True:
109  d = (yield)
110  if fn(d):
111  send(d)
112 
113 @coroutine
114 def min(send, axis=None):
115  while True:
116  d = (yield)
117  send(np.min(d,axis))
118 
119 @coroutine
120 def max(send, axis=None):
121  while True:
122  d = (yield)
123  send(np.max(d,axis))
124 
125 minmaxmean = lambda d: (np.min(d),np.mean(d),np.max(d))
126 
127 @coroutine
128 def minmax(send, axis=None):
129  while True:
130  d = (yield)
131  send((np.min(d,axis),np.max(d,axis)))
132 
133 @coroutine
134 def clip(send, min, max):
135  while True:
136  d = (yield)
137  send(np.clip(d, min, max))
138 
139 @coroutine
140 def symclip(send):
141  while True:
142  d = (yield)
143  l = np.min([np.abs(np.min(d)),np.max(d)])
144  send(np.clip(d, -l, l))
145 
146 @coroutine
147 def printer(send,fn=lambda d: d):
148  while True:
149  d = (yield)
150  if 'f' in send:
151  f = send['f']
152  print fn(d)
153  send(d)
154 
155 @coroutine
156 def produce(send,d):
157  while True:
158  (yield)
159  send(d)
160 
161 @coroutine
162 def generate(send,d=None):
163  while True:
164  r = (yield)
165  if d is None:
166  d = r
167  for i in d:
168  send(i)
169 
170 def getval(p,*args):
171  @coroutine
172  def exitandraise(send):
173  d = (yield)
174  raise StopIteration(d)
175  try:
176  (p | exitandraise()).send(*args)
177  except StopIteration as inst:
178  if(len(inst.args)==1):
179  return inst.args[0]
180  else:
181  return inst.args
182 
183 
184 @coroutine
185 def pipe(send,p=None):
186  if p is None:
187  while True:
188  send((yield))
189  else:
190  @coroutine
191  def helper(send2):
192  while True:
193  d2 = (yield)
194  send(d2)
195  subpipe = p | helper()
196  while True:
197  d = (yield)
198  subpipe.send(d)
199 
200 def inject(send,p):
201  @coroutine
202  def helper(send2):
203  while True:
204  d2 = (yield)
205  send(d2)
206  subpipe = p | helper()
207  return subpipe
208 
209 @coroutine
210 def call(send,f,*args,**kwargs):
211  while True:
212  d = (yield)
213  f(*args,**kwargs)
214  send(d)
215 
216 @coroutine
217 def iterate(send):
218  while True:
219  d = (yield)
220  for i in d:
221  send(i)
222 
223 @coroutine
224 def select(send,frame=None):
225  f = send['f']
226  while True:
227  d = (yield)
228  if frame is None:
229  if isinstance(d,str):
230  i = int(d.rstrip(".bin").split("_")[-1])
231  else:
232  i = d
233  else:
234  i = frame
235  if isinstance(f,tuple) or isinstance(f,list):
236  for file in f:
237  file.select(i)
238  else:
239  f.select(i)
240  send(d)
241 
242 @coroutine
243 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):
244  from matplotlib.colors import LogNorm
245  kwargs.setdefault("rasterized",True)
246  p = None
247  fig,sub = send['fig'],send['sub']
248  if clim==None:
249  rescale = lambda p: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
250  else:
251  rescale = lambda p: p.set_clim(clim[0],clim[1])
252  ex = kwargs.get('extent')
253  if ex is not None:
254  print ex
255  f = send['f']
256  try:
257  kwargs['extent'] = ex(f)
258  except:
259  pass
260 
261  while True:
262  d = (yield)
263  if p==None:
264  if cscale=='log':
265  norm=LogNorm()
266  elif cscale=='symlog':
267  norm=SymLogNorm(0.01)
268  elif cscale=='arcsinh':
269  norm=ArcsinhNorm()
270  p = sub.imshow(d.T,
271  interpolation='none',
272  cmap=cmap,
273  clim=clim,
274  norm=norm,
275  origin='lower',
276  *args,
277  **kwargs)
278  ax = p.axes
279  if aspect is not None:
280  ax.set_aspect(aspect)
281  ax.set_xlabel(xlabel)
282  ax.set_ylabel(ylabel)
283  if xscale is not None:
284  ax.set_xscale(xscale)
285  if yscale is not None:
286  ax.set_yscale(yscale)
287  cbar = cax.colorbar(p)
288  if clabel!=None and cbar is not None:
289  cbar.set_label(clabel)
290  if clim==None:
291  rescale2 = lambda: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
292  else:
293  rescale2 = lambda: p.set_clim(clim[0],clim[1])
294  connectKey(fig,'backspace',rescale2)
295  rescale2()
296  else:
297  p.set_array(d.T)
298  rescale(p)
299  send(d)
300 
301 @coroutine
302 def surface(send,f,fig,sub,aspect=1,cmap=stdcmap,cax=plt,clim=None,cscale=None,norm=None,xscale=None,yscale=None,*args,**kwargs):
303  from matplotlib.colors import LogNorm
304  p = None
305  while True:
306  d = (yield)
307  if p==None:
308  if cscale=='log':
309  norm=LogNorm()
310  bccart = f['/mesh/bary_centers']
311  X = bccart[:,:,0]
312  Y = bccart[:,:,1]
313  #p = sub.plot_surface(
314  p = sub.plot_trisurf(
315  X.flatten(), Y.flatten(),
316  d.flatten(),
317  linewidth=0.,
318 # rstride = 1,
319 # cstride = 1,
320  norm=norm,
321  cmap=cmap,
322  *args,
323  **kwargs)
324  ax = p.axes
325  ax.set_aspect(aspect)
326  if xscale is not None:
327  ax.set_xscale(xscale)
328  if yscale is not None:
329  ax.set_yscale(yscale)
330  cax.colorbar(p)
331  if clim==None:
332  rescale = lambda: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
333  else:
334  rescale = lambda: p.set_clim(clim[0],clim[1])
335  connectKey(fig,'backspace',rescale)
336  rescale()
337  else:
338  #p.set_array(d.T)
339  p.set_array(d.flatten())
340  send(d)
341 
342 @coroutine
343 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):
344  f = send.get('f')
345  fig,sub = send['fig'],send['sub']
346  p, = sub.plot([],[],fmt,**kwargs)
347  ax = p.axes
348  ax.grid(True)
349  ax.set_xlabel(xlabel)
350  ax.set_ylabel(ylabel)
351  if aspect is not None:
352  ax.set_aspect(aspect)
353  title = ax.text(0.95,0.9,'',transform=ax.transAxes,ha='right')
354  def rescale():
355  minmax = lambda data: (np.min(data), np.max(data))
356  x, y = p.get_data()
357  if(xlim==None):
358  sub.set_xlim(*minmax(x))
359  else:
360  sub.set_xlim(xlim)
361  if(ylim==None):
362  sub.set_ylim(*minmax(y))
363  else:
364  sub.set_ylim(ylim)
365  connectKey(fig,"backspace",rescale)
366  first = True
367 
368  while True:
369  d = (yield)
370  try:
371  p.set_data(*d)
372  except:
373  if xdata is None:
374  p.set_data(np.arange(len(d)),d)
375  else:
376  p.set_data(xdata,d)
377  if f is not None:
378  title.set_text(text(f))
379  if first:
380  if xscale is not None:
381  sub.set_xscale(xscale)
382  if yscale is not None:
383  sub.set_yscale(yscale)
384  rescale()
385  first = not first
386  send(d)
387 
388 @coroutine
389 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):
390  #marker='xo+ps*'
391  fig,sub = send['fig'],send['sub']
392  minmax = lambda d: (np.min(d),np.max(d))
393  ax = None
394  p = []
395  def rescale():
396  xl = minmax(np.concatenate([l.get_xdata() for l in p]))
397  yl = minmax(np.concatenate([l.get_ydata() for l in p]))
398  ax.set_xlim(xl)
399  ax.set_ylim(yl)
400 # sub.set_xlim(auto=True)
401 # sub.set_ylim(auto=True)
402  def press(event):
403  print 'press', event.key
404  if(event.key in keys):
405  keys[event.key]()
406  fig.canvas.draw()
407  keys = dict(backspace = lambda: rescale())
408  fig.canvas.mpl_connect('key_press_event', press)
409  for i,fmt,label in it.izip_longest(it.count(0),fmts,labels,fillvalue=None):
410  x,y = (yield)
411  if repeat==0 or i<repeat:
412  c = color[len(p) % len(color)]
413  ls = linestyle[len(p) % len(linestyle)]
414  if marker is not None:
415  m = marker[len(p) % len(marker)]
416  #print marker,len(p),len(marker),len(p) % len(marker),m
417  #kwargs.setdefault('marker',m)
418  else:
419  m= None
420  kwargs.setdefault('markevery',int(len(y)/10.))
421  if fmt != None:
422  p.append(sub.plot(x,y,fmt,label=label,color=c,marker=m,linestyle=ls,**kwargs)[0])
423  else:
424  p.append(sub.plot(x,y,label=label,color=c,marker=m,linestyle=ls,**kwargs)[0])
425  if len(p)==1:
426  ax = p[0].axes
427  ax.grid(True)
428  ax.set_xlabel(xlabel)
429  ax.set_ylabel(ylabel)
430  if xscale is not None:
431  ax.set_xscale(xscale)
432  if yscale is not None:
433  ax.set_yscale(yscale)
434  ax.legend(loc=loc,ncol=ncol)
435  rescale()
436  if ltitle is not None:
437  ax.set_title(ltitle(),loc='left')
438  if rtitle is not None:
439  ax.set_title(rtitle(),loc='right')
440  ax.set_xlim(*xlim)
441  ax.set_ylim(*ylim)
442  else:
443  p[i%repeat].set_ydata(y)
444  send((x,y))
445 
446 @coroutine
447 def makelist(send,n=lambda f: len(f),l=None):
448  f = send.get('f')
449  l = None
450  i = 0
451  nolist=False
452  while True:
453  d = (yield)
454  if not isinstance(d, (list,tuple)):
455  d = (d,)
456  nolist=True
457  i += 1
458  if l==None:
459  l = tuple([e] for e in d)
460  else:
461  for a,e in zip(l,d):
462  a.append(e)
463  if(i%n(f)==0):
464  if nolist:
465  l, = l
466  send(l)
467  l=None
468 
469 @coroutine
470 def cut(send,s):
471  sel = tuple()
472  for i in s:
473  if i==None:
474  sel += (slice(None,None),)
475  else:
476  sel += (i,)
477  while True:
478  d = (yield)
479  send(d[sel])
480 
481 #with interpolation
482 @coroutine
483 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):
484  import streamplot as sp
485  from scipy.interpolate import griddata
486  f,fig,sub = send['f'],send['fig'],send['sub']
487  minmax = lambda d: [np.min(d),np.max(d)]
488  bc = f['/mesh/bary_centers']/scale
489  bx,by = bc[:,:,0].flatten(),bc[:,:,1].flatten()
490  if xlim is None:
491  xlim = minmax(bx)
492  if ylim is None:
493  ylim = minmax(by)
494  x,y = np.linspace(xlim[0],xlim[1],res),np.linspace(ylim[0],ylim[1],res)
495  xi,yi = np.meshgrid(x,y)
496 
497  #mask for inner hole
498  minr2 = np.min(bx**2+by**2)
499  mask = xi**2+yi**2 < minr2
500 
501  minmax = lambda d: [np.nanmin(d),np.nanmax(d)]
502 
503  interpolate = lambda d: griddata(zip(bx,by),d.flatten(),(xi,yi))
504  firsttime = True
505  p = None
506  while True:
507  u,v = (yield)
508  speed = color(u,v,f)
509  gu,gv=interpolate(u),interpolate(v)
510  gu[mask] = np.nan
511  gspeed=interpolate(speed)
512  if p!=None:
513  p.lines.remove()
514 
516  keep = lambda x: not isinstance(x, mpl.patches.FancyArrowPatch)
517  ax = sub.axes
518  ax.patches = [patch for patch in ax.patches if keep(patch)]
519  #sub.cla() # only available method at the moment
520  #firsttime=True
521  #p = sub.streamplot(x,y,gu,gv,color=gspeed,linewidth=lw,cmap=cmap,*args,**kwargs)
522  #try:
523  # p = sp.streamplot(sub,x,y,gu,gv,color=gspeed,linewidth=lw(gspeed),cmap=cmap,*args,**kwargs)
524  #except sp.InvalidIndexError:
525  if True:
526  print "Could not start at index point. Disabling start points for now"
527  kw = kwargs
528  kw['start_points'] = None
529  kw['density'] = 0.5
530  kw['maxlength'] = 4.
531  kw['integration_direction'] = 'both'
532  p = sp.streamplot(sub,x,y,gu,gv,color=gspeed,linewidth=lw(gspeed),cmap=cmap,*args,**kw)
533 
534  ax = sub.axes
535  if p is not None and firsttime:
536  #from mpl_toolkits.axes_grid1 import make_axes_locatable
537 
542  cbar = plt.colorbar(p.lines,use_gridspec=True)
543  if clabel is not None:
544  cbar.set_label(clabel)
545  firsttime=False
546  ax.set_aspect('equal')
547  ax.set_xlim(xlim)
548  ax.set_ylim(ylim)
549  #else:
550  #cbar = plt.colorbar(p.lines)
551  #cbar.update_normal(p.lines)
552  #cbar.remove()
553  #cbar = plt.colorbar(p.lines)
554  send((u,v))
555 
556 
557 @coroutine
558 def streamplot(send,scale=1.,*args,**kwargs):
559  f,fig,sub = send['f'],send['fig'],send['sub']
560  bc = f['/mesh/bary_centers']/scale
561  x,y = bc[:,0,0],bc[0,:,1]
562  p = None
563  while True:
564  u,v = (yield)
565  if p!=None:
566 # p.lines.remove()
567 # p.arrows.remove() # does not work: not implemented for this collection!
568  sub.cla() # only available method at the moment
569  p = sub.streamplot(x,y,u.T,v.T,*args,**kwargs)
570  send((u,v))
571 
572 @coroutine
573 def contour(send,*args,**kwargs):
574  from matplotlib.colors import LogNorm
575  f,sub = send['f'],send['sub']
576  bary = f['/mesh/bary_centers']
577  x = bary[:,:,0].T
578  y = bary[:,:,1].T
579  p = None
580  cscale=kwargs.get('cscale')
581  if cscale=='log':
582  norm=LogNorm()
583  else:
584  norm=None
585  while True:
586  d = (yield)
587  if p==None:
588  p = sub.contour(x,y,d.T,*args,norm=norm,**kwargs)
589  #plt.clabel(p,inline=1)
590  else:
591  p.set_array(d.T)
592  send(d)
593 
594 @coroutine
595 def nextsub(send):
596  subs = send['subs']
597  send['sub'] = subs.next()
598  while True:
599  d = (yield)
600  send(d)
601 
602 @coroutine
603 def selectsub(send,i):
604  grid = send['grid']
605  send['sub'] = grid[i]
606  while True:
607  d = (yield)
608  send(d)
609 
610 
611 @coroutine
612 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):
613  kwargs.setdefault("rasterized",True)
614  p = None
615  d = None
616  fig,sub = send['fig'],send['sub']
617  minmax = lambda d: (np.min(d),np.max(d))
618  rescale = lambda: p.set_clim(*minmax(d))
619  def press(event):
620  #print 'press', event.key
621  if(event.key in keys):
622  keys[event.key]()
623  fig.canvas.draw()
624  keys = dict(backspace = lambda: rescale())
625  fig.canvas.mpl_connect('key_press_event', press)
626  f=send.get('files')
627  if f is not None:
628  f = f[0]
629  while True:
630  d = (yield)
631  if p==None:
632  if cscale=='log':
633  norm=LogNorm()
634  elif cscale=='symlog':
635  norm=SymLogNorm(0.01)
636  elif cscale=='arcsinh':
637  norm=ArcsinhNorm()
638  if X is None: X=send.get('X')
639  if Y is None: Y=send.get('Y')
640  if X is None:
641  X=f['/mesh/grid_x']/scale
642  else:
643  X=X(f)
644  if Y is None:
645  Y=f['/mesh/grid_y']/scale
646  else:
647  Y=Y(f)
648  # Squeeze any additional dimensions with extent=1 from the grid,
649  # e.g. in case of 3D->2D data:
650  X = np.squeeze(X)
651  Y = np.squeeze(Y)
652  p = sub.pcolormesh(X,Y,
653  d,cmap=cmap,
654  edgecolors=edgecolors,
655  linewidth=linewidth,
656  norm=norm,
657  *args,**kwargs)#,
658  #picker=True)
659  plist = send.get('p')
660  if plist is None:
661  plist = [p]
662  else:
663  plist.append(p)
664  send['p'] = plist
665  ax = p.axes
666  ax.set_aspect(aspect)
667  ax.set_xlabel(xlabel)
668  ax.set_ylabel(ylabel)
669  plt.autoscale(tight=True)
670  if xscale is not None:
671  ax.set_xscale(xscale)
672  if yscale is not None:
673  ax.set_yscale(yscale)
674  if xlim!=None:
675  ax.set_xlim(*xlim)
676  if ylim!=None:
677  ax.set_ylim(*ylim)
678  if yticks is not None:
679  ax.set_yticks(yticks[0])
680  ax.set_yticklabels(yticks[1])
681  if zoom is not None:
682  from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
683  from mpl_toolkits.axes_grid1.inset_locator import mark_inset
684  axins = zoomed_inset_axes(sub, 4, loc=2) # zoom = 6
685  pz = axins.pcolormesh(X,Y,
686  d,cmap=cmap,
687  edgecolors=edgecolors,
688  linewidth=linewidth,
689  norm=norm,
690  *args,**kwargs)
691  pz.set_clim(*clim)
692  axins.set_xlim(*zoom[0])
693  axins.set_ylim(*zoom[1])
694  plt.xticks(visible=False)
695  plt.yticks(visible=False)
696  # draw a bbox of the region of the inset axes in the parent axes and
697  # connecting lines between the bbox and the inset axes area
698  mark_inset(sub, axins, loc1=3, loc2=1, fc="none", ec="0.5")
699 
700  #fix cax
701  from mpl_toolkits.axes_grid1 import make_axes_locatable
702  divider = make_axes_locatable(sub)
703  cax = divider.append_axes("right", size="5%", pad=0.05)
704 
705  if nbins is not None:
706  #sub.locator_params(nbins=nbins)
707  #from matplotlib.ticker import MaxNLocator
708  ax.locator_params(nbins=nbins)
709  #ax.xaxis.set_major_locator(MaxNLocator(nbins=nbins,prune='both'))
710  #ax.yaxis.set_major_locator(MaxNLocator(nbins=nbins,prune='both'))
711  textbox = ax.text(0.95,0.90,'',color=tcolor,transform=ax.transAxes,ha='right')
712  if isinstance(cax,(int,long)):
713  grid = send['grid']
714  cax = grid.cbar_axes[cax]
715  if cax is None:
716  #from mpl_toolkits.axes_grid1 import make_axes_locatable
717 
722  cbar = fig.colorbar(p,use_gridspec=True)
723  elif cax!='' and cax!=None:
724  cbar = plt.colorbar(p,cax=cax)
725  #try:
726  # #cbar = cax.colorbar(p,rasterized=True)
727  # cbar = plt.colorbar(p,cax=cax,rasterized=True)
728  #except:
729  # cbar = None
730  # pass
731  else:
732  cbar = None
733  if cbar is not None:
734  cbar.update_ticks()
735  # to use scaling factor
736  if norm is None:
737  cbar.formatter.set_scientific(True)
738  cbar.formatter.set_powerlimits((0,0))
739  cbar.update_ticks()
740  if clabel!=None and cbar is not None:
741  cbar.set_label(clabel)
742  if clim is not None:
743  p.set_clim(*clim)
744  p.set_clim(*clim)
745  else:
746  p.set_array(d.ravel())
747  if autoscale:
748  if clim is None:
749  # Yes, two times is correct here.
750  # There seems to be a bug? feature? in mpl,
751  # and therefore the colorbar is only updated
752  # after the second call
753  # Its the same, when calling "rescale" per
754  # hand, but it doesn't matter there too much.
755  p.set_clim(*minmax(d))
756  p.set_clim(*minmax(d))
757  fig.canvas.draw()
758  if ltitle is not None:
759  ax.set_title(ltitle(),loc='left')
760  if rtitle is not None:
761  ax.set_title(rtitle(),loc='right')
762  if text is not None:
763  textbox.set_text(text(f))
764  else:
765  time = send['files'][0]['/timedisc/time']
766  textbox.set_text('n = %i\nt = %.2e' % (f.getNumber(), time))
767  send(d)
768 
769 @coroutine
770 def text(send,x,y,label,*args,**kwargs):
771  first = True
772  while True:
773  d = (yield)
774  if first:
775  sub,f = send['sub'],send.get('f')
776  kwargs.setdefault('transform',sub.transAxes)
777  kwargs.setdefault('ha','right')
778  sub.text(x,y,label(f),*args,**kwargs)
779  first = False
780  send(d)
781 
782 @coroutine
783 def annotate(send,label,xy,xytext,*args,**kwargs):
784  first = True
785  while True:
786  d = (yield)
787  if first:
788  sub,f = send['sub'],send.get('f')
789  kwargs.setdefault('xycoords','axes fraction')
790  sub.annotate(label(f),xy=xy,xytext=xytext,*args,**kwargs)
791  first = False
792  send(d)
793 
794 @coroutine
795 def colorbar(send,i=0,label="",*args,**kwargs):
796  fig = send.get('fig')
797  p = send.get('p')
798  grid = send['grid']
799  try:
800  cax = grid.cbar_axes[i]
801  except:
802  import matplotlib as mpl
803  cax,kw = mpl.colorbar.make_axes([ax for ax in grid.flat])
804  #cbar = cax.colorbar(p[i],*args,**kwargs)
805  cbar = fig.colorbar(p[i],cax=cax)
806  try:
807  cax.toggle_label(True)
808  cax.axis[cax.orientation].set_label(label)
809  except:
810  cbar.set_label(label)
811 
812  #print cbar
813  #cbar.update_ticks()
814  # to use scaling factor
815  #if norm is None:
816  #cbar.formatter.set_scientific(True)
817  #cbar.formatter.set_powerlimits((0,0))
818  while True:
819  d = (yield)
820  send(d)
821 
822 @coroutine
823 def addtitle(send,i=0,label="",*args,**kwargs):
824  grid = send['grid']
825  grid[i].set_title(label,*args,**kwargs)
826  while True:
827  d = (yield)
828  send(d)
829 
830 def pcolorflat(*args,**kwargs):
831  scale=1.
832  if 'scale' in kwargs:
833  scale = kwargs['scale']
834  #get = lambda f,i: f['/mesh/bary_centers'][:,:,i]
835  def get(f,i):
836  if i==0:
837  return f['/mesh/grid_x']
838  elif i==1:
839  return f['/mesh/grid_y']
840  else:
841  raise "not allowed"
842  X = lambda f: np.sqrt(get(f,0)**2+get(f,1)**2)/scale
843  def Y(f):
844  d = np.arctan2(get(f,1),get(f,0))
845  if d[0,-1]<0.:
846  d[:,-1] += 2.*np.pi
847  d /= np.pi
848  return d
849  kwargs.update({'X':X,'Y':Y})
850  return pcolormesh(*args,**kwargs)
851 
852 @coroutine
853 def timelistgrid(send,scale=1.,tscale=1.):
854  first=True
855  def get(f,i):
856  if i==0:
857  return f['/mesh/grid_x']
858  elif i==1:
859  return f['/mesh/grid_y']
860  else:
861  raise "not allowed"
862  while True:
863  time,radius,data = (yield)
864  if first:
865  #t = []
866  #for f in tqdm(file):
867  # t.append(file['/timedisc/time'])
868  t = np.zeros(len(time)+1)
869  t[0:-1] = time
870  t[-1] = (time[-1] + (time[-1]-time[-2]))
871  send['X'] = lambda d: np.array(t) / tscale
872  send['Y'] = lambda d: radius/scale
873  #send['Y'] = lambda d: np.sqrt(get(f,0)**2+get(f,1)**2)[:,0] / scale
874  first = not first
875  send(data)
876 
877 @coroutine
878 def moviesave(send,filename,fps=60,ffmpeg_params=['-preset','slow','-crf','4'],*args,**kwargs):
879  from moviepy.editor import VideoClip
880  from moviepy.video.io.bindings import mplfig_to_npimage
881  fig = send['fig']
882  f = send['f']
883  #duration = int(len(f)/fps)
884  duration = len(f)/fps
885  while True:
886  d = (yield)
887  def make_frame(t):
888  i = int(t*fps)
889  f.select(i)
890  send(d)
891  # hack! probably not always right..
892  #fig.canvas.draw()
893  return mplfig_to_npimage(fig)
894  anim = VideoClip(make_frame, duration=duration)
895  #ani = animation.FuncAnimation(fig, anifn, frames=frames)#, blit=True, repeat=False)
896  #ani.save(filename,*args,**kwargs)
897  anim.write_videofile(filename,fps,ffmpeg_params=ffmpeg_params,*args,**kwargs)
898 
899 @coroutine
900 def anisave(send,filename,frames,*args,**kwargs):
901  fig = send['fig']
902  f = send['f']
903  while True:
904  d = (yield)
905  def anifn(i):
906  f.select(i)
907  send(d)
908  # hack! probably not always right..
909  #fig.canvas.draw()
910  return fig.axes[0],
911  ani = animation.FuncAnimation(fig, anifn, frames=frames)#, blit=True, repeat=False)
912  ani.save(filename,*args,**kwargs)
913 
914 @coroutine
915 def animate(send,*args,**kwargs):
916  while True:
917  names = (yield)
918  def anifn(a):
919  send(names)
920  # hack! probably not always right..
921  fig.canvas.draw()
922  return fig.axes[0],
923  ani = animation.FuncAnimation(fig, anifn, f, interval=interval, blit=True, repeat=False)
924 
925 
926 @coroutine
927 def timeseries(send):
928  f = send['f']
929 # it = range(len(f))
930  while True:
931  names = (yield)
932  for i in tqdm(f): #it:
933  #f.select(i)
934  send(names)
935 
936 @coroutine
937 def series(send,it):
938  f = send['f']
939  while True:
940  names = (yield)
941  try:
942  for i in tqdm(it(f)):
943  f.select(i)
944  send(names)
945  except:
946  for i in tqdm(it):
947  f.select(i)
948  send(names)
949 
950 def getData(f, names):
951  if(isinstance(names,list)):
952  return list([f[name] for name in names])
953  elif(isinstance(names,tuple)):
954  return tuple((f[name] for name in names))
955  else:
956  return f[names]
957 
958 
959 @coroutine
960 def get(send):
961  f = send['f']
962  while True:
963  names = (yield)
964  send(getData(f,names))
965 
966 @coroutine
967 def savetxt(send,name,*args,**kwargs):
968  while True:
969  d = (yield)
970  np.savetxt(name,np.transpose(d),*args,**kwargs)
971  send(d)
972 
973 @coroutine
974 def loadtxt(send,*args,**kwargs):
975  kwargs.setdefault('unpack',True)
976  while True:
977  d = (yield)
978  try:
979  d = np.loadtxt(d,*args,**kwargs)
980  except:
981  d = np.loadtxt(d[0],*args,**kwargs)
982  send(d)
983 
984 @coroutine
985 def savefig(send,name,*args,**kwargs):
986  fig = send['fig']
987  kwargs.setdefault("bbox_inches","tight")
988  while True:
989  d = (yield)
990  if isinstance(name,list):
991  n = name.pop(0)
992  elif(hasattr(name, '__call__')):
993  n = name(send['f'])
994  else:
995  n = name
996  #print "Save: %s" % n
997  fig.savefig(n,*args,**kwargs)
998  send(d)
999 
1000 def savepng(name,*args,**kwargs):
1001  name = name.rstrip(".png")
1002  return savefig(name + ".png",*args,**kwargs)
1003 
1004 def savepdf(name,*args,**kwargs):
1005  name = name.rstrip(".pdf")
1006  return savefig(name + ".png",*args,**kwargs) \
1007  | savefig(name + ".pdf",*args,**kwargs)
1008 
1009 @coroutine
1010 def axvline(send,x,*args,**kwargs):
1011  sub = send['sub']
1012  sub.axvline(x,*args,**kwargs)
1013  while True:
1014  d = (yield)
1015  send(d)
1016 
1017 @coroutine
1018 def saveimg(send,name,*args,**kwargs):
1019  fig = send['fig']
1020  kwargs.setdefault("bbox_inches","tight")
1021  while True:
1022  d = (yield)
1023  if isinstance(name,list):
1024  n = name.pop(0)
1025  elif(hasattr(name, '__call__')):
1026  n = name(send['f'])
1027  else:
1028  n = name
1029  sp = n.rsplit(".",1)
1030  if len(sp) != 2:
1031  raise Exception("No suffix/filetype has been given in '%s'." % n)
1032  ext = sp[1]
1033  n = sp[0]
1034  if ext=='pgf':
1035  try:
1036  fig.savefig(n + ".png",*args,**kwargs)
1037  except:
1038  pass # dont fail on latex errors?!
1039  fig.savefig(n + "." + ext,*args,**kwargs)
1040  send(d)
1041 
1042 @coroutine
1043 def savepgf(send,name,*args,**kwargs):
1044  fig = send['fig']
1045  kwargs.setdefault("bbox_inches","tight")
1046  while True:
1047  d = (yield)
1048  if isinstance(name,list):
1049  n = name.pop(0)
1050  elif(hasattr(name, '__call__')):
1051  n = name(send['f'])
1052  else:
1053  n = name
1054  #print "Save: %s" % n
1055  n = n.rstrip(".pgf")
1056  try:
1057  fig.savefig(n + ".png",*args,**kwargs)
1058  except:
1059  pass # dont fail on latex errors?!
1060  fig.savefig(n + ".pgf",*args,**kwargs)
1061  send(d)
1062 
1063 @coroutine
1064 def save(send,name,*args,**kwargs):
1065  while True:
1066  d = (yield)
1067  np.save(name,d,*args,**kwargs)
1068  send(d)
1069 
1070 @coroutine
1071 def load(send,*args,**kwargs):
1072  while True:
1073  name = (yield)
1074  d = np.load(name,*args,**kwargs)
1075  send(d)
1076 
1077 @coroutine
1078 def psave(send,name,*args,**kwargs):
1079  import cPickle as pickle
1080  while True:
1081  d = (yield)
1082  pickle.dump(d,open(name,"wb"),*args,**kwargs)
1083  send(d)
1084 
1085 @coroutine
1086 def pload(send,*args,**kwargs):
1087  import cPickle as pickle
1088  while True:
1089  name = (yield)
1090  if isinstance(name, (tuple,list)):
1091  name = name[0]
1092  d = pickle.load(open(name,"rb"),*args,**kwargs)
1093  send(d)
1094 
1095 @coroutine
1096 def rfft(send):
1097  from numpy.fft import rfft,rfft2
1098  while True:
1099  d = (yield)
1100  rank = len(d.shape)
1101  if(rank==1):
1102  send(rfft(d))
1103  elif(rank==2):
1104  send(rfft2(d))
1105  else:
1106  throw('Only 1D or 2D ffts available')
1107 
1108 @coroutine
1109 def irfft(send):
1110  from numpy.fft import irfft,irfft2
1111  while True:
1112  d = (yield)
1113  rank = len(d.shape)
1114  if(rank==1):
1115  send(irfft(d))
1116  elif(rank==2):
1117  send(irfft2(d))
1118  else:
1119  throw('Only 1D or 2D ffts available')
1120 
1121 @coroutine
1122 def abs(send):
1123  while True:
1124  send(np.abs((yield)))
1125 
1126 @coroutine
1127 def log10(send):
1128  while True:
1129  send(np.log10((yield)))
1130 
1131 @coroutine
1132 def log(send):
1133  while True:
1134  send(np.log((yield)))
1135 
1136 @coroutine
1137 def only(send,i,p):
1138  d = None
1139  @coroutine
1140  def helper(send2):
1141  while True:
1142  di = (yield)
1143  t = tuple()
1144  for j,e in enumerate(d):
1145  if j==i:
1146  t += (di,)
1147  else:
1148  t += (e,)
1149  send(t)
1150  subpipe = p | helper()
1151  subpipe.update(send)
1152  while True:
1153  d = (yield)
1154  subpipe.send(d[i])
1155 
1156 @coroutine
1157 def waiter(send, n):
1158  from itertools import count
1159  for i in count(0):
1160  d = (yield)
1161  if i % n == 0:
1162  send(d)
1163 
1164 @coroutine
1165 def onlyif(send, fn):
1166  f = send['f']
1167  while True:
1168  d = (yield)
1169  if fn(f):
1170  send(d)
1171 
1172 @coroutine
1173 def each(send, p):
1174  serial = reflist([])
1175  @coroutine
1176  def join(sendj,serial,l):
1177  while True:
1178  res = (yield)
1179  serial.append(res)
1180  if(len(serial)==l):
1181  send(tuple(serial.get()))
1182  serial.set([])
1183  pipes = []
1184  while True:
1185  d = (yield)
1186  if len(pipes)<len(d):
1187  for p in pipes:
1188  p.close()
1189  pipes = []
1190  for e in d:
1191  pipes.append(p() | join(serial,len(d)))
1192  for e,subpipe in zip(d,pipes):
1193  send.ref(subpipe)
1194  subpipe.send(e)
1195 
1196 
1197 # This defines a list reference as new datatype
1198 class reflist:
1199  def __init__(self,l): self.l = l
1200  def get(self): return self.l
1201  def set(self,l): self.l = l
1202  def append(self,l): self.l.append(l)
1203  def __len__(self): return len(self.l)
1204 
1205 @coroutine
1206 def split(send,*args):
1207  serial = reflist([])
1208  @coroutine
1209  def join(sendj,serial):
1210  while True:
1211  res = (yield)
1212  serial.append(res)
1213  if(len(serial)==len(args)):
1214  send(tuple(serial.get()))
1215  serial.set([])
1216 
1217  while True:
1218  d = (yield)
1219  for e,p in zip(d,args):
1220  subpipe = (p | join(serial))
1221  send.ref(subpipe)
1222  subpipe.send(e)
1223 
1224 @coroutine
1225 def repeat(send,no):
1226  while True:
1227  d = (yield)
1228  d = (d,)*no
1229  send(d)
1230 
1231 @coroutine
1232 def broadcast(send,*args):
1233  while True:
1234  d = (yield)
1235  for p in args:
1236  p.update(send)
1237  p.send(d)
1238  send(d)
1239 
1240 @coroutine
1241 def normalize(send,i=None,norm=lambda d,d0: d/d0):
1242  if i==None:
1243  i=0
1244  while True:
1245  d = (yield)
1246  if isinstance(i, int):
1247  res = [norm(e,d[i]) for e in d]
1248  else:
1249  res = [norm(e,i) for e in d]
1250  send(res)
1251 
1252 @coroutine
1253 def normalize2(send, norm=lambda x,y: x/y):
1254  d0 = None
1255  while True:
1256  d = (yield)
1257  if d0 is None:
1258  d0 = d
1259  send(norm(d,d0))
1260 
1261 @coroutine
1262 def numexpr(send,expr):
1263  import numexpr as ne
1264  while True:
1265  d = (yield)
1266 # send(ne.evaluate(expr,local_dict=send))
1267  if 'f' in send:
1268  f = send['f']
1269  vars = dict(d=d)
1270  ex = ""
1271  for i,l in enumerate(expr.split("f['")):
1272  if i==0:
1273  ex = l
1274  else:
1275  l=l.split("']",1)
1276  label = l[0].rsplit('/',1)[-1]
1277  ex += label + l[1]
1278  vars[label] = f[l[0]]
1279  send(ne.evaluate(ex,vars))
1280  else:
1281  send(ne.evaluate(expr))
1282 
1283 @coroutine
1284 def apply(send,fn):
1285  while True:
1286  d = (yield)
1287  #try:
1288  # res = fn(*d)
1289  #except:
1290  # res = fn(d)
1291  res = fn(d)
1292  send(res)
1293 
1294 @coroutine
1295 def movingaverage(send,order=3):
1296  from collections import deque
1297  last = deque(maxlen=order)
1298  while True:
1299  d = (yield)
1300  last.append(d)
1301  res = np.sum(last)/np.float64(len(last))
1302  #print d, "-->", res
1303  send(res)
1304 
1305 
1306 @coroutine
1307 def forall(send,fn):
1308  while True:
1309  d = (yield)
1310  d = tuple(fn(dd) for dd in d)
1311  send(d)
1312 
1313 @coroutine
1314 def diff_backward(send,order=1):
1315  from collections import deque
1316  from scipy.special import binom
1317  last = deque(maxlen=order+1)
1318  t0 = None
1319  while True:
1320  time, d = (yield)
1321  last.appendleft(d)
1322  n = len(last)
1323  if n > 1:
1324  ord = n - 1
1325  dt = time - t0
1326  res = np.sum([(-1.)**i*binom(ord,i)*last[i] for i in range(n)]) / dt**ord
1327  send((time,res))
1328  t0 = time
1329 
1330 
1331 @coroutine
1332 def timediff(send,reset=None):
1333  from itertools import count
1334  if reset is None:
1335  t0, d0 = None, None
1336  for i in count(0):
1337  if reset is not None:
1338  if i % reset == 0:
1339  t0, d0 = None, None
1340  time, d = (yield)
1341  if not t0==None:
1342  send((0.5*(time+t0),(d-d0)/(time-t0)))
1343  t0, d0 = time, d
1344 
1345 @coroutine
1346 def timediff2(send):
1347  while True:
1348  t, d = (yield)
1349  tdiff = 0.5*(t[1:]+t[:-1])
1350  ddiff = (d[1:]-d[:-1])/(t[1:]-t[:-1])
1351  send((tdiff,ddiff))
1352 
1353 @coroutine
1354 def vecabs(send):
1355  while True:
1356  d = (yield)
1357  if isinstance(d,tuple):
1358  x,y = d
1359  send(np.sqrt(x**2+y**2))
1360  else:
1361  send(np.sqrt(d[:,:,0]**2+d[:,:,1]**2))
1362 
1363 
1364 def diff(f, d, dir):
1365  dlx = f['/mesh/dlx']
1366  dly = f['/mesh/dly']
1367  bhx = f['/mesh/bhx']
1368  bhy = f['/mesh/bhy']
1369  dlx = dlx/bhx
1370  dly = dly/bhy
1371  if dir==0:
1372  gx = np.empty(d.shape)
1373  gx[1:-1,:] = 0.5*(d[2:,:]-d[:-2,:])/dlx[1:-1,:]
1374  gx[0,:] = (d[1,:] - d[0,:])/dlx[0,:]
1375  gx[-1,:] = (d[-1,:] - d[-2,:])/dlx[-1,:]
1376  return gx
1377  elif dir==1:
1378  gy = np.empty(d.shape)
1379  gy[:,1:-1] = 0.5*(d[:,2:]-d[:,:-2])/dly[:,1:-1]
1380  gy[:,0] = (d[:,1] - d[:,0])/dly[:,0]
1381  gy[:,-1] = (d[:,-1] - d[:,-2])/dly[:,-1]
1382  return gy
1383 
1384 @coroutine
1385 def grad(send):
1386  f = send['f']
1387  while True:
1388  d = (yield)
1389  send((diff(f, d,0)/f['/mesh/bhx'],diff(f, d,1)/f['/mesh/bhy']))
1390 
1391 @coroutine
1392 def delR(send):
1393  f = send['f']
1394  while True:
1395  d = (yield)
1396  send(diff(f, d,0)/f['/mesh/bhx'])
1397 
1398 def absgrad(f):
1399  return grad(f) | vecabs()
1400 
1401 @coroutine
1402 def curl(send):
1403  f = send['files'][0]
1404  bhx = f['/mesh/bhx']
1405  bhy = f['/mesh/bhy']
1406  invsqrtg = 1./(bhx*bhy)
1407  while True:
1408  vx,vy = (yield)
1409  # the curl of a plane 2D vector field is a scalar
1410  send(invsqrtg*(diff(f,bhy*vy,0)-diff(f,bhx*vx,1)))
1411 
1412 @coroutine
1413 def div(send):
1414  f = send['f']
1415  bhx = f['/mesh/bhx']
1416  bhy = f['/mesh/bhy']
1417  invsqrtg = 1./(bhx*bhy)
1418  while True:
1419  vx,vy = (yield)
1420  send(invsqrtg*(diff(f,bhy*vx,0)+diff(f,bhx*bhy,1)))
1421 
1422 @coroutine
1423 def cross(send,f,a):
1424  a1, a2 = a
1425  while True:
1426  b1,b2 = (yield)
1427  send(a1*b2-a2*b1)
1428 
1429 @coroutine
1431  f = send['f']
1432  rot = f['/mesh/rotation']
1433  while True:
1434  vxi, veta = (yield)
1435  vx = np.cos(rot)*vxi + np.sin(rot)*veta
1436  vy = -np.sin(rot)*vxi + np.cos(rot)*veta
1437  send((vx,vy))
1438 
1439 @coroutine
1440 def inner(send):
1441  #component sum
1442  def compsum(l):
1443  res = l.pop()
1444  while len(l) > 0:
1445  res += l.pop()
1446  return res
1447 
1448  while True:
1449  d = (yield)
1450  send(compsum([np.multiply(i,j) for i,j in d]))
1451 
1452 @coroutine
1453 def readdirs(send):
1454  from read import read
1455  from os.path import join
1456  while True:
1457  fnames = (yield)
1458  if not isinstance(fnames,(tuple,list)): fnames = [fnames]
1459  fnames = [ join(name,"*.bin") for name in fnames]
1460  f = [read(fname) for fname in fnames]
1461  send['files'] = f
1462  if len(f)==1: f=f[0]
1463  send['f'] = f
1464  send(f)
1465 
1466 
1467 @coroutine
1468 def readbin(send):
1469  from read import read
1470  while True:
1471  fnames = (yield)
1472  if not isinstance(fnames,(tuple,list)): fnames = [fnames]
1473  if not any('*' in x or '?' in x for x in fnames):
1474  fnames.sort()
1475  fnames = [list(v) for k,v in itertools.groupby(fnames,key=lambda x:x.rsplit('_',1)[0])]
1476  f = [read(fname) for fname in fnames]
1477  send['files'] = f
1478  if len(f)==1: f=f[0]
1479  send['f'] = f
1480  send(f)
1481 
1482 @coroutine
1483 def pltshow(send):
1484  plt.show()
1485  while True:
1486  send((yield))
1487 
1488 @coroutine
1489 def mkplt(send,*args,**kwargs):
1490  plt.clf()
1491  show = kwargs.pop('show',False)
1492  fig = plt.figure(*args,**kwargs)
1493  sub = fig.add_subplot(111)
1494  send['fig'],send['sub'] = fig,sub
1495  try:
1496  while True:
1497  send((yield))
1498  if show:
1499  plt.show()
1500  except GeneratorExit:
1501  plt.close(fig)
1502 
1503 @coroutine
1504 def mksubplots(send,grid=(1,2),*args,**kwargs):
1505  plt.clf()
1506  show = kwargs.pop('show',False)
1507  kwargs.setdefault('sharex',True)
1508  kwargs.setdefault('sharey',True)
1509  fig,grid = plt.subplots(grid[0],grid[1],*args,**kwargs)
1510  subs = itertools.cycle(grid.flat)
1511  send.update({'fig' : fig, 'subs' : subs, 'grid' : grid, 'sub' : subs.next()})
1512  try:
1513  while True:
1514  send((yield))
1515  except GeneratorExit:
1516  plt.close(fig)
1517 
1518 @coroutine
1519 def mkgrid(send,grid,figsize=None,**kwargs):
1520  import itertools
1521  plt.clf()
1522  c = {"nrows_ncols" : grid,
1523  "direction" : "column",
1524  "axes_pad" : 0.1,
1525  "add_all" : True,
1526  "label_mode" : "L",
1527  "share_all" : True,
1528  "cbar_pad" : 0.1}
1529  #"cbar_mode" : "single",
1530  #"cbar_location" : "right",
1531  #"cbar_size" : "2%",
1532  #"cbar_pad" : 0.2}
1533  c.update(kwargs)
1534  rc = c['nrows_ncols']
1535  fig = plt.figure(1,figsize)
1536  from mpl_toolkits.axes_grid1 import ImageGrid
1537  grid = ImageGrid(fig, 111, **c)
1538  subs = itertools.cycle(grid)
1539  send.update({'fig' : fig, 'subs' : subs, 'grid' : grid, 'sub' : subs.next()})
1540  try:
1541  while True:
1542  send((yield))
1543  except GeneratorExit:
1544  plt.close(fig)
1545 
1546 
1547 
1548 @coroutine
1549 def control(send,i=None):
1550  import sys
1551  d = None
1552  show = True
1553  fig = plt.figure()
1554  sub = fig.add_subplot(111)
1555  send['fig'],send['sub'] = fig,sub
1556  f = send.get('f')
1557  def select(i):
1558  if isinstance(f,tuple) or isinstance(f,list):
1559  for file in f:
1560  file.select(i)
1561  else:
1562  f.select(i)
1563  def mvframe(i):
1564  if isinstance(f,tuple) or isinstance(f,list):
1565  for file in f:
1566  file.select(file.frame+i)
1567  else:
1568  select(f.frame+i)
1569  def setframe(i):
1570  select(i)
1571  def press(event):
1572  #print 'press', event.key
1573  if(event.key in keys):
1574  keys[event.key]()
1575  try:
1576  send(d)
1577  except StopIteration:
1578  pass
1579  fig.canvas.draw()
1580  fig.canvas.mpl_connect('key_press_event', press)
1581  keys = dict(\
1582  right = lambda: mvframe(1),
1583  left = lambda: mvframe(-1),
1584  up = lambda: mvframe(10),
1585  down = lambda: mvframe(-10),
1586  home = lambda: setframe(0),
1587  end = lambda: setframe(-1),
1588 # a = lambda: toggleAnimate(),
1589 # backspace = lambda: plotfn.rescale(),
1590 # pageup =
1591 # pagedown =
1592  q = lambda: sys.exit(0),
1593  )
1594  if i!=None:
1595  select(i)
1596  try:
1597  while True:
1598  d = (yield)
1599  send(d)
1600  if show:
1601  plt.show()
1602  except GeneratorExit:
1603  plt.close(fig)
1604 
1605 @coroutine
1606 def append(send, l):
1607  while True:
1608  d = (yield)
1609  l.append(d)
1610  send(d)
1611 
1612 @coroutine
1613 def togglemax(send):
1614  C = True
1615  A = False
1616  B = False
1617  a = 0.0
1618  while True:
1619  d = (yield)
1620  d = d[500,:] # this value needs to be adjusted
1621 # print d.shape
1622  # toggles between amax and amin
1623  if C:
1624  amax = np.amax(d)
1625  if amax > a:
1626  A = True
1627  if amax < a:
1628  B = True
1629  if (A and B) and (amax > a):
1630  A = B = False
1631  C = False
1632  amax = np.amin(d)
1633  a = amax
1634  else:
1635  amin = np.amin(d)
1636  if amin < a:
1637  A = True
1638  if amin > a:
1639  B = True
1640  if (A and B) and (amin < a):
1641  A = B = False
1642  C = True
1643  amin = np.amax(d)
1644  a = amin
1645  print a
1646  send(a);
1647 
1648 @coroutine
1649 def printmeta(send):
1650  while True:
1651  d = (yield)
1652  print send.data
1653  send(d)
1654 
1655 @coroutine
1656 def setmeta(send,d):
1657  send.update(d)
1658  while True:
1659  send((yield))
1660 
1661 @coroutine
1662 def consumemeta(send,name):
1663  while True:
1664  d = (yield)
1665  send[name] = d
1666  send(d)
1667 
1668 # relevant physical quantities:
1669 
1670 def vorticity(norm=lambda x,y: x):
1671  #return produce(("/timedisc/xvelocity","/timedisc/yvelocity")) | get(f) | only(1, numexpr("d+%f*f['/mesh/bhy']" % omega,f)) | curl(f)
1672  #return produce(("/timedisc/xvelocity","/timedisc/yvelocity")) | get(f) | only(1, numexpr("d-f['/mesh/bhy']**(-0.5)+%f*f['/mesh/bhy']" % omega,f)) | curl(f)
1673  return apply(lambda f: (f["/timedisc/xvelocity"],f["/timedisc/yvelocity"]+f.get('/mesh/radius',0.)*f['/config/mesh/omega'])) | each(lambda: normalize2(norm=norm)) | curl()
1674  #return produce(("/timedisc/xvelocity","/timedisc/yvelocity")) | get(f) | only(1, numexpr("d-f['/mesh/bhy']**(-0.5)+%f*f['/mesh/bhy']" % omega,f)) | curl(f)
1675  #return apply(lambda f: (f['/timedisc/xvelocity'],f['/timedisc/yvelocity']-f['/mesh/bhy']**(-0.5)+f['/config/mesh/omega']*f['/mesh/bhy'])) | curl()
1676 
1678  units = f['/config/physics/units']
1679  if units == 1:
1680  GN = 6.6742E-11
1681  elif units == 3:
1682  GN = 1.
1683  else:
1684  raise "unknown units"
1685  mass = f["/sources/grav/pmass/mass"]
1686  return np.sqrt(GN*mass/f['/mesh/radius'])
1687 
1689  return apply(lambda f: (f["/timedisc/xvelocity"],f["/timedisc/yvelocity"]+f.get('/mesh/radius',0.)*f['/config/mesh/omega'] - kepvelocity(f))) | curl()
1690 
1691 def potvorticity(f,omega=0.):
1692  return apply(lambda d: (f['/timedisc/xvelocity'],f['/timedisc/yvelocity'])) | curl(f) | apply(lambda d: d + 2*omega) | apply(lambda d: d/f['/timedisc/density'])
1693 
1694 def vortensity(f,omega=0.):
1695  return vorticity(f,omega) | numexpr("d/f['/timedisc/density']",f)
1696 
1697 def specifictorque(f,omega=0.):
1698  #return numexpr("f['/mesh/bhy'] * (f['/timedisc/yvelocity'] + f['/mesh/bhy'] * %f)" % omega, f)
1699  return produce(("/timedisc/xvelocity","/timedisc/yvelocity")) | get(f) | Convert2Cartesian(f) | cross(f,(f['/mesh/bary_centers_x'],f['/mesh/bary_centers_y'],))
1700 
1701 def mass(f):
1702  return numexpr("f['/timedisc/density'] * f['/mesh/volume']",f)
1703 
1704 # e.g. control(f,fig) | specifictorqueflux(f,0.1) | imshow(fig,sub,aspect=4)
1705 def specifictorqueflux(f,csiso=None,omega=0.):
1706  if csiso==None:
1707  return produce((1,2)) | split(\
1708  specifictorque(f,omega) | grad(f), \
1709  produce(('/timedisc/xvelocity','/timedisc/yvelocity')) | get(f)\
1710  ) | inner() | numexpr("d + f['/mesh/bhy']*f['/timedisc/pressure']", f)
1711  else:
1712  return produce((1,2)) | split(\
1713  produce((1,2)) | split(\
1714  specifictorque(f,omega) | grad(f), \
1715  produce(('/timedisc/xvelocity','/timedisc/yvelocity')) | get(f)\
1716  ) | inner(),\
1717  produce((0.,2)) | only(1,numexpr("f['/mesh/bhy']*f['/timedisc/density']*%f**2" % csiso, f)) | div(f) \
1718  ) | apply(lambda a,b: a + b)
1719 
1720 # only for cartesian coords. for now
1722  return produce(("/timedisc/xvelocity","/timedisc/yvelocity")) | get(f) | Convert2Cartesian(f) | cross(f,(f['/mesh/bary_centers_x'],f['/mesh/bary_centers_y'],)) \
1723  | apply(lambda d: d * f['/mesh/volume'] * f['/timedisc/density'])
1724 
1725 # Ready to use plots:
1726 
1727 line = lambda v: produce(('/mesh/bary_centers_x',v)) | control(f,fig) | get(f) | plot(f,fig,sub)
1728 
1729 def im(v = "/timedisc/density",normalize=False,**kwargs):
1730  if normalize:
1731  return produce(v) | control(f,fig) | get(f) | normalize2() | imshow(fig,sub,**kwargs)
1732  else:
1733  return produce(v) | control(f,fig) | get(f) | imshow(fig,sub,**kwargs)
1734 
1736  return control(f,fig) | timeseries(f) | angularmomentum(f) | sum() | makelist(len(f)) | apply(lambda d: d,) | normalize() | numexpr('abs(d-1)') | apply(lambda d: d.clip(1.E-16,1.)) | printer() | log10() | plot(f,fig,sub)
1737 
1739  c = f['/mesh/corners']
1740  return control(f,fig) | apply(lambda d: (c[:,0,1,0]-c[:,0,0,0])/(c[:,0,3,1]-c[:,0,2,1])) | plot(f,fig,sub)
1741 
1742 def gettemp(f):
1743  MU = 6.02E-4 #kg/mol, 75/25 Massenmischung H/He, vollständig ionisiert
1744  RG = 8.3144598 #J/(mol*K) allgemeine gaskonstante
1745  mH = 1.67E-27 #kg, mass of H-atom
1746  kB = 1.381E-23 #J/K, boltzmann constant
1747  fac = MU/RG
1748  #fac = 0.5 * mH/kB
1749  if '/timedisc/pressure' in f.keys():
1750  return f['/timedisc/pressure']/f['/timedisc/density']*fac
1751  else:
1752  return fac*f['/physics/bccsound']**2
1753 
1755  return apply(lambda f: gettemp(f))
1756 
1757 def massspectrum(logscale=True,omega=0.):
1758  @coroutine
1759  def sort(send,f,logscale):
1760  while True:
1761  m, l = (yield)
1762  m, l = np.ravel(m),np.ravel(l)
1763  s = np.argsort(l)
1764  l = l[s]
1765  m = np.cumsum(m[s])
1766  if logscale:
1767  l = np.log10(l)
1768  m = np.log10(m)
1769  send((l,m))
1770  return produce((1,2)) | control(f,fig) | split(specifictorque(f,omega),mass(f)) | sort(f,logscale) | plot(f,fig,sub)
1771 
1772 omega = lambda f: f['/timedisc/yvelocity']/f['/mesh/radius'] + f['/config/mesh/omega']
1773 
1774 epicyclicfrequency = lambda f: np.sqrt(2.*omega(f)/f['/mesh/radius']*diff(f,f['/mesh/radius']**2*omega(f),0)/f['/mesh/bhx'])
1775 
1776 #toomre stable for >1
1777 def toomre(kappa=omega):
1778  return apply(lambda f: f['/physics/bccsound']*np.abs(kappa(f))/(3.14159*6.67384E-11*f['/timedisc/density']))
1779 
1780 #def toomre(omega=1.,gamma=2.):
1781 # gn = 6.67408e-11
1782 # return apply(lambda f: (np.sqrt(gamma*f['/timedisc/pressure'])*omega)/(np.pi*gn*(f['/timedisc/density'])**(1.5)))
1783 #
1784 #def toomre2(f,omega=1.,gamma=2.):
1785 # gn = 6.67408e-11
1786 # cs = gn*10*np.pi
1787 # return apply(lambda d: (cs*omega)/(np.pi*gn*f['/timedisc/density']))
1788 
1789 def kinetic_energy(f,omega=1.):
1790  gn = 6.67408e-11
1791  return apply(lambda d: (0.5*f['/timedisc/density']*(f['/timedisc/xvelocity']**2+(f['/timedisc/yvelocity']+1.5*omega*f['/mesh/bary_centers'][:,:,0])**2)))
1792 
1794  return apply(lambda d: f['/timedisc/density']*f['/sources/grav/self/phi'])
1795 
1797  return apply(lambda d: 1.5*f['/timedisc/pressure'])
1798 
1800  return apply(lambda f: (f['/timedisc/xvelocity'],f['/timedisc/yvelocity']+f['/mesh/radius']*f['/config/mesh/omega'])) | Convert2Cartesian()
1801 
1802 def mach():
1803  return apply(lambda f: f['/timedisc/xvelocity']/f['/physics/bccsound'],(f['/timedisc/yvelocity']+f['/mesh/radius']*f['/config/mesh/omega'])/f['/physics/omega'])
1804 
1805 def overR(p,i=0):
1806  return apply(lambda f: (f['/mesh/radius'][:,i],p(f)[:,i]))
1807 
1808 
1809 
1810 @coroutine
1811 def getvars(send,l):
1812  f = send.get('f')
1813  # Remove not available keys
1814  l = [n for n in l if n in f]
1815  while True:
1816  (yield)
1817  send(np.array([f[i].T for i in l]).T)
1818 
1819 pvars = lambda: getvars(['/timedisc/%s' % s for s in ['density','xvelocity','yvelocity','pressure']])
1820 cvars = lambda: getvars(['/timedisc/%s' % s for s in ['density','xmomentum','ymomentum','energy']])
1821 
1822 @coroutine
1823 def L1(send):
1824  f = send.get('f')
1825  inum,jnum = f['/config/mesh/inum'],f['/config/mesh/jnum']
1826  d0 = None
1827  while True:
1828  d = (yield)
1829  if d0 is None:
1830  d0 = d
1831  dU = np.abs(d-d0)
1832  sumdU = np.sum(dU,(0,1))
1833  L1 = np.sqrt(np.sum(sumdU**2)) / (inum*jnum)
1834  send(L1)
1835 
1836 
1837 if __name__=="__main__":
1838  parser = argparse.ArgumentParser()
1839  group = parser.add_mutually_exclusive_group()
1840  group.add_argument('-p','--plot',help='enable 2d plotting',action="store_true")
1841  group.add_argument('-P','--plot3d',help='enable 3d plotting',action="store_true")
1842  parser.add_argument('-i','--import',nargs='?',help='import extra coroutines')
1843  parser.add_argument('pipe',metavar='pipe',help='pipe')
1844  parser.add_argument('filename',nargs='+',metavar='filename',help='filename')
1845  args = parser.parse_args()
1846  #f = [read(fname) for fname in args.filename]
1847  #if len(f) == 1: f = f[0]
1848  d = vars(args)
1849  if d['import']: execfile(d['import'])
1850  #if args.plot:
1851  #fig = plt.figure()
1852  #sub = fig.add_subplot(111)
1853  elif args.plot3d:
1854  fig = plt.figure()
1855  sub = fig.add_subplot(111, projection='3d')
1856  p = eval(args.pipe)
1857  #print p,type(p),args.pipe
1858  p.send(args.filename)
1859  #if args.plot:
1860  # plt.show()
1861 
1862  # example:
1863  # ~/fosite/tools/plot/coplot.py -p "line('/timedisc/density')" pringle.xmf
def mksubplots(send, grid=(1, 2), args, kwargs)
Definition: coplot.py:1504
def cut(send, s)
Definition: coplot.py:470
def psave(send, name, args, kwargs)
Definition: coplot.py:1078
def kinetic_energy(f, omega=1.)
Definition: coplot.py:1789
def annotate(send, label, xy, xytext, args, kwargs)
Definition: coplot.py:783
def apply(send, fn)
Definition: coplot.py:1284
def togglemax(send)
Definition: coplot.py:1613
def mass(f)
Definition: coplot.py:1701
type(dict_typ) function, pointer, public dict(n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13, n14, n15, n16, n17, n18, n19, n20)
Construct a new dictionary from several key/value pairs. Together with the Assign subroutine and over...
def vortensity(f, omega=0.)
Definition: coplot.py:1694
def loadtxt(send, args, kwargs)
Definition: coplot.py:974
def log(send)
Definition: coplot.py:1132
def getData(f, names)
Definition: coplot.py:950
def kepvelocity(f)
Definition: coplot.py:1677
def anisave(send, filename, frames, args, kwargs)
Definition: coplot.py:900
def mean(send, axis=None)
Definition: coplot.py:101
def setmeta(send, d)
Definition: coplot.py:1656
def pltshow(send)
Definition: coplot.py:1483
def numexpr(send, expr)
Definition: coplot.py:1262
def moviesave(send, filename, fps=60, ffmpeg_params=['-preset', slow, crf, args, kwargs)
Definition: coplot.py:878
def median_filter(send, args, kwargs)
Definition: coplot.py:85
def broadcast(send, args)
Definition: coplot.py:1232
def inner(send)
Definition: coplot.py:1440
def min(send, axis=None)
Definition: coplot.py:114
def select(send, frame=None)
Definition: coplot.py:224
def ArcsinhNorm(scale=1., args, kwargs)
Definition: FunctionNorm.py:9
def set(self, l)
Definition: coplot.py:1201
def normalize
Definition: coplot.py:1241
def Convert2Cartesian(send)
Definition: coplot.py:1430
def savetxt(send, name, args, kwargs)
Definition: coplot.py:967
def mach()
Definition: coplot.py:1802
def connectKey(fig, key, action)
Definition: coplot.py:43
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)
Definition: coplot.py:343
def colorbar(send, i=0, label="", args, kwargs)
Definition: coplot.py:795
def normalize2
Definition: coplot.py:1253
def axvline(send, x, args, kwargs)
Definition: coplot.py:1010
def selectsub(send, i)
Definition: coplot.py:603
def save(send, name, args, kwargs)
Definition: coplot.py:1064
def timediff(send, reset=None)
Definition: coplot.py:1332
def makelist(send, n=lambda f:len(f), l=None)
Definition: coplot.py:447
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)
Definition: coplot.py:243
def get(self)
Definition: coplot.py:1200
def clip(send, min, max)
Definition: coplot.py:134
def vecabs(send)
Definition: coplot.py:1354
def repeat(send, no)
Definition: coplot.py:1225
def inject(send, p)
Definition: coplot.py:200
def readbin(send)
Definition: coplot.py:1468
def L1(send)
Definition: coplot.py:1823
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)
Definition: coplot.py:389
def savefig(send, name, args, kwargs)
Definition: coplot.py:985
def produce(send, d)
Definition: coplot.py:156
def div(send)
Definition: coplot.py:1413
def angularmomentum(f)
Definition: coplot.py:1721
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)
Definition: coplot.py:612
def streamplot(send, scale=1., args, kwargs)
Definition: coplot.py:558
def savepgf(send, name, args, kwargs)
Definition: coplot.py:1043
def diff_backward(send, order=1)
Definition: coplot.py:1314
def diff(f, d, dir)
Definition: coplot.py:1364
def cartvelocity()
Definition: coplot.py:1799
def forall(send, fn)
Definition: coplot.py:1307
tqdm
Definition: coplot.py:27
def gaussian_filter(send, args, kwargs)
Definition: coplot.py:66
def savepdf(name, args, kwargs)
Definition: coplot.py:1004
def temperature()
Definition: coplot.py:1754
action
Definition: coplot.py:1840
def timeseries(send)
Definition: coplot.py:927
def abs(send)
Definition: coplot.py:1122
def uniform_filter(send, args, kwargs)
Definition: coplot.py:93
def cellaspectratio()
Definition: coplot.py:1738
def pipe(send, p=None)
Definition: coplot.py:185
def grad(send)
Definition: coplot.py:1385
def kepvorticity()
Definition: coplot.py:1688
def potvorticity(f, omega=0.)
Definition: coplot.py:1691
def timelistgrid(send, scale=1., tscale=1.)
Definition: coplot.py:853
def contour(send, args, kwargs)
Definition: coplot.py:573
def each(send, p)
Definition: coplot.py:1173
def savepng(name, args, kwargs)
Definition: coplot.py:1000
def mkplt(send, args, kwargs)
Definition: coplot.py:1489
def curl(send)
Definition: coplot.py:1402
def toomre(kappa=omega)
Definition: coplot.py:1777
def pcolorflat(args, kwargs)
Definition: coplot.py:830
def surface(send, f, fig, sub, aspect=1, cmap=stdcmap, cax=plt, clim=None, cscale=None, norm=None, xscale=None, yscale=None, args, kwargs)
Definition: coplot.py:302
def getvars(send, l)
Definition: coplot.py:1811
def text(send, x, y, label, args, kwargs)
Definition: coplot.py:770
def cross(send, f, a)
Definition: coplot.py:1423
def vorticity
Definition: coplot.py:1670
def only(send, i, p)
Definition: coplot.py:1137
def iterate(send)
Definition: coplot.py:217
def append(send, l)
Definition: coplot.py:1606
def specifictorque(f, omega=0.)
Definition: coplot.py:1697
def thermal_energy(f)
Definition: coplot.py:1796
def irfft(send)
Definition: coplot.py:1109
def sum(send, axis=None)
Definition: coplot.py:60
def delR(send)
Definition: coplot.py:1392
def series(send, it)
Definition: coplot.py:937
def generate(send, d=None)
Definition: coplot.py:162
def mkgrid(send, grid, figsize=None, kwargs)
Definition: coplot.py:1519
def consumemeta(send, name)
Definition: coplot.py:1662
def movingaverage(send, order=3)
Definition: coplot.py:1295
def onlyif(send, fn)
Definition: coplot.py:1165
def specifictorqueflux(f, csiso=None, omega=0.)
Definition: coplot.py:1705
def __len__(self)
Definition: coplot.py:1203
def timediff2(send)
Definition: coplot.py:1346
def nextsub(send)
Definition: coplot.py:595
def saveimg(send, name, args, kwargs)
Definition: coplot.py:1018
def control(send, i=None)
Definition: coplot.py:1549
def gaussiankernel_filter(send, stddev, args, kwargs)
Definition: coplot.py:74
def __init__(self, l)
Definition: coplot.py:1199
def gettemp(f)
Definition: coplot.py:1742
def angularmomentumconservation()
Definition: coplot.py:1735
def animate(send, args, kwargs)
Definition: coplot.py:915
def pload(send, args, kwargs)
Definition: coplot.py:1086
def printmeta(send)
Definition: coplot.py:1649
def append(self, l)
Definition: coplot.py:1202
def im(v="/timedisc/density", normalize=False, kwargs)
Definition: coplot.py:1729
def minmax(send, axis=None)
Definition: coplot.py:128
def max(send, axis=None)
Definition: coplot.py:120
def load(send, args, kwargs)
Definition: coplot.py:1071
def get(send)
Definition: coplot.py:960
def addtitle(send, i=0, label="", args, kwargs)
Definition: coplot.py:823
def massspectrum(logscale=True, omega=0.)
Definition: coplot.py:1757
def log10(send)
Definition: coplot.py:1127
def symclip(send)
Definition: coplot.py:140
def customfilter(send, fn)
Definition: coplot.py:107
def overR(p, i=0)
Definition: coplot.py:1805
def rfft(send)
Definition: coplot.py:1096
def gravitational_energy(f)
Definition: coplot.py:1793
def waiter(send, n)
Definition: coplot.py:1157
def once(send, data)
Definition: coplot.py:51
def getval(p, args)
Definition: coplot.py:170
def absgrad(f)
Definition: coplot.py:1398
def split(send, args)
Definition: coplot.py:1206
def readdirs(send)
Definition: coplot.py:1453
def streamplot2
Definition: coplot.py:483
def call(send, f, args, kwargs)
Definition: coplot.py:210
def printer(send, fn=lambda d:d)
Definition: coplot.py:147