Numerical solution of PDE:s, Part 3: 2D diffusion problem

In the earlier posts related to PDE numerical integration, I showed how to discretize 1-dimensional diffusion or heat conduction equations either by explicit or implicit methods. The 1d model can work well in some situations where the symmetry of a physical system makes the concentration or temperature field practically depends on only one cartesian coordinate and is independent of the position along two other orthogonal coordinate axes.

The 2-dimensional version of the diffusion/heat equation is

CodeCogsEqn(44).gif

assuming that the diffusion is isotropic, i.e. its rate does not depend on direction.

In a discretized description, the function C(x,y,t) would be replaced by a three-index object

codecogseqn45

assuming that one of the corners of the domain is at the origin. Practically the same can also be done with two indices, as in

codecogseqn46

where N_x is the number of discrete points in x-direction.

Using the three-index version of the 2D diffusion equation and doing an explicit discretization, we get this kind of a discrete difference equation:

CodeCogsEqn(47).gif

which can be simplified a bit if we have \Delta x = \Delta y .

Below, I have written a sample R-Code program that calculates the evolution of a Gaussian concentration distribution by diffusion, in a domain where the x-interval is 0 < x < 6 and y-interval is 0 < y < 6. The boundary condition is that nothing diffuses through the boundaries of the domain, i.e. the two-dimensional integral of C(x,y,t) over the area [0,6]\times [0,6] does not depend on t.

library(graphics) #load the graphics library needed for plotting

lx <- 6.0 #length of the computational domain in x-direction
ly <- 6.0 #length of the computational domain in y-direction
lt <- 6 #length of the simulation time interval
nx <- 30 #number of discrete lattice points in x-direction
ny <- 30 #number of discrete lattice points in y-direction
nt <- 600 #number of timesteps
dx <- lx/nx #length of one discrete lattice cell in x-direction
dy <- ly/ny #length of one discrete lattice cell in y-direction
dt <- lt/nt #length of timestep

D <- 1.0 #diffusion constant (assumed isotropic)

Conc2d = matrix(nrow=ny,ncol=nx)
DConc2d <- matrix(nrow=ny, ncol=nx) #a vector for the changes in concentration during a timestep
xaxis <- c(0:(nx-1))*dx #the x values corresponding to the discrete lattice points
yaxis <- c(0:(ny-1))*dy #the y values corresponding to the discrete lattice points

kappax <- D*dt/(dx*dx) #a parameter needed in the discretization
kappay <- D*dt/(dy*dy) #a parameter needed in the discretization

for (i in c(1:ny)) {
for (j in c(1:nx)) {
Conc2d[i,j] = exp(-(i*dy-3)*(i*dy-3)-(j*dx-3)*(j*dx-3)) #2D Gaussian initial concentration distribution
DConc2d[i,j] <- 0 #all initial values in DConc vector zeroed
}
}

for (j in c(1:nt)) { #main time stepping loop

for(k in c(1:nx))
{
Conc2d[1,k] <- Conc2d[k,2] #fluxes through the boundaries of the domain are forced to stay zero
Conc2d[nx,k] <- Conc2d[nx-1,k]
}

for(k in c(1:ny)) {
Conc2d[k,1] <- Conc2d[k,2]
Conc2d[k,nx] <- Conc2d[k,nx-1]
}
for (k in c(2:(ny-1))) {
for (l in c(2:(nx-1))) {
DConc2d[k,l] <- kappax*(Conc2d[k,l-1]-2*Conc2d[k,l]+Conc2d[k,l+1]) + kappay*(Conc2d[k-1,l]-2*Conc2d[k,l]+Conc2d[k+1,l]) #time stepping
}
}

for (k in c(2:(ny-1))) {
for (l in c(2:(nx-1))) {
Conc2d[k,l] <- Conc2d[k,l]+DConc2d[k,l] #add the changes to the vector Conc
}
}
k <- 0
l <- 0

if(j %% 3 == 1) { #make plots of C(x,y) on every third timestep
jpeg(file = paste("plot_",j,".jpg",sep=""))
persp(yaxis,xaxis,Conc2d,zlim=c(0,1))
title(paste("C(x,y) at t =",j*dt))
dev.off()
}
}

To plot the distribution C(x,y) with a color map instead of a 3D surface, you can change the line

persp(yaxis,xaxis,Conc2d,zlim=c(0,1))

to

image(yaxis,xaxis,Conc2d,zlim=c(0,0.3))

The two kinds of graphs are shown below for three different values of t.

2d-explicit-surf1.jpg

2d-explicit-surf2.jpg

2d-explicit-surf3.jpg

Figure 1. Surface plots of the time development of a Gaussian mass or temperature distribution spreading by diffusion.

explicit-color1.jpg

explicit-color2.jpg

explicit-color3

Figure 2. Time development of a Gaussian mass or temperature distribution spreading by diffusion, plotted with a red-orange-yellow color map.

To obtain an implicit differencing scheme, we need to write the discretized equation as a matrix-vector equation where C_{i;j;k} is obtained from C_{i;j;k+1} by backward time stepping. In the square matrix, there is one row (column) for every lattice point of the discrete coordinate system. Therefore, if there are N points in x-direction and N points in y-direction, then the matrix is an N^2 \times N^2 – matrix. From this it’s quite obvious that the computation time increases very quickly when the spatial resolution is increased.

