Parabolic PDE

Heat equation:
$$ u_t - c u_{xx} = 0\quad \text{in}\, \Omega\, \times\, [0,T] $$ $$ u(0,x) = g(x)\quad \text{in}\, \Omega\, $$ $$ u(t,0) = u(t,1) = 0 $$ Let: $$ g(x) = sin(\pi x) $$

Solution

$$ u(t,x) = e^{-\pi^2t}sin(\pi x) $$

Step 1: Import packages

  • numpy is used for vectors and linear algebra
  • scipy is unused here, but is common for scientific computing applications
  • matpllotlib.pyplot is used for plotting
In [1]:
%matplotlib inline
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import math

Step 2: Set up grid

dx: grid spacing in the $x$-direction
x: grid coordinates
xx: really fine grid coordinates

In [2]:
nx = 200
x = np.linspace(0, 1, nx, endpoint=False)
dx = x[1] - x[0]

Step 3: Set time parameters

In [3]:
T = 1.0 # end time
dt = 0.009
nt = int(T/dt)
print('T = %g' % T)
print('tsteps = %d' % nt)
print('    dx = %g' % dx)
print('    dt = %g' % dt)
T = 1
tsteps = 111
    dx = 0.005
    dt = 0.009

Step 4: Set initial condition

In [4]:
PI = math.pi
def g(x):
    return np.sin(PI*x)  

Step 5: Plot solution

In [5]:
import time

plotit = True
u = g(x)

if plotit:
    fig = plt.figure(figsize=(8,8))
    ax = fig.add_subplot(111)
    ax.set_title('u vs x')
    line1, = ax.plot(x, u, lw=3, clip_on=False)
    def init():
        line1.set_data([], [])
        
def timestepper(n):
    uex = np.exp(-1*PI**2*(n+1)*dt)*g(x)
    line1.set_data(x, uex)    
    return line1

from JSAnimation import IPython_display
from matplotlib import animation
animation.FuncAnimation(fig, timestepper, init_func=init, frames=nt, interval=10, blit=True)
Out[5]:


Once Loop Reflect