Python解决一维波动方程和动画

时间:2014-11-20 12:42:38

标签: python

我改编了一个解决1d波动方程的代码。我的问题是动画时间相关的结果。我用下面的代码试了一下,知道我错了什么吗?我使用了动画包,但有些人总是说不止一个元素是暧昧的...

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import matplotlib.animation as animation

#Set Helvetica Font
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
class wave1d(object):
    def __init__(self,width,T,nx,nt,c):

        self.x = np.linspace(-0.5*width,0.5*width,nx)
        self.t = np.linspace(0,T,nt+1)

        self.dx = self.x[1]-self.x[0]
        self.dt = self.t[1]-self.t[0]

        self.xx = self.x

        # Gamma_x squared
        self.gx2 = c*self.dt/self.dx

        # 2*(1-gamma_x^2-gamma_y^2)
        self.gamma = 2*(1 - self.gx2)


    def solve(self,ffun,gfun):

        f = ffun(self.xx)
        g = gfun(self.xx) 

        u = np.zeros((nx,nt+1))

        # Set initial condition
        u[:,0] = f

        """ Compute first time step """
        u[:,1] = 0.5*self.gamma*f+self.dt*g
        u[1:-1,1] += 0.5*self.gx2*(f[2:]+f[:-2])


        for k in range(1,nt):
            # Every point contains these terms
            u[:,k+1] = self.gamma*u[:,k] - u[:,k-1]

            # Interior points
            u[1:-1,k+1] += self.gx2*(u[2:,k]+u[:-2,k])


            # Right boundary
            u[-1,k+1] += 2*self.gx2*u[-2,k] 


            # Left boundary
            u[0,k+1] += 2*self.gx2*u[1,k] 


        return u        

if __name__ == '__main__':

    # Final time
    T = 2

    # Domain dimensions
    width = 8

    # Wave speed
    c = 1

    # Number of time steps
    nt = 400

    # Grid points in x direction
    nx = 500

    wave_eq = wave1d(width,T,nx,nt,c)

    # Initial value functions
    f = lambda x: np.sin(x-width)
    g = lambda x: 0

    u = wave_eq.solve(f,g)

    x = wave_eq.x

    frames = []
    fig = plt.figure(1,(16,8))
    for k in range(nt+1):
        frame = plt.show(u[:,k])
        frames.append([frame])
    ani = animation.ArtistAnimation(fig,frames,interval=50, blit=True,repeat_delay=1000)
#    ani.save('wave1d.mp4',dpi=300)
plt.show()

0 个答案:

没有答案