Exemple #1
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()
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()
Exemple #3
0
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()
Exemple #5
0
def slides_waves():
    L = 10.
    a = 0.5
    B0 = 1.
    A = B0/5
    t0 = 3.
    v = 1.
    x0 = lambda t: L/4 + v*t if t < t0 else L/4 + v*t0
    sigma = 1.0

    def bottom(x, t):
        return (B(x, a, L, B0) + S(x, A, x0(t), sigma))

    def depth(x, t):
        return -bottom(x, t)

    import scitools.std as plt
    x = np.linspace(0, L, 101)
    plt.plot(x, bottom(x, 0), x, depth(x, 0), legend=['bottom', 'depth'])
    plt.show()
    raw_input()
    plt.figure()
    dt_b = 0.01
    solver(I=0, V=0,
           f=lambda x, t: -(depth(x, t-dt_b) - 2*depth(x, t) + depth(x, t+dt_b))/dt_b**2,
           c=lambda x, t: np.sqrt(np.abs(depth(x, t))),
           U_0=None,
           U_L=None,
           L=L,
           dt=0.1,
           C=0.9,
           T=20,
           user_action=PlotSurfaceAndBottom(B, S, a, L, B0, A, x0, sigma, umin=-2, umax=2),
           stability_safety_factor=0.9)
Exemple #6
0
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()
Exemple #7
0
def demo_two_stars(animate=True):
    # Initial condition
    ic = [0.6, 0, 0, 1,   # star A: velocity (0,1)
          0, 0, 0, -0.5]  # star B: velocity (0,-0.5)
    # Solve ODEs
    x_A, x_B, y_A, y_B, t = solver(
        alpha=0.5, ic=ic, T=4*np.pi, dt=0.05)
    if animate:
        # Animate motion and draw the objects' paths in time
        for i in range(len(x_A)):
            plt.plot(x_A[:i+1], x_B[:i+1], 'r-',
                     y_A[:i+1], y_B[:i+1], 'b-',
                     [x_A[0], x_A[i]], [x_B[0], x_B[i]], 'r2o',
                     [y_A[0], y_A[i]], [y_B[0], y_B[i]], 'b4o',
                     daspectmode='equal',  # axes aspect
                     legend=['A', 'B', 'A', 'B'],
                     axis=[-1, 1, -1, 1],
                     savefig='tmp_%04d.png' % i,
                     title='t=%.2f' % t[i])
    else:
        # Make a simple static plot of the solution
        plt.plot(x_A, x_B, 'r-', y_A, y_B, 'b-',
                 daspectmode='equal', legend=['A', 'B'],
                 axis=[-1, 1, -1, 1], savefig='tmp_two_stars.png')
    #plt.axes().set_aspect('equal')  # mpl
    plt.show()
Exemple #8
0
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()
Exemple #9
0
 def visualize(self):
     u = self.solver.u; t = self.solver.t   # short forms
     num_periods = vib_plot_empirical_freq_and_amplitude(u, t)
     if num_periods <= 40:
         plt.figure()
         vib_visualize(u, t)
     else:
         vib_visualize_front(u, t, self.window_width, self.savefig)
         vib_visualize_front_ascii(u, t)
     plt.show()
Exemple #10
0
 def visualize(self):
     u = self.solver.u; t = self.solver.t   # short forms
     num_periods = vib_plot_empirical_freq_and_amplitude(u, t)
     if num_periods <= 40:
         plt.figure()
         vib_visualize(u, t)
     else:
         vib_visualize_front(u, t, self.window_width, self.savefig)
         vib_visualize_front_ascii(u, t)
     plt.show()
Exemple #11
0
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()
Exemple #12
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()
Exemple #13
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()
Exemple #14
0
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()
Exemple #15
0
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 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()
Exemple #17
0
def demo_two_stars(animate=True):
    # Initial condition
    ic = [
        0.6,
        0,
        0,
        1,  # star A: velocity (0,1)
        0,
        0,
        0,
        -0.5
    ]  # star B: velocity (0,-0.5)
    # Solve ODEs
    x_A, x_B, y_A, y_B, t = solver(alpha=0.5, ic=ic, T=4 * np.pi, dt=0.05)
    if animate:
        # Animate motion and draw the objects' paths in time
        for i in range(len(x_A)):
            plt.plot(
                x_A[:i + 1],
                x_B[:i + 1],
                'r-',
                y_A[:i + 1],
                y_B[:i + 1],
                'b-',
                [x_A[0], x_A[i]],
                [x_B[0], x_B[i]],
                'r2o',
                [y_A[0], y_A[i]],
                [y_B[0], y_B[i]],
                'b4o',
                daspectmode='equal',  # axes aspect
                legend=['A', 'B', 'A', 'B'],
                axis=[-1, 1, -1, 1],
                savefig='tmp_%04d.png' % i,
                title='t=%.2f' % t[i])
    else:
        # Make a simple static plot of the solution
        plt.plot(x_A,
                 x_B,
                 'r-',
                 y_A,
                 y_B,
                 'b-',
                 daspectmode='equal',
                 legend=['A', 'B'],
                 axis=[-1, 1, -1, 1],
                 savefig='tmp_two_stars.png')
    #plt.axes().set_aspect('equal')  # mpl
    plt.show()
Exemple #18
0
def main():
    problem = Problem()
    solver = Solver(problem)
    viz = Visualizer(problem, solver)

    parser = problem.define_command_line_options()
    parser = solver.define_command_line_options(parser)
    args = parser.parse_args()
    problem.init_from_command_line(args)
    solver.init_from_command_line(args)

    solver.solve()
    import matplotlib.pyplot as plt
    plt = viz.plot(plt=plt)
    plt.show()
def main():
	problem = Problem()
	solver = Solver(problem)
	viz = Visualizer(problem, solver)

	parser = problem.define_command_line_options()
	parser = solver.define_command_line_options(parser)
	args = parser.parse_args()
	problem.init_from_command_line(args)
	solver.init_from_command_line(args)
	
	solver.solve()
	import matplotlib.pyplot as plt
	plt = viz.plot(plt = plt)
	plt.show()	
Exemple #20
0
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 main():
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--I", type=float, default=1.0)
    parser.add_argument("--V", type=float, default=0.0)
    parser.add_argument("--m", type=float, default=1.0)
    parser.add_argument("--b", type=float, default=0.0)
    parser.add_argument("--s", type=str, default="u")
    parser.add_argument("--F", type=str, default="0")
    parser.add_argument("--dt", type=float, default=0.05)
    # parser.add_argument('--T', type=float, default=10)
    parser.add_argument("--T", type=float, default=20)
    parser.add_argument("--window_width", type=float, default=30.0, help="Number of periods in a window")
    parser.add_argument("--damping", type=str, default="linear")
    parser.add_argument("--savefig", action="store_true")
    # Hack to allow --SCITOOLS options (scitools.std reads this argument
    # at import)
    parser.add_argument("--SCITOOLS_easyviz_backend", default="matplotlib")
    a = parser.parse_args()
    from scitools.std import StringFunction

    s = StringFunction(a.s, independent_variable="u")
    F = StringFunction(a.F, independent_variable="t")
    I, V, m, b, dt, T, window_width, savefig, damping = (
        a.I,
        a.V,
        a.m,
        a.b,
        a.dt,
        a.T,
        a.window_width,
        a.savefig,
        a.damping,
    )

    u, t = solver(I, V, m, b, s, F, dt, T, damping)

    num_periods = plot_empirical_freq_and_amplitude(u, t)
    if num_periods <= 40:
        plt.figure()
        visualize(u, t)
    else:
        visualize_front(u, t, window_width, savefig)
        visualize_front_ascii(u, t)
    plt.show()
Exemple #22
0
def slides_waves():
    L = 10.
    a = 0.5
    B0 = 1.
    A = B0 / 5
    t0 = 3.
    v = 1.
    x0 = lambda t: L / 4 + v * t if t < t0 else L / 4 + v * t0
    sigma = 1.0

    def bottom(x, t):
        return (B(x, a, L, B0) + S(x, A, x0(t), sigma))

    def depth(x, t):
        return -bottom(x, t)

    import scitools.std as plt
    x = np.linspace(0, L, 101)
    plt.plot(x, bottom(x, 0), x, depth(x, 0), legend=['bottom', 'depth'])
    plt.show()
    raw_input()
    plt.figure()
    dt_b = 0.01
    solver(I=0,
           V=0,
           f=lambda x, t: -(depth(x, t - dt_b) - 2 * depth(x, t) + depth(
               x, t + dt_b)) / dt_b**2,
           c=lambda x, t: np.sqrt(np.abs(depth(x, t))),
           U_0=None,
           U_L=None,
           L=L,
           dt=0.1,
           C=0.9,
           T=20,
           user_action=PlotSurfaceAndBottom(B,
                                            S,
                                            a,
                                            L,
                                            B0,
                                            A,
                                            x0,
                                            sigma,
                                            umin=-2,
                                            umax=2),
           stability_safety_factor=0.9)
Exemple #23
0
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--I', type=float, default=1.0)
    parser.add_argument('--V', type=float, default=0.0)
    parser.add_argument('--m', type=float, default=1.0)
    parser.add_argument('--b', type=float, default=0.0)
    parser.add_argument('--s', type=str, default='4*pi**2*u')
    parser.add_argument('--F', type=str, default='0')
    parser.add_argument('--dt', type=float, default=0.05)
    parser.add_argument('--T', type=float, default=20)
    parser.add_argument('--window_width',
                        type=float,
                        default=30.,
                        help='Number of periods in a window')
    parser.add_argument('--damping', type=str, default='linear')
    parser.add_argument('--savefig', action='store_true')
    # Hack to allow --SCITOOLS options
    # (scitools.std reads this argument at import)
    parser.add_argument('--SCITOOLS_easyviz_backend', default='matplotlib')
    a = parser.parse_args()
    from scitools.std import StringFunction
    s = StringFunction(a.s, independent_variable='u')
    F = StringFunction(a.F, independent_variable='t')
    I, V, m, b, dt, T, window_width, savefig, damping = \
       a.I, a.V, a.m, a.b, a.dt, a.T, a.window_width, a.savefig, \
       a.damping

    # compute u by both methods and then visualize the difference
    u, t = solver2(I, V, m, b, s, F, dt, T, damping)
    u_bw, _ = solver_bwdamping(I, V, m, b, s, F, dt, T, damping)
    u_diff = u - u_bw

    num_periods = plot_empirical_freq_and_amplitude(u_diff, t)
    if num_periods <= 40:
        plt.figure()
        legends = [
            '1st-2nd order method', '2nd order method', '1st order method'
        ]
        visualize([(u_diff, t), (u, t), (u_bw, t)], legends)
    else:
        visualize_front(u_diff, t, window_width, savefig)
        #visualize_front_ascii(u_diff, t)
    plt.show()
Exemple #24
0
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()
Exemple #25
0
def u_sines():
    """
    Plot sine basis functions and a resulting u to
    illustrate what it means to use global basis functions.
    """
    import matplotlib.pyplot as plt
    x = np.linspace(0, 4, 1001)
    psi0 = np.sin(2*np.pi/4*x)
    psi1 = np.sin(2*np.pi*x)
    psi2 = np.sin(2*np.pi*4*x)
    u = 4*psi0 - 0.5*psi1 - 0*psi2
    plt.plot(x, psi0, 'r-', label=r"$\psi_0$")
    plt.plot(x, psi1, 'g-', label=r"$\psi_1$")
    #plt.plot(x, psi2, label=r"$\psi_2$")
    plt.plot(x, u, 'b-', label=r"u")
    plt.legend()
    plt.savefig('tmp_u_sines.pdf')
    plt.savefig('tmp_u_sines.png')
    plt.show()
Exemple #26
0
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--I', type=float, default=1.0)
    parser.add_argument('--V', type=float, default=0.0)
    parser.add_argument('--m', type=float, default=1.0)
    parser.add_argument('--b', type=float, default=0.0)
    parser.add_argument('--s', type=str, default='4*pi**2*u')
    parser.add_argument('--F', type=str, default='0')
    parser.add_argument('--dt', type=float, default=0.05)
    parser.add_argument('--T', type=float, default=20)
    parser.add_argument('--window_width', type=float, default=30.,
                        help='Number of periods in a window')
    parser.add_argument('--damping', type=str, default='linear')
    parser.add_argument('--savefig', action='store_true')
    # Hack to allow --SCITOOLS options
    # (scitools.std reads this argument at import)
    parser.add_argument('--SCITOOLS_easyviz_backend',
                        default='matplotlib')
    a = parser.parse_args()
    from scitools.std import StringFunction
    s = StringFunction(a.s, independent_variable='u')
    F = StringFunction(a.F, independent_variable='t')
    I, V, m, b, dt, T, window_width, savefig, damping = \
       a.I, a.V, a.m, a.b, a.dt, a.T, a.window_width, a.savefig, \
       a.damping

    # compute u by both methods and then visualize the difference
    u, t = solver2(I, V, m, b, s, F, dt, T, damping)
    u_bw, _ = solver_bwdamping(I, V, m, b, s, F, dt, T, damping)
    u_diff = u - u_bw

    num_periods = plot_empirical_freq_and_amplitude(u_diff, t)
    if num_periods <= 40:
        plt.figure()
        legends = ['1st-2nd order method',
                   '2nd order method',
                   '1st order method']
        visualize([(u_diff, t), (u, t), (u_bw, t)], legends)
    else:
        visualize_front(u_diff, t, window_width, savefig)
        #visualize_front_ascii(u_diff, t)
    plt.show()
Exemple #27
0
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()
Exemple #28
0
def u_sines():
    """
    Plot sine basis functions and a resulting u to
    illustrate what it means to use global basis functions.
    """
    import matplotlib.pyplot as plt
    x = np.linspace(0, 4, 1001)
    psi0 = np.sin(2*np.pi/4*x)
    psi1 = np.sin(2*np.pi*x)
    psi2 = np.sin(2*np.pi*4*x)
    #u = 4*psi0 - 0.5*psi1 - 0*psi2
    u = 4*psi0 - 0.5*psi1
    plt.plot(x, psi0, 'r-', label=r"$\psi_0$")
    plt.plot(x, psi1, 'g-', label=r"$\psi_1$")
    #plt.plot(x, psi2, label=r"$\psi_2$")
    plt.plot(x, u, 'b-', label=r"$u=4\psi_0 - \frac{1}{2}\psi_1$")
    plt.legend()
    plt.savefig('u_example_sin.pdf')
    plt.savefig('u_example_sin.png')
    plt.show()
Exemple #29
0
def main():
    problem = Problem()
    solver = Solver(problem)
    viz = Visualizer(problem, solver)

    # Read input from the command line
    parser = problem.define_command_line_options()
    parser = solver. define_command_line_options(parser)
    args = parser.parse_args()
    problem.init_from_command_line(args)
    solver. init_from_command_line(args)

    # Solve and plot
    solver.solve()
    import matplotlib.pyplot as plt
    #import scitools.std as plt
    plt = viz.plot(plt=plt)
    E = solver.error()
    if E is not None:
        print 'Error: %.4E' % E
    plt.show()
Exemple #30
0
def main():
    problem = Problem()
    solver = Solver(problem)
    viz = Visualizer(problem, solver)

    # Read input from the command line
    parser = problem.define_command_line_options()
    parser = solver. define_command_line_options(parser)
    args = parser.parse_args()
    problem.init_from_command_line(args)
    solver. init_from_command_line(args)

    # Solve and plot
    solver.solve()
    import matplotlib.pyplot as plt
    #import scitools.std as plt
    plt = viz.plot(plt=plt)
    E = solver.error()
    if E is not None:
        print 'Error: %.4E' % E
    plt.show()
Exemple #31
0
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--I', type=float, default=1.0)
    parser.add_argument('--V', type=float, default=0.0)
    parser.add_argument('--m', type=float, default=1.0)
    parser.add_argument('--b', type=float, default=0.0)
    parser.add_argument('--s', type=str, default='u')
    parser.add_argument('--F', type=str, default='0')
    parser.add_argument('--dt', type=float, default=0.05)
    #parser.add_argument('--T', type=float, default=10)
    parser.add_argument('--T', type=float, default=20)
    parser.add_argument('--window_width',
                        type=float,
                        default=30.,
                        help='Number of periods in a window')
    parser.add_argument('--damping', type=str, default='linear')
    parser.add_argument('--savefig', action='store_true')
    # Hack to allow --SCITOOLS options (scitools.std reads this argument
    # at import)
    parser.add_argument('--SCITOOLS_easyviz_backend', default='matplotlib')
    a = parser.parse_args()
    from scitools.std import StringFunction
    s = StringFunction(a.s, independent_variable='u')
    F = StringFunction(a.F, independent_variable='t')
    I, V, m, b, dt, T, window_width, savefig, damping = \
       a.I, a.V, a.m, a.b, a.dt, a.T, a.window_width, a.savefig, \
       a.damping

    u, t = solver(I, V, m, b, s, F, dt, T, damping)

    num_periods = plot_empirical_freq_and_amplitude(u, t)
    if num_periods <= 40:
        plt.figure()
        visualize(u, t)
    else:
        visualize_front(u, t, window_width, savefig)
        visualize_front_ascii(u, t)
    plt.show()
