Example #1
0
def viz(I, V, f, c, L, dt, C, T, umin, umax, animate=True):
    """Run solver and visualize u at each time level."""
    import scitools.std as plt
    import time, glob, os

    def plot_u(u, x, t, n):
        """user_action function for solver."""
        u_e = u_exact(x,t,n)
        plt.plot(x, u, 'r-', x, u_e, 'bo',
                 xlabel='x', ylabel='u',
                 axis=[0, L, umin, umax],
                 title='t=%f' % t[n], legend=['numerical sol.', 'Exact sol.'],
                 show=True)

        # Let the initial condition stay on the screen for 2
        # seconds, else insert a pause of 0.2 s between each plot
        time.sleep(2) if t[n] == 0 else time.sleep(0.2)
        plt.savefig('frame_%04d.png' % n)  # for movie making

    def write_error(u,x,t,n):
        u_e      = u_exact(x,t,n)
        max_diff = ((u-u_e)).max()
        err_list.append(max_diff)
        print "At t= %.2f, maximum error: %.4E" %(t[n],max_diff)

        axis_max = 0.00073*len(t) # Experimentally found (max_err scales ~linearly)
        plt.plot(x, u-u_e, 'r-',
                 xlabel='x', ylabel='u_{num}-u_{exact}',
                 axis=[0, (len(x)-1)/2.0, -axis_max, axis_max],
                 title='t=%f' % t[n], legend='Absolute error',
                 show=True)
    def plot_both(u,x,t,n):
        u_e      = u_exact(x,t,n)
        max_diff = ((u-u_e)).max()
        err_list.append(max_diff)
        print "At t= %.2f, maximum error: %.4E" %(t[n],max_diff)

        axis_max = 0.00073*len(t) # Experimentally found (max_err scales ~linearly)
        plt.subplot(211)
        plt.plot(x, u, 'r-', x, u_e, 'bo',
                 xlabel='x', ylabel='u',
                 axis=[0, L, umin, umax],
                 title='t=%f' % t[n], legend=['numerical sol.', 'Exact sol.'])
        plt.subplot(212)
        plt.plot(x, u-u_e, 'r-',
                 xlabel='x', ylabel='u_{num}-u_{exact}',
                 axis=[0, (len(x)-1)/2.0, -axis_max, axis_max],
                 legend='Absolute error',
                 show=True)


    # Clean up old movie frames
    for filename in glob.glob('frame_*.png'):
        os.remove(filename)

    # Choose user_action
    if animate == None:
        user_action = plot_both
    else:
        user_action = plot_u if animate else write_error
    # Let the magic happen
    u, x, t, cpu = solver(I, V, f, c, L, dt, C, T, user_action)
def viz(
    I,
    V,
    f,
    c,
    L,
    dt,
    C,
    T,
    ymax,  # y axis: [-ymax, ymax]
    u_exact,  # u_exact(x, t)
    animate='u and u_exact',  # or 'error'
    movie_filename='movie',
):
    """Run solver and visualize u at each time level."""
    import scitools.std as plt
    import time, glob, os

    class Plot:
        def __init__(self, ymax, frame_name='frame'):
            self.max_error = []  # hold max amplitude errors
            self.max_error_t = []  # time points corresp. to max_error
            self.frame_name = frame_name
            self.ymax = ymax

        def __call__(self, u, x, t, n):
            """user_action function for solver."""
            if animate == 'u and u_exact':
                plt.plot(x,
                         u,
                         'r-',
                         x,
                         u_exact(x, t[n]),
                         'b--',
                         xlabel='x',
                         ylabel='u',
                         axis=[0, L, -self.ymax, self.ymax],
                         title='t=%f' % t[n],
                         show=True)
            else:
                error = u_exact(x, t[n]) - u
                local_max_error = np.abs(error).max()
                # self.max_error holds the increasing amplitude error
                if self.max_error == [] or \
                       local_max_error > max(self.max_error):
                    self.max_error.append(local_max_error)
                    self.max_error_t.append(t[n])
                # Use user's ymax until the error exceeds that value.
                # This gives a growing max value of the yaxis (but
                # never shrinking)
                self.ymax = max(self.ymax, max(self.max_error))
                plt.plot(x,
                         error,
                         'r-',
                         xlabel='x',
                         ylabel='error',
                         axis=[0, L, -self.ymax, self.ymax],
                         title='t=%f' % t[n],
                         show=True)
            plt.savefig('%s_%04d.png' % (self.frame_name, n))

    # Clean up old movie frames
    for filename in glob.glob('frame_*.png'):
        os.remove(filename)

    plot = Plot(ymax)
    u, x, t, cpu = solver(I, V, f, c, L, dt, C, T, plot)

    # Make plot of max error versus time
    plt.figure()
    plt.plot(plot.max_error_t, plot.max_error)
    plt.xlabel('time')
    plt.ylabel('max abs(error)')
    plt.savefig('error.png')
    plt.savefig('error.pdf')

    # Make .flv movie file
    fps = 4  # Frames per second
    codec2ext = dict(flv='flv')  #, libx64='mp4',
    #libvpx='webm', libtheora='ogg')

    filespec = 'frame_%04d.png'
    movie_program = 'avconv'  # or 'ffmpeg'
    for codec in codec2ext:
        ext = codec2ext[codec]
        cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\
              '-vcodec %(codec)s %(movie_filename)s.%(ext)s' % vars()
        os.system(cmd)
Example #3
0
def viz(I, V, f, c, L, Nx, C, T,
        ymax,                      # y axis: [-ymax, ymax]
        u_exact,                   # u_exact(x, t)
        animate='u and u_exact',   # or 'error'
        movie_filename='movie',
        ):
    """Run solver and visualize u at each time level."""
    import scitools.std as plt
    import time, glob, os

    class Plot:
        def __init__(self, ymax, frame_name='frame'):
            self.max_error = []   # hold max amplitude errors
            self.max_error_t = [] # time points corresponding to max_error
            self.frame_name = frame_name
            self.ymax = ymax

        def __call__(self, u, x, t, n):
            """user_action function for solver."""
            if animate == 'u and u_exact':
                plt.plot(x, u, 'r-',
                         x, u_exact(x, t[n]), 'b--',
                         xlabel='x', ylabel='u',
                         axis=[0, L, -self.ymax, self.ymax],
                         title='t=%f' % t[n], show=True)
            else:
                error = u_exact(x, t[n]) - u
                local_max_error = np.abs(error).max()
                # self.max_error holds the increasing amplitude error
                if self.max_error == [] or \
                       local_max_error > max(self.max_error):
                    self.max_error.append(local_max_error)
                    self.max_error_t.append(t[n])
                # Use user's ymax until the error exceeds that value.
                # This gives a growing max value of the yaxis (but
                # never shrinking)
                self.ymax = max(self.ymax, max(self.max_error))
                plt.plot(x, error, 'r-',
                         xlabel='x', ylabel='error',
                         axis=[0, L, -self.ymax, self.ymax],
                         title='t=%f' % t[n], show=True)
            plt.savefig('%s_%04d.png' % (self.frame_name, n))

    # Clean up old movie frames
    for filename in glob.glob('frame_*.png'):
        os.remove(filename)

    plot = Plot(ymax)
    u, x, t, cpu = solver(I, V, f, c, L, Nx, C, T, plot)

    # Make plot of max error versus time
    plt.figure()
    plt.plot(plot.max_error_t, plot.max_error)
    plt.xlabel('time'); plt.ylabel('max abs(error)')
    plt.savefig('error.png')
    plt.savefig('error.pdf')

    # Make .flv movie file
    fps = 4  # Frames per second
    codec2ext = dict(flv='flv') #, libx64='mp4', libvpx='webm', libtheora='ogg')

    filespec = 'frame_%04d.png'
    movie_program = 'avconv'  # or 'ffmpeg'
    for codec in codec2ext:
        ext = codec2ext[codec]
        cmd = '%(movie_program)s -r %(fps)d -i %(filespec)s '\
              '-vcodec %(codec)s %(movie_filename)s.%(ext)s' % vars()
        os.system(cmd)