def comparison_plot(f, u, Omega, filename='tmp.pdf', plot_title='', ymin=None, ymax=None, u_legend='approximation'): """Compare f(x) and u(x) for x in Omega in a plot.""" x = sm.Symbol('x') print 'f:', f f = sm.lambdify([x], f, modules="numpy") u = sm.lambdify([x], u, modules="numpy") if len(Omega) != 2: raise ValueError('Omega=%s must be an interval (2-list)' % str(Omega)) # When doing symbolics, Omega can easily contain symbolic expressions, # assume .evalf() will work in that case to obtain numerical # expressions, which then must be converted to float before calling # linspace below if not isinstance(Omega[0], (int,float)): Omega[0] = float(Omega[0].evalf()) if not isinstance(Omega[1], (int,float)): Omega[1] = float(Omega[1].evalf()) resolution = 401 # no of points in plot xcoor = linspace(Omega[0], Omega[1], resolution) # Vectorized functions expressions does not work with # lambdify'ed functions without the modules="numpy" exact = f(xcoor) approx = u(xcoor) plot(xcoor, approx, '-') hold('on') plot(xcoor, exact, '-') legend([u_legend, 'exact']) title(plot_title) xlabel('x') if ymin is not None and ymax is not None: axis([xcoor[0], xcoor[-1], ymin, ymax]) savefig(filename)
def run_solvers_and_check_amplitudes(solvers, timesteps_per_period=20, num_periods=1, I=1, w=2 * np.pi): P = 2 * np.pi / w # duration of one period dt = P / timesteps_per_period Nt = num_periods * timesteps_per_period T = Nt * dt t_mesh = np.linspace(0, T, Nt + 1) file_name = 'Amplitudes' # initialize filename for plot for solver in solvers: solver.set(f_kwargs={'w': w}) solver.set_initial_condition([0, I]) u, t = solver.solve(t_mesh) solver_name = \ 'CrankNicolson' if solver.__class__.__name__ == \ 'MidpointImplicit' else solver.__class__.__name__ file_name = file_name + '_' + solver_name minima, maxima = minmax(t, u[:, 0]) a = amplitudes(minima, maxima) plt.plot(range(len(a)), a, '-', label=solver_name) plt.hold('on') plt.xlabel('Number of periods') plt.ylabel('Amplitude (absolute value)') plt.legend(loc='upper left') plt.savefig(file_name + '.png') plt.savefig(file_name + '.pdf') plt.show()
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
def visualize_front(u, t, I, w, savefig=False): """ Visualize u and the exact solution vs t, using a moving plot window and continuous drawing of the curves as they evolve in time. Makes it easy to plot very long time series. """ import scitools.std as st from scitools.MovingPlotWindow import MovingPlotWindow P = 2*pi/w # one period umin = -1.2*I; umax = -umin plot_manager = MovingPlotWindow( window_width=8*P, dt=t[1]-t[0], yaxis=[umin, umax], mode='continuous drawing') for n in range(1,len(u)): if plot_manager.plot(n): s = plot_manager.first_index_in_plot st.plot(t[s:n+1], u[s:n+1], 'r-1', t[s:n+1], I*cos(w*t)[s:n+1], 'b-1', title='t=%6.3f' % t[n], axis=plot_manager.axis(), show=not savefig) # drop window if savefig if savefig: st.savefig('tmp_vib%04d.png' % n) plot_manager.update(n)
def run_solvers_and_plot(solvers, rhs, T, dt, title=''): Nt = int(round(T/float(dt))) t_mesh = np.linspace(0, T, Nt+1) t_fine = np.linspace(0, T, 8*Nt+1) # used for very accurate solution legends = [] solver_exact = odespy.RK4(rhs) for solver in solvers: solver.set_initial_condition([rhs.I, 0]) u, t = solver.solve(t_mesh) solver_name = 'CrankNicolson' if solver.__class__.__name__ == \ 'MidpointImplicit' else solver.__class__.__name__ if len(t_mesh) <= 50: plt.plot(t, u[:,0]) # markers by default else: plt.plot(t, u[:,0], '-2') # no markers plt.hold('on') legends.append(solver_name) # Compare with RK4 on a much finer mesh solver_exact.set_initial_condition([rhs.I, 0]) u_e, t_e = solver_exact.solve(t_fine) plt.plot(t_e, u_e[:,0], '-') # avoid markers by spec. line type legends.append('exact (RK4, dt=%g)' % (t_fine[1]-t_fine[0])) plt.legend(legends, loc='upper right') plt.xlabel('t'); plt.ylabel('u') plt.title(title) plotfilestem = '_'.join(legends) plt.savefig('tmp_%s.png' % plotfilestem) plt.savefig('tmp_%s.pdf' % plotfilestem)
def approximate(f, symbolic=False, d=1, N_e=4, Omega=[0, 1], filename='tmp'): phi = basis(d) print 'phi basis (reference element):\n', phi nodes, elements = mesh_uniform(N_e, d, Omega, symbolic) A, b = assemble(nodes, elements, phi, f, symbolic=symbolic) print 'nodes:', nodes print 'elements:', elements print 'A:\n', A print 'b:\n', b print sp.latex(A, mode='plain') #print sp.latex(b, mode='plain') if symbolic: c = A.LUsolve(b) else: c = np.linalg.solve(A, b) print 'c:\n', c print 'Plain interpolation/collocation:' x = sp.Symbol('x') f = sp.lambdify([x], f, modules='numpy') try: f_at_nodes = [f(xc) for xc in nodes] except NameError as e: raise NameError('numpy does not support special function:\n%s' % e) print f_at_nodes if not symbolic and filename is not None: xf = np.linspace(Omega[0], Omega[1], 10001) U = np.asarray(c) xu, u = u_glob(U, elements, nodes) plt.plot(xu, u, '-', xf, f(xf), '--') plt.legend(['u', 'f']) plt.savefig(filename + '.pdf') plt.savefig(filename + '.png')
def non_physical_behavior(I, a, T, dt, theta): """ Given lists/arrays a and dt, and numbers I, dt, and theta, make a two-dimensional contour line B=0.5, where B=1>0.5 means oscillatory (unstable) solution, and B=0<0.5 means monotone solution of u'=-au. """ a = np.asarray(a) dt = np.asarray(dt) # must be arrays B = np.zeros((len(a), len(dt))) # results for i in range(len(a)): for j in range(len(dt)): u, t = solver(I, a[i], T, dt[j], theta) # Does u have the right monotone decay properties? correct_qualitative_behavior = True for n in range(1, len(u)): if u[n] > u[n - 1]: # Not decaying? correct_qualitative_behavior = False break # Jump out of loop B[i, j] = float(correct_qualitative_behavior) a_, dt_ = st.ndgrid(a, dt) # make mesh of a and dt values st.contour(a_, dt_, B, 1) st.grid('on') st.title('theta=%g' % theta) st.xlabel('a') st.ylabel('dt') st.savefig('osc_region_theta_%s.png' % theta) st.savefig('osc_region_theta_%s.eps' % theta)
def __call__(self, u, x, t, n): """user_action function for solver.""" if animate == 'u and u_exact': plt.plot(x, u, 'r-', x, u_exact(x, t[n]), 'b--', xlabel='x', ylabel='u', axis=[0, L, -self.ymax, self.ymax], title='t=%f' % t[n], show=True) else: error = u_exact(x, t[n]) - u local_max_error = np.abs(error).max() # self.max_error holds the increasing amplitude error if self.max_error == [] or \ local_max_error > max(self.max_error): self.max_error.append(local_max_error) self.max_error_t.append(t[n]) # Use user's ymax until the error exceeds that value. # This gives a growing max value of the yaxis (but # never shrinking) self.ymax = max(self.ymax, max(self.max_error)) plt.plot(x, error, 'r-', xlabel='x', ylabel='error', axis=[0, L, -self.ymax, self.ymax], title='t=%f' % t[n], show=True) plt.savefig('%s_%04d.png' % (self.frame_name, n))
def visualize_front(u, t, I, w, savefig=False): """ Visualize u and the exact solution vs t, using a moving plot window and continuous drawing of the curves as they evolve in time. Makes it easy to plot very long time series. """ import scitools.std as st from scitools.MovingPlotWindow import MovingPlotWindow P = 2 * pi / w # one period umin = 1.2 * u.min() umax = -umin plot_manager = MovingPlotWindow(window_width=8 * P, dt=t[1] - t[0], yaxis=[umin, umax], mode='continuous drawing') for n in range(1, len(u)): if plot_manager.plot(n): s = plot_manager.first_index_in_plot st.plot(t[s:n + 1], u[s:n + 1], 'r-1', t[s:n + 1], I * cos(w * t)[s:n + 1], 'b-1', title='t=%6.3f' % t[n], axis=plot_manager.axis(), show=not savefig) # drop window if savefig if savefig: filename = 'tmp_vib%04d.png' % n st.savefig(filename) print 'making plot file', filename, 'at t=%g' % t[n] plot_manager.update(n)
def visualize_front(u, t, window_width, savefig=False): """ Visualize u and the exact solution vs t, using a moving plot window and continuous drawing of the curves as they evolve in time. Makes it easy to plot very long time series. P is the approximate duration of one period. """ import scitools.std as st from scitools.MovingPlotWindow import MovingPlotWindow umin = 1.2*u.min(); umax = -umin plot_manager = MovingPlotWindow( window_width=window_width, tau=t[1]-t[0], yaxis=[umin, umax], mode='continuous drawing') for n in range(1,len(u)): if plot_manager.plot(n): s = plot_manager.first_index_in_plot st.plot(t[s:n+1], u[s:n+1], 'r-1', title='t=%6.3f' % t[n], axis=plot_manager.axis(), show=not savefig) # drop window if savefig if savefig: print 't=%g' % t[n] st.savefig('tmp_vib%04d.png' % n) plot_manager.update(n)
def run_solvers_and_check_amplitudes(solvers, timesteps_per_period=20, num_periods=1, I=1, w=2*np.pi): P = 2*np.pi/w # duration of one period dt = P/timesteps_per_period Nt = num_periods*timesteps_per_period T = Nt*dt t_mesh = np.linspace(0, T, Nt+1) file_name = 'Amplitudes' # initialize filename for plot for solver in solvers: solver.set(f_kwargs={'w': w}) solver.set_initial_condition([0, I]) u, t = solver.solve(t_mesh) solver_name = \ 'CrankNicolson' if solver.__class__.__name__ == \ 'MidpointImplicit' else solver.__class__.__name__ file_name = file_name + '_' + solver_name minima, maxima = minmax(t, u[:,0]) a = amplitudes(minima, maxima) plt.plot(range(len(a)), a, '-', label=solver_name) plt.hold('on') plt.xlabel('Number of periods') plt.ylabel('Amplitude (absolute value)') plt.legend(loc='upper left') plt.savefig(file_name + '.png') plt.savefig(file_name + '.pdf') plt.show()
def demo(): """ Demonstrate difference between Euler-Cromer and the scheme for the corresponding 2nd-order ODE. """ I = 1.2 w = 2.0 T = 5 dt = 2 / w # longest possible time step from vib_undamped import solver as solver2 # 2nd-order ODE import scitools.std as plt for k in range(4): dt /= 4 u2, t2 = solver2(I, w, dt, T) u, v, t = solver(I, w, dt, T) plt.figure() plt.plot(t, u, t2, u2, legend=('Euler-Cromer', 'center scheme for $u' '+u=0$'), title='dt=%.3g' % dt) raw_input() plt.savefig('ECvs2nd_%d' % k + '.png') plt.savefig('ECvs2nd_%d' % k + '.pdf')
def demo(): """ Demonstrate difference between Euler-Cromer and the scheme for the corresponding 2nd-order ODE. """ I = 1.2 V = 0.2 m = 4 b = 0.2 s = lambda u: 2 * u F = lambda t: 0 w = np.sqrt(2. / 4) # approx freq dt = 0.9 * 2 / w # longest possible time step w = 0.5 P = 2 * pi / w T = 4 * P from vib import solver as solver2 import scitools.std as plt for k in range(4): u2, t2 = solver2(I, V, m, b, s, F, dt, T, 'quadratic') u, v, t = solver(I, V, m, b, s, F, dt, T, 'quadratic') plt.figure() plt.plot(t, u, 'r-', t2, u2, 'b-') plt.legend(['Euler-Cromer', 'centered scheme']) plt.title('dt=%.3g' % dt) raw_input() plt.savefig('tmp_%d' % k + '.png') plt.savefig('tmp_%d' % k + '.pdf') dt /= 2
def non_physical_behavior(I, a, T, dt, theta): """ Given lists/arrays a and dt, and numbers I, dt, and theta, make a two-dimensional contour line B=0.5, where B=1>0.5 means oscillatory (unstable) solution, and B=0<0.5 means monotone solution of u'=-au. """ a = np.asarray(a); dt = np.asarray(dt) # must be arrays B = np.zeros((len(a), len(dt))) # results for i in range(len(a)): for j in range(len(dt)): u, t = solver(I, a[i], T, dt[j], theta) # Does u have the right monotone decay properties? correct_qualitative_behavior = True for n in range(1, len(u)): if u[n] > u[n-1]: # Not decaying? correct_qualitative_behavior = False break # Jump out of loop B[i,j] = float(correct_qualitative_behavior) a_, dt_ = st.ndgrid(a, dt) # make mesh of a and dt values st.contour(a_, dt_, B, 1) st.grid('on') st.title('theta=%g' % theta) st.xlabel('a'); st.ylabel('dt') st.savefig('osc_region_theta_%s.png' % theta) st.savefig('osc_region_theta_%s.pdf' % theta)
def demo(): """ Demonstrate difference between Euler-Cromer and the scheme for the corresponding 2nd-order ODE. """ I = 1.2 V = 0.2 m = 4 b = 0.2 s = lambda u: 2 * u F = lambda t: 0 w = np.sqrt(2.0 / 4) # approx freq dt = 0.9 * 2 / w # longest possible time step w = 0.5 P = 2 * pi / w T = 4 * P from vib import solver as solver2 import scitools.std as plt for k in range(4): u2, t2 = solver2(I, V, m, b, s, F, dt, T, "quadratic") u, v, t = solver(I, V, m, b, s, F, dt, T, "quadratic") plt.figure() plt.plot(t, u, "r-", t2, u2, "b-") plt.legend(["Euler-Cromer", "centered scheme"]) plt.title("dt=%.3g" % dt) raw_input() plt.savefig("tmp_%d" % k + ".png") plt.savefig("tmp_%d" % k + ".pdf") dt /= 2
def visualize_front(u, t, window_width, savefig=False): """ Visualize u and the exact solution vs t, using a moving plot window and continuous drawing of the curves as they evolve in time. Makes it easy to plot very long time series. P is the approximate duration of one period. """ import scitools.std as st from scitools.MovingPlotWindow import MovingPlotWindow umin = 1.2 * u.min() umax = -umin plot_manager = MovingPlotWindow(window_width=window_width, dt=t[1] - t[0], yaxis=[umin, umax], mode='continuous drawing') for n in range(1, len(u)): if plot_manager.plot(n): s = plot_manager.first_index_in_plot st.plot(t[s:n + 1], u[s:n + 1], 'r-1', title='t=%6.3f' % t[n], axis=plot_manager.axis(), show=not savefig) # drop window if savefig if savefig: print 't=%g' % t[n] st.savefig('tmp_vib%04d.png' % n) plot_manager.update(n)
def plot(self, include_exact=True, plt=None): """ Add solver.u curve to the plotting object plt, and include the exact solution if include_exact is True. This plot function can be called several times (if the solver object has computed new solutions). """ if plt is None: import scitools.std as plt # can use matplotlib as well plt.plot(self.solver.t, self.solver.u, '--o') plt.hold('on') theta2name = {0: 'FE', 1: 'BE', 0.5: 'CN'} name = theta2name.get(self.solver.theta, '') legends = ['numerical %s' % name] if include_exact: t_e = linspace(0, self.problem.T, 1001) u_e = self.problem.exact_solution(t_e) plt.plot(t_e, u_e, 'b-') legends.append('exact') plt.legend(legends) plt.xlabel('t') plt.ylabel('u') plt.title('theta=%g, dt=%g' % (self.solver.theta, self.solver.dt)) plt.savefig('%s_%g.png' % (name, self.solver.dt)) return plt
def a(N): def psi(x, i): #return sin((i+1)*x) return sin((2 * i + 1) * x) #return sin((2*(i+1))*x) u, c = least_squares_numerical( f, psi, N, x, #integration_method='trapezoidal', integration_method='scipy', orthogonal_basis=True) os.system('rm -f *.png') u_sum = 0 print 'XXX c', c for i in range(N + 1): u_sum = u_sum + c[i] * psi(x, i) plt.plot(x, f(x), '-', x, u_sum, '-', legend=['exact', 'approx'], title='Highest frequency component: sin(%d*x)' % (2 * i + 1), axis=[x[0], x[-1], -1.5, 1.5]) plt.savefig('tmp_frame%04d.png' % i) time.sleep(0.3) cmd = 'avconv -r 2 -i tmp_frame%04d.png -vcodec libtheora movie.ogg'
def run_solvers_and_plot(solvers, rhs, T, dt, title=''): Nt = int(round(T / float(dt))) t_mesh = np.linspace(0, T, Nt + 1) t_fine = np.linspace(0, T, 8 * Nt + 1) # used for very accurate solution legends = [] solver_exact = odespy.RK4(rhs) for solver in solvers: solver.set_initial_condition([rhs.I, 0]) u, t = solver.solve(t_mesh) solver_name = 'CrankNicolson' if solver.__class__.__name__ == \ 'MidpointImplicit' else solver.__class__.__name__ if len(t_mesh) <= 50: plt.plot(t, u[:, 0]) # markers by default else: plt.plot(t, u[:, 0], '-2') # no markers plt.hold('on') legends.append(solver_name) # Compare with RK4 on a much finer mesh solver_exact.set_initial_condition([rhs.I, 0]) u_e, t_e = solver_exact.solve(t_fine) plt.plot(t_e, u_e[:, 0], '-') # avoid markers by spec. line type legends.append('exact (RK4, dt=%g)' % (t_fine[1] - t_fine[0])) plt.legend(legends, loc='upper right') plt.xlabel('t') plt.ylabel('u') plt.title(title) plotfilestem = '_'.join(legends) plt.savefig('tmp_%s.png' % plotfilestem) plt.savefig('tmp_%s.pdf' % plotfilestem)
def plot_u(u, x, xv, y, yv, t, n): if t[n] == 0: time.sleep(1) st.plot(x, u[:,1],'--',x, u_exact(x, t[n], a, Lx),'o') filename = 'tmp_%04d.png' % n st.savefig(filename) time.sleep(0.1)
def comparison_plot(u, Omega, u_e=None, filename='tmp.eps', plot_title='', ymin=None, ymax=None): x = sp.Symbol('x') u = sp.lambdify([x], u, modules="numpy") if len(Omega) != 2: raise ValueError('Omega=%s must be an interval (2-list)' % str(Omega)) # When doing symbolics, Omega can easily contain symbolic expressions, # assume .evalf() will work in that case to obtain numerical # expressions, which then must be converted to float before calling # linspace below if not isinstance(Omega[0], (int,float)): Omega[0] = float(Omega[0].evalf()) if not isinstance(Omega[1], (int,float)): Omega[1] = float(Omega[1].evalf()) resolution = 401 # no of points in plot xcoor = linspace(Omega[0], Omega[1], resolution) # Vectorized functions expressions does not work with # lambdify'ed functions without the modules="numpy" approx = u(xcoor) plot(xcoor, approx) legends = ['approximation'] if u_e is not None: exact = u_e(xcoor) hold('on') plot(xcoor, exact) legends = ['exact'] legend(legends) title(plot_title) xlabel('x') if ymin is not None and ymax is not None: axis([xcoor[0], xcoor[-1], ymin, ymax]) savefig(filename)
def plot(self, include_exact=True, plt=None): """ Add solver.u curve to scitools plotting object plt, and include the exact solution if include_exact is True. This plot function can be called several times (if the solver object has computed new solutions). """ if plt is None: import scitools.std as plt plt.plot(self.solver.t, self.solver.u, '--o') plt.hold('on') theta = self.solver.get('theta') theta2name = {0: 'FE', 1: 'BE', 0.5: 'CN'} name = theta2name.get(theta, '') legends = ['numerical %s' % name] if include_exact: t_e = np.linspace(0, self.problem.get('T'), 1001) u_e = self.problem.exact_solution(t_e) plt.plot(t_e, u_e, 'b-') legends.append('exact') plt.legend(legends) plt.xlabel('t') plt.ylabel('u') dt = self.solver.get('dt') plt.title('theta=%g, dt=%g' % (theta, dt)) plt.savefig('%s_%g.png' % (name, dt)) return plt
def plot_u(u, x, xv, y, yv, t, n): """User action function for plotting.""" if t[n] == 0: time.sleep(2) if plot_method == 1: # Works well with Gnuplot backend, not with Matplotlib st.mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1], caxis=[-1,1]) elif plot_method == 2: # Works well with Gnuplot backend, not with Matplotlib st.surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1], colorbar=True, colormap=st.hot(), caxis=[-1,1], shading='flat') elif plot_method == 3: print 'Experimental 3D matplotlib...under development...' # Probably too slow #plt.clf() ax = fig.add_subplot(111, projection='3d') u_surf = ax.plot_surface(xv, yv, u, alpha=0.3) #ax.contourf(xv, yv, u, zdir='z', offset=-100, cmap=cm.coolwarm) #ax.set_zlim(-1, 1) # Remove old surface before drawing if u_surf is not None: ax.collections.remove(u_surf) plt.draw() time.sleep(1) elif plot_method == 4: # Mayavi visualization mlab.clf() extent1 = (0, 20, 0, 20,-2, 2) s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1) mlab.axes(s, color=(.7, .7, .7), extent=extent1, ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='', zlabel='', x_axis_visibility=False, z_axis_visibility=False) mlab.outline(s, color=(0.7, .7, .7), extent=extent1) mlab.text(6, -2.5, '', z=-4, width=0.14) mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None) mlab.title('Gaussian t=%g' % t[n]) mlab.view(142, -72, 50) f = mlab.gcf() camera = f.scene.camera camera.yaw(0) if plot_method > 0: time.sleep(0) # pause between frames if save_plot: filename = 'tmp_%04d.png' % n if plot_method == 4: mlab.savefig(filename) # time consuming! elif plot_method in (1,2): st.savefig(filename) # time consuming!
def plot_u(u, x, xv, y, yv, t, n): if t[n] == 0: time.sleep(1) #mesh(x, y, u, title='t=%g' % t[n]) st.plot(y, u[1,:], title='t=%g' % t[n], ylim=[-2.4, 2.4]) filename = 'tmp_%04d.png' % n st.savefig(filename) time.sleep(0.4)
def plot_u(u, x, t, n): plt.plot(x, u, 'r-', axis=[0, L, umin, umax], title='t=%f' % t[n]) if framefiles: plt.savefig('tmp_frame%04d.png' % n) if t[n] == 0: time.sleep(2) elif not framefiles: # It takes time to write files so pause is needed # for screen only animation time.sleep(0.2)
def plot_u(u, x, t, n): plt.plot(x, u, "r-", axis=[0, L, umin, umax], title="t=%f" % t[n]) if framefiles: plt.savefig("tmp_frame%04d.png" % n) if t[n] == 0: time.sleep(2) elif not framefiles: # It takes time to write files so pause is needed # for screen only animation time.sleep(0.2)
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
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
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
def plot(self, plt = None): if plt is None: import scitools.std as plt plt.plot(self.solver.t, self.solver.v, 'b--o') plt.hold("on") plt.xlabel("t") plt.ylabel("v") plt.savefig("%g.png" % (self.solver.dt)) return plt
def visualize(u, t, title='', filename='tmp'): plt.plot(t, u, 'b-') plt.xlabel('t') plt.ylabel('u') dt = t[1] - t[0] plt.title('dt=%g' % dt) umin = 1.2*u.min(); umax = 1.2*u.max() plt.axis([t[0], t[-1], umin, umax]) plt.title(title) plt.savefig(filename + '.png') plt.savefig(filename + '.pdf') plt.show()
def plot_u(u, x, xv, y, yv, t, n): if t[n] == 0: time.sleep(1) #mesh(x, y, u, title='t=%g' % t[n]) #st.plot(x, u[:,1], 'o', '-', title='t=%g' % t[n], ylim=[-2.4, 2.4]) #st.plot(x, u_exact(x, t[n], a, Lx), 'o', ylim=[-2.4, 2.4]) st.plot(y, u[1,:],'--',y, u_exact(y, t[n], a, Ly),'o') #plt.plot(x, u_exact(x, t[n], a, Lx)) #plt.show() filename = 'tmp_%04d.png' % n st.savefig(filename) time.sleep(0.1)
def plot_phase_error(): w = 1 # relevant value in a scaled problem m = linspace(1, 101, 101) period = 2*pi/w dt_values = [period/num_timesteps_per_period for num_timesteps_per_period in (4, 8, 16, 32)] for dt in dt_values: e = m*2*pi*(1./w - 1/tilde_w(w, dt)) plot(m, e, '-', title='peak location error (phase error)', xlabel='no of periods', ylabel='phase error') hold('on') savefig('phase_error.png')
def demo_circular(): # Mass B is at rest at the origin, # mass A is at (1, 0) with vel. (0, 1) ic = [1, 0, 0, 1, 0, 0, 0, 0] x_A, x_B, y_A, y_B, t = solver( alpha=0.001, ic=ic, T=2*np.pi, dt=0.01) plt.plot(x_A, x_B, 'r2-', y_A, y_B, 'b2-', legend=['A', 'B'], daspectmode='equal') # x and y axis have same scaling plt.savefig('tmp_circular.png') plt.savefig('tmp_circular.pdf') plt.show()
def visualize(list_of_curves, legends, title='', filename='tmp'): """Plot list of curves: (u, t).""" for u, t in list_of_curves: plt.plot(t, u) plt.hold('on') plt.legend(legends) plt.xlabel('t') plt.ylabel('u') plt.title(title) plt.savefig(filename + '.png') plt.savefig(filename + '.pdf') plt.show()
def plot(self, plt=None): if plt is None: import scitools.std as plt plt.plot(self.solver.t, self.solver.v, 'b--o') plt.hold("on") plt.xlabel("t") plt.ylabel("v") plt.savefig("%g.png" % (self.solver.dt)) return plt
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 fe_basis_function_figure(d, target_elm=[1], N_e=3, derivative=0, filename='tmp.pdf', labels=False): """ Draw all basis functions (or their derivative), of degree d, associated with element target_elm (may be list of elements). Add a mesh with N_e elements. """ nodes, elements = mesh_uniform(N_e, d) """ x = 1.1 print locate_element_vectorized(x, elements, nodes) print locate_element_scalar(x, elements, nodes) x = 0.1, 0.4, 0.8 print locate_element_vectorized(x, elements, nodes) """ if isinstance(target_elm, int): target_elm = [target_elm] # wrap in list # Draw the basis functions for element 1 phi_drawn = [] # list of already drawn phi functions ymin = ymax = 0 for e in target_elm: for i in elements[e]: if not i in phi_drawn: x, y = phi_glob(i, elements, nodes, derivative=derivative) if x is None and y is None: return # abort ymax = max(ymax, max(y)) ymin = min(ymin, min(y)) plt.plot(x, y, '-') plt.hold('on') if labels: if plt.backend == 'gnuplot': if derivative == 0: plt.legend(r'basis func. %d' % i) else: plt.legend(r'derivative of basis func. %d' % i) elif plt.backend == 'matplotlib': if derivative == 0: plt.legend(r'\varphi_%d' % i) else: plt.legend(r"\varphi_%d'(x)" % i) phi_drawn.append(i) plt.axis([nodes[0], nodes[-1], ymin - 0.1, ymax + 0.1]) plot_fe_mesh(nodes, elements, element_marker=[ymin - 0.1, ymax + 0.1]) plt.hold('off') plt.savefig(filename)
def visualize(u, t, title="", filename="tmp"): plt.plot(t, u, "b-") plt.xlabel("t") plt.ylabel("u") dt = t[1] - t[0] plt.title("dt=%g" % dt) umin = 1.2 * u.min() umax = 1.2 * u.max() plt.axis([t[0], t[-1], umin, umax]) plt.title(title) plt.savefig(filename + ".png") plt.savefig(filename + ".pdf") plt.show()
def comparison_plot(f, u, Omega, filename='tmp.pdf'): x = sm.Symbol('x') f = sm.lambdify([x], f, modules="numpy") u = sm.lambdify([x], u, modules="numpy") resolution = 401 # no of points in plot xcoor = linspace(Omega[0], Omega[1], resolution) exact = f(xcoor) approx = u(xcoor) plot(xcoor, approx) hold('on') plot(xcoor, exact) legend(['approximation', 'exact']) savefig(filename)
def plot_u(u, x, xv, y, yv, t, n): b_a = zeros((xv.shape[0],yv.shape[1])) b_a[:,:] = bottom(xv, yv) st.plot(xv[:,0], u[:,0], '-', xv[:,0], b_a[:,0], '--', ylim=[zmin, zmax]) #show() #hold('on') #axis([0.0,400.0,0.0,430.0,-500.0,300.0]) #show() #time.sleep(5.0) filename = 'tmp_1d_box_slit%04d.png' % n st.savefig(filename)
def __call__(self, u, x, t, n): from scitools.std import plot, savefig umin = -0.1 umax = 1.1 # axis limits for plotting title = 'Method: %s, C=%g, t=%f' % \ (theta2name[self.theta], self.C, t[n]) plot(x, u, 'r-', axis=[0, self.L, umin, umax], title=title) savefig(os.path.join(self.plotdir, 'frame_%04d.png' % n)) # Pause the animation initially, otherwise 0.2 s between frames if n == 0: time.sleep(2) else: time.sleep(0.2)
def u_P1(): """ Plot P1 basis functions and a resulting u to illustrate what it means to use finite elements. """ import matplotlib.pyplot as plt x = [0, 1.5, 2.5, 3.5, 4] phi = [np.zeros(len(x)) for i in range(len(x)-2)] for i in range(len(phi)): phi[i][i+1] = 1 #u = 5*x*np.exp(-0.25*x**2)*(4-x) u = [0, 8, 5, 4, 0] for i in range(len(phi)): plt.plot(x, phi[i], 'r-') #, label=r'$\varphi_%d$' % i) plt.text(x[i+1], 1.2, r'$\varphi_%d$' % i) plt.plot(x, u, 'b-', label='$u$') plt.legend(loc='upper left') plt.axis([0, x[-1], 0, 9]) plt.savefig('tmp_u_P1.png') plt.savefig('tmp_u_P1.pdf') # Mark elements for xi in x[1:-1]: plt.plot([xi, xi], [0, 9], 'm--') # Mark nodes #plt.plot(x, np.zeros(len(x)), 'ro', markersize=4) plt.savefig('tmp_u_P1_welms.png') plt.savefig('tmp_u_P1_welms.pdf') plt.show()
def fe_basis_function_figure(d, target_elm=[1], n_e=3, derivative=0, filename='tmp.pdf', labels=False): """ Draw all basis functions (or their derivative), of degree d, associated with element target_elm (may be list of elements). Add a mesh with n_e elements. """ nodes, elements = mesh_uniform(n_e, d) """ x = 1.1 print locate_element_vectorized(x, elements, nodes) print locate_element_scalar(x, elements, nodes) x = 0.1, 0.4, 0.8 print locate_element_vectorized(x, elements, nodes) """ if isinstance(target_elm, int): target_elm = [target_elm] # wrap in list # Draw the basis functions for element 1 phi_drawn = [] # list of already drawn phi functions ymin = ymax = 0 for e in target_elm: for i in elements[e]: if not i in phi_drawn: x, y = phi_glob(i, elements, nodes, derivative=derivative) if x is None and y is None: return # abort ymax = max(ymax, max(y)) ymin = min(ymin, min(y)) plt.plot(x, y, '-') plt.hold('on') if labels: if plt.backend == 'gnuplot': if derivative == 0: plt.legend(r'basis function no. %d' % i) else: plt.legend(r'derivative of basis function no. %d' % i) elif plt.backend == 'matplotlib': if derivative == 0: plt.legend(r'\varphi_%d' % i) else: plt.legend(r"\varphi_%d'(x)" % i) phi_drawn.append(i) plt.axis([nodes[0], nodes[-1], ymin-0.1, ymax+0.1]) plot_fe_mesh(nodes, elements, element_marker=[ymin-0.1, ymax+0.1]) plt.hold('off') plt.savefig(filename)
def comparison_plot(f, u, Omega, plotfile='tmp'): """Compare f(x,y) and u(x,y) for x,y in Omega in a plot.""" x, y = sm.symbols('x y') f = sm.lambdify([x,y], f, modules="numpy") u = sm.lambdify([x,y], u, modules="numpy") # When doing symbolics, Omega can easily contain symbolic expressions, # assume .evalf() will work in that case to obtain numerical # expressions, which then must be converted to float before calling # linspace below for r in range(2): for s in range(2): if not isinstance(Omega[r][s], (int,float)): Omega[r][s] = float(Omega[r][s].evalf()) resolution = 41 # no of points in plot xcoor = linspace(Omega[0][0], Omega[0][1], resolution) ycoor = linspace(Omega[1][0], Omega[1][1], resolution) xv, yv = ndgrid(xcoor, ycoor) # Vectorized functions expressions does not work with # lambdify'ed functions without the modules="numpy" exact = f(xv, yv) approx = u(xv, yv) figure() surfc(xv, yv, exact, title='f(x,y)', colorbar=True, colormap=hot(), shading='flat') if plotfile: savefig('%s_f.pdf' % plotfile, color=True) savefig('%s_f.png' % plotfile) figure() surfc(xv, yv, approx, title='f(x,y)', colorbar=True, colormap=hot(), shading='flat') if plotfile: savefig('%s_u.pdf' % plotfile, color=True) savefig('%s_u.png' % plotfile)
def u_P1(): """ Plot P1 basis functions and a resulting u to illustrate what it means to use finite elements. """ import matplotlib.pyplot as plt x = [0, 1.5, 2.5, 3.5, 4] phi = [np.zeros(len(x)) for i in range(len(x)-2)] for i in range(len(phi)): phi[i][i+1] = 1 #u = 5*x*np.exp(-0.25*x**2)*(4-x) u = [0, 8, 5, 4, 0] for i in range(len(phi)): plt.plot(x, phi[i], 'r-') #, label=r'$\varphi_%d$' % i) plt.text(x[i+1], 1.2, r'$\varphi_%d$' % i) plt.plot(x, u, 'b-', label='$u$') plt.legend(loc='upper left') plt.axis([0, x[-1], 0, 9]) plt.savefig('u_example_P1.png') plt.savefig('u_example_P1.pdf') # Mark elements for xi in x[1:-1]: plt.plot([xi, xi], [0, 9], 'm--') # Mark nodes #plt.plot(x, np.zeros(len(x)), 'ro', markersize=4) plt.savefig('u_example_P1_welms.png') plt.savefig('u_example_P1_welms.pdf') plt.show()
def demo1(f=f1, nx=4, ny=3, viewx=58, viewy=345, plain_gnuplot=True): vertices, cells = mesh(nx, ny, x=[0, 1], y=[0, 1], diagonal='right') if f == 'basis': # basis function zvalues = np.zeros(vertices.shape[0]) zvalues[int(round(len(zvalues) / 2.)) + int(round(nx / 2.))] = 1 else: zvalues = fill(f1, vertices) if plain_gnuplot: plt = Gnuplotter() else: import scitools.std as plt """ if plt.backend == 'gnuplot': gpl = plt.get_backend() gpl('unset border; unset xtics; unset ytics; unset ztics') #gpl('replot') """ draw_mesh(vertices, cells, plt) draw_surface(zvalues, vertices, cells, plt) plt.axis([0, 1, 0, 1, 0, zvalues.max()]) plt.view(viewx, viewy) if plain_gnuplot: plt.savefig('tmp') else: plt.savefig('tmp.pdf') plt.savefig('tmp.eps') plt.savefig('tmp.png') plt.show()
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
def visualize_front(u, t, I, w, savefig=False, skip_frames=1): """ Visualize u and the exact solution vs t, using a moving plot window and continuous drawing of the curves as they evolve in time. Makes it easy to plot very long time series. Plots are saved to files if savefig is True. Only each skip_frames-th plot is saved (e.g., if skip_frame=10, only each 10th plot is saved to file; this is convenient if plot files corresponding to different time steps are to be compared). """ import scitools.std as st from scitools.MovingPlotWindow import MovingPlotWindow from math import pi # Remove all old plot files tmp_*.png import glob, os for filename in glob.glob('tmp_*.png'): os.remove(filename) P = 2 * pi / w # one period umin = 1.2 * u.min() umax = -umin dt = t[1] - t[0] plot_manager = MovingPlotWindow(window_width=8 * P, dt=dt, yaxis=[umin, umax], mode='continuous drawing') frame_counter = 0 for n in range(1, len(u)): if plot_manager.plot(n): s = plot_manager.first_index_in_plot st.plot(t[s:n + 1], u[s:n + 1], 'r-1', t[s:n + 1], I * cos(w * t)[s:n + 1], 'b-1', title='t=%6.3f' % t[n], axis=plot_manager.axis(), show=not savefig) # drop window if savefig if savefig and n % skip_frames == 0: filename = 'tmp_%04d.png' % frame_counter st.savefig(filename) print 'making plot file', filename, 'at t=%g' % t[n] frame_counter += 1 plot_manager.update(n)
def demo_circular(): # Mass B is at rest at the origin, # mass A is at (1, 0) with vel. (0, 1) ic = [1, 0, 0, 1, 0, 0, 0, 0] x_A, x_B, y_A, y_B, t = solver(alpha=0.001, ic=ic, T=2 * np.pi, dt=0.01) plt.plot(x_A, x_B, 'r2-', y_A, y_B, 'b2-', legend=['A', 'B'], daspectmode='equal') # x and y axis have same scaling plt.savefig('tmp_circular.png') plt.savefig('tmp_circular.pdf') plt.show()
def animate_series(fk, M, N, xmin, xmax, ymin, ymax, n, exact): x = np.linspace(xmin, xmax, n) S = 0 # summation variable for k in range(M, N + 1): S += fk(k, x) plt.plot(x, S, 'b-', x, exact(x), 'r-', axis=[xmin, xmax, ymin, ymax], legend=['k=%d' % k, 'exact']) # filenames: tmp_0000.png tmp_0001.png, tmp_0002.png plt.savefig('tmp_%04d.png' % k) time.sleep(1) # pause: 1 sec
def plot_frequency_approximations(): w = 1 # relevant value in a scaled problem stability_limit = 2. / w dt = np.linspace(0.2, stability_limit, 111) # time steps series_approx = w + (1. / 24) * dt**2 * w**3 P = 2 * np.pi / w # one period num_timesteps_per_period = P / dt # more instructive import scitools.std as plt plt.plot(num_timesteps_per_period, tilde_w(w, dt), 'r-', num_timesteps_per_period, series_approx, 'b--', legend=('exact discrete frequency', '2nd-order expansion'), xlabel='no of time steps per period', ylabel='numerical frequency') plt.savefig('discrete_freq.png') plt.savefig('discrete_freq.pdf')
def draw_sparsity_pattern(elements, num_nodes): """Illustrate the matrix sparsity pattern.""" import matplotlib.pyplot as plt sparsity_pattern = {} for e in elements: for i in range(len(e)): for j in range(len(e)): sparsity_pattern[(e[i],e[j])] = 1 y = [i for i, j in sorted(sparsity_pattern)] x = [j for i, j in sorted(sparsity_pattern)] y.reverse() plt.plot(x, y, 'bo') ax = plt.gca() ax.set_aspect('equal') plt.axis('off') plt.plot([-1, num_nodes, num_nodes, -1, -1], [-1, -1, num_nodes, num_nodes, -1], 'k-') plt.savefig('tmp_sparsity_pattern.pdf') plt.savefig('tmp_sparsity_pattern.png') plt.show()
def plot_u(u, x, xv, y, yv, t, n): b_a = zeros((xv.shape[0], yv.shape[1])) b_a[:, :] = bottom(xv, yv) st.plot(xv[:, 0], u[:, 0], '-', xv[:, 0], b_a[:, 0], '--', ylim=[zmin, zmax]) #show() #hold('on') #axis([0.0,400.0,0.0,430.0,-500.0,300.0]) #show() #time.sleep(5.0) filename = 'tmp_1d_box_slit%04d.png' % n st.savefig(filename)