Exemple #32
0
def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--I', type=float, default=1.0)
    parser.add_argument('--V', type=float, default=0.0)
    parser.add_argument('--m', type=float, default=1.0)
    parser.add_argument('--b', type=float, default=0.0)
    parser.add_argument('--s', type=str, default='u')
    parser.add_argument('--F', type=str, default='0')
    parser.add_argument('--dt', type=float, default=0.05)
    #parser.add_argument('--T', type=float, default=10)
    parser.add_argument('--T', type=float, default=20)
    parser.add_argument('--window_width', type=float, default=30.,
                        help='Number of periods in a window')
    parser.add_argument('--damping', type=str, default='linear')
    parser.add_argument('--savefig', action='store_true')
    # Hack to allow --SCITOOLS options (scitools.std reads this argument
    # at import)
    parser.add_argument('--SCITOOLS_easyviz_backend', default='matplotlib')
    a = parser.parse_args()
    from scitools.std import StringFunction
    s = StringFunction(a.s, independent_variable='u')
    F = StringFunction(a.F, independent_variable='t')
    I, V, m, b, dt, T, window_width, savefig, damping = \
       a.I, a.V, a.m, a.b, a.dt, a.T, a.window_width, a.savefig, \
       a.damping

    u, t = solver(I, V, m, b, s, F, dt, T, damping)

    num_periods = plot_empirical_freq_and_amplitude(u, t)
    if num_periods <= 40:
        plt.figure()
        visualize(u, t)
    else:
        visualize_front(u, t, window_width, savefig)
        visualize_front_ascii(u, t)
    plt.show()
Exemple #33
0
b = 1
w = 1
delta_t = (2 * pi) / (w * n)
counter = 0
X = []
Y = []

for k in range(n + 1):
    tk = k * delta_t  #each time through we need to add a new k value
    x = a * cos(w * tk)
    y = b * sin(w * tk)
    X.append(x)
    Y.append(y)
    XP = array(X)
    YP = array(Y)
    XF = array([x])
    YF = array([y])
    velo = w * sqrt(a**2 * sin(w * tk)**2 + b**2 * cos(w * tk)**2)
    plot(XP,
         YP,
         '-r',
         XF,
         YF,
         'bo',
         axis=[-1.2, 1.2, -1.2, 1.2],
         title='Planetary orbit',
         legend=(['Instaneous velocity=%6f' % velo, 'present location']),
         savefig='pix/planet%4d.png' % counter)
    counter += 1
    show()
Exemple #34
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()
 def plot(self):
     filename = 'logistic_' + str(self.problem) + '.pdf'
     plot(self.t, self.u)
     title(str(self.problem) + ', dt=%g' % self.dt)
     savefig(filename)
     show()
Exemple #36
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 00:23:08 2015

@author: shiftehs
"""

import numpy as np 
import matplotlib.pyplot as plt 
import scitools.std as sci

x = np.linspace(1,10,100)
y = np.cos(x)
sci.plot(x,y)
sci.xaxis = [0,3]
sci.show()  

Exemple #37
0
 def plot(self):
     filename = 'logistic_' + str(self.problem) + '.pdf'
     plot(self.t, self.u)
     title(str(self.problem) + ', dt=%g' % self.dt)
     savefig(filename)
     show()
Exemple #38
0
solvers_theta = [
    odespy.ForwardEuler(f),
    # Implicit methods must use Newton solver to converge
    odespy.BackwardEuler(f, nonlinear_solver='Newton'),
    odespy.CrankNicolson(f, nonlinear_solver='Newton'),
]

solvers_RK = [odespy.RK2(f), odespy.RK4(f)]
solvers_accurate = [
    odespy.RK4(f),
    odespy.CrankNicolson(f, nonlinear_solver='Newton'),
    odespy.DormandPrince(f, atol=0.001, rtol=0.02)
]
solvers_CN = [odespy.CrankNicolson(f, nonlinear_solver='Newton')]

if __name__ == '__main__':
    timesteps_per_period = 20
    solver_collection = 'theta'
    num_periods = 1
    try:
        # Example: python vib_odespy.py 30 accurate 50
        timesteps_per_period = int(sys.argv[1])
        solver_collection = sys.argv[2]
        num_periods = int(sys.argv[3])
    except IndexError:
        pass  # default values are ok
    solvers = eval('solvers_' + solver_collection)  # list of solvers
    run_solvers_and_plot(solvers, timesteps_per_period, num_periods)
    plt.show()
    raw_input()
Exemple #39
0
def visualize(t):
    plot(range(len(t)), log(abs(t)), ’ro’)
    # or just plot(log(abs(t)), ’ro’)
    show()
Exemple #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