In [1]:
import netCDF4
In [310]:
from tempfile import NamedTemporaryFile
VIDEO_TAG = """<video controls>
<source src="data:video/webm;base64,{0}" type="video/webm">
Your browser does not support the video tag.
</video>"""
def anim_to_html(anim):
if not hasattr(anim, '_encoded_video'):
with NamedTemporaryFile(suffix='.webm') as f:
fps = 1000.0/anim._interval
fps = min(1, fps) # should be at least 1 for ffmpeg to work
anim.save(f.name, fps=fps, extra_args=['-vcodec', 'libvpx'])
video = open(f.name, "rb").read()
anim._encoded_video = video.encode("base64")
return VIDEO_TAG.format(anim._encoded_video)
from IPython.display import HTML
def display_animation(anim):
plt.close(anim._fig)
return HTML(anim_to_html(anim))
from matplotlib import animation
animation.Animation._repr_html_ = anim_to_html
In [302]:
ds = netCDF4.Dataset('/Users/baart_f/models/duifp/subgrid_map.nc')
In [43]:
xcc = ds.variables['FlowElem_xcc']
ycc = ds.variables['FlowElem_ycc']
In [308]:
def animate_variable(ds, varname, vmin, vmax, tstart=0):
long_name = getattr(ds.variables[varname], 'long_name', '')
units = getattr(ds.variables[varname], 'units', '')
label='%s relative to t0 [%s]' % (long_name, units)
fig, ax = plt.subplots()
t = 0
var0 = ds.variables[varname][t]
import copy
C = copy.deepcopy(matplotlib.cm.RdBu_r)
C._segmentdata['alpha'] = matplotlib.cm.RdBu_r._segmentdata['green']
N = matplotlib.colors.Normalize(vmin, vmax, clip=True)
sc = ax.scatter(xcc, ycc, c=C(N(var0)),
marker='.',
edgecolor='none',
animated=True,
label=label
)
extra_sc = ax.scatter([xcc[0:1]], ycc[0:1],
c=np.zeros_like(var0[0:1]),
edgecolor='none',
facecolor='none',
vmin=vmin,
vmax=vmax,
cmap=C,
label=label)
plt.colorbar(extra_sc, ax=ax)
def init():
# we already created the scatter
return sc,
def animate(i):
ax.set_title("Variable %s\nt=%s" % (long_name, ds.variables['time'][tstart+i]))
var1 = ds.variables[varname][tstart + i]
sc.set_facecolor(C(N(var1), alpha=0.5))
return sc,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=100, interval=200, blit=True)
return anim
In [309]:
anim = animate_variable(ds=ds, varname = 's1', vmin = -3., vmax = -3.1)
display_animation(anim)
Out[309]:
In [271]:
anim = animate_variable(ds=ds, varname='unorm', vmin=-0.3, vmax=0.3, tstart=1450)
display_animation(anim)
Out[271]:
In [338]:
his = netCDF4.Dataset('/Users/baart_f/models/duifp/subgrid_his.nc')
time = netCDF4.num2date(his.variables['time'][:], his.variables['time'].units)
In [340]:
_ = plt.plot_date(time, his.variables['qio'][:], fmt='-')
_ = plt.ylabel(his.variables['qio'].long_name)
In [341]:
_ = plt.plot_date(time, his.variables['precipitation_total'][:], fmt='-')
_ = plt.ylabel(his.variables['precipitation_total'].long_name)
In [ ]: