def visualize(frames, gif_name, lb=None, ub=None): """ Create a gif file from the given frames, and display the result. :param frames: A list of numpy 2D arrays having same size; a single element is a value function. :param gif_name: Name of the outcome. :param lb: Lower bound of value function. :param ub: Upper bound of value function. """ plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi=72) patch = plt.imshow(frames[0], cmap='plasma') if lb is not None and ub is not None: plt.clim(lb, ub) plt.colorbar() plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) anim.save(gif_name, dpi=80, writer='imagemagick') display(display_animation(anim, default_mode='loop'))
def running_JSAnimation(): dpi = 40 mode = 'loop' figsize = (game.shape[1] * 1. / dpi, game.shape[0] * 1. / dpi) fig = plt.figure(figsize=figsize, dpi=dpi) ax = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False) im = ax.imshow(game, cmap=plt.cm.binary, interpolation='nearest') # initialization function: plot the background of each frame def init(): im.set_data(game_blank) return (im, ) # animation function. This is called sequentially def animate(i): im.set_data(animate.game) animate.game = game_of_life(animate.game) return (im, ) animate.game = game anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=100) return display_animation(anim, default_mode=mode)
def view_anim(self, backend=None): self.anim = animation.FuncAnimation(self.f, self.animator,\ frames=self.nframes, interval=self.interval) if backend == 'JS': return display_animation(self.anim) elif backend is None: return self.anim
def run(self, reset=False): """ This function creates the animation. The animation frame size is based on the first element of the stored image. Users can use the reset option in order to reset the stored image. Note that only the stored image will reset but the animation will be kept. If users redo this function with ``reset = True``, users will get an error. Args: reset(boolean): resets at the end of animation. """ assert len(self) > 0, "No length" frame_r = self.frames plt.figure(figsize=(frame_r[0].shape[1] / self.ratio, frame_r[0].shape[0] / self.ratio), dpi=self.dpi) image = plt.imshow(frame_r[0]) plt.axis("off") def animate(i): image.set_data(frame_r[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frame_r), interval=50) # #saves animation # if save==True: # anim.save(name+".mp4") # anim.save("movie_cartpole.mp4") display(display_animation(anim)) if reset: self.reset()
def show_frames(name, frames, satisf): """ generate animation inline notebook: frames - list of pictures """ plt.figure(figsize=(frames[0].shape[1] / 9.0, frames[0].shape[0] / 18.0), dpi=72) plt.suptitle(name) plt.subplot(121) patch1 = plt.imshow(frames[0]) plt.axis('off') plt.title("WORLD") plt.subplot(122) patch2 = plt.imshow(satisf[0]) plt.axis('off') plt.title("SATISFACTION MAP") def animate(i): patch1.set_data(frames[i]) patch2.set_data(satisf[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) display(display_animation(anim, default_mode='once'))
def display_frames_as_gif(frames): plt.figure(figsize=(frames[0].shape[1]/72,frames[0].shape[0]/72),dpi=72) patch=plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim=animation.FuncAnimation(plt.gcf(),animate,frames=len(frames),interval=50) anim.save('movie_cartpole.mp4') display(display_animation(anim,default_mode='loop'))
def _display_gif(self): """Displays list of frames as a gif, with controls.""" patch = plt.imshow(self.frames[0]) plt.axis('off') anim = animation.FuncAnimation( plt.gcf(), lambda i: patch.set_data(self.frames[i]), frames=len(self.frames), interval=20) display(display_animation(anim, default_mode='once'))
def animate_frames(frames): plt.axis('off') # color option for plotting # use Greys for greyscale cmap = None if len(frames[0].shape) == 3 else 'Greys' patch = plt.imshow(frames[0], cmap=cmap) fanim = animation.FuncAnimation(plt.gcf(), lambda x: patch.set_data(frames[x]), frames=len(frames), interval=30) display(display_animation(fanim, default_mode='once'))
def display_frames_as_gif(frames): """Displays a list of frames as a gif, with controls.""" patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation( plt.gcf(), animate, frames=len(frames), interval=50 ) display(display_animation(anim, default_mode='loop'))
def display_game(self, game_n): patch = plt.imshow(self.game_frames[game_n][0]) plt.axis('off') def animate(i): patch.set_data(self.game_frames[game_n][i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(self.game_frames[game_n]), interval=50) display(display_animation(anim, default_mode='once'))
def display_frames(frames): patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) display(display_animation(anim, default_mode='once', fps=60))
def display_frames_as_gif(frames): """ Displays a list of frames as a gif, with controls """ #plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi = 72) patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames = len(frames), interval=50) display(display_animation(anim, default_mode='loop'))
def display_frames_as_git(frames): plt.figure(figsize=(frames[0].shape[1] / 72, frames[0].shape[0] / 72), ) patch = plt.imshow(frames[0]) plt.axis("off") def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) display(display_animation(anim, default_mode=50))
def life_animation(X, dpi=10, frames=10, interval=300, mode='loop'): """Produce a Game of Life Animation Parameters ---------- X : array_like a two-dimensional numpy array showing the game board dpi : integer the number of dots per inch in the resulting animation. This controls the size of the game board on the screen frames : integer The number of frames to compute for the animation interval : float The time interval (in milliseconds) between frames mode : string The default mode of the animation. Options are ['loop'|'once'|'reflect'] """ X = np.asarray(X) assert X.ndim == 2 X = X.astype(bool) X_blank = np.zeros_like(X) figsize = (X.shape[1] * 1. / dpi, X.shape[0] * 1. / dpi) fig = plt.figure(figsize=figsize, dpi=dpi) ax = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False) im = ax.imshow(X, cmap=plt.cm.binary, interpolation='nearest') im.set_clim(-0.05, 1) # Make background gray # initialization function: plot the background of each frame def init(): im.set_data(X_blank) return (im, ) # animation function. This is called sequentially def animate(i): im.set_data(animate.X) animate.X = life_step(animate.X) return (im, ) animate.X = X anim = animation.FuncAnimation(fig, animate, init_func=init, frames=frames, interval=interval) #print anim_to_html(anim) return display_animation(anim, default_mode=mode)
def display_frames_as_gif(frames, title): """ Displays a list of frames as a gif, with controls """ plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi=72) plt.title(title) patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=30) display(display_animation(anim, default_mode='loop'))
def display_frames_as_gif(frames): plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi=72) patch = plt.imshow(frames[0]) plt.axis('off') # アニメーションの定期処理 def animate(i): patch.set_data(frames[i]) # アニメーション再生 anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) display(display_animation(anim, default_mode='loop'))
def display_frames_as_gif(frames): """ Displays a list of frames as a gif, with controls """ plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi=72) patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) anim.save('movie_cartpole_dueling_network.mp4') # 動画のファイル名と保存です display(display_animation(anim, default_mode='loop'))
def life_animation(X, dpi=10, frames=10, interval=300, mode='loop'): """Produce a Game of Life Animation Parameters ---------- X : array_like a two-dimensional numpy array showing the game board dpi : integer the number of dots per inch in the resulting animation. This controls the size of the game board on the screen frames : integer The number of frames to compute for the animation interval : float The time interval (in milliseconds) between frames mode : string The default mode of the animation. Options are ['loop'|'once'|'reflect'] """ X = np.asarray(X) assert X.ndim == 2 X = X.astype(bool) X_blank = np.zeros_like(X) figsize = (X.shape[1] * 1. / dpi, X.shape[0] * 1. / dpi) fig = plt.figure(figsize=figsize, dpi=dpi) ax = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[], frameon=False) im = ax.imshow(X, cmap=plt.cm.binary, interpolation='nearest') im.set_clim(-0.05, 1) # Make background gray # initialization function: plot the background of each frame def init(): im.set_data(X_blank) return (im,) # animation function. This is called sequentially def animate(i): im.set_data(animate.X) animate.X = life_step(animate.X) return (im,) animate.X = X anim = animation.FuncAnimation(fig, animate, init_func=init, frames=frames, interval=interval) #print anim_to_html(anim) return display_animation(anim, default_mode=mode)
def display_frames_as_gif(frames, filename_gif=None): """ Making GIF from continuous photos """ plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi=72) patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) if filename_gif: anim.save(filename_gif, writer='imagemagick', fps=50) display(display_animation(anim, default_mode='loop'))
def display_frames_as_gif(frames): """ Displays a list of frames as a gif, with controls """ fig = plt.figure("Animation",figsize=(7,5)) ax = fig.add_subplot(111) #plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi = 72) ims = [] npad = ((4, 4), (4, 4),(0,0)) for i in range(len(frames)): img = np.pad(frames[i][0], pad_width=npad, mode='constant', constant_values=255.) #pad white frame = ax.imshow(img) ax.axis('off') t = ax.annotate(frames[i][1],(1,1)) # add text t.set_fontsize(12) ims.append([frame,t]) # add both the image and the text to the list of artists anim = animation.ArtistAnimation(fig, ims, interval=50, blit=True) display(display_animation(anim, default_mode='loop'))
def show_frames(frames): """ generate animation inline notebook: input: frames - list of pictures """ plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi=72) patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) # not working in matplotlib 3.1 display(display_animation(anim, default_mode='loop'))
def animate(examples, cmap=pylab.cm.bone, save=False): fig = plt.figure() im = plt.imshow(examples[0], cmap=cmap) # function to update figure def updatefig(j): data = examples[j] im.set_data(data) im.set_extent([0, data.shape[0], 0, data.shape[1]]) return im, # kick off the animation ani = animation.FuncAnimation(fig, updatefig, frames=len(examples), interval=50, blit=True) if save is not False: ani.save(save, writer='imagemagick', fps=10) return display_animation(ani, default_mode='loop')
def show_frames_and_distribution(frames, distributions, name, support): """ generate animation inline notebook with distribtuions plot input: frames - list of pictures input: distributions - list of arrays of fixed size input: name - title name input: support - indexes for support of distribution """ plt.figure(figsize=(frames[0].shape[1] / 34.0, frames[0].shape[0] / 72.0), dpi=72) plt.subplot(121) patch = plt.imshow(frames[0]) plt.axis('off') plt.subplot(122) plt.title(name) action_patches = [] for a in range(distributions.shape[1]): action_patches.append( plt.bar(support, distributions[0][a], width=support[1] - support[0])) def animate(i): patch.set_data(frames[i]) for a, action_patch in enumerate(action_patches): for rect, yi in zip(action_patch, distributions[i][a]): rect.set_height(yi) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames) - 1, interval=50) # not working in matplotlib 3.1 display(display_animation(anim, default_mode='loop'))
u[0,:]=u[1,:] u[-1,:]=u[-2,:] u[:,0]=u[:,1] u[:,-1]=u[:,-2] v[0,:]=v[1,:] v[-1,:]=v[-2,:] v[:,0]=v[:,1] v[:,-1]=v[:,-2]#nuemann boundaries if i%100==0: um[j,:,:]=u j+=1 #print(j) i+=1 return um unew=ftcs(U,V,nt,dt,dh,Du,Dv,F,k) fig = pyplot.figure(figsize=(8,5), dpi=72) img = pyplot.imshow(unew[0],cmap = cm.RdBu) def animate(data): img.set_array(data) return img, anim = animation.FuncAnimation(fig, animate, frames=unew, interval=85) display_animation(anim, default_mode='once') #run in jupyter-notebook
rho_plus = np.zeros_like(rho) rho_minus = np.zeros_like(rho) flux = np.zeros_like(rho) for t in range(1,nt): rho_plus[:-1] = rho[1:] rho_minus[:] = rho[:] flux = 0.5*(F(V_max,rho_max,rho_minus)+ F(V_max,rho_max,rho_plus)- dx/dt*(rho_plus-rho_minus)) rho_n[t,1:-1] = rho[1:-1]+dt/dx*(flux[:-2]-flux[1:-1]) rho_n[t,0] = rho[0] rho_n[t,-1] = rho[-1] rho = rho_n[t].copy() return rho_n sigma = 1.0 dt = sigma*dx rho = rho_red_light(nx,rho_max,rho_in) rho_n = Godunov(rho,nt,dt,dx,rho_max,V_max) fig = plt.figure(); ax = plt.axes(xlim=(0,4),ylim=(4.5,11),xlabel=('Distance'),ylabel=('Traffic Density')); line, = ax.plot([],[],color='#003366', lw=2); anim = animation.FuncAnimation(fig,animate,frames=rho_n,interval=50) display_animation(anim,default_mode='reflect')
print('Velocity at 2.5m: '), u25 print('Pressure at 2.5m: '), P25 print('Density at 2.5m: '), rho25 fig = plt.figure() ax = plt.axes(xlim=(-10, 10), ylim=(0, 600), xlabel=('Distance'), ylabel=('Velocity')) line, = ax.plot([], [], color='k', lw=2) anim = animation.FuncAnimation(fig, animate, frames=pltvelocity[1:, :], interval=50) display_animation(anim, default_mode='reflect') fig = plt.figure() ax = plt.axes(xlim=(-10, 10), ylim=(0, 1.1), xlabel=('Distance'), ylabel=('Density')) line, = ax.plot([], [], color='k', lw=2) anim = animation.FuncAnimation(fig, animate, frames=pltdensity[1:, :], interval=50) display_animation(anim, default_mode='reflect') fig = plt.figure()
circle.set_data([], []) x_pos_marker.set_data([], []) y_pos_marker.set_data([], []) x_pos_line.set_data([], []) y_pos_line.set_data([], []) return circle, x_pos_marker, y_pos_marker, x_pos_line, y_pos_line # This function moves the polygons as a function of the frame i def animate(i): t = 2.*np.pi*float(i/(Nframes - 1.)) x_marker = rad*np.cos(t) y_marker = rad*np.sin(t) circle.set_data(x_marker, y_marker) x_pos_marker.set_data(x_marker, t) y_pos_marker.set_data(t, y_marker) all_t = np.linspace(0, 2.*np.pi, Nframes) x = rad*np.cos(all_t) y = rad*np.sin(all_t) x_pos_line.set_data(x, all_t) y_pos_line.set_data(all_t, y) return circle, x_pos_marker, y_pos_marker, x_pos_line, y_pos_line # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, animate, init_func=init, frames=Nframes, interval=20, blit=True) # call our new function to display the animation display_animation(anim)
ustar[:-1] = u[:-1] - dt/dx * (F[1:]-F[:-1]) + damp_term Fstar = computeF(ustar) un[n,1:] = .5 * (u[1:]+ustar[1:] - dt/dx * (Fstar[1:] - Fstar[:-1])) u = un[n].copy() print(len(damp_term)) print(len(ustar)) return un nx = 81 nt = 70 dx = 4.0/(nx-1) def animate(data): x = numpy.linspace(0,4,nx) y = data line.set_data(x,y) return line, u = u_initial(nx) sigma = .5 dt = sigma*dx un = maccormack(u,nt,dt,dx) fig = pyplot.figure(); ax = pyplot.axes(xlim=(0,4),ylim=(-.5,2)); line, = ax.plot([],[],lw=2); anim = animation.FuncAnimation(fig, animate, frames=un, interval=50) display_animation(anim, default_mode='once')
def play(env, act, gif_name, gamma=1., feed_obs=False, episode_length=None, frame_size=(180, 180)): """ Given an agent, play the environment once, then show the observation while saving it as an image. Reference: http://nbviewer.jupyter.org/github/patrickmineault/xcorr-notebooks/blob/master/Render%20OpenAI%20gym%20as%20GIF.ipynb :param env: Instance of gym.env :param act: Agent targeting env, should have *.__call__(state_index) :param gamma: Discount factor. :param feed_obs: If True, feed observation to act. :param episode_length: Maximum length of an episode. :param gif_name: Name of the output gif, should end with '.gif' :param frame_size: Size of the output gif, should be a tuple (int, int) """ if episode_length is None: if hasattr(act, 'episode_length'): episode_length = act.episode_length elif hasattr(env, 'episode_length'): episode_length = env.episode_length else: episode_length = 2147483647 obs, done = env.reset(), False state = None if not feed_obs: state = env.cheat() episode_rew = 0 episode_safety = 0 frames = [] t = 0 while not done: if t > episode_length: break # Create image frame = env.render(mode='rgb_array') frames.append(resize( frame, dsize=frame_size, )) # Do step input_ = obs if feed_obs else state _, rew, done, info = env.step(act.step(input_)) if not feed_obs: state = info['state'] episode_safety = episode_safety * info['safety'] episode_rew = gamma * episode_rew + rew t += 1 print("Total reward: %.6f" % episode_rew) print("Total safety: %.1f" % episode_safety) env.close() plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi=72) patch = plt.imshow(frames[0]) plt.axis('off') def animate(i): patch.set_data(frames[i]) anim = animation.FuncAnimation(plt.gcf(), animate, frames=len(frames), interval=50) anim.save(gif_name, dpi=80, writer='imagemagick') display(display_animation(anim, default_mode='loop')) return frames
def render_anim(ani, **kwargs): return display_animation(ani)
return (pt,) + tuple(trails) def update(i): ix = i - n_trails pt.set_data(x[i], y[i]) for j,trail in zip(range(len(trails))[::-1],trails): if ix+j < 0: continue trail.set_data(x[ix+j], y[ix+j]) return (pt,) + tuple(trails) ani = animation.FuncAnimation(fig, update, n_frames, init_func=init, interval=20, blit=True) display_animation(ani)
rhon = np.zeros((nt,len(rho))) rhon[0,:]=rho.copy() for t in range(1,nt): F=Flux(V_max, rho_max, rho) rhon[t,1:] = rho[1:] - dt/dx*(F[1:]-F[:-1]) rhon[t,0] = rho[0] rhon[t,-1] = rho[-1] rho = rhon[t].copy() return rhon #Running Forward Time/Backward Space sigma = 1. dt = sigma*dx rhon = FTBS(rho, nt, dt, dx, rho_max, V_max) fig = plt.figure(); ax = plt.axes(xlim=(0,4),ylim=(-.5,11),xlabel=('Distance'),ylabel=('Traffic Density')); line, = ax.plot([],[],color='r',lw=2); def animate(data): x = np.linspace(0,4,nx) y = data line.set_data(x,y) return line, anim = animation.FuncAnimation(fig, animate, frames=rhon,interval=50) display_animation(anim, default_mode='once') plt.show()