Advertisement
steffenkame

1D-wave-simulation

Jan 18th, 2014
433
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.13 KB | None | 0 0
  1. from math import sin, pi
  2. from numpy import zeros, linspace
  3. from scitools.numpyutils import iseq
  4. import time
  5.  
  6. import matplotlib.pyplot as plt
  7. import numpy as np
  8. fig, ax = plt.subplots()
  9.  
  10.  
  11.  
  12. def I(x):  
  13.     return sin(2*x*pi/L)  
  14.  
  15. def f(x,t):
  16.     return 0
  17.  
  18. def solver0(I, f, c, L, n, dt, tstop):
  19.  
  20.     ##########
  21.     # PLOT
  22.     ##########
  23.  
  24.     x = []
  25.     y = []
  26.     for i in range(n+1):
  27.         x.append(i)
  28.         y.append(3)
  29.     points, = ax.plot(x, y, marker='o', linestyle='None', alpha = 0.3)
  30.     ax.set_xlim(0, 20)
  31.     ax.set_ylim(-20, 20)
  32.  
  33.  
  34.     # f is a function of x and t, I is a function of x
  35.     x = linspace(0, L, n+1) # grid points in x dir
  36.     dx = L/float(n)
  37.     if dt <= 0: dt = dx/float(c) # max time step
  38.     C2 = (c*dt/dx)**2 # help variable in the scheme
  39.     dt2 = dt*dt
  40.  
  41.     up = zeros(n+1) # NumPy solution array
  42.     u = up.copy() # solution at t-dt
  43.     um = up.copy() # solution at t-2*dt
  44.  
  45.     t = 0.0
  46.     for i in iseq(0,n):
  47.         u[i] = I(x[i])*4        # I = initial force
  48.     for i in iseq(1,n-1):
  49.         um[i] = u[i] + 0.5*C2*(u[i-1] - 2*u[i] + u[i+1]) + \
  50.                 dt2*f(x[i], t)
  51.  
  52.     um[0] = 0; um[n] = 0
  53.  
  54.     while t <= tstop:
  55.           t_old = t; t += dt
  56.           # update all inner points:
  57.           for i in iseq(start=1, stop=n-1):
  58.               up[i] = - um[i] + 2*u[i] + \
  59.                       C2*(u[i-1] - 2*u[i] + u[i+1]) + \
  60.                       dt2*f(x[i], t_old)
  61.  
  62.           #print "len(up)", len(up)
  63.          
  64.           # insert boundary conditions:
  65.           up[0] = 0; up[n] = 0; #up[70] = 0
  66.           # update data structures for next step
  67.           um = u.copy(); u = up.copy()
  68.  
  69.           # PLOT
  70.           #print len(x), len(up[0:101])
  71.           new_y = up[0:n+1]
  72.           points.set_data(x, new_y)
  73.           plt.draw()
  74.           time.sleep(.1)
  75.  
  76.     return u
  77.  
  78. if __name__ == '__main__':
  79.  
  80. # When choosing the parameters you should also check that the units are correct
  81.  
  82.    c = 5100     # wave velocity
  83.    L = 20       # length of the array
  84.    n = 100      # amount of points
  85.    dt = 0.00004
  86.    tstop = 3
  87.    a = solver0(I, f, c, L, n, dt, tstop)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement