Richard.L
Richard.L

Reputation: 139

Using matplotlib.pyplot to make the animation of the 1D wave equation

I have been using matplotlib from python to show the animation of 1D wave equation.But I got a problem of making the animation.I want the image of the wave to change with time.It means that I may need a loop to form many different pictures of the wave equation.But it seems that the time cannot be put into the wave functions ,so the images do not change at all.Please help me with the mistake that I made. Here are the codes that I wrote:(Part of the codes comes from the book "Python Scripting for Computational Science")

from numpy import zeros,linspace,sin,pi

import matplotlib.pyplot as mpl

def I(x):
    return sin(2*x*pi/L)

def f(x,t):
    return sin(x*t)

def solver0(I,f,c,L,n,dt,tstop):
    # f is a function of x and t, I is a function of x
    x = linspace(0,L,n+1)
    dx = L/float(n)
    if dt <= 0:
        dt = dx/float(c)
    C2 = (c*dt/dx)**2
    dt2 = dt*dt
    up = zeros(n+1)
    u = up.copy()
    um = up.copy()
    t = 0.0
    for i in range(0,n):
        u[i] = I(x[i])
    for i in range(1,n-1):
        um[i] = u[i]+0.5*C2*(u[i-1] - 2*u[i] + u[i+1]) + dt2*f(x[i],t)
    um[0] = 0
    um[n] = 0    
    while t <= tstop:
        t_old = t
        t += dt
        #update all inner points:
        for i in range(1,n-1):
            up[i] = -um[i] + 2*u[i] + C2*(u[i-1] - 2*u[i] + u[i+1]) + dt2*f(x[i],t_old)
        #insert boundary conditions:
        up[0] = 0
        up[n] = 0
        #update data structures for next step
        um = u.copy()
        u = up.copy()   
    return u

c = 3.0  #given by myself
L = 10
n = 100
dt = 0
tstart = 0
tstop = 6
x = linspace(0,L,n+1)
t_values = linspace(tstart,tstop,31)
mpl.ion()
y = solver0(I, f, c, L, n, dt, tstop)
lines = mpl.plot(x,y)
mpl.axis([x[0], x[-1], -1.0, 1.0])
mpl.xlabel('x')
mpl.ylabel('y')

counter = 0
for t in t_values:
    y = solver0(I,f,c,L,n,dt,tstop)
    lines[0].set_ydata(y)
    mpl.draw()
    mpl.legend(['t=%4.1f' % t])
    mpl.savefig('sea_%04d.png' %counter)
    counter += 1

Upvotes: 2

Views: 614

Answers (1)

Tony O
Tony O

Reputation: 513

Maybe that's what you need?

y = solver0(I,f,c,L,n,dt,t)

Upvotes: 1

Related Questions