1D 1st-order Linear Convection

The Wave Equation

  • Understand the Problem
  • Formulate the Problem
  • Design Algorithm
  • Implement Algorithm
  • Conclusions

Implement the Algorithm in Python

In [41]:
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline 
In [81]:
def convection (nt, nx, tmax, xmax, c):
    """
    returns the velocity field and distance
    """
    # Increments in space and time
    dt = tmax/(nt-1)
    dx = xmax/(nx-1)
    
    # Initialization of data sructures
    u = np.zeros((nx, nt))
    x = np.zeros(nx)
    
    # BCs
    u[0, :] = u[nx-1, :] = 1
    
    #ICs - 1st way
    for i in range(0, nx-1):
        if (i > (nx-1)/4 and i < (nx-1)/2):
            u[i, 0] = 2
        else:
            u[i, 0] = 1
    
    # Loop
    for n in range(0, nt-1):
        for i in range(1, nx-1):
            u[i, n+1] = u[i, n]-c*(dt/dx)*(u[i, n]-u[i-1, n])
            
    # X loop
    for i in range(0, nx):
        x[i] = i*dx
    
    return u, x
    
def plot(u, x, nt, title):
    """
    Plots the Velocity Field Results in 1D
    """
    plt.figure()
    plt.show()
    for i in range(0, nt, 10):
        plt.plot(x, u[:,i], 'r')
        plt.xlabel('x [m]')
        plt.ylabel('u [m/s]')
        plt.ylim([0, 2.2])
        plt.title(title)
        plt.grid(True, linestyle='-.', linewidth='0.5', color='black')
       

Run

In [82]:
u,x = convection(151, 51, 0.5, 2.0, 0.5)
plot(u,x,151,'Figure 1: c=0.5m/s, nt=151, nx=51, tmax=0.5s')

u,x = convection(151, 1001, 0.5, 2.0, 0.5)
plot(u,x,151,'Figure 2: c=0.5m/s, nt=151, nx=1001, tmax=0.5s')

u,x = convection(151, 51, 2.0, 2.0, 0.5)
plot(u,x,151,'Figure 3: c=0.5m/s, nt=151, nx=51, tmax=2s')
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
In [ ]:
 
In [ ]: