3 from __future__
import division
6 from mpl_toolkits.mplot3d
import Axes3D
7 import matplotlib.animation
as animation
8 import matplotlib.pyplot
as plt
9 import matplotlib
as mpl
11 from coroutine
import coroutine
14 import itertools
as it
15 from scipy.optimize
import curve_fit
18 from matplotlib.colors
import LogNorm,SymLogNorm
19 from FunctionNorm
import FunctionNorm,ArcsinhNorm
21 from centercmap
import centercmap
22 stdcmap = plt.cm.viridis
30 from matplotlib
import rc
40 rc(
'keymap',back=
'c',forward=
'v',zoom=
'z',home=
'h')
48 fig.canvas.mpl_connect(
'key_press_event', press)
60 def sum(send, axis=None):
67 from scipy.ndimage.filters
import gaussian_filter
75 from astropy.convolution
import Gaussian1DKernel, convolve
77 g = Gaussian1DKernel(stddev=stddev)
78 kwargs.setdefault(
"boundary",
"extend")
81 a = convolve(d, g, *args,**kwargs)
86 from scipy.signal
import medfilt
89 a = medfilt(d,*args,**kwargs)
94 from scipy.ndimage.filters
import uniform_filter
104 send(np.mean(d,axis))
125 minmaxmean =
lambda d: (np.min(d),np.mean(d),np.max(d))
131 send((np.min(d,axis),np.max(d,axis)))
137 send(np.clip(d, min, max))
143 l = np.min([np.abs(np.min(d)),np.max(d)])
144 send(np.clip(d, -l, l))
172 def exitandraise(send):
174 raise StopIteration(d)
176 (p | exitandraise()).send(*args)
177 except StopIteration
as inst:
178 if(len(inst.args)==1):
195 subpipe = p | helper()
206 subpipe = p | helper()
210 def call(send,f,*args,**kwargs):
229 if isinstance(d,str):
230 i = int(d.rstrip(
".bin").
split(
"_")[-1])
235 if isinstance(f,tuple)
or isinstance(f,list):
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)
247 fig,sub = send[
'fig'],send[
'sub']
249 rescale =
lambda p: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
251 rescale =
lambda p: p.set_clim(clim[0],clim[1])
252 ex = kwargs.get(
'extent')
257 kwargs[
'extent'] = ex(f)
266 elif cscale==
'symlog':
267 norm=SymLogNorm(0.01)
268 elif cscale==
'arcsinh':
271 interpolation=
'none',
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)
291 rescale2 =
lambda: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
293 rescale2 =
lambda: p.set_clim(clim[0],clim[1])
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
310 bccart = f[
'/mesh/bary_centers']
314 p = sub.plot_trisurf(
315 X.flatten(), Y.flatten(),
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)
332 rescale =
lambda: p.set_clim(np.min(p.get_array()),np.max(p.get_array()))
334 rescale =
lambda: p.set_clim(clim[0],clim[1])
339 p.set_array(d.flatten())
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):
345 fig,sub = send[
'fig'],send[
'sub']
346 p, = sub.plot([],[],fmt,**kwargs)
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')
355 minmax =
lambda data: (np.min(data), np.max(data))
374 p.set_data(np.arange(len(d)),d)
378 title.set_text(
text(f))
380 if xscale
is not None:
381 sub.set_xscale(xscale)
382 if yscale
is not None:
383 sub.set_yscale(yscale)
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):
391 fig,sub = send[
'fig'],send[
'sub']
392 minmax =
lambda d: (np.min(d),np.max(d))
396 xl =
minmax(np.concatenate([l.get_xdata()
for l
in p]))
397 yl =
minmax(np.concatenate([l.get_ydata()
for l
in p]))
403 print 'press', event.key
404 if(event.key
in keys):
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):
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)]
420 kwargs.setdefault(
'markevery',int(len(y)/10.))
422 p.append(sub.plot(x,y,fmt,label=label,color=c,marker=m,linestyle=ls,**kwargs)[0])
424 p.append(sub.plot(x,y,label=label,color=c,marker=m,linestyle=ls,**kwargs)[0])
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)
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')
443 p[i%repeat].set_ydata(y)
454 if not isinstance(d, (list,tuple)):
459 l = tuple([e]
for e
in d)
474 sel += (slice(
None,
None),)
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()
494 x,y = np.linspace(xlim[0],xlim[1],res),np.linspace(ylim[0],ylim[1],res)
495 xi,yi = np.meshgrid(x,y)
498 minr2 = np.min(bx**2+by**2)
499 mask = xi**2+yi**2 < minr2
501 minmax =
lambda d: [np.nanmin(d),np.nanmax(d)]
503 interpolate =
lambda d: griddata(zip(bx,by),d.flatten(),(xi,yi))
509 gu,gv=interpolate(u),interpolate(v)
511 gspeed=interpolate(speed)
516 keep =
lambda x:
not isinstance(x, mpl.patches.FancyArrowPatch)
518 ax.patches = [patch
for patch
in ax.patches
if keep(patch)]
526 print "Could not start at index point. Disabling start points for now" 528 kw[
'start_points'] =
None 531 kw[
'integration_direction'] =
'both' 532 p = sp.streamplot(sub,x,y,gu,gv,color=gspeed,linewidth=lw(gspeed),cmap=cmap,*args,**kw)
535 if p
is not None and firsttime:
542 cbar = plt.colorbar(p.lines,use_gridspec=
True)
543 if clabel
is not None:
544 cbar.set_label(clabel)
546 ax.set_aspect(
'equal')
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]
569 p = sub.streamplot(x,y,u.T,v.T,*args,**kwargs)
574 from matplotlib.colors
import LogNorm
575 f,sub = send[
'f'],send[
'sub']
576 bary = f[
'/mesh/bary_centers']
580 cscale=kwargs.get(
'cscale')
588 p = sub.contour(x,y,d.T,*args,norm=norm,**kwargs)
597 send[
'sub'] = subs.next()
605 send[
'sub'] = grid[i]
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)
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))
621 if(event.key
in keys):
624 keys =
dict(backspace =
lambda: rescale())
625 fig.canvas.mpl_connect(
'key_press_event', press)
634 elif cscale==
'symlog':
635 norm=SymLogNorm(0.01)
636 elif cscale==
'arcsinh':
638 if X
is None: X=send.get(
'X')
639 if Y
is None: Y=send.get(
'Y')
641 X=f[
'/mesh/grid_x']/scale
645 Y=f[
'/mesh/grid_y']/scale
652 p = sub.pcolormesh(X,Y,
654 edgecolors=edgecolors,
659 plist = send.get(
'p')
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)
678 if yticks
is not None:
679 ax.set_yticks(yticks[0])
680 ax.set_yticklabels(yticks[1])
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)
685 pz = axins.pcolormesh(X,Y,
687 edgecolors=edgecolors,
692 axins.set_xlim(*zoom[0])
693 axins.set_ylim(*zoom[1])
694 plt.xticks(visible=
False)
695 plt.yticks(visible=
False)
698 mark_inset(sub, axins, loc1=3, loc2=1, fc=
"none", ec=
"0.5")
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)
705 if nbins
is not None:
708 ax.locator_params(nbins=nbins)
711 textbox = ax.text(0.95,0.90,
'',color=tcolor,transform=ax.transAxes,ha=
'right')
712 if isinstance(cax,(int,long)):
714 cax = grid.cbar_axes[cax]
722 cbar = fig.colorbar(p,use_gridspec=
True)
723 elif cax!=
'' and cax!=
None:
724 cbar = plt.colorbar(p,cax=cax)
737 cbar.formatter.set_scientific(
True)
738 cbar.formatter.set_powerlimits((0,0))
740 if clabel!=
None and cbar
is not None:
741 cbar.set_label(clabel)
746 p.set_array(d.ravel())
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')
763 textbox.set_text(
text(f))
765 time = send[
'files'][0][
'/timedisc/time']
766 textbox.set_text(
'n = %i\nt = %.2e' % (f.getNumber(), time))
770 def text(send,x,y,label,*args,**kwargs):
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)
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)
796 fig = send.get(
'fig')
800 cax = grid.cbar_axes[i]
802 import matplotlib
as mpl
803 cax,kw = mpl.colorbar.make_axes([ax
for ax
in grid.flat])
805 cbar = fig.colorbar(p[i],cax=cax)
807 cax.toggle_label(
True)
808 cax.axis[cax.orientation].set_label(label)
810 cbar.set_label(label)
825 grid[i].set_title(label,*args,**kwargs)
832 if 'scale' in kwargs:
833 scale = kwargs[
'scale']
837 return f[
'/mesh/grid_x']
839 return f[
'/mesh/grid_y']
842 X =
lambda f: np.sqrt(
get(f,0)**2+
get(f,1)**2)/scale
844 d = np.arctan2(
get(f,1),
get(f,0))
849 kwargs.update({
'X':X,
'Y':Y})
857 return f[
'/mesh/grid_x']
859 return f[
'/mesh/grid_y']
863 time,radius,data = (
yield)
868 t = np.zeros(len(time)+1)
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
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
884 duration = len(f)/fps
893 return mplfig_to_npimage(fig)
894 anim = VideoClip(make_frame, duration=duration)
897 anim.write_videofile(filename,fps,ffmpeg_params=ffmpeg_params,*args,**kwargs)
900 def anisave(send,filename,frames,*args,**kwargs):
911 ani = animation.FuncAnimation(fig, anifn, frames=frames)
912 ani.save(filename,*args,**kwargs)
923 ani = animation.FuncAnimation(fig, anifn, f, interval=interval, blit=
True, repeat=
False)
942 for i
in tqdm(it(f)):
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))
970 np.savetxt(name,np.transpose(d),*args,**kwargs)
975 kwargs.setdefault(
'unpack',
True)
979 d = np.loadtxt(d,*args,**kwargs)
981 d = np.loadtxt(d[0],*args,**kwargs)
987 kwargs.setdefault(
"bbox_inches",
"tight")
990 if isinstance(name,list):
992 elif(hasattr(name,
'__call__')):
997 fig.savefig(n,*args,**kwargs)
1001 name = name.rstrip(
".png")
1002 return savefig(name +
".png",*args,**kwargs)
1005 name = name.rstrip(
".pdf")
1006 return savefig(name +
".png",*args,**kwargs) \
1007 |
savefig(name +
".pdf",*args,**kwargs)
1012 sub.axvline(x,*args,**kwargs)
1020 kwargs.setdefault(
"bbox_inches",
"tight")
1023 if isinstance(name,list):
1025 elif(hasattr(name,
'__call__')):
1029 sp = n.rsplit(
".",1)
1031 raise Exception(
"No suffix/filetype has been given in '%s'." % n)
1036 fig.savefig(n +
".png",*args,**kwargs)
1039 fig.savefig(n +
"." + ext,*args,**kwargs)
1045 kwargs.setdefault(
"bbox_inches",
"tight")
1048 if isinstance(name,list):
1050 elif(hasattr(name,
'__call__')):
1055 n = n.rstrip(
".pgf")
1057 fig.savefig(n +
".png",*args,**kwargs)
1060 fig.savefig(n +
".pgf",*args,**kwargs)
1064 def save(send,name,*args,**kwargs):
1067 np.save(name,d,*args,**kwargs)
1074 d = np.load(name,*args,**kwargs)
1079 import cPickle
as pickle
1082 pickle.dump(d,open(name,
"wb"),*args,**kwargs)
1087 import cPickle
as pickle
1090 if isinstance(name, (tuple,list)):
1092 d = pickle.load(open(name,
"rb"),*args,**kwargs)
1097 from numpy.fft
import rfft,rfft2
1106 throw(
'Only 1D or 2D ffts available')
1110 from numpy.fft
import irfft,irfft2
1119 throw(
'Only 1D or 2D ffts available')
1124 send(np.abs((
yield)))
1129 send(np.log10((
yield)))
1134 send(np.log((
yield)))
1144 for j,e
in enumerate(d):
1150 subpipe = p | helper()
1151 subpipe.update(send)
1158 from itertools
import count
1176 def join(sendj,serial,l):
1181 send(tuple(serial.get()))
1186 if len(pipes)<len(d):
1191 pipes.append(
p() | join(serial,len(d)))
1192 for e,subpipe
in zip(d,pipes):
1209 def join(sendj,serial):
1213 if(len(serial)==len(args)):
1214 send(tuple(serial.get()))
1219 for e,p
in zip(d,args):
1220 subpipe = (p | join(serial))
1246 if isinstance(i, int):
1247 res = [norm(e,d[i])
for e
in d]
1249 res = [norm(e,i)
for e
in d]
1263 import numexpr
as ne
1271 for i,l
in enumerate(expr.split(
"f['")):
1276 label = l[0].rsplit(
'/',1)[-1]
1278 vars[label] = f[l[0]]
1279 send(ne.evaluate(ex,vars))
1281 send(ne.evaluate(expr))
1296 from collections
import deque
1297 last = deque(maxlen=order)
1301 res = np.sum(last)/np.float64(len(last))
1310 d = tuple(fn(dd)
for dd
in d)
1315 from collections
import deque
1316 from scipy.special
import binom
1317 last = deque(maxlen=order+1)
1326 res = np.sum([(-1.)**i*binom(ord,i)*last[i]
for i
in range(n)]) / dt**ord
1333 from itertools
import count
1337 if reset
is not None:
1342 send((0.5*(time+t0),(d-d0)/(time-t0)))
1349 tdiff = 0.5*(t[1:]+t[:-1])
1350 ddiff = (d[1:]-d[:-1])/(t[1:]-t[:-1])
1357 if isinstance(d,tuple):
1359 send(np.sqrt(x**2+y**2))
1361 send(np.sqrt(d[:,:,0]**2+d[:,:,1]**2))
1365 dlx = f[
'/mesh/dlx']
1366 dly = f[
'/mesh/dly']
1367 bhx = f[
'/mesh/bhx']
1368 bhy = f[
'/mesh/bhy']
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,:]
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]
1389 send((
diff(f, d,0)/f[
'/mesh/bhx'],
diff(f, d,1)/f[
'/mesh/bhy']))
1396 send(
diff(f, d,0)/f[
'/mesh/bhx'])
1403 f = send[
'files'][0]
1404 bhx = f[
'/mesh/bhx']
1405 bhy = f[
'/mesh/bhy']
1406 invsqrtg = 1./(bhx*bhy)
1410 send(invsqrtg*(
diff(f,bhy*vy,0)-
diff(f,bhx*vx,1)))
1415 bhx = f[
'/mesh/bhx']
1416 bhy = f[
'/mesh/bhy']
1417 invsqrtg = 1./(bhx*bhy)
1420 send(invsqrtg*(
diff(f,bhy*vx,0)+
diff(f,bhx*bhy,1)))
1432 rot = f[
'/mesh/rotation']
1435 vx = np.cos(rot)*vxi + np.sin(rot)*veta
1436 vy = -np.sin(rot)*vxi + np.cos(rot)*veta
1450 send(compsum([np.multiply(i,j)
for i,j
in d]))
1454 from read
import read
1455 from os.path
import join
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]
1462 if len(f)==1: f=f[0]
1469 from read
import read
1472 if not isinstance(fnames,(tuple,list)): fnames = [fnames]
1473 if not any(
'*' in x
or '?' in x
for x
in fnames):
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]
1478 if len(f)==1: f=f[0]
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
1500 except GeneratorExit:
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()})
1515 except GeneratorExit:
1522 c = {
"nrows_ncols" : grid,
1523 "direction" :
"column",
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()})
1543 except GeneratorExit:
1554 sub = fig.add_subplot(111)
1555 send[
'fig'],send[
'sub'] = fig,sub
1558 if isinstance(f,tuple)
or isinstance(f,list):
1564 if isinstance(f,tuple)
or isinstance(f,list):
1566 file.select(file.frame+i)
1573 if(event.key
in keys):
1577 except StopIteration:
1580 fig.canvas.mpl_connect(
'key_press_event', press)
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),
1592 q =
lambda: sys.exit(0),
1602 except GeneratorExit:
1629 if (A
and B)
and (amax > a):
1640 if (A
and B)
and (amin < a):
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()
1678 units = f[
'/config/physics/units']
1684 raise "unknown units" 1685 mass = f[
"/sources/grav/pmass/mass"]
1686 return np.sqrt(GN*mass/f[
'/mesh/radius'])
1689 return apply(
lambda f: (f[
"/timedisc/xvelocity"],f[
"/timedisc/yvelocity"]+f.get(
'/mesh/radius',0.)*f[
'/config/mesh/omega'] -
kepvelocity(f))) |
curl()
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'])
1699 return produce((
"/timedisc/xvelocity",
"/timedisc/yvelocity")) |
get(f) |
Convert2Cartesian(f) |
cross(f,(f[
'/mesh/bary_centers_x'],f[
'/mesh/bary_centers_y'],))
1702 return numexpr(
"f['/timedisc/density'] * f['/mesh/volume']",f)
1709 produce((
'/timedisc/xvelocity',
'/timedisc/yvelocity')) |
get(f)\
1710 ) |
inner() |
numexpr(
"d + f['/mesh/bhy']*f['/timedisc/pressure']", f)
1715 produce((
'/timedisc/xvelocity',
'/timedisc/yvelocity')) |
get(f)\
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)
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'])
1729 def im(v = "/timedisc/density",normalize=False,**kwargs):
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)
1749 if '/timedisc/pressure' in f.keys():
1750 return f[
'/timedisc/pressure']/f[
'/timedisc/density']*fac
1752 return fac*f[
'/physics/bccsound']**2
1759 def sort(send,f,logscale):
1762 m, l = np.ravel(m),np.ravel(l)
1772 omega =
lambda f: f[
'/timedisc/yvelocity']/f[
'/mesh/radius'] + f[
'/config/mesh/omega']
1774 epicyclicfrequency =
lambda f: np.sqrt(2.*
omega(f)/f[
'/mesh/radius']*
diff(f,f[
'/mesh/radius']**2*
omega(f),0)/f[
'/mesh/bhx'])
1778 return apply(
lambda f: f[
'/physics/bccsound']*np.abs(kappa(f))/(3.14159*6.67384E-11*f[
'/timedisc/density']))
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)))
1794 return apply(
lambda d: f[
'/timedisc/density']*f[
'/sources/grav/self/phi'])
1797 return apply(
lambda d: 1.5*f[
'/timedisc/pressure'])
1800 return apply(
lambda f: (f[
'/timedisc/xvelocity'],f[
'/timedisc/yvelocity']+f[
'/mesh/radius']*f[
'/config/mesh/omega'])) |
Convert2Cartesian()
1803 return apply(
lambda f: f[
'/timedisc/xvelocity']/f[
'/physics/bccsound'],(f[
'/timedisc/yvelocity']+f[
'/mesh/radius']*f[
'/config/mesh/omega'])/f[
'/physics/omega'])
1806 return apply(
lambda f: (f[
'/mesh/radius'][:,i],
p(f)[:,i]))
1814 l = [n
for n
in l
if n
in f]
1817 send(np.array([f[i].T
for i
in l]).T)
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']])
1825 inum,jnum = f[
'/config/mesh/inum'],f[
'/config/mesh/jnum']
1832 sumdU = np.sum(dU,(0,1))
1833 L1 = np.sqrt(np.sum(sumdU**2)) / (inum*jnum)
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()
1849 if d[
'import']: execfile(d[
'import'])
1855 sub = fig.add_subplot(111, projection=
'3d')
1858 p.send(args.filename)
def mksubplots(send, grid=(1, 2), args, kwargs)
def psave(send, name, args, kwargs)
def kinetic_energy(f, omega=1.)
def annotate(send, label, xy, xytext, args, kwargs)
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.)
def loadtxt(send, args, kwargs)
def anisave(send, filename, frames, args, kwargs)
def mean(send, axis=None)
def moviesave(send, filename, fps=60, ffmpeg_params=['-preset', slow, crf, args, kwargs)
def median_filter(send, args, kwargs)
def broadcast(send, args)
def select(send, frame=None)
def ArcsinhNorm(scale=1., args, kwargs)
def Convert2Cartesian(send)
def savetxt(send, name, args, kwargs)
def connectKey(fig, key, action)
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)
def colorbar(send, i=0, label="", args, kwargs)
def axvline(send, x, args, kwargs)
def save(send, name, args, kwargs)
def timediff(send, reset=None)
def makelist(send, n=lambda f:len(f), l=None)
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)
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)
def savefig(send, name, args, kwargs)
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)
def streamplot(send, scale=1., args, kwargs)
def savepgf(send, name, args, kwargs)
def diff_backward(send, order=1)
def gaussian_filter(send, args, kwargs)
def savepdf(name, args, kwargs)
def uniform_filter(send, args, kwargs)
def potvorticity(f, omega=0.)
def timelistgrid(send, scale=1., tscale=1.)
def contour(send, args, kwargs)
def savepng(name, args, kwargs)
def mkplt(send, args, kwargs)
def pcolorflat(args, kwargs)
def surface(send, f, fig, sub, aspect=1, cmap=stdcmap, cax=plt, clim=None, cscale=None, norm=None, xscale=None, yscale=None, args, kwargs)
def text(send, x, y, label, args, kwargs)
def specifictorque(f, omega=0.)
def generate(send, d=None)
def mkgrid(send, grid, figsize=None, kwargs)
def consumemeta(send, name)
def movingaverage(send, order=3)
def specifictorqueflux(f, csiso=None, omega=0.)
def saveimg(send, name, args, kwargs)
def control(send, i=None)
def gaussiankernel_filter(send, stddev, args, kwargs)
def angularmomentumconservation()
def animate(send, args, kwargs)
def pload(send, args, kwargs)
def im(v="/timedisc/density", normalize=False, kwargs)
def minmax(send, axis=None)
def load(send, args, kwargs)
def addtitle(send, i=0, label="", args, kwargs)
def massspectrum(logscale=True, omega=0.)
def customfilter(send, fn)
def gravitational_energy(f)
def call(send, f, args, kwargs)
def printer(send, fn=lambda d:d)