Esempio n. 1
1
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)
Esempio n. 2
0
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)
Esempio n. 3
0
    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
Esempio n. 4
0
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()
Esempio n. 5
0
    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
Esempio n. 6
0
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)
Esempio n. 7
0
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)
Esempio n. 8
0
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()
Esempio n. 9
0
def plot_fe_mesh(nodes, elements, element_marker=[0, 0.1]):
    """Illustrate elements and nodes in a finite element mesh."""
    plt.hold('on')
    all_x_L = [nodes[elements[e][0]] for e in range(len(elements))]
    element_boundaries = all_x_L + [nodes[-1]]
    for x in element_boundaries:
        plt.plot([x, x], element_marker, 'm--')  # m gives dotted lines
    plt.plot(nodes, [0]*len(nodes), 'ro2')
Esempio n. 10
0
def plot_fe_mesh(nodes, elements, element_marker=[0, 0.1]):
    """Illustrate elements and nodes in a finite element mesh."""
    plt.hold('on')
    all_x_L = [nodes[elements[e][0]] for e in range(len(elements))]
    element_boundaries = all_x_L + [nodes[-1]]
    for x in element_boundaries:
        plt.plot([x, x], element_marker, 'm--')  # m gives dotted eps/pdf lines
    plt.plot(nodes, [0]*len(nodes), 'ro2')
Esempio n. 11
0
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()
Esempio n. 12
0
    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
Esempio n. 13
0
	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
Esempio n. 14
0
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()
Esempio n. 15
0
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')
Esempio n. 16
0
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)
Esempio n. 17
0
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)
Esempio n. 18
0
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)
Esempio n. 19
0
def plot_empirical_freq_and_amplitude(u, t):
    minima, maxima = minmax(t, u)
    p = periods(maxima)
    a = amplitudes(minima, maxima)
    plt.figure()
    from math import pi
    w = 2*pi/p    
    plt.plot(range(len(p)), w, 'r-')
    plt.hold('on')
    plt.plot(range(len(a)), a, 'b-')
    ymax = 1.1*max(w.max(), a.max())
    ymin = 0.9*min(w.min(), a.min())
    plt.axis([0, max(len(p), len(a)), ymin, ymax])
    plt.legend(['estimated frequency', 'estimated amplitude'],
               loc='upper right')
    return len(maxima)
Esempio n. 20
0
def plot_empirical_freq_and_amplitude(u, t):
    minima, maxima = minmax(t, u)
    p = periods(maxima)
    a = amplitudes(minima, maxima)
    plt.figure()
    from math import pi
    w = 2 * pi / p
    plt.plot(range(len(p)), w, 'r-')
    plt.hold('on')
    plt.plot(range(len(a)), a, 'b-')
    ymax = 1.1 * max(w.max(), a.max())
    ymin = 0.9 * min(w.min(), a.min())
    plt.axis([0, max(len(p), len(a)), ymin, ymax])
    plt.legend(['estimated frequency', 'estimated amplitude'],
               loc='upper right')
    return len(maxima)
Esempio n. 21
0
def run_solvers_and_plot(solvers, timesteps_per_period=20,
                         num_periods=1, b=0):
    w = 2*np.pi    # frequency of undamped free oscillations
    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)
    t_fine = np.linspace(0, T, 8*Nt+1)  # used for very accurate solution

    legends = []
    solver_exact = odespy.RK4(f)

    for solver in solvers:
        solver.set_initial_condition([solver.users_f.I, 0])
        u, t = solver.solve(t_mesh)

        solver_name = 'CrankNicolson' if solver.__class__.__name__ == \
                      'MidpointImplicit' else solver.__class__.__name__

        # Make plots (plot last 10 periods????)
        if num_periods <= 80:
            plt.figure(1)
            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 exact solution plotted on a very fine mesh
    #t_fine = np.linspace(0, T, 10001)
    #u_e = solver.users_f.exact(t_fine)
    # Compare with RK4 on a much finer mesh
    solver_exact.set_initial_condition([solver.users_f.I, 0])
    u_e, t_e = solver_exact.solve(t_fine)

    if num_periods < 80:
        plt.figure(1)
        plt.plot(t_e, u_e[:,0], '-') # avoid markers by spec. line type
        legends.append('exact (RK4)')
        plt.legend(legends, loc='upper left')
        plt.xlabel('t');  plt.ylabel('u')
        plt.title('Time step: %g' % dt)
        plt.savefig('vib_%d_%d_u.png' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_u.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_u.eps' % (timesteps_per_period, num_periods))
Esempio n. 22
0
def run_solvers_and_plot(solvers, timesteps_per_period=20, num_periods=1, b=0):
    w = 2 * np.pi  # frequency of undamped free oscillations
    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)
    t_fine = np.linspace(0, T, 8 * Nt + 1)  # used for very accurate solution

    legends = []
    solver_exact = odespy.RK4(f)

    for solver in solvers:
        solver.set_initial_condition([solver.users_f.I, 0])
        u, t = solver.solve(t_mesh)

        solver_name = 'CrankNicolson' if solver.__class__.__name__ == \
                      'MidpointImplicit' else solver.__class__.__name__

        # Make plots (plot last 10 periods????)
        if num_periods <= 80:
            plt.figure(1)
            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 exact solution plotted on a very fine mesh
    #t_fine = np.linspace(0, T, 10001)
    #u_e = solver.users_f.exact(t_fine)
    # Compare with RK4 on a much finer mesh
    solver_exact.set_initial_condition([solver.users_f.I, 0])
    u_e, t_e = solver_exact.solve(t_fine)

    if num_periods < 80:
        plt.figure(1)
        plt.plot(t_e, u_e[:, 0], '-')  # avoid markers by spec. line type
        legends.append('exact (RK4)')
        plt.legend(legends, loc='upper left')
        plt.xlabel('t')
        plt.ylabel('u')
        plt.title('Time step: %g' % dt)
        plt.savefig('vib_%d_%d_u.png' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_u.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_u.eps' % (timesteps_per_period, num_periods))
Esempio n. 23
0
def test_VanDerPol(mu=0):
    problem = VanDerPolOscillator(mu=mu, U0=[1,0])
    d = problem.default_parameters()
    tp = d['time_points']
    # test f_args, jac_kwargs etc
    methods = [Vode, RK4, RungeKutta4, ForwardEuler, BackwardEuler]
    for method in methods:
        name = method.__name__
        print name
        solver = method(problem.f, jac=problem.jac,
                        atol=d['atol'], rtol=d['rtol'])
        solver.set_initial_condition(problem.U0)
        u, t = solver.solve(tp)
        plot(t, u[:,0], legend=name,
             legend_fancybox=True, legend_loc='upper left')
        hold('on')
        e = problem.verify(u, t)
        if e is not None: print e
Esempio n. 24
0
def test_VanDerPol(mu=0):
    problem = VanDerPolOscillator(mu=mu, U0=[1,0])
    d = problem.default_parameters()
    tp = d['time_points']
    # test f_args, jac_kwargs etc
    methods = [Vode, RK4, RungeKutta4, ForwardEuler, BackwardEuler]
    for method in methods:
        name = method.__name__
        print(name)
        solver = method(problem.f, jac=problem.jac,
                        atol=d['atol'], rtol=d['rtol'])
        solver.set_initial_condition(problem.U0)
        u, t = solver.solve(tp)
        plot(t, u[:,0], legend=name,
             legend_fancybox=True, legend_loc='upper left')
        hold('on')
        e = problem.verify(u, t)
        if e is not None: print(e)
def plotter(v0,T,dt,C_D,rho,rho_b,A,V,d,mu):
	
	g = 9.81 # Gravitational constant
	
	a_s = 3*pi*rho*d*mu/(rho_b*V) # Constant to be used for the Stokes model
	a_q = 0.5*C_D*rho*A/(rho_b*V) # Constant to be used for the quadratic model
	b = g*(-1 + rho/rho_b) # A common constant for both Stokes and quad. model
	rdm = rho*d/mu         # A constant related to the Reynolds number 
	
	t,v = vm.solver(T,dt,a_s,a_q,b,v0,rdm)

	F_b   = rho*g*V*ones(len(v))
	F_g   = -g*rho_b*V*ones(len(v))  

	rdm = rho*d/float(mu) 
	Re = rdm*fabs(v0)
	
	F_d_s = -a_s*v
	F_d_q = -a_q*v*fabs(v) 
	
	# The following code attempts to create a force vector based on the appropriate 
    # Reynolds value :
	
	F_d = zeros(len(v))
	R_e = rdm*fabs(v0)
	for n in range(len(v)) :
		if Re < 1 :
			F_d[n] = F_d_s[n] 
		else :
			F_d[n] = F_d_q[n]
		# Update Re :
		R_e = rdm*fabs(v[n])
	plot(t,F_b,
		 t,F_g,
		 xlabel='t',ylabel='F',
		 legend=('Buouncy Force','Gravity Force'),
		 title='Forces acting on a sphere')
	hold('on')
	plot(t,F_d,legend='Stokes and Quad for spesific Re')
	
	raw_input('Press any key.')
Esempio n. 26
0
def simulate_n_paths(n, N, x0, p0, M, m):
    xm = np.zeros(N + 1)  # mean of x
    pm = np.zeros(N + 1)  # mean of p
    xs = np.zeros(N + 1)  # standard deviation of x
    ps = np.zeros(N + 1)  # standard deviation of p
    for i in range(n):
        x, p = simulate_one_path(N, x0, p0, M, m)
        # Accumulate paths
        xm += x
        pm += p
        xs += x**2
        ps += p**2

        # Show 5 random sample paths
        if i % (n / 5) == 0:
            figure(1)
            plot(x, title='sample paths of investment')
            hold('on')
            figure(2)
            plot(p, title='sample paths of interest rate')
            hold('on')
    figure(1)
    savefig('tmp_sample_paths_investment.pdf')
    figure(2)
    savefig('tmp_sample_paths_interestrate.pdf')

    # Compute average
    xm /= float(n)
    pm /= float(n)
    # Compute standard deviation
    xs = xs / float(n) - xm * xm  # variance
    ps = ps / float(n) - pm * pm  # variance
    # Remove small negative numbers (round off errors)
    print 'min variance:', xs.min(), ps.min()
    xs[xs < 0] = 0
    ps[ps < 0] = 0
    xs = np.sqrt(xs)
    ps = np.sqrt(ps)
    return xm, xs, pm, ps
Esempio n. 27
0
def plot_boundaries(outer_boundary, inner_boundaries=[], marked_points=None):
    if not isinstance(inner_boundaries, (tuple, list)):
        inner_boundaries = [inner_boundaries]
    boundaries = [outer_boundary]
    boundaries.extend(inner_boundaries)

    # Find max/min of plotting area
    plot_area = [
        min([b.x.min() for b in boundaries]),
        max([b.x.max() for b in boundaries]),
        min([b.y.min() for b in boundaries]),
        max([b.y.max() for b in boundaries])
    ]

    aspect = (plot_area[3] - plot_area[2]) / (plot_area[1] - plot_area[0])
    for b in boundaries:
        plot(b.x, b.y, daspect=[aspect, 1, 1], daspectratio='manual')
        hold('on')
    axis(plot_area)
    title('Specification of domain with %d boundaries' % len(boundaries))
    if marked_points:
        for pt, name in marked_points:
            text(pt[0], pt[1], name)
Esempio n. 28
0
def plot_boundaries(outer_boundary, inner_boundaries=[], marked_points=None):
    if not isinstance(inner_boundaries, (tuple, list)):
        inner_boundaries = [inner_boundaries]
    boundaries = [outer_boundary]
    boundaries.extend(inner_boundaries)

    # Find max/min of plotting area
    plot_area = [
        min([b.x.min() for b in boundaries]),
        max([b.x.max() for b in boundaries]),
        min([b.y.min() for b in boundaries]),
        max([b.y.max() for b in boundaries]),
    ]

    aspect = (plot_area[3] - plot_area[2]) / (plot_area[1] - plot_area[0])
    for b in boundaries:
        plot(b.x, b.y, daspect=[aspect, 1, 1], daspectratio="manual")
        hold("on")
    axis(plot_area)
    title("Specification of domain with %d boundaries" % len(boundaries))
    if marked_points:
        for pt, name in marked_points:
            text(pt[0], pt[1], name)
Esempio n. 29
0
def simulate_n_paths(n, N, x0, p0, M, m):
    xm = np.zeros(N+1)  # mean of x
    pm = np.zeros(N+1)  # mean of p
    xs = np.zeros(N+1)  # standard deviation of x
    ps = np.zeros(N+1)  # standard deviation of p
    for i in range(n):
        x, p = simulate_one_path(N, x0, p0, M, m)
        # Accumulate paths
        xm += x
        pm += p
        xs += x**2
        ps += p**2

        # Show 5 random sample paths
        if i % (n/5) == 0:
            figure(1)
            plot(x, title='sample paths of investment')
            hold('on')
            figure(2)
            plot(p, title='sample paths of interest rate')
            hold('on')
    figure(1); savefig('tmp_sample_paths_investment.eps')
    figure(2); savefig('tmp_sample_paths_interestrate.eps')

    # Compute average
    xm /= float(n)
    pm /= float(n)
    # Compute standard deviation
    xs = xs/float(n) - xm*xm  # variance
    ps = ps/float(n) - pm*pm  # variance
    # Remove small negative numbers (round off errors)
    print 'min variance:', xs.min(), ps.min()
    xs[xs < 0] = 0
    ps[ps < 0] = 0
    xs = np.sqrt(xs)
    ps = np.sqrt(ps)
    return xm, xs, pm, ps
Esempio n. 30
0
 def amplification_factor(names):
     # Use SciTools since it adds markers to colored lines
     from scitools.std import (plot, title, xlabel, ylabel, hold, savefig,
                               axis, legend, grid, show, figure)
     figure()
     curves = {}
     p = linspace(0, 3, 99)
     curves['exact'] = A_exact(p)
     plot(p, curves['exact'])
     hold('on')
     name2theta = dict(FE=0, BE=1, CN=0.5)
     for name in names:
         curves[name] = A(p, name2theta[name])
         plot(p, curves[name])
         axis([p[0], p[-1], -20, 20])
         #semilogy(p, curves[name])
     plot([p[0], p[-1]], [0, 0], '--')  # A=0 line
     title('Amplification factors')
     grid('on')
     legend(['exact'] + names, loc='lower left', fancybox=True)
     xlabel(r'$p=-a\cdot dt$')
     ylabel('Amplification factor')
     savefig('A_growth.png')
     savefig('A_growth.pdf')
Esempio n. 31
0
 def amplification_factor(names):
     # Use SciTools since it adds markers to colored lines
     from scitools.std import (
         plot, title, xlabel, ylabel, hold, savefig,
         axis, legend, grid, show, figure)
     figure()
     curves = {}
     p = linspace(0, 3, 99)
     curves['exact'] = A_exact(p)
     plot(p, curves['exact'])
     hold('on')
     name2theta = dict(FE=0, BE=1, CN=0.5)
     for name in names:
         curves[name] = A(p, name2theta[name])
         plot(p, curves[name])
         axis([p[0], p[-1], -20, 20])
         #semilogy(p, curves[name])
     plot([p[0], p[-1]], [0, 0], '--')  # A=0 line
     title('Amplification factors')
     grid('on')
     legend(['exact'] + names, loc='lower left', fancybox=True)
     xlabel(r'$p=-a\cdot dt$')
     ylabel('Amplification factor')
     savefig('A_growth.png'); savefig('A_growth.pdf')
Esempio n. 32
0
D = 500
dt = dx**2*D
dt = 1.25
D = dt/dx**2
T = 2.5
umin = u_R
umax = u_L

a_consts = [[0, 1]]
a_consts = [[0, 1], [0.5, 8]]
a_consts = [[0, 1], [0.5, 8], [0.75, 0.1]]
a = fill_a(a_consts, L, Nx)
#a = random.uniform(0, 10, Nx+1)

from scitools.std import plot, hold, subplot, figure, show

figure()
subplot(2,1,1)
u, x, cpu = viz(I, a, L, Nx, D, T, umin, umax, theta, u_L, u_R)

v = u_exact_stationary(x, a, u_L, u_R)
print 'v', v
print 'u', u
hold('on')
symbol = 'bo' if Nx < 32 else 'b-'
plot(x, v, symbol, legend='exact stationary')

subplot(2,1,2)
plot(x, a, legend='a')
show()
Esempio n. 33
0
def run(gamma, beta=10, delta=40, scaling=1, animate=False):
    """Run the scaled model for welding."""
    if scaling == 1:
        v = gamma
        a = 1
    elif scaling == 2:
        v = 1
        a = 1.0/gamma

    b = 0.5*beta**2
    L = 1.0
    ymin = 0
    # Need gloal to be able change ymax in closure process_u
    global ymax
    ymax = 1.2

    I = lambda x: 0
    f = lambda x, t: delta*np.exp(-b*(x - v*t)**2)

    import time
    import scitools.std as plt
    plot_arrays = []

    def process_u(u, x, t, n):
        global ymax
        if animate:
            plt.plot(x, u, 'r-',
                     x, f(x, t[n])/delta, 'b-',
                     axis=[0, L, ymin, ymax], title='t=%f' % t[n],
                     xlabel='x', ylabel='u and f/%g' % delta)
        if t[n] == 0:
            time.sleep(1)
            plot_arrays.append(x)
        dt = t[1] - t[0]
        tol = dt/10.0
        if abs(t[n] - 0.2) < tol or abs(t[n] - 0.5) < tol:
            plot_arrays.append((u.copy(), f(x, t[n])/delta))
            if u.max() > ymax:
                ymax = u.max()

    Nx = 100
    D = 10
    T = 0.5
    u_L = u_R = 0
    theta = 1.0
    cpu = solver(
        I, a, f, L, Nx, D, T, theta, u_L, u_R, user_action=process_u)
    x = plot_arrays[0]
    plt.figure()
    for u, f in plot_arrays[1:]:
        plt.plot(x, u, 'r-', x, f, 'b--', axis=[x[0], x[-1], 0, ymax],
                 xlabel='$x$', ylabel=r'$u, \ f/%g$' % delta)
        plt.hold('on')
    plt.legend(['$u,\\ t=0.2$', '$f/%g,\\ t=0.2$' % delta,
                '$u,\\ t=0.5$', '$f/%g,\\ t=0.5$' % delta])
    filename = 'tmp1_gamma%g_s%d' % (gamma, scaling)
    s = 'diffusion' if scaling == 1 else 'source'
    plt.title(r'$\beta = %g,\ \gamma = %g,\ $' % (beta, gamma)
              + 'scaling=%s' % s)
    plt.savefig(filename + '.pdf');  plt.savefig(filename + '.png')
    return cpu
Esempio n. 34
0
def run_solvers_and_plot(solvers, timesteps_per_period=20,
                         num_periods=1, I=1, w=2*np.pi):
    P = 2*np.pi/w  # one period
    dt = P/timesteps_per_period
    N = num_periods*timesteps_per_period
    T = N*dt
    t_mesh = np.linspace(0, T, N+1)

    legends = []
    for solver in solvers:
        solver.set(f_kwargs={'w': w})
        solver.set_initial_condition([I, 0])
        u, t = solver.solve(t_mesh)

        # Make plots
        if num_periods <= 80:
            plt.figure(1)
            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.__class__.__name__)
            plt.figure(2)
            if len(t_mesh) <= 50:
                plt.plot(u[:,0], u[:,1])        # markers by default
            else:
                plt.plot(u[:,0], u[:,1], '-2')  # no markers
            plt.hold('on')

        if num_periods > 20:
            minima, maxima = minmax(t, u[:,0])
            p = periods(maxima)
            a = amplitudes(minima, maxima)
            plt.figure(3)
            plt.plot(range(len(p)), 2*np.pi/p, '-')
            plt.hold('on')
            plt.figure(4)
            plt.plot(range(len(a)), a, '-')
            plt.hold('on')

    # Compare with exact solution plotted on a very fine mesh
    t_fine = np.linspace(0, T, 10001)
    u_e = I*np.cos(w*t_fine)
    v_e = -w*I*np.sin(w*t_fine)

    if num_periods < 80:
        plt.figure(1)
        plt.plot(t_fine, u_e, '-') # avoid markers by spec. line type
        legends.append('exact')
        plt.legend(legends, loc='upper left')
        plt.xlabel('t');  plt.ylabel('u')
        plt.title('Time step: %g' % dt)
        plt.savefig('vb_%d_%d_u.png' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_u.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_u.eps' % (timesteps_per_period, num_periods))

        plt.figure(2)
        plt.plot(u_e, v_e, '-') # avoid markers by spec. line type
        plt.legend(legends, loc='lower right')
        plt.xlabel('u(t)');  plt.ylabel('v(t)')
        plt.title('Time step: %g' % dt)
        plt.savefig('vb_%d_%d_pp.png' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_pp.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_pp.eps' % (timesteps_per_period, num_periods))
        del legends[-1]  # fig 3 and 4 does not have exact value

    if num_periods > 20:
        plt.figure(3)
        plt.legend(legends, loc='center right')
        plt.title('Empirically estimated periods')
        plt.savefig('vb_%d_%d_p.eps' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_p.png' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_p.eps' % (timesteps_per_period, num_periods))
        plt.figure(4)
        plt.legend(legends, loc='center right')
        plt.title('Empirically estimated amplitudes')
        plt.savefig('vb_%d_%d_a.eps' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_a.png' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_a.eps' % (timesteps_per_period, num_periods))
Esempio n. 35
0
def run_solvers_and_plot(solvers,
                         timesteps_per_period=20,
                         num_periods=1,
                         I=1,
                         w=2 * np.pi):
    P = 2 * np.pi / w  # one period
    dt = P / timesteps_per_period
    N = num_periods * timesteps_per_period
    T = N * dt
    t_mesh = np.linspace(0, T, N + 1)

    legends = []
    for solver in solvers:
        solver.set(f_kwargs={'w': w})
        solver.set_initial_condition([I, 0])
        u, t = solver.solve(t_mesh)

        # Make plots
        if num_periods <= 80:
            plt.figure(1)
            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.__class__.__name__)
            plt.figure(2)
            if len(t_mesh) <= 50:
                plt.plot(u[:, 0], u[:, 1])  # markers by default
            else:
                plt.plot(u[:, 0], u[:, 1], '-2')  # no markers
            plt.hold('on')

        if num_periods > 20:
            minima, maxima = minmax(t, u[:, 0])
            p = periods(maxima)
            a = amplitudes(minima, maxima)
            plt.figure(3)
            plt.plot(range(len(p)), 2 * np.pi / p, '-')
            plt.hold('on')
            plt.figure(4)
            plt.plot(range(len(a)), a, '-')
            plt.hold('on')

    # Compare with exact solution plotted on a very fine mesh
    t_fine = np.linspace(0, T, 10001)
    u_e = I * np.cos(w * t_fine)
    v_e = -w * I * np.sin(w * t_fine)

    if num_periods < 80:
        plt.figure(1)
        plt.plot(t_fine, u_e, '-')  # avoid markers by spec. line type
        legends.append('exact')
        plt.legend(legends, loc='upper left')
        plt.xlabel('t')
        plt.ylabel('u')
        plt.title('Time step: %g' % dt)
        plt.savefig('vb_%d_%d_u.png' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_u.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_u.eps' % (timesteps_per_period, num_periods))

        plt.figure(2)
        plt.plot(u_e, v_e, '-')  # avoid markers by spec. line type
        plt.legend(legends, loc='lower right')
        plt.xlabel('u(t)')
        plt.ylabel('v(t)')
        plt.title('Time step: %g' % dt)
        plt.savefig('vb_%d_%d_pp.png' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_pp.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_pp.eps' % (timesteps_per_period, num_periods))
        del legends[-1]  # fig 3 and 4 does not have exact value

    if num_periods > 20:
        plt.figure(3)
        plt.legend(legends, loc='center right')
        plt.title('Empirically estimated periods')
        plt.savefig('vb_%d_%d_p.eps' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_p.png' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_p.eps' % (timesteps_per_period, num_periods))
        plt.figure(4)
        plt.legend(legends, loc='center right')
        plt.title('Empirically estimated amplitudes')
        plt.savefig('vb_%d_%d_a.eps' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_a.png' % (timesteps_per_period, num_periods))
        plt.savefig('vb_%d_%d_a.eps' % (timesteps_per_period, num_periods))
Esempio n. 36
0
import sys
#import matplotlib.pyplot as plt
import scitools.std as plt

def f(u, t):
    return -a*u

def u_exact(t):
    return I*np.exp(-a*t)

I = 1; a = 2; T = 5
tol = float(sys.argv[1])
solver = odespy.DormandPrince(f, atol=tol, rtol=0.1*tol)

Nt = 1  # just one step - let the scheme find its intermediate points
t_mesh = np.linspace(0, T, Nt+1)
t_fine = np.linspace(0, T, 10001)

solver.set_initial_condition(I)
u, t = solver.solve(t_mesh)

# u and t will only consist of [I, u^Nt] and [0,T]
# solver.u_all and solver.t_all contains all computed points
plt.plot(solver.t_all, solver.u_all, 'ko')
plt.hold('on')
plt.plot(t_fine, u_exact(t_fine), 'b-')
plt.legend(['tol=%.0E' % tol, 'exact'])
plt.savefig('tmp_odespy_adaptive.png')
plt.show()

Esempio n. 37
0
def run(gamma, beta=10, delta=40, scaling=1, animate=False):
    """Run the scaled model for welding."""
    gamma = float(gamma)  # avoid integer division
    if scaling == 'a':
        v = gamma
        a = 1
        L = 1.0
        b = 0.5*beta**2
    elif scaling == 'b':
        v = 1
        a = 1.0/gamma
        L = 1.0
        b = 0.5*beta**2
    elif scaling == 'c':
        v = 1
        a = beta/gamma
        L = beta
        b = 0.5
    elif scaling == 'd':
        # PDE: u_t = gamma**(-1)u_xx + gamma**(-1)*delta*f
        v = 1
        a = 1.0/gamma
        L = 1.0
        b = 0.5*beta**2
        delta *= 1.0/gamma

    ymin = 0
    # Need global ymax to be able change ymax in closure process_u
    global ymax
    ymax = 1.2

    I = lambda x: 0
    f = lambda x, t: delta*np.exp(-b*(x - v*t)**2)

    import time
    import scitools.std as plt
    plot_arrays = []
    if scaling == 'c':
        plot_times = [0.2*beta, 0.5*beta]
    else:
        plot_times = [0.2, 0.5]

    def process_u(u, x, t, n):
        """
        Animate u, and store arrays in plot_arrays if
        t coincides with chosen times for plotting (plot_times).
        """
        global ymax
        if animate:
            plt.plot(x, u, 'r-',
                     x, f(x, t[n])/delta, 'b-',
                     axis=[0, L, ymin, ymax], title='t=%f' % t[n],
                     xlabel='x', ylabel='u and f/%g' % delta)
        if t[n] == 0:
            time.sleep(1)
            plot_arrays.append(x)
        dt = t[1] - t[0]
        tol = dt/10.0
        if abs(t[n] - plot_times[0]) < tol or \
           abs(t[n] - plot_times[1]) < tol:
            plot_arrays.append((u.copy(), f(x, t[n])/delta))
            if u.max() > ymax:
                ymax = u.max()

    Nx = 100
    D = 10
    if scaling == 'c':
        T = 0.5*beta
    else:
        T = 0.5
    u_L = u_R = 0
    theta = 1.0
    cpu = solver(
        I, a, f, L, Nx, D, T, theta, u_L, u_R, user_action=process_u)
    x = plot_arrays[0]
    plt.figure()
    for u, f in plot_arrays[1:]:
        plt.plot(x, u, 'r-', x, f, 'b--', axis=[x[0], x[-1], 0, ymax],
                 xlabel='$x$', ylabel=r'$u, \ f/%g$' % delta)
        plt.hold('on')
    plt.legend(['$u,\\ t=%g$' % plot_times[0],
                '$f/%g,\\ t=%g$' % (delta, plot_times[0]),
                '$u,\\ t=%g$' % plot_times[1],
                '$f/%g,\\ t=%g$' % (delta, plot_times[1])])
    filename = 'tmp1_gamma%g_%s' % (gamma, scaling)
    plt.title(r'$\beta = %g,\ \gamma = %g,\ $' % (beta, gamma)
              + 'scaling=%s' % scaling)
    plt.savefig(filename + '.pdf');  plt.savefig(filename + '.png')
    return cpu
Esempio n. 38
0
def run_solvers_and_plot(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)

    legends = []
    for solver in solvers:
        solver.set(f_kwargs={'w': w})
        solver.set_initial_condition([I, 0])
        u, t = solver.solve(t_mesh)

        # Compute energy
        dt = t[1] - t[0]
        E = 0.5*((u[2:,0] - u[:-2,0])/(2*dt))**2 + 0.5*w**2*u[1:-1,0]**2
        # Compute error in energy
        E0 = 0.5*0**2 + 0.5*w**2*I**2
        e_E = E - E0

        solver_name = 'CrankNicolson' if solver.__class__.__name__ == \
                      'MidpointImplicit' else solver.__class__.__name__
        print '*** Relative max error in energy for %s [0,%g] with dt=%g: %.3E' % (solver_name, t[-1], dt, np.abs(e_E).max()/E0)

        # Make plots
        if num_periods <= 80:
            plt.figure(1)
            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.__class__.__name__)
            plt.figure(2)
            if len(t_mesh) <= 50:
                plt.plot(u[:,0], u[:,1])        # markers by default
            else:
                plt.plot(u[:,0], u[:,1], '-2')  # no markers
            plt.hold('on')

        if num_periods > 20:
            minima, maxima = minmax(t, u[:,0])
            p = periods(maxima)
            a = amplitudes(minima, maxima)
            plt.figure(3)
            plt.plot(range(len(p)), 2*np.pi/p, '-')
            plt.hold('on')
            plt.figure(4)
            plt.plot(range(len(a)), a, '-')
            plt.hold('on')

    # Compare with exact solution plotted on a very fine mesh
    t_fine = np.linspace(0, T, 10001)
    u_e = I*np.cos(w*t_fine)
    v_e = -w*I*np.sin(w*t_fine)

    if num_periods < 80:
        plt.figure(1)
        plt.plot(t_fine, u_e, '-') # avoid markers by spec. line type
        legends.append('exact')
        plt.legend(legends, loc='upper left')
        plt.xlabel('t');  plt.ylabel('u')
        plt.title('Time step: %g' % dt)
        plt.savefig('vib_%d_%d_u.png' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_u.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_u.eps' % (timesteps_per_period, num_periods))

        plt.figure(2)
        plt.plot(u_e, v_e, '-') # avoid markers by spec. line type
        plt.legend(legends, loc='lower right')
        plt.xlabel('u(t)');  plt.ylabel('v(t)')
        plt.title('Time step: %g' % dt)
        plt.savefig('vib_%d_%d_pp.png' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_pp.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_pp.eps' % (timesteps_per_period, num_periods))
        del legends[-1]  # fig 3 and 4 does not have exact value

    if num_periods > 20:
        plt.figure(3)
        plt.legend(legends, loc='center right')
        plt.title('Empirically estimated periods')
        plt.savefig('vib_%d_%d_p.eps' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_p.png' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_p.eps' % (timesteps_per_period, num_periods))
        plt.figure(4)
        plt.legend(legends, loc='center right')
        plt.title('Empirically estimated amplitudes')
        plt.savefig('vib_%d_%d_a.eps' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_a.png' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_a.eps' % (timesteps_per_period, num_periods))
def run_solvers_and_plot(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)

    legends = []
    for solver in solvers:
        solver.set(f_kwargs={'w': w})
        solver.set_initial_condition([I, 0])
        u, t = solver.solve(t_mesh)

        # Compute energy
        dt = t[1] - t[0]
        E = 0.5 * ((u[2:, 0] - u[:-2, 0]) /
                   (2 * dt))**2 + 0.5 * w**2 * u[1:-1, 0]**2
        # Compute error in energy
        E0 = 0.5 * 0**2 + 0.5 * w**2 * I**2
        e_E = E - E0

        solver_name = 'CrankNicolson' if solver.__class__.__name__ == \
                      'MidpointImplicit' else solver.__class__.__name__
        print '*** Relative max error in energy for %s [0,%g] with dt=%g: %.3E' % (
            solver_name, t[-1], dt, np.abs(e_E).max() / E0)

        # Make plots
        if num_periods <= 80:
            plt.figure(1)
            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)
            plt.figure(2)
            if len(t_mesh) <= 50:
                plt.plot(u[:, 0], u[:, 1])  # markers by default
            else:
                plt.plot(u[:, 0], u[:, 1], '-2')  # no markers
            plt.hold('on')

        if num_periods > 20:
            minima, maxima = minmax(t, u[:, 0])
            p = periods(maxima)
            a = amplitudes(minima, maxima)
            plt.figure(3)
            plt.plot(range(len(p)), 2 * np.pi / p, '-')
            plt.hold('on')
            plt.figure(4)
            plt.plot(range(len(a)), a, '-')
            plt.hold('on')

    # Compare with exact solution plotted on a very fine mesh
    t_fine = np.linspace(0, T, 10001)
    u_e = I * np.cos(w * t_fine)
    v_e = -w * I * np.sin(w * t_fine)

    if num_periods < 80:
        plt.figure(1)
        plt.plot(t_fine, u_e, '-')  # avoid markers by spec. line type
        legends.append('exact')
        plt.legend(legends, loc='upper left')
        plt.xlabel('t')
        plt.ylabel('u')
        plt.title('Time step: %g' % dt)
        plt.savefig('vib_%d_%d_u.png' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_u.pdf' % (timesteps_per_period, num_periods))

        plt.figure(2)
        plt.plot(u_e, v_e, '-')  # avoid markers by spec. line type
        plt.legend(legends, loc='lower right')
        plt.xlabel('u(t)')
        plt.ylabel('v(t)')
        plt.title('Time step: %g' % dt)
        plt.savefig('vib_%d_%d_pp.png' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_pp.pdf' % (timesteps_per_period, num_periods))
        del legends[-1]  # fig 3 and 4 does not have exact value

    if num_periods > 20:
        plt.figure(3)
        plt.legend(legends, loc='center right')
        plt.title('Empirically estimated periods')
        plt.savefig('vib_%d_%d_p.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_p.png' % (timesteps_per_period, num_periods))
        plt.figure(4)
        plt.legend(legends, loc='center right')
        plt.title('Empirically estimated amplitudes')
        plt.savefig('vib_%d_%d_a.pdf' % (timesteps_per_period, num_periods))
        plt.savefig('vib_%d_%d_a.png' % (timesteps_per_period, num_periods))
Esempio n. 40
0
    T = num_periods * P
    t = np.linspace(0, T, time_steps_per_period * num_periods + 1)
    import odespy

    def f(u, t, alpha):
        # Note the sequence of unknowns: v, u (v=du/dt)
        v, u = u
        return [-alpha * np.sign(v) - u, v]

    solver = odespy.RK4(f, f_args=[alpha])
    solver.set_initial_condition([beta, 1])  # sequence must match f
    uv, t = solver.solve(t)
    u = uv[:, 1]  # recall sequence in f: v, u
    v = uv[:, 0]
    return u, t


if __name__ == "__main__":
    alpha_values = [0, 0.05, 0.1]
    for alpha in alpha_values:
        u, t = simulate(alpha, 0, 6, 60)
        plt.plot(t, u)
        plt.hold("on")
    plt.legend([r"$\alpha=%g$" % alpha for alpha in alpha_values])
    plt.xlabel(r"$\bar t$")
    plt.ylabel(r"$\bar u$")
    plt.savefig("tmp.png")
    plt.savefig("tmp.pdf")
    plt.show()
    raw_input()  # for scitools' matplotlib engine
Esempio n. 41
0
"""
Exercise 5.25: Investigate the behaviour of Langrange's interpolating polynomials
Author: Weiyun Lu
"""

import Lagrange_poly2
from scitools.std import hold, figure

figure()
for n in [2,4,6,10]:
    Lagrange_poly2.graph(abs, n, -2, 2)
    hold('on')   
hold('off')

figure()
for n in [13,20]:
    Lagrange_poly2.graph(abs, n, -2, 2)
    hold('on')
hold('off')
Esempio n. 42
0
def f(u, t):
    return -a * u


def exact_solution(t):
    return I * np.exp(-a * t)


I = 1
a = 2
T = 5
tol = float(sys.argv[1])
solver = odespy.DormandPrince(f, atol=tol, rtol=0.1 * tol)

N = 1  # just one step - let the scheme find its intermediate points
t_mesh = np.linspace(0, T, N + 1)
t_fine = np.linspace(0, T, 10001)

solver.set_initial_condition(I)
u, t = solver.solve(t_mesh)

# u and t will only consist of [I, u^N] and [0,T]
# solver.u_all and solver.t_all contains all computed points
plt.plot(solver.t_all, solver.u_all, 'ko')
plt.hold('on')
plt.plot(t_fine, exact_solution(t_fine), 'b-')
plt.legend(['tol=%.0E' % tol, 'exact'])
plt.savefig('tmp_odespy_adaptive.png')
plt.show()
Esempio n. 43
0
def estimate(truncation_error, T, N_0, m, makeplot=True):
    """
    Compute the truncation error in a problem with one independent
    variable, using m meshes, and estimate the convergence
    rate of the truncation error.

    The user-supplied function truncation_error(dt, N) computes
    the truncation error on a uniform mesh with N intervals of
    length dt::

      R, t, R_a = truncation_error(dt, N)

    where R holds the truncation error at points in the array t,
    and R_a are the corresponding theoretical truncation error
    values (None if not available).

    The truncation_error function is run on a series of meshes
    with 2**i*N_0 intervals, i=0,1,...,m-1.
    The values of R and R_a are restricted to the coarsest mesh.
    and based on these data, the convergence rate of R (pointwise)
    and time-integrated R can be estimated empirically.
    """
    N = [2**i*N_0 for i in range(m)]

    R_I = np.zeros(m) # time-integrated R values on various meshes
    R   = [None]*m    # time series of R restricted to coarsest mesh
    R_a = [None]*m    # time series of R_a restricted to coarsest mesh
    dt = np.zeros(m)
    legends_R = [];  legends_R_a = []  # all legends of curves

    for i in range(m):
        dt[i] = T/float(N[i])
        R[i], t, R_a[i] = truncation_error(dt[i], N[i])

        R_I[i] = np.sqrt(dt[i]*np.sum(R[i]**2))

        if i == 0:
            t_coarse = t           # the coarsest mesh

        stride = N[i]/N_0
        R[i] = R[i][::stride]      # restrict to coarsest mesh
        R_a[i] = R_a[i][::stride]

        if makeplot:
            plt.figure(1)
            plt.plot(t_coarse, R[i], log='y')
            legends_R.append('N=%d' % N[i])
            plt.hold('on')

            plt.figure(2)
            plt.plot(t_coarse, R_a[i] - R[i], log='y')
            plt.hold('on')
            legends_R_a.append('N=%d' % N[i])

    if makeplot:
        plt.figure(1)
        plt.xlabel('time')
        plt.ylabel('pointwise truncation error')
        plt.legend(legends_R)
        plt.savefig('R_series.png')
        plt.savefig('R_series.pdf')
        plt.figure(2)
        plt.xlabel('time')
        plt.ylabel('pointwise error in estimated truncation error')
        plt.legend(legends_R_a)
        plt.savefig('R_error.png')
        plt.savefig('R_error.pdf')

    # Convergence rates
    r_R_I = convergence_rates(dt, R_I)
    print 'R integrated in time; r:',
    print ' '.join(['%.1f' % r for r in r_R_I])
    R = np.array(R)  # two-dim. numpy array
    r_R = [convergence_rates(dt, R[:,n])[-1]
           for n in range(len(t_coarse))]

    # Plot convergence rates
    if makeplot:
        plt.figure()
        plt.plot(t_coarse, r_R)
        plt.xlabel('time')
        plt.ylabel('r')
        plt.axis([t_coarse[0], t_coarse[-1], 0, 2.5])
        plt.title('Pointwise rate $r$ in truncation error $\sim\Delta t^r$')
        plt.savefig('R_rate_series.png')
        plt.savefig('R_rate_series.pdf')
import scitools.std as plt
import sys
import numpy as np
import matplotlib.pyplot as plt

x, y = np.loadtxt('volt.txt', delimiter=',', unpack=True)

plt.figure(1)
plt.plot(x, y, '*', linewidth=1)  # avoid markers by spec. line type
#plt.xlim([0.0, 10])
#plt.ylim([0.0, 2])
plt.legend(['Force-- Tip'],
           loc='upper right',
           prop={"family": "Times New Roman"})
plt.xlabel('Sampled time')
plt.ylabel('$Force /m$')
plt.savefig('volt1v.png')
plt.savefig('volt1v.pdf')
plt.hold(True)
Esempio n. 45
0
def run(gamma, beta=10, delta=40, scaling=1, animate=False):
    """Run the scaled model for welding."""
    if scaling == 1:
        v = gamma
        a = 1
    elif scaling == 2:
        v = 1
        a = 1.0 / gamma

    b = 0.5 * beta**2
    L = 1.0
    ymin = 0
    # Need gloal to be able change ymax in closure process_u
    global ymax
    ymax = 1.2

    I = lambda x: 0
    f = lambda x, t: delta * np.exp(-b * (x - v * t)**2)

    import time
    import scitools.std as plt
    plot_arrays = []

    def process_u(u, x, t, n):
        global ymax
        if animate:
            plt.plot(x,
                     u,
                     'r-',
                     x,
                     f(x, t[n]) / delta,
                     'b-',
                     axis=[0, L, ymin, ymax],
                     title='t=%f' % t[n],
                     xlabel='x',
                     ylabel='u and f/%g' % delta)
        if t[n] == 0:
            time.sleep(1)
            plot_arrays.append(x)
        dt = t[1] - t[0]
        tol = dt / 10.0
        if abs(t[n] - 0.2) < tol or abs(t[n] - 0.5) < tol:
            plot_arrays.append((u.copy(), f(x, t[n]) / delta))
            if u.max() > ymax:
                ymax = u.max()

    Nx = 100
    D = 10
    T = 0.5
    u_L = u_R = 0
    theta = 1.0
    cpu = solver(I, a, f, L, Nx, D, T, theta, u_L, u_R, user_action=process_u)
    x = plot_arrays[0]
    plt.figure()
    for u, f in plot_arrays[1:]:
        plt.plot(x,
                 u,
                 'r-',
                 x,
                 f,
                 'b--',
                 axis=[x[0], x[-1], 0, ymax],
                 xlabel='$x$',
                 ylabel=r'$u, \ f/%g$' % delta)
        plt.hold('on')
    plt.legend([
        '$u,\\ t=0.2$',
        '$f/%g,\\ t=0.2$' % delta, '$u,\\ t=0.5$',
        '$f/%g,\\ t=0.5$' % delta
    ])
    filename = 'tmp1_gamma%g_s%d' % (gamma, scaling)
    s = 'diffusion' if scaling == 1 else 'source'
    plt.title(r'$\beta = %g,\ \gamma = %g,\ $' % (beta, gamma) +
              'scaling=%s' % s)
    plt.savefig(filename + '.pdf')
    plt.savefig(filename + '.png')
    return cpu
Esempio n. 46
0
def run(gamma, beta=10, delta=40, scaling=1, animate=False):
    """Run the scaled model for welding."""
    gamma = float(gamma)  # avoid integer division
    if scaling == 'a':
        v = gamma
        a = 1
        L = 1.0
        b = 0.5 * beta**2
    elif scaling == 'b':
        v = 1
        a = 1.0 / gamma
        L = 1.0
        b = 0.5 * beta**2
    elif scaling == 'c':
        v = 1
        a = beta / gamma
        L = beta
        b = 0.5
    elif scaling == 'd':
        # PDE: u_t = gamma**(-1)u_xx + gamma**(-1)*delta*f
        v = 1
        a = 1.0 / gamma
        L = 1.0
        b = 0.5 * beta**2
        delta *= 1.0 / gamma

    ymin = 0
    # Need global ymax to be able change ymax in closure process_u
    global ymax
    ymax = 1.2

    I = lambda x: 0
    f = lambda x, t: delta * np.exp(-b * (x - v * t)**2)

    import time
    import scitools.std as plt
    plot_arrays = []
    if scaling == 'c':
        plot_times = [0.2 * beta, 0.5 * beta]
    else:
        plot_times = [0.2, 0.5]

    def process_u(u, x, t, n):
        """
        Animate u, and store arrays in plot_arrays if
        t coincides with chosen times for plotting (plot_times).
        """
        global ymax
        if animate:
            plt.plot(x,
                     u,
                     'r-',
                     x,
                     f(x, t[n]) / delta,
                     'b-',
                     axis=[0, L, ymin, ymax],
                     title='t=%f' % t[n],
                     xlabel='x',
                     ylabel='u and f/%g' % delta)
        if t[n] == 0:
            time.sleep(1)
            plot_arrays.append(x)
        dt = t[1] - t[0]
        tol = dt / 10.0
        if abs(t[n] - plot_times[0]) < tol or \
           abs(t[n] - plot_times[1]) < tol:
            plot_arrays.append((u.copy(), f(x, t[n]) / delta))
            if u.max() > ymax:
                ymax = u.max()

    Nx = 100
    D = 10
    if scaling == 'c':
        T = 0.5 * beta
    else:
        T = 0.5
    u_L = u_R = 0
    theta = 1.0
    cpu = solver(I, a, f, L, Nx, D, T, theta, u_L, u_R, user_action=process_u)
    x = plot_arrays[0]
    plt.figure()
    for u, f in plot_arrays[1:]:
        plt.plot(x,
                 u,
                 'r-',
                 x,
                 f,
                 'b--',
                 axis=[x[0], x[-1], 0, ymax],
                 xlabel='$x$',
                 ylabel=r'$u, \ f/%g$' % delta)
        plt.hold('on')
    plt.legend([
        '$u,\\ t=%g$' % plot_times[0],
        '$f/%g,\\ t=%g$' % (delta, plot_times[0]),
        '$u,\\ t=%g$' % plot_times[1],
        '$f/%g,\\ t=%g$' % (delta, plot_times[1])
    ])
    filename = 'tmp1_gamma%g_%s' % (gamma, scaling)
    plt.title(r'$\beta = %g,\ \gamma = %g,\ $' % (beta, gamma) +
              'scaling=%s' % scaling)
    plt.savefig(filename + '.pdf')
    plt.savefig(filename + '.png')
    return cpu