Initially, one may think that the equation corresponding to diffusion in a really coarse 3 \times 3 grid is the following one:

implicit2d-1

Where I’ve used the denotation k_x = \frac{D\Delta t}{(\Delta x)^2} and k_y = \frac{D\Delta t}{(\Delta x)^2} The problem with this is that there are unnecessary terms -k_x in here, creating a cyclic boundary condition (mass that is diffusing through the boundary described by line x = L reappears from the boundary on the other side, x = 0. The correct algorithm for assigning the nonzero elements A_{ij} of the matrix A is

1. A_{ij} = 1 + 2k_x + 2k_y , when i = j
2. A_{ij} = -k_x , when j=i-1 AND i\neq 1 (modulo N_x)
3. A_{ij} = -k_x , when j=i+1 AND i\neq 0 (modulo N_x)
4. A_{ij} = -k_y , when j=i+N_x OR j=i-N_x

when you want to get a boundary condition which ensures that anything that diffuses through the boundaries is lost forever. Then the matrix-vector equation in the case of 3 \times 3 lattice is

implicit-2d-2.jpg

Unlike the linear system in the 1D diffusion time stepping, this is not a tridiagonal problem and consequently is slower to solve. An R-Code that produces a series of images of the diffusion process for a Gaussian concentration distribution in a 15 \times 15 discrete lattice is given below.

library(graphics) #load the graphics library needed for plotting

lx <- 6.0 #length of the computational domain in x-direction
ly <- 6.0 #length of the computational domain in y-direction
lt <- 6 #length of the simulation time interval
nx <- 15 #number of discrete lattice points in x-direction
ny <- 15 #number of discrete lattice points in y-direction
nt <- 180 #number of timesteps
dx <- lx/nx #length of one discrete lattice cell in x-direction
dy <- ly/ny #length of one discrete lattice cell in y-direction
dt <- lt/nt #length of timestep

D <- 1.0 #diffusion constant

C = c(1:(nx*ny))
Cu = c(1:(nx*ny))
Conc2d = matrix(nrow=ny,ncol=nx)
xaxis <- c(0:(nx-1))*dx #the x values corresponding to the discrete lattice points
yaxis <- c(0:(ny-1))*dy #the y values corresponding to the discrete lattice points

kappax <- D*dt/(dx*dx) #a parameter needed in the discretization
kappay <- D*dt/(dy*dy) #a parameter needed in the discretization

A = matrix(nrow=(nx*ny),ncol=(nx*ny))

for(i in c(1:(nx*ny))) {
for(j in c(1:(nx*ny))) {
A[i,j] <- 0
if(i==j) A[i,j] <- 1+2*kappax+2*kappay
if(j==i+1 && (i%%nx != 0)) A[i,j] <- -kappax
if(j==i-1 && (i%%nx != 1)) A[i,j] <- -kappax
if(j==i+nx) A[i,j] <- -kappay
if(j==i-nx) A[i,j] <- -kappay
}
}

for (i in c(1:ny)) {
for (j in c(1:nx)) {
Conc2d[i,j] <- exp(-2*(i*dy-3)*(i*dy-3)-2*(j*dx-3)*(j*dx-3)) #2D Gaussian initial concentration distribution
}
}

for (j in c(1:nt)) { #main time stepping loop

for(k in c(1:ny)) {
for(l in c(1:nx)) {
C[(k-1)*nx+l] <- Conc2d[k,l]
}
}

Cu <- solve(A,C)

for(k in c(1:ny)) {
for(l in c(1:nx)) {
Conc2d[k,l] <- Cu[(k-1)*nx+l]
}
}

k <- 0
l <- 0

if(j %% 3 == 1) { #make plots of C(x,y) on every third timestep
jpeg(file = paste("plot_",j,".jpg",sep=""))
persp(y=xaxis,x=yaxis,z=Conc2d,zlim=c(0,1))
title(paste("C(x) at t =",j*dt))
dev.off()
}
}

Note that the function C(x,y) approaches a constant zero function as t increases, try modifying the code yourself to make a boundary condition that doesn’t let anything diffuse through the boundaries!

Save

Advertisements

Why does quantum mechanics need an infinite dimensional vector space?

When undergraduate physics students are trying to learn quantum mechanics, one of the most difficult obstacles is that abstract infinite dimensional vector spaces are needed, which makes it impossible for a person to mentally “see” the geometry in their minds in the way a three-dimensional space can be imagined. The fact that the coordinates of the points in that vector space are complex numbers certainly doesn’t make it any easier. When I was studying that myself in the early undergraduate studies, it took me over a year to get a hold of the concept that any self-adjoint operator acting on vectors in the quantum state space has a set of eigenvectors that form a basis of that space.

Sometimes, however, a quantum mechanics problem can be handled by approximating the state space with a finite-dimensional vector space. In fact, several physics Nobel prizes have been awarded for the study of two-state quantum systems. One example of a situation, where a quantum system is effectively a two-state system, is something where the ground state (n=0) and the first excited state (n=1) have energies that are close to each other, and the energy gap between the first and second (n = 2) excited states is unusually wide. Then, if the system is at low temperature, the Boltzmann factors of the lowest-lying two states,

CodeCogsEqn(37).gif

and

CodeCogsEqn(38).gif

are much larger numbers that the Boltzmann factors of any other states, and it is unlikely that a measurement of total energy will give a result other than one of the two lowest energy eigenvalues.

How, then, does one know that a quantum state space actually has to be infinite-dimensional? I once saw, in a mathematical physics textbook, a practice problem where this had to be proved, and I was proud for almost immediately finding the correct answer.

A cornerstone of nonrelativistic quantum mechanics is the position-momentum commutation relation

CodeCogsEqn(39).gif

Now, if the quantum state space were finite-dimensional with dimension N, then these operators \hat{x} and \hat{p} would be N\times N square matrices, and the constant i\hbar on the RHS would be a diagonal matrix where all the diagonal elements have value i\hbar

Actually, this equation can’t hold in the finite-dimensional case. To see this, consider the calculation rules for taking the trace of a matrix sum or a matrix product:

CodeCogsEqn(40).gif

codecogseqn43

Now, if you take the trace of both sides of the commutation relation equation, and use these rules, you will get the result

codecogseqn42

Which clearly isn’t possible. So, we have done a false assumption somewhere in the derivation of the contradictory equation above, and the false assumption must be the finite-dimensionality of the space where x and p are defined. An infinite dimensional operator doesn’t always have a trace at all, and this is the case with the operator xp-px.

An interested reader may try to form finite-dimensional matrix representations for the raising and lowering operators of a quantum harmonic oscillator, use those those to form matrices for operators \hat{x} and \hat{p}, and see what happens when you calculate their commutator.

A continuity curiosity

It’s sunday, and I don’t feel like writing lots of source code and posting it here today, so I’ll make a shorter post this time…

In physics and engineering, functions describing physical quantities are often classified as piecewise continuous, everywhere continuous, differentiable, continuously differentiable or complex analytical, which is a list of requirements of increasing strictness. In classical mechanics, most functions are continuous and “well-behaved”, excluding some fractal phase-space curves in chaotic systems.

In pure mathematics, there often happens some kind of play with badly discontinuous or in some other way “detached from reality” functions. Let me show one example of this kind of a function.

The continuity of a real function f:\mathbb{R}\rightarrow\mathbb{R} at point x_0 is defined by

codecogseqn23

or in other words

CodeCogsEqn(24).gif

which practically means that if we set any error bars f(x_o)-\epsilon \leq f(x) \leq f(x_0)+\epsilon for f(x), no matter how strict, there are always some error bars x_0 - \delta \leq x \leq x_0 + \delta for x that will keep the function value between those error bars.

So, here’s an example curious function that is special in the sense that it is continuous at only one point:

CodeCogsEqn(22).gif

which is a real function that has value x when x is a rational number and has value -x when x is an irrational number (the notation \mathbb{Q}^C means the complement of \mathbb{Q}).

Left as an exercise for the reader, is to explain how this function is continuous only at the point x=0.

Sometimes later, I’ll write about fractal curves, which are continuous everywhere but are nowhere differentiable and have no finite curve length.

Numerical solution of PDE:s, Part 2: Implicit method

In the previous blog post, I showed how to solve the diffusion equation

codecogseqn6

using the explicit method, where the equation is converted to a discrete one

codecogseqn12

which can be simplified by using the notation

CodeCogsEqn(16).gif

The problem with this approach is that if we want to have a high resolution, i.e. \Delta x is very small, the timestep \Delta t has to be made even much smaller to keep the procedure numerically stable. The stability of this kind of calculations can be investigated with Von Neumann stability analysis, and there you will find out that the instability acts by amplifying the short-wavelength Fourier components of the numerical discretization error.

The specific stability condition for the explicit solution of diffusion equation is

CodeCogsEqn(17).gif

In the better method to solve the diffusion equation, the implicit method, we will not solve the numbers f_{i;j+1} in a straightforward way from the numbers f_{i;j}. Instead, we use backward time stepping to write the f_{i;j} as a function of the numbers f_{i-1;j+1}, f_{i;j+1} and f_{i+1;j+1}, as in the equation below:

CodeCogsEqn(18).gif

which represents a linear system of equations. More specifically, it is a tridiagonal system, and in matrix-vector form it reads

CodeCogsEqn(26).png

for the case of a relatively small mesh n_x = 7. So, now we have to solve this tridiagonal system on each timestep, and this take more computation time than the explicit method but has the advantage of making the calculation stable even when \Delta t is not necessarily made much smaller than \Delta x.

A code for solving this kind of a linear system can be found from the book “Numerical Recipes for C” or from the corresponding book written for FORTRAN.

Now, let’s use the implicit method to solve a diffusion problem where the x-domain is

x \in [0,6],

and the step sizes are

\Delta x = 0.01 and \Delta t = 0.05 .

The initial concentration profile is chosen to be

CodeCogsEqn(19).gif

(don’t be confused by the fact that the function is now called C instead of f) and we use a boundary condition that forces the value of C(x,t) at the left endpoint to be C(0,t)=1 and that at the right endpoint to be C(6,t) = 0. This means that the left boundary is an infinite source of concentration (or heat in the case of conduction problem) and the right boundary is an infinite “sink”. With physical intuition, it is easy to deduce that this kind of system evolves toward a steady state where the value of C(x) decreases linearly from 1 to 0 on the interval [0,6]

A C++ code for doing this calculation is shown below.

// This program calculates the time development of a diffusion or heat conduction
// system with implicit finite differencing. The system described is the development of a concentration or temperature field
// between boundary points where it is constrained to stay at different constant values.
// Teemu Isojärvi, Feb 2017

#include 
#include 

using namespace std;

#define LX 6. // Length of spatial domain
#define NX 600 // Number of lattice points
#define LT 3. // Length of time interval
#define NT 60 // Number of timesteps

#define D 1. // Diffusion coefficient

int main(void)
{

double dx = (double)LX/(double)NX; // Lattice spacing
double dt = (double)LT/(double)NT; // Length of timestep

double c[NX]; // Concentration values at lattice points

double x; // Auxiliary position variable

double kappa = D*dt/(dx*dx); // Auxiliary variable for representing the linear system

double g[NX];
double b;
double q;

double u[NX]; // Vector for storing the solution on each timestep

for(int m = 0; m<NX; m++)
{
x = (double)m*dx;
c[m]=exp(-3*x*x); // Gaussian initial concentration
}

for(int n = 0; n<NT; n++)
{
c[0]=1;
c[NX-1]=0;

u[0]=(c[0]+kappa)/(2*kappa+1);
q = 2*kappa + 1;

for(int m = 1; m < NX; m++) { // First loop for solving the tridiagonal system g[m]=-kappa/q; q = (2*kappa + 1) + kappa*g[m]; u[m]=(c[m]+kappa*u[m-1])/q; } for(int m=(NX-2); m>=0; m--) u[m] -= g[m+1]*u[m+1]; // Second loop

for(int m=0; m<NX; m++) c[m] = u[m]; // Updating the concentration or temperature field

}

for(int m = 0; m<NX; m++)
{
x = (double)m*dx;
cout << x << " " << c[m] << "\n"; // Output with the results at time t = LT
}

return 0;
}

Running this program three times, with domain lenght parameters L=0.5, L=1.0 and L=3.0 and keeping the time step constant, we get data points that can be plotted in the same coordinate system with a graphing program, like below:

penetration_cpp

Figure 1. Time evolution of a concentration field C(x,t) in a system where the concentration is forced to stay at constant values at the endpoints of the domain.

The simulation seems to proceed as expected, approaching a linearly decreasing function C(x)

An equivalent code for FORTRAN is in the next box:

! Calculates the time development of a concentration distribution C(x,t) with implicit
! finite-differencing of a diffusion equation. The boundary condition is that the left boundary is an infinite source
! of solute/heat and the value of C(x) at x=0 stays at constant value 1. The value of C at the right boundary stays zero.
! Therefore, the function C(x) evolves towards a linearly decreasing function.
! Teemu Isojärvi, Feb 2017

PROGRAM MAIN

real :: DX, DT, LX, LT, D, KAPPA,B,Q ! Real variables for discretization and the diffusion constant
integer :: NT,NX ! Number of time and position steps

REAL :: C(600) ! Concentration field as an array of data points, dimension same as value of NX
REAL :: G(600)
REAL :: U(600)

REAL :: X ! Auxiliary variable

INTEGER :: M ! Integer looping variables
INTEGER :: N

LX = 6. ! Length of x-interval
LT = 3.0 ! Length of t-interval
NX = 600 ! Number of lattice points
NT = 300 ! Number of time steps
DX = LX/NX ! Distance between neighboring lattice points
DT = LT/NT ! Length of time step
D = 1. ! Diffusion/heat conduction coefficient
KAPPA = D*DT/(DX*DX)

do M = 1, NX ! Initial values of concentration
X = M*DX
C(M) = EXP(-3*X*X) ! Gaussian initial concentration distribution
end do

do N = 1, NT ! Time stepping loop

C(1)=1
C(NX)=0

U(1)=(C(1) + 2 * KAPPA)/(2 * KAPPA + 1)
Q = 2 * KAPPA + 1

do M = 2, NX ! First loop for solving the tridiagonal system
G(M) = -KAPPA/Q
Q = (2 * KAPPA + 1) + KAPPA * G(M)
U(M) = (C(M) + KAPPA * U(M-1))/Q
end do

do M = (NX-1), 1
U(M) = U(M) - G(M+1) * U(M+1) ! Second loop
end do

do M = 1, NX-1
C(M) = U(M) ! Updating the concentration or temperature field
end do

end do

do M = 1, NX
X = M*DX
print *,X,C(M) ! Print the x and concentration values at data points
end do

END

To test the implicit method with R-Code, let’s solve a problem where the length of the x-domain is 20, the time interval has length 3 and the initial distribution is

CodeCogsEqn(20).gif

to ensure that we can set the boundary conditions C(0,t)=C(L,t)=0 (the Gaussian distribution doesn’t have time to spread all the way to the boundaries in a time interval of 3 units). The code for this calculation is shown below:

library(graphics) #load the graphics library needed for plotting
library(limSolve)

lx <- 20.0 #length of the computational domain
lt <- 3. #length of the simulation time interval
nx <- 4000 #number of discrete lattice points
nt <- 300 #number of timesteps
dx <- lx/nx #length of one discrete lattice cell
dt <- lt/nt #length of timestep

D <- 1.0 #diffusion constant

Conc <- c(1:nx) #define a vector to put the x- and t-dependent concentration values in

xaxis <- c(1:nx) #the x values corresponding to the discrete lattice points

kappa <- D*dt/(dx*dx) #a parameter needed in the discretization

offdiagonal <- rep(-kappa, times = nx-1)
ondiagonal <- rep(1+2*kappa, times = nx)

for (i in c(1:nx)) {
Conc[i] <- exp(-2*(i*dx-10)*(i*dx-10)) #a Gaussian initial concentration field

xaxis[i] <- i*dx #calculate the x coordinates of lattice points
}

for (j in c(1:nt)) { #main time stepping loop

sol <- Solve.tridiag(offdiagonal, ondiagonal, offdiagonal, Conc)

for (k in c(1:nx)) {
Conc[k] <- sol[k]
}

if(j %% 3 == 1) { #make plots of C(x) on every third timestep
jpeg(file = paste("plot_",j,".jpg",sep=""))
plot(xaxis,Conc,xlab="position (x)", ylab="concentration",ylim=c(0,2))
title(paste("C(x) at t =",j*dt))
lines(xaxis,Conc)
dev.off()
}
}

An animation of the results can be viewed in this link. If you test the code yourself, remember to install the limSolve package first, by writing the command

install.packages(“limSolve”)

in the R console. If you don’t want to load the video, here are the plots for 3 different values of t:

plot_34.jpgplot_142plot_289

When solving PDE:s other than the ordinary diffusion equation, the implicit method is often even more necessary that it was in the examples here. For example, when solving the time-development of a quantum wave packet from the time-dependent Schroedinger equation, the solution function doesn’t stay normalized if one tries to do a simple explicit time stepping. The solution of Schroedinger equations with implicit method will be shown in the next post. The TDSE is a complex diffusion equation of the form

CodeCogsEqn(21).gif

where the equation has been simplified by setting the Planck constant to value 2\pi and the particle mass to m=1.

The 1D diffusion and Schroedinger equations are simple in the sense that the linear system to be solved on each timestep is tridiagonal, with makes the solution considerably faster than is the case with a general linear system. Systems that are not tridiagonal will appear when one wants to solve equations with more than one space coordinate (i.e. x and y instead of just x), or when the equation contains higher than 2nd order derivatives with respect to the position coordinate (this can be demonstrated with the thin-film equation, which is fourth-order with respect to x).

Save

Numerical solution of PDE:s, Part 1: Explicit method

In this post and a few ones following it, I will show how to write C++, Fortran or R-Code programs that solve partial differential equations like diffusion equation or Schroedinger equation numerically, either by explicit or implicit method. An explicit method is a very simple direct calculation, while the implicit (Crank-Nicolson) method involves solving a linear system of equations on every discrete timestep.

A simple example of a PDE is the Poisson equation

CodeCogsEqn(5).gif ,

which describes things like the electric potential field produced by a charge distribution which is the function \rho multiplied by a constant, and can be solved if the function \rho and the boundary values of the function f on some closed surface are known.

In the case of these posts, the equations that I will handle are time-evolution equations, where we are solving a function f(x,t), where the variables are 1D position and time, and the boundary conditions are the function f(x,0) (function f at an initial moment t=0) and some conditions for f(0,t) and f(L,t), where x=0 and x=L are the left and right boundaries of a computational domain.

The equation that describes both diffusion (spreading of a dissolved substance in solution, or spreading of an unevenly distributed component in gas phase) and heat conduction in a 1-dimensional domain is of the form

CodeCogsEqn(6).gif .

Here f(x,t) is a function that gives solute concentration or temperature at point x at time t, and D is a constant that tells how quickly the diffusion or conduction takes place in medium.

To solve this kind of an equation numerically, we have to choose some domains in time and space

codecogseqn7 ,

and define the object f_{i;j} , where the i and j are discrete indices and there is an approximate correspondence

CodeCogsEqn(8).gif .

Here \Delta x is the spatial discretization step and \Delta t is the timestep. The initial condition means that we know the numbers f_{i;0} for all values of i. This is equivalent to knowing the function f(x,0).

The most simple way of converting the PDE into a difference equation for the object f_{i;j} is to use straightforward finite differencing for the derivatives in x and t:

CodeCogsEqn(11).gif

codecogseqn10
With these substitutions and some rearrangement, the PDE becomes

CodeCogsEqn(12).gif

So, now we know what kind of numbers to add to the values f_{i;j} for i = 0,1,2,\dots ,n_x - 1 at timestep j to get the numbers f_{i;j+1} for i = 0,1,2,\dots ,n_x - 1. Note that I now call the total number of discrete x-axis points n_x.

Next, as an example I will solve this discretized equation with the domains and step sizes

L = 6
n_x = 30
t_{end} = 6
n_t = 600
D = 1

and an initial condition

CodeCogsEqn(13).gif

i.e. a Gaussian temperature/concentration profile. I will also set a boundary condition for the position derivative of f(x,t) at the domain boundaries:

CodeCogsEqn(14).gif

which basically means that the endpoints are impenetrable walls that don’t let anything to diffuse/conduct through them. In other words, the system can be described as “closed” or “adiabatic” depending on whether it’s a diffusion or conduction system.

An example C++ code to do this numerical calculation and to print the values f_{i;j} at the final time j = n_t is shown below:

// This program calculates the time development of a diffusion or heat conduction
// system with explicit finite differencing.
// Teemu Isojärvi, Feb 2017

#include <math.h>;
#include <iostream>;

using namespace std;

#define LX 6. // Length of spatial domain
#define NX 30 // Number of lattice points
#define LT 6 // Length of time interval
#define NT 600 // Number of timesteps

#define D 1. // Diffusion coefficient

int main(void)
{

double dx = (double)LX/(double)NX; // Lattice spacing
 double dt = (double)LT/(double)NT; // Length of timestep

double c[NX]; // Concentration values at lattice points
 double dc[NX]; // Change of concentration during timestep

double x; // Auxiliary position variable

 for(int m = 0; m<NX; m++)
 {
 x = ((double)m+0.5)*dx;
 c[m]=exp(-2*(x-3)*(x-3)); // Gaussian initial concentration
 }

for(int n = 0; n<NT; n++)
 {
 c[0]=c[1]; // Derivative zeroed at left boundary point
 c[NX-1] = c[NX-2]; // Derivative zeroed at right boundary point

for(int m = 0; m<NX; m++)
 {
 dc[m] = (D*dt/(dx*dx))*(c[m+1]-2*c[m]+c[m-1]); // Main finite differencing
 }

for(int m = 1; m<NX-1; m++) c[m] += dc[m]; // Updating the concentration
 }

for(int m = 0; m<NX; m++)
 {
 x = (double)m*dx;
 cout << x << " " << c[m] << "\n"; // Output with the results at time t = LT
 }

return 0;
}

The code can easily be edited to use different initial or boundary conditions, or different discretization step sizes or domain intervals. Doing the calculation three times with time interval lenghths L=0.5, L=1, and L=6, and plotting the output data in a single graph with Grace or similar free graphing program, the result is Fig 1.

diffusion1

Figure 1. Diffusive time evolution of a Gaussian temperature/concentration distribution

To make this kind of graphs, you need to run the program from command line and direct the standard output into a file – in Linux this is done with a command like

./diffusion > out.txt

and in Windows command line it’s done as

diffusion.exe > out.txt

The same code is also easy to write with FORTRAN. This code is shown below.

! Calculates the time development of an initially uneven concentration distribution C(x,t) with explicit
! finite-differencing of a diffusion equation. The boundary condition is that no solute diffuses through the boundaries
! Teemu Isojärvi, Feb 2017

PROGRAM MAIN

real :: DX, DT, LX, LT, D ! Real variables for discretization and the diffusion constant
integer :: NT,NX ! Number of time and position steps

REAL :: C(30) ! Concentration field as an array of data points, dimension same as value of NX
REAL :: DC(30) ! Change of the above quantity during a time step

REAL :: X ! Auxiliary variable

INTEGER :: M ! Integer looping variables
INTEGER :: N

LX = 6. ! Length of x-interval
LT = 6. ! Length of t-interval
NX = 30 ! Number of lattice points
NT = 600 ! Number of time steps
DX = LX/NX ! Distance between neighboring lattice points
DT = LT/NT ! Length of time step
D = 1 ! Diffusion/heat conduction coefficient

do M = 1, NX ! Initial values of concentration
 X = M*DX
 C(M) = EXP(-2*(X-3)*(X-3)) ! Gaussian initial concentration distribution
end do

do N = 1, NT ! Time stepping loop 

 C(1)=C(2)
 C(NX)=C(NX-1)

do M = 2, NX-1
 DC(M) = (D*DT/(DX*DX))*(C(M+1)-2*C(M)+C(M-1)) ! Main time stepping calculation
 end do

do M = 1, NX
 C(M) = C(M)+DC(M) ! Update the data points
 end do

end do

do M = 1, NX
 X = M*DX
 print *,X,C(M) ! Print the x and concentration values at data points
end do

END

Finally, I will show a way to write, with R-Code programming language, a program that will do the same calculation and automatically produce output files with plots of the function f(x,t) on every one timestep out of 3:

library(graphics) #load the graphics library needed for plotting

lx <- 6.0 #length of the computational domain
lt <- 6 #length of the simulation time interval
nx <- 30 #number of discrete lattice points
nt <- 600 #number of timesteps
dx <- lx/nx #length of one discrete lattice cell
dt <- lt/nt #length of timestep

D <- 1.0 #diffusion constant

Conc <- c(1:nx) #define a vector to put the x- and t-dependent concentration values in
DConc <- c(1:nx) #a vector for the changes in concentration during a timestep
xaxis <- c(1:nx) #the x values corresponding to the discrete lattice points

kappa <- D*dt/(dx*dx) #a parameter needed in the discretization

for (i in c(1:nx)) {
Conc[i] = exp(-2*(i*dx-3)*(i*dx-3)) #Gaussian initial concentration distribution
DConc[i] <- 0 #all initial values in DConc vector zeroed
xaxis[i] <- i*dx #calculate the x coordinates of lattice points
}

for (j in c(1:nt)) { #main time stepping loop
Conc[1] <- Conc[2] #derivatives of C(x) at both ends of domain forced to stay zero
Conc[nx] <- Conc[nx-1]

for (k in c(2:(nx-1))) {
DConc[k] <- kappa*(Conc[k-1]-2*Conc[k]+Conc[k+1]) #calculate the changes in concentration
}

for (l in c(1:nx)) {
Conc[l] <- Conc[l]+DConc[l] #add the changes to the vector Conc
}
k <- 0
l <- 0
if(j %% 3 == 0) { #make plots of C(x) on every third timestep
jpeg(file = paste("plot_",j,".jpg",sep=""))
plot(xaxis,Conc,xlab="position (x)", ylab="concentration",ylim=c(0:1))
title(paste("C(x) at t =",j*dt))
lines(xaxis,Conc)
dev.off()
}

So, the output image files are named as plot_1.jpg, plot_2.jpg, and so on. Now we can use the free ImageJ program (or something else with the same functionality) to import this sequence of images and to save it as an AVI video file. The video can be viewed here.

As an another example, I will give an R-Code that calculates the diffusion or conduction through a layer of intermediate material, given that the function f(x,t) is set to have a constant nonzero value at x=0 and the boundary condition that its derivative with respect to x is zero at the domain endpoints:

library(graphics) #load the graphics library needed for plotting

lx <- 6.0 #length of the computational domain
lt <- 6 #length of the simulation time interval
nx <- 30 #number of discrete lattice points
nt <- 600 #number of timesteps
dx <- lx/nx #length of one discrete lattice cell
dt <- lt/nt #length of timestep

D <- 1.0 #diffusion constant

Conc <- c(1:nx) #define a vector to put the x- and t-dependent concentration values in
DConc <- c(1:nx) #a vector for the changes in concentration during a timestep
xaxis <- c(1:nx) #the x values corresponding to the discrete lattice points

kappa <- D*dt/(dx*dx) #a parameter needed in the discretization

for (i in c(1:nx)) {
Conc[i] <- 0.5*(1+tanh(5-5*i*dx)) #a hyperbolic tangent initial concentration field
DConc[i] <- 0 #all elements zeroed initially
xaxis[i] <- i*dx #calculate the x coordinates of lattice points
}

for (j in c(1:nt)) { #main time stepping loop

Conc[1] <- 1 #force the C to stay at value 1 at left boundary
Conc[2] <- 1 #force the derivative of C to zero at left boundary
Conc[nx] <- Conc[nx-1] #force the derivative of C to zero at right boundary

for (k in c(2:(nx-1))) {
DConc[k] <- kappa*(Conc[k-1]-2*Conc[k]+Conc[k+1]) #calculate the changes in concentration
}

for (l in c(2:(nx-1))) {
Conc[l] <- Conc[l]+DConc[l] #add the changes to the vector Conc
}

if(j %% 3 == 1) { #make plots of C(x) on every third timestep
jpeg(file = paste("plot_",j,".jpg",sep=""))
plot(xaxis,Conc,xlab="position (x)", ylab="concentration",ylim=c(0,2))
title(paste("C(x) at t =",j*dt))
lines(xaxis,Conc)
dev.off()
}
}

The animation made of this simulation can be viewed here

So, here were the first examples of PDE solving with discretization. The problem with the explicit finite differencing used here, is that if one decides to use a very small spatial step size \Delta x, the timestep \Delta t may have to be made prohibitively small to keep the simulation numerically stable. Suppose we do the simulation with parameters L = 6, n_x = 300, t_{end} = 1, n_t = 100. Now the end result plotted with Grace looks like this:

unstable_explicit.jpg

Figure 2. Unstable behavior of explicit method discretization of diffusion equation.

So obviously the numerical errors done in the discretization accumulate exponentially and “blow up” when trying to use too short a \Delta x compared to \Delta t. In later blog posts I will show how to use these programming languages to write an implicit PDE solver that corrects this problem for the diffusion/conduction equation, as well as makes it possible to solve Schroedinger equation (a complex-valued version of diffusion equation, which can have wave-like solutions with reflection, interference, etc.). Also, I will extend the method to problems with more than one spatial dimension, and show how to solve a nonlinear PDE called thin-film equation.

Save

Linear algebra for balancing chemical reaction equations

The balancing of chemical reaction equations is familiar for many, either from high school chemistry or introductory university chemistry. A simple example of such a problem is the reaction equation for the combustion of methane in oxygen:

aCH_4 + bO_2 \rightarrow cCO_2 + dH_2 O,

for which we are supposed to find coefficients a,b,c and d that make the reaction possible in terms of conservation of the number of atoms of any element that is present. In this case, it is rather easy to see that the number of CO_2 molecules must be equal to the number of CH_4 molecules, and that the number of water molecules must be twice that. Therefore the possible equations are

CH_4 + 2O_2 \rightarrow CO_2 + 2H_2 O , or

2CH_4 + 4O_2 \rightarrow 2CO_2 + 4H_2 O, or

3CH_4 + 6O_2 \rightarrow 3CO_2 + 6H_2 O ,

or any other “multiple” of the first equation (obtained by multiplying all the coefficients in the equation with the same number).

Usually this kind of balancing is done mainly by intuition and trying to guess the right coefficients, but this can be difficult if the reactants and product contain many different elements, each of which are present in more than one kind of molecule. One example of a more complicated (but still quite simple) reaction is the reaction of chlorine dioxide (ClO_2) with alkaline water to form chlorate (ClO_3^-), chlorite (ClO_2^-) and water:

aClO_2 + bOH^- \rightarrow cClO_2^- + dClO_3^- + eH_2 O .

Now, an easily applicable way to solve a set of acceptable coefficients a,b,c,d and e is to explicitly write the balancing condition equations for each element that appears in the equation. These balancing conditions are:

a = c + d                                 (balancing of chlorine)
2a + b = 2c + 3d + e             (balancing of oxygen)
b = 2e                                   (balancing of hydrogen)
b = c + d                                (balancing of electric charge)

This can be solved with many kinds of mathematical software, either free (there’s lots of free math programs especially for Linux) or commercial (like Wolfram Mathematica).

But there’s one another thing. Because the number of unknowns in the system of equations above is larger than the number of equations by one, we need to decide the value of one of the coefficients a, \dots , b arbitrarily. So let’s say that a = 1. Now the set of equations is:

a = 1                                   (arbitrary choice of one coeffiecient)
a = c + d                            (balancing of chlorine)
2a + b = 2c + 3d + e          (balancing of oxygen)
b = 2e                              (balancing of hydrogen)
b = c + d                           (balancing of electric charge)

Using the column vector

codecogseqn3

the system of equations can be written in matrix form

matrix.gif

This can be solved in Mathematica by writing the command

Solve[{a == 1, a == c + d, 2a + b == 2*c + 3*d + e, b == 2e, b == c + d}]

and the result is

a = 2,

b = 2,

c = 1,

d = 1,

e = 1,
which leads to the reaction equation

2ClO_2 + 2OH^- \rightarrow ClO_2^- + ClO_3^- + H_2 O

which doesn’t even need to be multiplied with any constant to make all the coefficients integers (usually that is necessary).
IMAGE SOURCE: The feature image of an Erlenmeyer flask on this blog post is a public domain image from Wikipedia, address https://en.wikipedia.org/wiki/Erlenmeyer_flask#/media/File:Duran_erlenmeyer_flask_narrow_neck_50ml.jpg .

Square roots of matrices and operators

Everyone knows the definition of the square root of a non-negative number: if x > 0, then the square root of x is a nonnegative number y for which we have y^2 = x, and it is denoted y = \sqrt{x}. We could also call the number -\sqrt{x} a square root of x, but by convention the positive solution of the equation y^2 = x is called “The” square root.

So, what if we have an algebraic system that is not the set of positive real numbers, but where there exists a defined multiplication operation “\diamond “? If a is an element of such a set, then a square root of a would obviously be an element b for which b\diamond b = a (\diamond is here the multiplication operation). The set of complex numbers is obviously such a set, but is there any other example?

Consider the set of 2 \times 2 matrices, the elements of which are denoted

codecogseqn

where a,b,c and d are real or complex numbers. So, could we define the square root of this kind of matrices in the same way as it is done with the real numbers, using the normal matrix multiplication as the operation “\diamond “? Non-commutativity shouldn’t be a problem here, because any algebraic object commutes with itself.

Let’s use the identity matrix as an example:

CodeCogsEqn(1).gif

What’s its square root? Really quickly one finds out that there are as many as four matrices that can be seen as the square root of I:

CodeCogsEqn(2).gif

and it is not at all obvious which one of these should be called “The Square Root of I“. Because of this, the concept of square root is not often used when working with matrices.

Sometimes, a square root can also be found for operators that act on a set of functions, like the second derivative operator \frac{d^2}{dx^2}, for which the operators \frac{d}{dx} and -\frac{d}{dx} are obvious “square root candidates”. The multiplication of operators doesn’t have to be commutative, so they are a bit like matrices, but they are usually not representable by finite-dimensional matrices unless the domain (the set of functions that the operator acts on) is artificially made very limited.

An example of the operator square root problem that actually occurs in the analysis of a real physical system is the Klein-Gordon equation, which was the first attempt to form a relativistic version of the time-dependent Schroedinger equation of quantum mechanics. The time dependent Schroedinger equation of a free particle (particle that is not acted on by any forces) is:

CodeCogsEqn(25).gif

where \Psi is a function of both time t and a space coordinate x (for a simple one-dimensional situation, that is). This can be written shortly as

CodeCogsEqn(27).gif

where the free-particle Hamiltonian operator

CodeCogsEqn(28).gif

is obtained from the classical expression of kinetic energy: E_k = p^2 /2m by replacing the classical one-dimensional momentum p with the corresponding quantum momentum operator

CodeCogsEqn(29).gif

The problem with the normal TDSE is that the time and space coordinates are treated differently in it, because it is first order with respect to time and second order with respect to position. This is not acceptable if we want to satisfy the principle of special relativity.

A naive attempt to form a relativistic Schroedinger equation is to take the formula of the energy of a moving body in special relativity

CodeCogsEqn(30).gif

and replace the momentum p with the quantum momentum operator \hat{p}. Then we would have

codecogseqn31

but the problem with this is how to define the square root of something that contains a derivative operator. One way to do this would be to use the Taylor series expansion of the square root:

codecogseqn32

equating the x here with the derivative operator, but this is not acceptable, because an equation that has derivatives of all positive integral orders up to infinity can be seen as equivalent to a difference equation like

codecogseqn33

which is non-local, and in an equation of motion like the Klein-Gordon equation this would mean that there can be immediate (faster than speed of light) interactions between objects. (if you want, try to write the difference equation above as an infinite-order differential equation by using Taylor expansion).

Because of the non-locality problem, the actual conventional Klein-Gordon equation is formed by making the square energy operator \hat{H}^2 using the formula of relativistic momentum, and equating \hat{H}^2 \Psi  with -\hbar^2 \frac{\partial^2 \Psi}{\partial t^2} . The result is

CodeCogsEqn(34).gif

This, however, causes other problems because the equation here allows particles to have a negative value of kinetic energy, which is hard to interpret physically. These problems are solved in quantum field theory (QFT), where the number of particles that are present in the system can be uncertain, similarly to how the position of a single quantum particle described by the Schroedinger equation can have some expectation value and nonzero standard deviation.