def viz(I, V, f, c, L, dt, C, T, umin, umax, animate=True): """Run solver and visualize u at each time level.""" import scitools.std as plt, time, glob, os def plot_u(u, x, t, n): """user_action function for solver.""" plt.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%f' % t[n]) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, L, dt, C, T, user_action) if animate: plt.movie('frame_*.png', encoder='html', fps=4, output_file='movie.html') return cpu
def viz(I, V, f, c, L, Nx, C, T, umin, umax, animate=True): """Run solver and visualize u at each time level.""" import scitools.std as plt import time, glob, os def plot_u(u, x, t, n): """user_action function for solver.""" plt.plot(x, u, "r-", xlabel="x", ylabel="u", axis=[0, L, umin, umax], title="t=%f" % t[n], show=True) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig("frame_%04d.png" % n) # for movie making # Clean up old movie frames for filename in glob.glob("frame_*.png"): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, L, Nx, C, T, user_action) # Make movie files fps = 4 # Frames per second plt.movie("frame_*.png", encoder="html", fps=fps, output_file="movie.html") codec2ext = dict(flv="flv", libx64="mp4", libvpx="webm", libtheora="ogg") filespec = "frame_%04d.png" movie_program = "avconv" # or 'ffmpeg' for codec in codec2ext: ext = codec2ext[codec] cmd = "%(movie_program)s -r %(fps)d -i %(filespec)s " "-vcodec %(codec)s movie.%(ext)s" % vars() os.system(cmd)
def make_movie_file(self): """ Create subdirectory based on casename, move all plot frame files to this directory, and generate an index.html for viewing the movie in a browser (as a sequence of PNG files). """ # Make HTML movie in a subdirectory directory = self.casename if os.path.isdir(directory): shutil.rmtree(directory) # rm -rf directory os.mkdir(directory) # mkdir directory # mv frame_*.png directory for filename in glob.glob('frame_*.png'): os.rename(filename, os.path.join(directory, filename)) os.chdir(directory) # cd directory fps = 4 # frames per second if self.backend is not None: from scitools.std import movie movie('frame_*.png', encoder='html', output_file='index.html', fps=fps) # Make other movie formats: Flash, Webm, Ogg, MP4 codec2ext = dict(flv='flv', libx264='mp4', libvpx='webm', libtheora='ogg') filespec = 'frame_%04d.png' movie_program = 'ffmpeg' # or 'avconv' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\ '-vcodec %(codec)s movie.%(ext)s' % vars() os.system(cmd) os.chdir(os.pardir) # move back to parent directory
def viz(I, V, f, c, U_0, U_L, L, Nx, C, T, umin, umax, version='scalar', animate=True): """Run solver and visualize u at each time level.""" import scitools.std as st, time, glob, os def plot_u(u, x, t, n): """user_action function for solver.""" st.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%f' % t[n]) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) st.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, U_0, U_L, L, Nx, C, T, user_action, version) if animate: st.movie('frame_*.png', encoder='mencoder', fps=4, output_file='movie.avi') st.movie('frame_*.png', encoder='html', fps=4, output_file='movie.html') return cpu
def MakeVideo(self, files): import scitools.std as sci sci.movie(files, encoder='mencoder', fps=25, output_file=self.result_path + '/movie.mpeg') for i in files: os.system('rm %s' % i)
def viz(I, V, f, c, L, dt, C, T, umin, umax, animate=True, version='vectorized'): """Run solver and visualize u at each time level.""" import scitools.std as plt, time, glob, os #num_frames = 100 # max no of frames in movie def plot_u(u, x, t, n): """user_action function for solver.""" try: every = t.size / num_frames except NameError: every = 1 # plot every frame if n % every == 0: plt.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%f' % t[n]) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, L, dt, C, T, user_action, version) if not animate: return cpu # Make movie files fps = 4 # Frames per second plt.movie('frame_*.png', encoder='html', fps=fps, output_file='movie.html') # Ex: avconv -r 4 -i frame_%04d.png -vcodec libtheora movie.ogg codec2ext = dict(flv='flv', libx264='mp4', libvpx='webm', libtheora='ogg') filespec = 'frame_%04d.png' movie_program = 'avconv' # or 'ffmpeg' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\ '-vcodec %(codec)s movie.%(ext)s' % vars() os.system(cmd) return cpu
def viz(I, V, f, c, U_0, U_L, x0, xL, Nx, C, T, umin, umax, version='scalar', animate=True, movie_dir='tmp'): """Run solver and visualize u at each time level.""" import scitools.std as plt, time, glob, os def plot_u(u, x, t, n): """user_action function for solver.""" plt.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[x0, xL, umin, umax], title='t=%f' % t[n]) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, U_0, U_L, L, Nx, C, T, user_action, version) if animate: # Make a directory with the frames if os.path.isdir(movie_dir): shutil.rmtree(movie_dir) os.mkdir(movie_dir) os.chdir(movie_dir) # Move all frame_*.png files to this subdirectory for filename in glob.glob(os.path.join(os.pardir, 'frame_*.png')): os.renamve(os.path.join(os.pardir, filename), filename) plt.movie('frame_*.png', encoder='html', fps=4, output_file='movie.html') # Invoke movie.html in a browser to steer the movie return cpu
def make_exact(self): if(self.exact!=None): sol = self.exact(self.X,self.Y,0) for k in xrange(self.Nt): mlab.mesh(self.X,self.Y,sol, color=(0.0, 0.3, 0.6)) sol = self.exact(self.X, self.Y, self.t[k]) mlab.savefig("wtmp%04d.png" %k) mlab.clf() filename = "exact_dt%2.1f.gif" %self.dt sci.movie("wtmp*.png",encoder='convert', fps=5, output_file=filename)
def second_animate(self,animation_type=None): filenames = [] for t in self._T: pop = self._poplist.get(T=t) plt.clf() pop.draw() num = str(t) plt.savefig('image'+num+'.png', format='png') filenames.append('image'+num+'.png') from scitools.std import movie movie('*.png',fps=1,output_file='thisismygif.gif')
def make_exact(self): if(self.exact!=None): sol = self.exact(self.X,self.Y,0) for k in xrange(self.Nt): mlab.view(0, 0) mlab.mesh(self.X,self.Y,sol, color=(0.0, 0.3, 0.6)) sol = self.exact(self.X, self.Y, self.t[k]) mlab.savefig("wtmp%04d.png" %k) mlab.clf() filename = "exact_dt%2.1f.gif" %self.dt sci.movie("wtmp*.png",encoder='convert', fps=5, output_file=filename)
def second_animate(self, animation_type=None): filenames = [] for t in self._T: pop = self._poplist.get(T=t) plt.clf() pop.draw() num = str(t) plt.savefig('image' + num + '.png', format='png') filenames.append('image' + num + '.png') from scitools.std import movie movie('*.png', fps=1, output_file='thisismygif.gif')
def viz(I, V, f, c, U_0, U_L, L, dt, C, T, umin, umax, version='scalar', animate=True): """Run solver and visualize u at each time level.""" import time, glob, os if callable(U_0): bc_left = 'u(0,t)=U_0(t)' elif U_0 is None: bc_left = 'du(0,t)/dx=0' else: bc_left = 'u(0,t)=0' if callable(U_L): bc_right = 'u(L,t)=U_L(t)' elif U_L is None: bc_right = 'du(L,t)/dx=0' else: bc_right = 'u(L,t)=0' def plot_u(u, x, t, n): """user_action function for solver.""" # Works only with scitools, see wave1D_u0.py for matplotlib versions plt.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%.3f, %s, %s' % (t[n], bc_left, bc_right)) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, U_0, U_L, L, dt, C, T, user_action, version) if animate: plt.movie('frame_*.png', encoder='html', fps=4, output_file='movie.html') # Make other movie formats: Flash, Webm, Ogg, MP4 codec2ext = dict(flv='flv', libx264='mp4', libvpx='webm', libtheora='ogg') fps = 6 filespec = 'frame_%04d.png' movie_program = 'ffmpeg' # or 'avconv' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\ '-vcodec %(codec)s movie.%(ext)s' % vars() print cmd os.system(cmd) return cpu
def viz(I, V, f, density, tension, L, Nx, C, T, umin, umax, animate=True, movie_filename='movie', version='vectorized'): """Run solver and visualize u at each time level.""" import scitools.std as plt, time, glob, os #num_frames = 100 # max no of frames in movie def plot_u(u, x, t, n): """user_action function for solver.""" try: every = t.size/num_frames except NameError: every = 1 # plot every frame if n % every == 0: plt.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%f' % t[n]) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, density, tension, L, Nx, C, T, user_action, version) if not animate: return cpu # Make movie files fps = 4 # Frames per second plt.movie('frame_*.png', encoder='html', fps=fps, output_file='movie.html') # Ex: avconv -r 4 -i frame_%04d.png -vcodec libtheora movie.ogg #codec2ext = dict(flv='flv', libx64='mp4', libvpx='webm', # libtheora='ogg') codec2ext = dict(libtheora='ogg') filespec = 'frame_%04d.png' movie_program = 'avconv' # or 'ffmpeg' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\ '-vcodec %(codec)s %(movie_filename)s.%(ext)s' % vars() os.system(cmd) return cpu
def main(): 'entry point' T = 2*pi xl = np.linspace(0.01, T-0.01, 100) tl = [x for x in xl] y = [f(t, T) for t in tl] counter = 0 filename = 'tmp_' for n in [1, 3, 20, 200]: yp = [S(t, n, T) for t in tl] #plot(tl, y) plot(tl, y, tl, yp, savefig='%s%04d.png' % (filename, counter)) counter += 1 movie('tmp*.png', encoder='convert', fps=2, output_file='sinesum.gif')
def viz(I, V, f, c, L, Nx, C, T, umin, umax, animate=True, version='vectorized'): """Run solver and visualize u at each time level.""" import scitools.std as st, time, glob, os #num_frames = 100 # max no of frames in movie def plot_u(u, x, t, n): """user_action function for solver.""" try: every = t.size / num_frames except NameError: every = 1 # plot every frame if n % every == 0: st.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%f' % t[n]) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) st.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, L, Nx, C, T, user_action, version) # Make movie files st.movie('frame_*.png', encoder='mencoder', fps=4, output_file='movie.avi') st.movie('frame_*.png', encoder='html', fps=4, output_file='movie.html') return cpu
def viz(I, V, f, c, U_0, U_L, L, Nx, C, T, umin, umax, version="scalar", animate=True): """Run solver and visualize u at each time level.""" import scitools.std as plt, time, glob, os def plot_u(u, x, t, n): """user_action function for solver.""" plt.plot(x, u, "r-", xlabel="x", ylabel="u", axis=[0, L, umin, umax], title="t=%f" % t[n]) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig("frame_%04d.png" % n) # for movie making # Clean up old movie frames for filename in glob.glob("frame_*.png"): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, U_0, U_L, L, Nx, C, T, user_action, version) if animate: plt.movie("frame_*.png", encoder="html", fps=4, output_file="movie.html") return cpu
def make_movie_file(self): """ Create subdirectory based on casename, move all plot frame files to this directory, and generate an index.html for viewing the movie in a browser (as a sequence of PNG files). """ # Make HTML movie in a subdirectory directory = self.casename if os.path.isdir(directory): shutil.rmtree(directory) # rm -rf directory os.mkdir(directory) # mkdir directory # mv frame_*.png directory for filename in glob.glob('frame_*.png'): os.rename(filename, os.path.join(directory, filename)) os.chdir(directory) # cd directory fps = 24 # frames per second if self.backend is not None: from scitools.std import movie movie('frame_*.png', encoder='html', output_file='index.html', fps=fps) # Make other movie formats: Flash, Webm, Ogg, MP4 codec2ext = dict(flv='flv', libx264='mp4', libvpx='webm', libtheora='ogg') filespec = 'frame_%04d.png' movie_program = 'ffmpeg' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\ '-vcodec %(codec)s movie.%(ext)s' % vars() os.system(cmd) os.chdir(os.pardir) # move back to parent directory
def viz(I, V, f, c, L, Nx, C, T, umin, umax, animate=True): """Run solver and visualize u at each time level.""" import scitools.std as plt import time, glob, os def plot_u(u, x, t, n): """user_action function for solver.""" plt.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%f' % t[n], show=True) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, L, Nx, C, T, user_action) # Make movie files fps = 4 # Frames per second plt.movie('frame_*.png', encoder='html', fps=fps, output_file='movie.html') codec2ext = dict(flv='flv', libx64='mp4', libvpx='webm', libtheora='ogg') filespec = 'frame_%04d.png' movie_program = 'avconv' # or 'ffmpeg' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\ '-vcodec %(codec)s movie.%(ext)s' % vars() os.system(cmd)
def viz(I, V, f, c, L, dt, C, T, umin, umax, animate=True): """Run solver and visualize u at each time level.""" import scitools.std as plt import time, glob, os def plot_u(u, x, t, n): """user_action function for solver.""" plt.plot(x, u, 'r-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%f' % t[n], show=True) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.2) plt.savefig('frame_%04d.png' % n) # for movie making # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) user_action = plot_u if animate else None u, x, t, cpu = solver(I, V, f, c, L, dt, C, T, user_action) # Make movie files fps = 4 # Frames per second plt.movie('frame_*.png', encoder='html', fps=fps, output_file='movie.html') codec2ext = dict(flv='flv', libx264='mp4', libvpx='webm', libtheora='ogg') filespec = 'frame_%04d.png' movie_program = 'avconv' # or 'ffmpeg' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\ '-vcodec %(codec)s movie.%(ext)s' % vars() os.system(cmd)
def MakeVideo(self,files): import scitools.std as sci sci.movie(files, encoder='mencoder', fps=25, output_file=self.result_path+'/movie.mpeg') for i in files: os.system('rm %s'%i)
P2 = 24 * 60 * 60 * 365. # oscillation period of 1 yr (in seconds) # angular frequency of yearly temperature variations (in rad/s) omega2 = 2 * pi / P2 a2 = sqrt(omega2 / (2 * k)) dt = P2 / 30 # time lag: 0.1 yr tmax = 3 * P2 # 3 year simulation T0 = 10 # mean surface temperature in Celsius D = -(1 / a1) * log(0.001) # max depth n = 501 # no of points in the z direction z = linspace(0, D, n) def z_scaled(x, s): a = x[0] b = x[-1] return a + (b - a) * ((x - a) / (b - a))**s zs = z_scaled(z, 3) animate(tmax, dt, zs, T, T0 - A2 - A1, T0 + A2 + A1, 0, 'z', 'T') movie('tmp_*.png', encoder='convert', fps=6) import glob import os # Remove frames for filename in glob.glob('tmp_*.png'): os.remove(filename)
if '--no-moviefile' in sys.argv: # Drop making movie files import sys; sys.exit(0) # Animated GIF cmd = 'convert -delay 50 tmp_*.png movie1.gif' os.system(cmd) # Flash video basic = 'avconv -r 12 -i tmp_%04d.png -c:v ' cmd = basic + 'flv movie1.flv' os.system(cmd) # MP4 video cmd = basic + 'libx264 movie1.mp4' os.system(cmd) # Ogg video cmd = basic + 'libtheora movie1.ogg' os.system(cmd) # WebM video cmd = basic + 'libvpx movie1.webm' os.system(cmd) # HTML (via scitools.easyviz.movie) movie('tmp_*.png', encoder='html', fps=3, output_file='tmpmovie.html') # play in HTML file
def solve_num(self): Nx = self.Nx Ny = self.Ny Nt = self.Nt I = self.I q = self.q f = self.f dt = self.dt V = self.V b = self.b C_x = self.C_x C_y = self.C_y f_f = self.f_f X = self.X Y = self.Y t = self.t u = zeros((Nx+2,Ny+2), float) up = u.copy() upp = up.copy() up[1:-1,1:-1] = I[1:-1,1:-1].copy() up[0,:] = up[1,:].copy() up[:,0] = up[:,1].copy() up[-1,:] = up[-2,:].copy() up[:,-1] = up[:,-2].copy() #making u^1 for i in xrange(1,Nx+1): for j in xrange(1,Ny+1): x_para = ((q[i][j] + q[i+1][j])*(up[i+1][j] - up[i][j]) - (q[i-1][j] + q[i][j])*(up[i][j] - up[i-1][j])) y_para = ((q[i][j] + q[i][j+1])*(up[i][j+1] - up[i][j]) - (q[i][j-1] + q[i][j])*(up[i][j] - up[i][j-1])) rest = f[i][j] + 4*up[i][j] + 2*dt*V[i][j]*(b*dt-2) u[i][j] = 1.0/(4.0)*(C_x**2*x_para + C_y**2*y_para + rest) u[0,:] = u[1,:].copy() u[:,0] = u[:,1].copy() u[-1,:] = u[-2,:].copy() u[:,-1] = u[:,-2].copy() #making u^-1 upp = 2*dt*V + u #vectorized: filename_2 = "num_dt%2.1f.gif"%dt ''' if self.standing: filename_2 = "standing_wave_dt%2.1f.gif"%dt else: ''' for filename in glob.glob('wtmp*.png'): os.remove(filename) for k in xrange(Nt): x_para = (q[1:-1,1:-1] + q[2:,1:-1])*(up[2:,1:-1] - up[1:-1,1:-1]) - (q[:-2, 1:-1] + q[1:-1,1:-1])*(up[1:-1,1:-1] - up[:-2,1:-1]) y_para = (q[1:-1,1:-1] + q[1:-1,2:])*(up[1:-1,2:] - up[1:-1,1:-1]) - (q[1:-1,:-2] + q[1:-1,1:-1])*(up[1:-1,1:-1] - up[1:-1,:-2]) f = f_f(X,Y,t[k]) rest = f[1:-1,1:-1] + 4*up[1:-1,1:-1] + upp[1:-1,1:-1]*(b*dt-2) u[1:-1,1:-1] = 1.0/(2+b*dt)*(C_x**2*x_para + C_y**2*y_para + rest) print (C_x**3)/(2+b*dt) u[0,:] = u[2,:] u[:,0] = u[:,2] u[-1,:] = u[-3,:] u[:,-1] = u[:,-3] if k%3 == 0: s = mlab.mesh(X,Y,u, color=(0.0,0.75,1.0)) mlab.savefig("wtmp%04d.png" %k) mlab.clf() upp = up.copy() up = u.copy() sci.movie("wtmp*.png",encoder='convert', fps=2, output_file=filename_2)
import numpy tp = numpy.linspace(0, 2*R, 25) dt = tp[1] - tp[0] # time step def move(t, fig): x_displacement = dt*v(t) fig['vehicle'].translate((x_displacement, 0)) files = animate(fig, tp, move, moviefiles=True, pause_per_frame=0) files_wildcard = files.split('%')[0] + '*.png' os.system('convert -delay 20 %s* vehicle0.gif' % (files_wildcard)) os.system('avconv -r 12 -i %s -c:v flv vehicle0.flv' % files) os.system('avconv -r 12 -i %s -c:v libvpx vehicle0.webm' % files) os.system('avconv -r 12 -i %s -c:v libtheora vehicle0.ogg' % files) os.system('avconv -r 12 -i %s -c:v libx264 -s:v 1000x520 vehicle0.mp4' % files) try: from scitools.std import movie except ImportError: raise ImportError( 'scitools must be installed for running the "movie" function.\n' 'scitools is installed by sudo apt-get install python-scitools\n' 'on Ubuntu or by sudo python setup.py install if the code is\n' 'downloaded from http://code.google.com/p/scitools.') # HTML page showing individual frames movie(files_wildcard, encoder='html', fps=4, output_file='vehicle0.html') raw_input()
def viz(I, V, f, c, L, dt, C, T, umin, umax, u_exact, user): """Run solver and visualize u at each time level.""" import scitools.std as plt import time, glob, os def plot_u(u, x, t, n): """user_action function for solver.""" u_exact_n = u_exact(x, t[n]) plt.plot(x, u, 'r-', x, u_exact_n, 'b-', xlabel='x', ylabel='u', axis=[0, L, umin, umax], title='t=%f' % t[n], show=True) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.002) plt.savefig('frame_%04d.png' % n) # for movie making def plot_error(u, x, t, n): """user_action function for solver.""" u_exact_n = u_exact(x, t[n]) error = abs(u_exact_n - u) plt.plot(x, error, 'r-', xlabel='x', ylabel='Error', axis=[0, L, umin, umax], title='t=%f' % t[n], show=True) # Let the initial condition stay on the screen for 2 # seconds, else insert a pause of 0.2 s between each plot time.sleep(2) if t[n] == 0 else time.sleep(0.002) plt.savefig('frame_%04d.png' % n) # for movie making def convergence_rate(u, x, t, n): """user_action function for solver.""" u_exact_n = u_exact(x, t[n]) # store error squared at time tn for the whole mesh E2 = sum((u_exact_n - u)**2) outfile.write('%f' % E2 + '\n') if user == 'animate': user_action = plot_u elif user == 'error_plot': user_action = plot_error elif user == 'convergence': user_action = convergence_rate outfile = open('error.dat', 'w') # Clean up old movie frames for filename in glob.glob('frame_*.png'): os.remove(filename) u, x, t, cpu = solver(I, V, f, c, L, dt, C, T, user_action) if user_action == 'animate' or user_action == 'error_plot': # Make movie files fps = 50 # Frames per second plt.movie('frame_*.png', encoder='html', fps=fps, output_file='movie.html') codec2ext = dict(flv='flv', libx264='mp4', libvpx='webm', libtheora='ogg') filespec = 'frame_%04d.png' movie_program = 'avconv' # or 'ffmpeg' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\ '-vcodec %(codec)s movie.%(ext)s' % vars() os.system(cmd) return u, x, t, cpu
# Show the movie, and make hardcopies of frames simulatenously counter = 0 for s in s_values: y = f(x, m, s) plot(x, y, '-', axis=[x[0], x[-1], -0.1, max_f], xlabel='x', ylabel='f', legend='s=%4.2f' % s, savefig='tmp_%04d.png' % counter) counter += 1 #time.sleep(0.2) # can insert a pause to control movie speed if '--no-moviefile' in sys.argv: # Drop making movie files import sys; sys.exit(0) # Make movie file the simplest possible way movie('tmp_*.png') import glob, os print 'generated the file', glob.glob('movie.*')[0] #os.remove(glob.glob('movie.*')[0]) # Make animated GIF movie in the file tmpmovie.gif movie('tmp_*.png', encoder='convert', fps=2, output_file='tmpmovie.gif') # Show movie (os.system runs an operating system command) os.system('animate tmpmovie.gif &') # Other formats # HTML movie('tmp_*.png', encoder='html', fps=3,
import numpy as np from scitools.std import plot, movie import glob import os # Clean up old frames for name in glob.glob('tmp_*.png'): os.remove(name) def wave_packet(x, t): return np.exp(-(x - 3 * t) ** 2) * np.sin(3 * np.pi * (x - t)) x = np.linspace(-10, 10, 1001) counter = 0 for t in np.linspace(-2, 2, 61): y = wave_packet(x, t) plot(x, y, axis=[x[0], x[-1], -1, 1], xlabel='x', ylabel='Amplitude', savefig='tmp_%04d.png' % counter) counter += 1 movie('tmp*.png') # Clean up new frames for name in glob.glob('tmp_*.png'): os.remove(name)
imgplot = plt.imshow(img) if(counter == 0): x, y, c = first_step(everyone) else: x, y, c = one_step(everyone) plt.scatter(x,y, c=c) plt.savefig('moviefiles/tmp%04d.png'% counter) plt.close() for e in everyone: e.update(everyone) counter += 1 savefile = sys.argv[5] sci.movie('moviefiles/tmp*.png',output_file= savefile, fps=6) for filename in glob.glob('moviefiles/tmp*.png'): os.remove(filename) os.system("animate "+savefile) """ fps = 10 sci.movie('moviefiles/tmp*.png', encoder='html', fps=fps, output_file='movie.html') codec2ext = dict(flv='flv', libx64='mp4', libvpx='webm',libtheora='ogg') filespec = 'moviefiles/tmp%04d.png' movie_program = 'avconv' for codec in codec2ext: ext = codec2ext[codec] cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s -vcodec %(codec)s movie.%(ext)s' % vars()
pause_per_frame=0) os.system('convert -delay 20 %s anim.gif' % files) os.system('ffmpeg -i "tmp_frame_%04d.png" -b 800k -r 25 -vcodec mpeg4 -y -qmin 2 -qmax 31 anim.mpeg') try: from scitools.std import movie except ImportError: raise ImportError( 'scitools must be installed for running the "movie" function.\n' 'scitools is installed by sudo apt-get install python-scitools\n' 'on Ubuntu or by sudo python setup.py install if the code is\n' 'downloaded from http://code.google.com/p/scitools.') # HTML page showing individual frames movie(files, encoder='html', fps=4, output_file='anim.html') # Standard GIF file movie(files, encoder='convert', fps=4, output_file='anim2.gif') # AVI format movie('tmp_*.png', encoder='ffmpeg', fps=4, output_file='anim.avi') # requires ffmpeg package # MPEG format movie('tmp_*.png', encoder='ffmpeg', fps=4, output_file='anim3.mpeg', vodec='mpeg2video') # or movie(files, encoder='ppmtompeg', fps=24, output_file='anim2.mpeg') # requires the netpbm package
def points(N): x = [0.5 * cos(2 * pi * i / N) for i in range(N + 1)] y = [0.5 * sin(2 * pi * i / N) for i in range(N + 1)] return x, y def pi_approx(N): x, y = points(N) return pi - pathlength(x, y) circle = points(100000) for N in xrange(4, 100): x, y = points(N) plot(x, y, circle[0], circle[1], title='Error in approximating pi: %8f' % pi_approx(N), xlabel='x', ylabel='y', savefig='tmp_' + 'N=%03d.png' % N, show=False) movie('tmp_*.png', encoder='convert', fps=6, outputfile='pi_polygon_movie.gif') # Remove frames for filename in glob.glob('tmp_*.png'): os.remove(filename)
os.system('convert -delay 20 %s anim.gif' % files) os.system( 'ffmpeg -i "tmp_frame_%04d.png" -b 800k -r 25 -vcodec mpeg4 -y -qmin 2 -qmax 31 anim.mpeg' ) try: from scitools.std import movie except ImportError: raise ImportError( 'scitools must be installed for running the "movie" function.\n' 'scitools is installed by sudo apt-get install python-scitools\n' 'on Ubuntu or by sudo python setup.py install if the code is\n' 'downloaded from http://code.google.com/p/scitools.') # HTML page showing individual frames movie(files, encoder='html', fps=4, output_file='anim.html') # Standard GIF file movie(files, encoder='convert', fps=4, output_file='anim2.gif') # AVI format movie('tmp_*.png', encoder='ffmpeg', fps=4, output_file='anim.avi') # requires ffmpeg package # MPEG format movie('tmp_*.png', encoder='ffmpeg', fps=4, output_file='anim3.mpeg', vodec='mpeg2video') # or
def animate(): movie('figs/*.png', fps=1, output_file='vid.gif') clip = mp.VideoFileClip("vid.gif") clip.write_videofile("vid.mp4")
x_displace = dt * v(t) angle = -x_displace / 2 * R fig['fig']['device']['tire'].rotate(degrees(angle), center=(X[i], H[i])) # vertical vibration Myspring = Spring(start=(X[i], H[i] + R), length=2 + R + u[i], width=R, bar_length=.1, num_windings=6, teeth=True) Myspring.set_linecolor('black') Myspring.draw() sHolder = Rectangle(lower_left_corner=(X[i] - 0.15 * R, H[i] + R), width=.3 * R, height=2 + R + u[i]) sHolder.set_linecolor('black') sHolder.set_filled_curves('black') sHolder.draw() fig['fig']['device']['over'].translate((0, u[i] - u[(i - 1)])) i += 1 animate(fig, tp, Move, moviefiles=True, pause_per_frame=0) from scitools.std import movie movie('tmp_frame_*.png', encoder='html', fps=2, output_file='Movie1.html')
def solve_num(self): Nx = self.Nx Ny = self.Ny Nt = self.Nt I = self.I q = self.q f = self.f dt = self.dt V = self.V b = self.b C_x = self.C_x C_y = self.C_y f_f = self.f_f X = self.X Y = self.Y t = self.t u = zeros((Nx + 2, Ny + 2), float) up = u.copy() upp = up.copy() up[1:-1, 1:-1] = I[1:-1, 1:-1].copy() up[0, :] = up[1, :].copy() up[:, 0] = up[:, 1].copy() up[-1, :] = up[-2, :].copy() up[:, -1] = up[:, -2].copy() #making u^1 for i in xrange(1, Nx + 1): for j in xrange(1, Ny + 1): x_para = ((q[i][j] + q[i + 1][j]) * (up[i + 1][j] - up[i][j]) - (q[i - 1][j] + q[i][j]) * (up[i][j] - up[i - 1][j])) y_para = ((q[i][j] + q[i][j + 1]) * (up[i][j + 1] - up[i][j]) - (q[i][j - 1] + q[i][j]) * (up[i][j] - up[i][j - 1])) rest = f[i][j] + 4 * up[i][j] + 2 * dt * V[i][j] * (b * dt - 2) u[i][j] = 1.0 / (4.0) * (C_x**2 * x_para + C_y**2 * y_para + rest) u[0, :] = u[1, :].copy() u[:, 0] = u[:, 1].copy() u[-1, :] = u[-2, :].copy() u[:, -1] = u[:, -2].copy() #making u^-1 upp = 2 * dt * V + u #vectorized: filename_2 = "num_dt%2.1f.gif" % dt ''' if self.standing: filename_2 = "standing_wave_dt%2.1f.gif"%dt else: ''' for filename in glob.glob('wtmp*.png'): os.remove(filename) for k in xrange(Nt): x_para = (q[1:-1, 1:-1] + q[2:, 1:-1]) * (up[2:, 1:-1] - up[1:-1, 1:-1]) - ( q[:-2, 1:-1] + q[1:-1, 1:-1]) * (up[1:-1, 1:-1] - up[:-2, 1:-1]) y_para = (q[1:-1, 1:-1] + q[1:-1, 2:]) * (up[1:-1, 2:] - up[1:-1, 1:-1]) - ( q[1:-1, :-2] + q[1:-1, 1:-1]) * (up[1:-1, 1:-1] - up[1:-1, :-2]) f = f_f(X, Y, t[k]) rest = f[1:-1, 1:-1] + 4 * up[1:-1, 1:-1] + upp[1:-1, 1:-1] * ( b * dt - 2) u[1:-1, 1:-1] = 1.0 / (2 + b * dt) * (C_x**2 * x_para + C_y**2 * y_para + rest) print(C_x**3) / (2 + b * dt) u[0, :] = u[2, :] u[:, 0] = u[:, 2] u[-1, :] = u[-3, :] u[:, -1] = u[:, -3] if k % 3 == 0: s = mlab.mesh(X, Y, u, color=(0.0, 0.75, 1.0)) mlab.savefig("wtmp%04d.png" % k) mlab.clf() upp = up.copy() up = u.copy() sci.movie("wtmp*.png", encoder='convert', fps=2, output_file=filename_2)
def makemovie(self, navn): sci.movie("%s*.png" % navn, encoder="convert", fps=10, output_file="%s_movie.gif" % navn) for i in glob.glob("%s*.png" % navn): os.remove(i)
import sys,os,glob; from scitools.std import movie; if(len(sys.argv)<3): print "you forgot filename-base as commandline argument, and/or filetype"; else: filenamebase = sys.argv[1]; filetype = sys.argv[2]; movie(filenamebase + "*."+filetype, encoder='convert',fps=4, output_file='movie_'+filenamebase+'.gif'); if(len(sys.argv)==4 and sys.argv[3]=='rm'): for i in glob.glob("%s*.%s"%(filenamebase,filetype)): os.remove(i);
import glob import os import operator def smoothed_Heaviside(x, e=1E-2): cond = operator.and_(-e <= x, x <= e) r = np.zeros(len(x)) r[x < -e] = 0.0 r[cond] = 0.5 + x[cond] / (2 * e) + 1 / (2 * pi) * sin(pi * x[cond] / e) r[x > e] = 1.0 return r x = np.linspace(-2, 2, 2001) counter = 0 for eps in np.linspace(2, 1e-15, 101): y = smoothed_Heaviside(x, eps) plot(x, y, axis=[x[-1], x[0], -1.5, 1.5], xlabel='x', ylabel='Heaviside(x)', savefig='tmp_%04d.png' % counter) counter += 1 movie('tmp_*.png') # Clean up frames for name in glob.glob('tmp_*.png'): os.remove(name)
if '--no-moviefile' in sys.argv: # Drop making movie files import sys sys.exit(0) # Animated GIF cmd = 'convert -delay 50 tmp_*.png movie1.gif' os.system(cmd) # Flash video basic = 'avconv -r 12 -i tmp_%04d.png -c:v ' cmd = basic + 'flv movie1.flv' os.system(cmd) # MP4 video cmd = basic + 'libx264 movie1.mp4' os.system(cmd) # Ogg video cmd = basic + 'libtheora movie1.ogg' os.system(cmd) # WebM video cmd = basic + 'libvpx movie1.webm' os.system(cmd) # HTML (via scitools.easyviz.movie) movie('tmp_*.png', encoder='html', fps=3, output_file='tmpmovie.html') # play in HTML file
h = H[i] x_prev = X[i - 1] h_prev = H[i - 1] # Device movement and Rotation global w_1, i, H, X fig["fig"]["device"].translate((x - x_prev, h - h_prev)) angle = -sqrt((x - x_prev) ** 2 + (h - h_prev) ** 2) / R fig["fig"]["device"]["tire"].rotate(degrees(angle), center=(x, h)) # vertical vibration Myspring = Spring(start=(x, h + R), length=2 + R + u[i], width=R, bar_length=0.1, num_windings=6, teeth=True) Myspring.set_linecolor("black") Myspring.draw() sHolder = Rectangle(lower_left_corner=(x - 0.15 * R, h + R), width=0.3 * R, height=2 + R + u[i]) sHolder.set_linecolor("black") sHolder.set_filled_curves("black") # sHolder.draw() fig["fig"]["device"]["over"].translate((0, u[i] - u[(i - 1)])) i += 1 animate(fig, t[: int(0.9 * len(t))], Move, moviefiles=True, pause_per_frame=1) from scitools.std import movie movie("tmp_frame_*.png", encoder="html", fps=2, output_file="Movie1.html")
for j in xrange(1,Ny): x_para = ((q[i][j] + q[i+1][j])*(up[i+1][j] - up[i][j]) - (q[i-1][j] + q[i][j])*(up[i][j] - up[i-1][j])) y_para = ((q[i][j] + q[i][j+1])*(up[i][j+1] - up[i][j]) - (q[i][j-1] + q[i][j])*(up[i][j] - up[i][j-1])) rest = f0[i][j] + 4*up[i][j] + upp[i][j]*(b*dt-2) u[i][j] = 1.0/(2+b*dt)*(C_x**2*x_para + C_y**2*y_para + rest) u[0,:] = u[1,:] u[:,0] = u[:,1] u[-1,:] = u[-2,:] u[:,-1] = u[:,-2] if k%5 == 0: #f = mlab.figure() #s = mlab.mesh(X,Y,u) s.mlab_source.scalars = u mlab.savefig("wtmp%04d.png" %k) #mlab.clf() #mlab.draw() #print k upp = up.copy() up = u.copy() """ #mlab.show() sci.movie("wtmp*.png", encoder='convert', fps=2, output_file=filename) """ for filename in glob.glob('wtmp*.png'): os.remove(filename) """
return L def points(N): x = [0.5 * cos(2 * pi * i / N) for i in range(N + 1)] y = [0.5 * sin(2 * pi * i / N) for i in range(N + 1)] return x, y def pi_approx(N): x, y = points(N) return pi - pathlength(x, y) circle = points(100000) for N in xrange(4, 100): x, y = points(N) plot(x, y, circle[0], circle[1], title='Error in approximating pi: %8f' % pi_approx(N), xlabel='x', ylabel='y', savefig='tmp_' + 'N=%03d.png' % N, show=False ) movie('tmp_*.png', encoder='convert', fps=6, outputfile='pi_polygon_movie.gif') # Remove frames for filename in glob.glob('tmp_*.png'): os.remove(filename)
fig['vehicle'].translate((L,0)) # move whole figure to start position def v(t): return -8*R*t*(1 - t/(2*R)) import numpy tp = numpy.linspace(0, 2*R, 25) dt = tp[1] - tp[0] # time step def move(t, fig): x_displacement = dt*v(t) fig['vehicle'].translate((x_displacement, 0)) # Rotate wheels global w_1 w_1 += x_displacement # R*angle = -x_displacement angle = - x_displacement/R w1 = fig['vehicle']['wheels']['wheel1'] w1.rotate(degrees(angle), center=(w_1, R)) w2 = fig['vehicle']['wheels']['wheel2'] w2.rotate(degrees(angle), center=(w_1 + L, R)) files = animate(fig, tp, move, moviefiles=True, pause_per_frame=0) from scitools.std import movie movie(files, encoder='html', output_file='anim') raw_input()
from scitools.std import movie movie("./movie_frames/*.png", fps=25, output_file="./movie.gif")
x = 5.0 drawing_tool.set_coordinate_system( xmin=-3, xmax=10, ymin=-2, ymax=7*H, axis=False, new_figure=True) rpos = Force((0,-0.5), (x, h(x)-0.15), '$\\boldsymbol{r_0}$', text_spacing=1./60, text_pos='start').set_linecolor('black') fig = Composition({'road': road, 'r': rpos, 'vehicle': draw_vehicle(x, h(x), x, h(x), 0)}) fig.draw() drawing_tool.display() drawing_tool.savefig('tmp_bumpy') sys.exit(0) drawing_tool.earse() fig = Composition({'road': road, 'solution': u_solution, 'vehicle': draw_vehicle(0, h(0), 0, h(0), 0)}) show = True try: if sys.argv[1] == 'batch': show = False except: pass title = 'm=%g, b=%g, k=%g' % (m, b, k) animate(fig, t[:int(0.9*len(t))], move, moviefiles=True, pause_per_frame=0.2, show_screen_graphics=show, title=title) from scitools.std import movie movie('tmp_frame_*.png',encoder='html',fps=2,output_file='index.html')
y, axis=[x[0], x[-1], -0.1, max_f], xlabel='x', ylabel='f', legend='s=%4.2f' % s, savefig='tmp_%04d.png' % counter) counter += 1 #time.sleep(0.2) # can insert a pause to control movie speed if '--no-moviefile' in sys.argv: # Drop making movie files import sys sys.exit(0) # Make movie file the simplest possible way movie('tmp_*.png') import glob, os print 'generated the file', glob.glob('movie.*')[0] #os.remove(glob.glob('movie.*')[0]) # Make animated GIF movie in the file tmpmovie.gif movie('tmp_*.png', encoder='convert', fps=2, output_file='tmpmovie.gif') # Show movie (os.system runs an operating system command) os.system('animate tmpmovie.gif &') # Other formats # HTML movie('tmp_*.png', encoder='html', fps=3,
k = 1E-6 # thermal diffusivity (in m**2/s) A1 = 15 # amplitude of the daily temperature variations (in C) P1 = 24 * 60 * 60. # oscillation period of 24 h (in seconds) omega1 = 2 * pi / P1 # angular freq of daily temp variations (in rad/s) a1 = sqrt(omega1 / (2 * k)) A2 = 7 # amplitude of yearly temperature variations (in C) P2 = 24 * 60 * 60 * 365. # oscillation period of 1 yr (in seconds) omega2 = 2 * pi / P2 # angular freq of yearly temp variations (in rad/s) a2 = sqrt(omega2 / (2 * k)) dt = P2 / 20 # time lag: 0.1 yr tmax = 3 * P2 # 3 year simulation T0 = 10 # mean surface temperature in Celsius D = -(1 / a1) * log(0.001) # max depth n = 501 # no of points in the z direction # set T0, A, k, omega, D, n, tmax, dt z = linspace(0, D, n) animate(tmax, dt, z, T, T0 - A2 - A1, T0 + A2 + A1, 0, 'z', 'T') movie('tmp_*.png', encoder='convert', fps=6, outputfile='tmp_heatwave.gif') import glob import os # Remove frames for filename in glob.glob('tmp_*.png'): os.remove(filename)
import operator def smoothed_Heaviside(x, e=1E-2): cond = operator.and_(-e <= x, x <= e) r = np.zeros(len(x)) r[x < -e] = 0.0 r[cond] = 0.5 + x[cond] / (2 * e) + 1 / (2 * pi) * sin(pi * x[cond] / e) r[x > e] = 1.0 return r x = np.linspace(-2, 2, 2001) counter = 0 for eps in np.linspace(2, 1e-15, 101): y = smoothed_Heaviside(x, eps) plot(x, y, axis=[x[-1], x[0], -1.5, 1.5], xlabel='x', ylabel='Heaviside(x)', savefig='tmp_%04d.png' % counter) counter += 1 movie('tmp_*.png') # Clean up frames for name in glob.glob('tmp_*.png'): os.remove(name)
def make_gif(frame_loc, frames_per_sec=1, output_file_loc="my_gif.gif"): movie(frame_loc + "/frame_*.jpg", fps=frames_per_sec, output_file=output_file_loc)
s = np.zeros(len(t)) for i in range(1, n + 1): s += 1.0 / (2 * i - 1) * np.sin(2 * (2 * i - 1) * np.pi * t / T) s *= 4 / np.pi return s def f(t, T): cond1 = operator.and_(0 <= t, t < T / 2.) cond2 = abs(t - T / 2.) < 1E-16 cond3 = operator.and_(T / 2. < t, t <= T) cond4 = operator.and_(t < 0, t > T) r = np.zeros(len(t)) r[cond1] = 1 r[cond2] = 0 r[cond3] = -1 r[cond4] = 111 # Error code if len(r[r == 111]) > 0: print 'Error: t must be between 0 and T' r = None return r animate_series(S, 50, 20, 1001, f, 'f(t)') movie('tmp_*.png', encoder='convert', fps=3) import glob import os # Remove old plot files for filename in glob.glob('tmp_*.png'): os.remove(filename)
dt = tp[1] - tp[0] # time step def move(t, fig): x_displacement = dt*v(t) fig['vehicle'].translate((x_displacement, 0)) # Rotate wheels global w_1 w_1 += x_displacement # R*angle = -x_displacement angle = - x_displacement/R w1 = fig['vehicle']['wheels']['wheel1'] w1.rotate(degrees(angle), center=(w_1, R)) w2 = fig['vehicle']['wheels']['wheel2'] w2.rotate(degrees(angle), center=(w_1 + L, R)) files = animate(fig, tp, move, moviefiles=True, pause_per_frame=0) files_wildcard = files.split('%')[0] + '*.png' os.system('convert -delay 20 %s* vehicle1.gif' % (files_wildcard)) os.system('avconv -r 12 -i %s -c:v flv vehicle1.flv' % files) os.system('avconv -r 12 -i %s -c:v libvpx vehicle1.webm' % files) os.system('avconv -r 12 -i %s -c:v libtheora vehicle1.ogg' % files) os.system('avconv -r 12 -i %s -c:v flv vehicle1.flv' % files) os.system('avconv -r 12 -i %s -c:v libx264 -s:v 1000x520 vehicle1.mp4' % files) from scitools.std import movie movie(files_wildcard, encoder='html', output_file='vehicle1') raw_input()