Step 5: Burgers’ Equation in 1-D#


You can read about Burgers’ Equation on its wikipedia page.

Burgers’ equation in one spatial dimension looks like this:

\[\frac{\partial u}{\partial t} + u \frac{\partial u}{\partial x} = \nu \frac{\partial ^2u}{\partial x^2}\]

As you can see, it is a combination of non-linear convection and diffusion. It is surprising how much you learn from this neat little equation!

We can discretize it using the methods we’ve already detailed in Steps 1 to 4. Using forward difference for time, backward difference for space and our 2nd-order method for the second derivatives yields:

\[\frac{u_i^{n+1}-u_i^n}{\Delta t} + u_i^n \frac{u_i^n - u_{i-1}^n}{\Delta x} = \nu \frac{u_{i+1}^n - 2u_i^n + u_{i-1}^n}{\Delta x^2}\]

As before, once we have an initial condition, the only unknown is \(u_i^{n+1}\). We will step in time as follows:

\[u_i^{n+1} = u_i^n - u_i^n \frac{\Delta t}{\Delta x} (u_i^n - u_{i-1}^n) + \nu \frac{\Delta t}{\Delta x^2}(u_{i+1}^n - 2u_i^n + u_{i-1}^n)\]

Initial and Boundary Conditions#

To examine some interesting properties of Burgers’ equation, it is helpful to use different initial and boundary conditions than we’ve been using for previous steps.

Our initial condition for this problem is going to be:

\begin{eqnarray} u &=& -\frac{2 \nu}{\phi} \frac{\partial \phi}{\partial x} + 4 \
\phi &=& \exp \bigg(\frac{-x^2}{4 \nu} \bigg) + \exp \bigg(\frac{-(x-2 \pi)^2}{4 \nu} \bigg) \end{eqnarray}

This has an analytical solution, given by:

\begin{eqnarray} u &=& -\frac{2 \nu}{\phi} \frac{\partial \phi}{\partial x} + 4 \
\phi &=& \exp \bigg(\frac{-(x-4t)^2}{4 \nu (t+1)} \bigg) + \exp \bigg(\frac{-(x-4t -2 \pi)^2}{4 \nu(t+1)} \bigg) \end{eqnarray}

Our boundary condition will be:

\[u(0) = u(2\pi)\]

This is called a periodic boundary condition. Pay attention! This will cause you a bit of headache if you don’t read carefully.

Saving Time with SymPy#

The initial condition we’re using for Burgers’ Equation can be a bit of a pain to evaluate by hand. The derivative \(\frac{\partial \phi}{\partial x}\) isn’t too terribly difficult, but it would be easy to drop a sign or forget a factor of \(x\) somewhere, so we’re going to use SymPy to help us out.

SymPy is the symbolic math library for Python. It has a lot of the same symbolic math functionality as Mathematica with the added benefit that we can easily translate its results back into our Python calculations (it is also free and open source).

Start by loading the SymPy library, together with our favorite library, NumPy.

import numpy as np
import sympy as sp

We’re also going to tell SymPy that we want all of its output to be rendered using \(\LaTeX\). This will make our Notebook beautiful!

sp.init_printing(use_latex=True)

Start by setting up symbolic variables for the three variables in our initial condition and then type out the full equation for \(\phi\). We should get a nicely rendered version of our \(\phi\) equation.

x, nu, t = sp.symbols('x nu t')
phi = (sp.exp(-(x - 4 * t)**2 / (4 * nu * (t + 1))) +
       sp.exp(-(x - 4 * t - 2 * sp.pi)**2 / (4 * nu * (t + 1))))
phi
_images/4797157e44b12211b615727416478e41dbc6b6cabf7ca6334d2b589fdd163dba.png

It’s maybe a little small, but that looks right. Now to evaluate our partial derivative \(\frac{\partial \phi}{\partial x}\) is a trivial task.

phiprime = phi.diff(x)
phiprime
_images/60f620a218f5ce781eb329e3ca3e678c31f5803847f1664f16e6bddee5e10547.png

If you want to see the unrendered version, just use the Python print command.

print(phiprime)
-(-8*t + 2*x)*exp(-(-4*t + x)**2/(4*nu*(t + 1)))/(4*nu*(t + 1)) - (-8*t + 2*x - 4*pi)*exp(-(-4*t + x - 2*pi)**2/(4*nu*(t + 1)))/(4*nu*(t + 1))

Now what?#

Now that we have the Pythonic version of our derivative, we can finish writing out the full initial condition equation and then translate it into a usable Python expression. For this, we’ll use the lambdify function, which takes a SymPy symbolic equation and turns it into a callable function.

from sympy.utilities.lambdify import lambdify

u = -2 * nu * (phiprime / phi) + 4
u
_images/b16cb08c034af7091081e6de37dcf2fb5eb488642626b64a73ab54ff28c617d7.png

Lambdify#

To lambdify this expression into a useable function, we tell lambdify which variables to request and the function we want to plug them in to.

ufunc = lambdify((t,x,nu),u)
ufunc(1,4,3)
_images/ed30f574347a95cccd3d5651f6e38309a1175b0b7367d1162e9b03bf00c3f263.png

Back to Burgers’ Equation#

Now that we have the initial conditions set up, we can proceed and finish setting up the problem. We can generate the plot of the initial condition using our lambdify-ed function.

from matplotlib import pyplot as plt

## variable declarations
nx = 401
nt = 100
dx = 2 * np.pi / (nx - 1)

nu = 0.07
dt = dx * nu

x = np.linspace(0,2*np.pi,nx)
un = np.zeros(nx)

t = 0

u = np.asarray([ufunc(t, x0, nu) for x0 in x])
# Convert ufunc to a numpy array u using np.asarray
# t = 0, nu = 0.07 and x0 in x, which is a np.linspace
#print(u)
u[-1]
_images/0de667931e8aba20bcb8feac5344681e301ecbc11873c979f1ad98d83802b919.png
# Set default font to Arial
plt.rcParams['font.family'] = 'arial'
# Set default font size
plt.rcParams['font.size'] = 16

# Create a new figure with a specific size
plt.figure(figsize=(11, 7), dpi = 100)

# Use pyplot to create a line plot of y vs. x with a specific color, linewidth, and label for the legend
plt.plot(x, u, color='blue', linewidth=2, marker='o', label='Initial')

# Add labels to the x and y axes with a specific font size
plt.xlabel('x', fontsize=16)
plt.ylabel('u0', fontsize=16)

# Add a title with a specific font size
plt.title('Plot of the initial condition', fontsize=18)

# Add a grid
plt.grid(True)

# Add a legend with a specific location
plt.legend(loc='upper right')

# Set the limit for the x and y axes
plt.xlim([0, 2*np.pi])
plt.ylim([0, 10])

# Set the ticks for the x and y axes
plt.xticks(np.arange(0, 2*np.pi, 1))
plt.yticks(np.arange(0, 10, 1))

# Display the plot
plt.show()
_images/cac3a24c32dc79b36465a8241aa041d74946e9e409ea1f23220dfe0c1ed8f588.png

This is definitely not the hat function we’ve been dealing with until now. We call it a “saw-tooth function”. Let’s proceed forward and see what happens.

Periodic Boundary Conditions#

One of the big differences between Step 5 and the previous lessons is the use of periodic boundary conditions. If you experiment with Steps 1 and 2 and make the simulation run longer (by increasing nt) you will notice that the wave will keep moving to the right until it no longer even shows up in the plot.

With periodic boundary conditions, when a point gets to the right-hand side of the frame, it wraps around back to the front of the frame.

Recall the discretization that we worked out at the beginning of this notebook:

\[u_i^{n+1} = u_i^n - u_i^n \frac{\Delta t}{\Delta x} (u_i^n - u_{i-1}^n) + \nu \frac{\Delta t}{\Delta x^2}(u_{i+1}^n - 2u_i^n + u_{i-1}^n)\]

What does \(u_{i+1}^n\) mean when \(i\) is already at the end of the frame?

Think about this for a minute before proceeding.

for n in range(nt):
    un = u.copy()
    for i in range(1, nx-1):
        u[i] = un[i] - un[i] * dt / dx *(un[i] - un[i-1]) + nu * dt / dx**2 *\
                (un[i+1] - 2 * un[i] + un[i-1])
    u[-1] = un[-1] - un[-1] * dt / dx *(un[-1] - un[-2]) + nu * dt / dx**2 *\
                (un[1] - 2 * un[-1] + un[-2])
    u[0] = u[-1]
    
    
u_analy = np.asarray([ufunc(nt * dt, xi, nu) for xi in x])
# Create a new figure with a specific size
plt.figure(figsize=(11, 7), dpi = 100)
plt.plot(x, u, color='blue', linewidth=2, marker='o', label='Computational')
plt.plot(x, u_analy, color='red', linewidth=2, label='Analytical')
# Add labels to the x and y axes with a specific font size
plt.xlabel('x', fontsize=16)
plt.ylabel('u', fontsize=16)

# Add a title with a specific font size
plt.title('Comparison of computational and analytical results', fontsize=18)

# Add a grid
plt.grid(True)

# Add a legend with a specific location
plt.legend(loc='upper right')

# Set the limit for the x and y axes
plt.xlim([0, 2*np.pi])
plt.ylim([0, 10])

# Set the ticks for the x and y axes
plt.xticks(np.arange(0, 2*np.pi, 1))
plt.yticks(np.arange(0, 10, 1))

# Display the plot
plt.show()
_images/d8dd18d8f7dfb8ed234c5bb7e3af6b69345ff2c1149bcf30cd2f46801a21e074.png

What next?#

The subsequent steps will be in two dimensions. But it is easy to extend the 1D finite-difference formulas to the partial derivatives in 2D or 3D. Just apply the definition — a partial derivative with respect to \(x\) is the variation in the \(x\) direction while keeping \(y\) constant.

Before moving on to Step 6, make sure you have completed your own code for steps 1 through 5 and you have experimented with the parameters and thought about what is happening.