예제 #1
0
파일: utils.py 프로젝트: gurcani/pyhw
def spec_anim(flname, outfl, vmin=1e-8, vmax=1e-2, ntav=2):
    global fl, Nt
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pylab as plt
    import matplotlib.animation as anim
    if (':' in flname):
        flname = sync_rf(flname)
    En, Fn, kn = spec(flname, ntav)
    w, h = plt.figaspect(0.8)
    fig, ax = plt.subplots(1, 1, sharey=True, figsize=(w, h))
    qd = ax.loglog(kn[En > eps], En[En > eps], 'x-', kn[Fn > eps],
                   Fn[Fn > eps], '+-')
    kr = np.arange(3, 50)
    ax.loglog(kn[kr], 1e-4 * kn[kr]**(-3), 'k--')
    ax.loglog(kn[kr], 1e-3 * kn[kr]**(-1), 'k--')
    ax.legend(['$E(k)$', '$F(k)$'], fontsize=14)
    ax.text(kn[kr[-10]], 3e-4 * kn[kr[-10]]**(-3), '$k^{-3}$', fontsize=14)
    ax.text(kn[kr[-10]], 3e-3 * kn[kr[-10]]**(-1), '$k^{-1}$', fontsize=14)
    ax.axis([kn[1] - eps, kn[-1], vmin, vmax])
    ani = anim.FuncAnimation(fig,
                             update_spec_anim,
                             interval=0,
                             frames=Nt - ntav,
                             blit=True,
                             fargs=(qd, phires, nres, ntav))
    ani.save(outfl, dpi=200, fps=25)
    fl.close()
    sbp.call(['vlc', outfl])
예제 #2
0
def plot_Surface_yx_3subplots(X,Y,T1,T2,T3,Titles):
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter
    
    fig = plt.figure(figsize=plt.figaspect(0.3)) #3 times as wide as high

    ax = fig.add_subplot(1,3,1,projection='3d')
    surf = ax.plot_surface(X, Y, T1, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('T [$^o$C]')
    ax.set_title(Titles[0])
    
    ax = fig.add_subplot(1,3,2,projection='3d')
    surf = ax.plot_surface(X, Y, T2, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('T [$^o$C]')
    ax.set_title(Titles[1])
    
    ax = fig.add_subplot(1,3,3,projection='3d')
    surf = ax.plot_surface(X, Y, T3, rstride=1, cstride=1, cmap=cm.coolwarm,
                           linewidth=0, antialiased=False)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('T [$^o$C]')
    ax.set_title(Titles[2])
        
    return fig, ax
예제 #3
0
def plot_sphere(grid):
	fig = plt.figure(figsize=plt.figaspect(1.))
	ax = fig.add_subplot(111, projection='3d')
	ax.set_xlabel("X")
	ax.set_ylabel("Y")
	ax.set_zlabel("Z")
	ax.set_aspect('equal')
	ax.plot_surface(grid[0], grid[1], grid[2])
	#ax.scatter(grid[0],grid[1],grid[2])
	#ax.set_axis_off()
	plt.savefig('sphere2.png')
	plt.show()
예제 #4
0
def plot_Surface_yx_3subplots(X, Y, T1, T2, T3, Titles):
    from mpl_toolkits.mplot3d import Axes3D
    from matplotlib import cm
    from matplotlib.ticker import LinearLocator, FormatStrFormatter

    fig = plt.figure(figsize=plt.figaspect(0.3))  #3 times as wide as high

    ax = fig.add_subplot(1, 3, 1, projection='3d')
    surf = ax.plot_surface(X,
                           Y,
                           T1,
                           rstride=1,
                           cstride=1,
                           cmap=cm.coolwarm,
                           linewidth=0,
                           antialiased=False)

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('T [$^o$C]')
    ax.set_title(Titles[0])

    ax = fig.add_subplot(1, 3, 2, projection='3d')
    surf = ax.plot_surface(X,
                           Y,
                           T2,
                           rstride=1,
                           cstride=1,
                           cmap=cm.coolwarm,
                           linewidth=0,
                           antialiased=False)

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('T [$^o$C]')
    ax.set_title(Titles[1])

    ax = fig.add_subplot(1, 3, 3, projection='3d')
    surf = ax.plot_surface(X,
                           Y,
                           T3,
                           rstride=1,
                           cstride=1,
                           cmap=cm.coolwarm,
                           linewidth=0,
                           antialiased=False)
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('T [$^o$C]')
    ax.set_title(Titles[2])

    return fig, ax
예제 #5
0
def plotP2_3d():
    '''A function that plots the normalized scattering phase function for
  diffuse scattering. For comparison see Myneni 1991 Fig 3.
  '''
    N = 16
    g_wt = np.array(gauss_wt[str(N)])
    mu_l = np.array(gauss_mu[str(N)])
    azi = np.linspace(0., 2. * np.pi, N)
    zen = np.linspace(0., np.pi, N)
    sun = (110. / 180. * np.pi, 180. / 180. * np.pi)  # sun zenith, azimuth
    arch = 'e'
    refl = 0.07
    trans = 0.03
    p = np.zeros((N, N))
    for i, a in enumerate(azi):
        for j, z in enumerate(zen):
            p[j, i] = P2((z, a), sun, arch, refl, trans)
    fig = plt.figure(figsize=plt.figaspect(0.5))
    ax = fig.add_subplot(1, 1, 1, projection='3d')
    a, z = np.meshgrid(azi * 180. / np.pi, zen * 180. / np.pi)
    surf = ax.plot_surface(a,
                           z,
                           p,
                           rstride=1,
                           cstride=1,
                           cmap=cm.coolwarm,
                           linewidth=0,
                           antialiased=False)
    #ax.set_zlim3d(0.62, 1.94)
    fig.colorbar(surf, shrink=0.5, aspect=10)
    s = '''sun zenith:%.2f, sun azimuth:%.2f, arch:%s,
  refl:%.2f, trans:%.2f''' % \
        (sun[0]*180/np.pi,sun[1]*180/np.pi, arch,\
        refl, trans)
    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
    '''plt.text(.5,.5, s, bbox = props, transform=ax.transAxes,\
      horizontalalignment='center', verticalalignment='center')'''
    ax.set_xlabel("Azimuth angle")
    ax.set_ylabel("Zenith angle")
    ax.set_zlabel("P")
    plt.title("P (Normalized Scattering Phase Function)")
    print 'min: %.3f, max: %.3f' % (np.min(p), np.max(p))
    plt.show()
예제 #6
0
def show_image(img, messages=None, fig=None, ax=None, cmap='Gray'):

    if not ax or not fig:
        w, h = plt.figaspect(img.shape[0] / img.shape[1])
        fig = plt.figure(figsize=(w, h))
        ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

    bbox_opts = dict(ec='k', fc='k')
    ax.clear()
    img_axes = ax.imshow(img, cmap=cmaps[cmap])
    ax.axis('off')
    ax.text(0.03, 0.97, messages['filename'], fontsize=8, color='w', ha='left', va='top', transform=ax.transAxes,
            bbox=bbox_opts)
    ax.text(0.03, 0.03, messages['text_bottom'], fontsize=8, color='w', ha='left', va='bottom',
            transform=ax.transAxes, bbox=bbox_opts)
    fig.canvas.draw()
    plt.autoscale(tight=True)
    fig.show()

    return fig, ax, img_axes
예제 #7
0
def my_contourf(x, y, z, levels=None, cmap=None, **kwargs):
    dx = x.max() - x.min()
    dy = y.max() - y.min()
    w, h = plt.figaspect(float(dy/dx)) # float is must
    # No frame, white background, w/h aspect ratio figure
    fig = plt.figure(figsize=(w/2,h/2), frameon=False, dpi=150, facecolor='w')
    # full figure subplot, no boarder, no axes
    ax = fig.add_axes([0,0,1,1], frameon=False, axisbg='w')
    # no ticks
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    # Default: there are 256 contour levels
    if levels is None:
        step = (z.max() - z.min()) / 32
        levels = np.arange(z.min(), z.max()+step, step)
    # Default: colormap is Spectral from matplotlib.cm
    if cmap is None:
        cmap = plt.cm.Spectral
    # actual plot
    ax.contourf(x, y, z, levels=levels, cmap=cmap, 
                antialiased=False, **kwargs)
예제 #8
0
파일: utils.py 프로젝트: gurcani/pyhw
def anim(flname, outfl, vm=1.0, vmn=1.0, ntav=2):
    import matplotlib as mpl
    mpl.use('Agg')
    import matplotlib.pylab as plt
    import matplotlib.animation as anim
    if (':' in flname):
        flname = sync_rf(flname)
    fl = h5.File(flname, "r")
    phi = fl['fields/phi']
    n = fl['fields/n']
    w, h = plt.figaspect(0.5)
    fig, ax = plt.subplots(1, 2, sharey=True, figsize=(w, h))
    qd0 = ax[0].pcolormesh(np.real(phi[0, ].T),
                           shading='flat',
                           vmin=-vm,
                           vmax=vm,
                           cmap='seismic',
                           rasterized=True)
    qd1 = ax[1].pcolormesh(np.real(n[0, ].T),
                           shading='flat',
                           vmin=-vmn,
                           vmax=vmn,
                           cmap='seismic',
                           rasterized=True)
    fig.tight_layout()
    ax[0].axis('square')
    ax[1].axis('square')
    Nt = phi.shape[0]
    ani = anim.FuncAnimation(fig,
                             update_anim,
                             interval=0,
                             frames=Nt,
                             blit=True,
                             fargs=((qd0, qd1), phi, n))
    ani.save(outfl, dpi=200, fps=25)
    sbp.call(['vlc', outfl])
    fl.close()
예제 #9
0
def plotP2_3d():
  '''A function that plots the normalized scattering phase function for
  diffuse scattering. For comparison see Myneni 1991 Fig 3.
  '''
  N = 16
  g_wt = np.array(gauss_wt[str(N)])
  mu_l = np.array(gauss_mu[str(N)])
  azi = np.linspace(0., 2.*np.pi, N)
  zen = np.linspace(0., np.pi, N)
  sun = (110./180.*np.pi,180./180.*np.pi) # sun zenith, azimuth
  arch = 'e'
  refl = 0.07
  trans = 0.03
  p = np.zeros((N,N)) 
  for i, a in enumerate(azi):
    for j, z in enumerate(zen):
      p[j, i] = P2((z, a), sun, arch, refl, trans)
  fig = plt.figure(figsize=plt.figaspect(0.5))
  ax = fig.add_subplot(1, 1, 1, projection='3d')
  a, z = np.meshgrid(azi*180./np.pi, zen*180./np.pi)
  surf = ax.plot_surface(a, z, p, rstride=1, cstride=1, cmap=cm.coolwarm,
      linewidth=0, antialiased=False)
  #ax.set_zlim3d(0.62, 1.94)
  fig.colorbar(surf, shrink=0.5, aspect=10)
  s = '''sun zenith:%.2f, sun azimuth:%.2f, arch:%s,
  refl:%.2f, trans:%.2f''' % \
      (sun[0]*180/np.pi,sun[1]*180/np.pi, arch,\
      refl, trans)
  props = dict(boxstyle='round',facecolor='wheat',alpha=0.5)
  '''plt.text(.5,.5, s, bbox = props, transform=ax.transAxes,\
      horizontalalignment='center', verticalalignment='center')'''
  ax.set_xlabel("Azimuth angle")
  ax.set_ylabel("Zenith angle")
  ax.set_zlabel("P")
  plt.title("P (Normalized Scattering Phase Function)") 
  print 'min: %.3f, max: %.3f' %(np.min(p), np.max(p))
  plt.show()
예제 #10
0
    '''                                          
    ax.plot(seq[:-1,0], seq[:-1,1], color=color, 
            linewidth=linewidth, linestyle=linestyle)
    ax.arrow(seq[-2,0], seq[-2,1], seq[-1,0]-seq[-2,0], seq[-1,1]-seq[-2,1],
            head_width=2.5, head_length=2, fc=color, ec=color, linewidth=1)


# In[4]:

logger.info("Initializing train dataset")
train_set, train_loader = data_loader(args, 'train', 'Biker')


# In[77]:

width, height = plt.figaspect(1) # 1.68
fig = plt.figure(figsize=(width,height), dpi=300)
ax = fig.add_subplot(1, 1, 1)
colors = iter(cm.rainbow(np.linspace(0, 1, args.batch_size)))

img = np.array(Image.open('reference.jpg'))
batch = next(iter(train_loader))

obs_seq_list, pred_seq_list = batch[0], batch[1]

ax.imshow(img)

for seq, pred in zip(obs_seq_list, pred_seq_list):
    color = next(colors)
    plot_seq(ax, img, seq.numpy(), color=color)
    plot_seq(ax, img, pred.numpy(), color=color, linestyle=':', linewidth=0.5)
예제 #11
0
plt.pcolor(theta, phi, scores.reshape((21, 21)))
plt.colorbar()
plt.axis("image")
plt.show()

# %%%%%%%%%%%%%%%%%%%%
#%% Visualize tuning on a sphere!
# %%%%%%%%%%%%%%%%%%%%
from matplotlib import cm, colors
from mpl_toolkits.mplot3d import Axes3D
phi = np.linspace(-np.pi / 2, np.pi / 2, 11)
theta = np.linspace(-np.pi / 2, np.pi / 2, 11)
phi, theta = np.meshgrid(phi, theta)

# The Cartesian coordinates of the unit sphere
x = np.cos(phi) * np.cos(theta)
y = np.cos(phi) * np.sin(theta)
z = np.sin(phi)
#%%
# Calculate the spherical harmonic Y(l,m) and normalize to [0,1]
fcolors = scores.reshape(x.shape)
fmax, fmin = fcolors.max(), fcolors.min()
fcolors = (fcolors - fmin) / (fmax - fmin)

# Set the aspect ratio to 1 so our sphere looks spherical
fig3d = plt.figure(figsize=plt.figaspect(1.))
ax = fig3d.add_subplot(111, projection='3d')
ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=cm.seismic(fcolors))
# Turn off the axis planes
ax.set_axis_off()
plt.show()