{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Exploring the diffusion equation with Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Most of what follows (except the Python code and the bit on fault scarps) is based on and inspired by Slingerland and Kump (2011): [Mathematical Modeling of Earth's Dynamical Systems](http://www.amazon.com/dp/0691145148/ref=cm_sw_r_tw_dp_iG3Wub0YJKYJK), Princeton University Press. The purpose is to go through the whole process of discretizing a partial differential equation, setting up a numerical scheme, and solving the resulting system of equations in Python and IPython notebook. I am learning this as I am doing it, so it may seem pedestrian and slow-moving to a lot of people but I am sure there are others who will find it useful."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Estimating the derivatives in the diffusion equation using the Taylor expansion"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This is the one-dimensional diffusion equation:\n",
"\n",
"$$ \\frac{\\partial T}{\\partial t} - D\\frac{\\partial^2 T}{\\partial x^2} = 0 $$\n",
"\n",
"Taylor expansion of value of a function $u$ at a point $\\Delta x$ ahead of the point $x$ where the function is known:\n",
"\n",
"$$ u(x+\\Delta x) = u(x) + \\Delta x \\frac{\\partial u}{\\partial x} + \\frac{\\Delta x^2}{2} \\frac{\\partial^2 u}{\\partial x^2} + \\frac{\\Delta x^3}{6} \\frac{\\partial^3 u}{\\partial x^3} + O(\\Delta x^4) $$\n",
"\n",
"Taylor expansion of value of the function $u$ at a point one space step behind:\n",
"\n",
"$$ u(x-\\Delta x) = u(x) - \\Delta x \\frac{\\partial u}{\\partial x} + \\frac{\\Delta x^2}{2} \\frac{\\partial^2 u}{\\partial x^2} - \\frac{\\Delta x^3}{6} \\frac{\\partial^3 u}{\\partial x^3} + O(\\Delta x^4) $$\n",
"\n",
"Solving the first Taylor expansion above for $\\frac{\\partial u}{\\partial x}$ and dropping all higher-order terms yields the forward difference operator:\n",
"\n",
"$$ \\frac{\\partial u}{\\partial x} = \\frac{u(x+\\Delta x)-u(x)}{\\Delta x} + O(\\Delta x) $$\n",
"\n",
"Similarly, the second equation yields the backward difference operator:\n",
"\n",
"$$ \\frac{\\partial u}{\\partial x} = \\frac{u(x)-u(x-\\Delta x)}{\\Delta x} + O(\\Delta x) $$\n",
"\n",
"Subtracting the second equation from the first one gives the centered difference operator:\n",
"\n",
"$$ \\frac{\\partial u}{\\partial x} = \\frac{u(x+\\Delta x)-u(x-\\Delta x)}{2\\Delta x} + O(\\Delta x^2) $$\n",
"\n",
"The centered difference operator is more accurate than the other two.\n",
"\n",
"Finally, if the two Taylor expansions are added, we get an estimate of the second order partial derivative:\n",
"\n",
"$$ \\frac{\\partial^2 u}{\\partial x^2} = \\frac{u(x+\\Delta x)-2u(x)+u(x-\\Delta x)}{\\Delta x^2} + O(\\Delta x^2) $$\n",
"\n",
"Next we use the forward difference operator to estimate the first term in the diffusion equation:\n",
"\n",
"$$ \\frac{\\partial T}{\\partial t} = \\frac{T(t+\\Delta t)-T(t)}{\\Delta t} $$\n",
"\n",
"The second term is expressed using the estimation of the second order partial derivative:\n",
"\n",
"$$ \\frac{\\partial^2 T}{\\partial x^2} = \\frac{T(x+\\Delta x)-2T(x)+T(x-\\Delta x)}{\\Delta x^2} $$\n",
"\n",
"Now the diffusion equation can be written as\n",
"\n",
"$$ \\frac{T(t+\\Delta t)-T(t)}{\\Delta t} - D \\frac{T(x+\\Delta x)-2T(x)+T(x-\\Delta x)}{\\Delta x^2} = 0 $$\n",
"\n",
"This is equivalent to\n",
"\n",
"$$ T(t+\\Delta t) - T(t) - \\frac{D\\Delta t}{\\Delta x^2}(T(x+\\Delta x)-2T(x)+T(x-\\Delta x)) = 0 $$\n",
"\n",
"The expression $ D\\frac{\\Delta t}{\\Delta x^2} $ is called the diffusion number, denoted here with $s$:\n",
"\n",
"$$ s = D\\frac{\\Delta t}{\\Delta x^2} $$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## FTCS explicit scheme and analytic solution"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"If we use $n$ to refer to indices in time and $j$ to refer to indices in space, the above equation can be written as\n",
"\n",
"$$ T[n+1,j] = T[n,j] + s(T[n,j+1]-2T[n,j]+T[n,j-1]) $$\n",
"\n",
"This is called a forward-in-time, centered-in-space (FTCS) scheme. Its 'footprint' looks like this:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"%matplotlib inline\n",
"%config InlineBackend.figure_format = 'svg' # display plots in SVG format\n",
"\n",
"fig = plt.figure(figsize=(6,3))\n",
"plt.plot([0,2],[0,0],'k')\n",
"plt.plot([1,1],[0,1],'k')\n",
"plt.plot([0,1,2,1],[0,0,0,1],'ko',markersize=10)\n",
"plt.text(1.1,0.1,'T[n,j]')\n",
"plt.text(0.1,0.1,'T[n,j-1]')\n",
"plt.text(1.1,1.1,'T[n+1,j]')\n",
"plt.text(2.1,0.1,'T[n,j+1]')\n",
"plt.xlabel('space')\n",
"plt.ylabel('time')\n",
"plt.axis('equal')\n",
"plt.yticks([0.0,1.0],[])\n",
"plt.xticks([0.0,1.0],[])\n",
"plt.title('FTCS explicit scheme',fontsize=12)\n",
"plt.axis([-0.5,2.5,-0.5,1.5]);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we are ready to write the code that is the solution for exercise 2 in Chapter 2 of Slingerland and Kump (2011). This is an example where the one-dimensional diffusion equation is applied to viscous flow of a Newtonian fluid adjacent to a solid wall. If the wall starts moving with a velocity of 10 m/s, and the flow is assumed to be laminar, the velocity profile of the fluid is described by the equation\n",
"\n",
"$$ \\frac{\\partial V}{\\partial t} - \\nu \\frac{\\partial^2 V}{\\partial y^2} = 0 $$\n",
"\n",
"where $\\nu$ is the kinematic viscosity of the fluid. We want to figure out how the velocity will change through time as a function of distance from the wall. [Note that I have changed the original 40 m/s to 10 m/s -- the former seems like an unnaturally large velocity to me].\n",
"\n",
"We can compare the numerical results with the analytic solution, which is known for this problem:\n",
"\n",
"$$ V = V_0 \\Big\\{ \\sum\\limits_{n=0}^\\infty erfc\\big(2n\\eta_1+\\eta\\big) - \\sum\\limits_{n=0}^\\infty erfc\\big(2(n+1)\\eta_1+\\eta\\big) \\Big\\} $$\n",
"\n",
"where\n",
"\n",
"$$ \\eta_1 = \\frac{h}{2\\sqrt{\\nu t}} $$\n",
"\n",
"and\n",
"\n",
"$$ \\eta = \\frac{y}{2\\sqrt{\\nu t}} $$"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"dt = 0.0005 # grid size for time (s)\n",
"dy = 0.0005 # grid size for space (m)\n",
"viscosity = 2*10**(-4) # kinematic viscosity of oil (m2/s)\n",
"y_max = 0.04 # in m\n",
"t_max = 1 # total time in s\n",
"V0 = 10 # velocity in m/s\n",
"\n",
"# function to calculate velocity profiles based on a finite difference approximation to the 1D diffusion equation and the \n",
"# FTCS (forward-in-time, centered-in-space) scheme:\n",
"def diffusion_FTCS(dt,dy,t_max,y_max,viscosity,V0):\n",
" # diffusion number (has to be less than 0.5 for the solution to be stable):\n",
" s = viscosity*dt/dy**2 \n",
" y = np.arange(0,y_max+dy,dy) \n",
" t = np.arange(0,t_max+dt,dt)\n",
" r = len(t)\n",
" c = len(y)\n",
" V = np.zeros([r,c])\n",
" V[:,0] = V0\n",
" for n in range(0,r-1): # time\n",
" for j in range(1,c-1): # space\n",
" V[n+1,j] = V[n,j] + s*(V[n,j-1] - 2*V[n,j] + V[n,j+1]) \n",
" return y,V,r,s\n",
"# note that this can be written without the for-loop in space, but it is easier to read it this way\n",
"\n",
"\n",
"from scipy.special import erfc\n",
"\n",
"# function to calculate velocity profiles using the analytic solution:\n",
"def diffusion_analytic(t,h,V0,dy,viscosity):\n",
" y = np.arange(0,h+dy,dy)\n",
" eta1 = h/(2*(t*viscosity)**0.5)\n",
" eta = y/(2*(t*viscosity)**0.5)\n",
" sum1 = 0\n",
" sum2 = 0\n",
" for n in range(0,1000):\n",
" sum1 = sum1 + erfc(2*n*eta1+eta)\n",
" sum2 = sum2 + erfc(2*(n+1)*eta1-eta)\n",
" V_analytic = V0*(sum1-sum2)\n",
" return V_analytic\n",
"\n",
"y,V,r,s = diffusion_FTCS(dt,dy,t_max,y_max,viscosity,V0)\n",
"\n",
"# plotting:\n",
"plt.figure(figsize=(7,5))\n",
"plot_times = np.arange(0.2,1.0,0.1)\n",
"for t in plot_times:\n",
" plt.plot(y,V[t/dt,:],'Gray',label='numerical')\n",
" V_analytic = diffusion_analytic(t,0.04,10,dy,viscosity)\n",
" plt.plot(y,V_analytic,'ok',label='analytic',markersize=3)\n",
" if t==0.2:\n",
" plt.legend(fontsize=12)\n",
"plt.xlabel('distance from wall (m)',fontsize=12)\n",
"plt.ylabel('velocity (m/s)',fontsize=12)\n",
"plt.axis([0,y_max,0,V0])\n",
"plt.title('comparison between explicit numerical \\n(FTCS scheme) and analytic solutions');"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The dots (analytic solution) overlap pretty well with the lines (numerical solution). However, this would not be the case if we changed the discretization so that the diffusion number was larger. Let's look at the stability of the FTCS numerical scheme, by computing the solution with different diffusion numbers. It turns out that the diffusion number $s$ has to be less than 0.5 for the FTCS scheme to remain stable. What follows is a reproduction of Figure 2.7 in Slingerland and Kump (2011):"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"dt = 0.0005 # grid size for time (m)\n",
"dy = 0.0005 # grid size for space (s)\n",
"y,V,r,s = diffusion_FTCS(dt,dy,t_max,y_max,viscosity,V0)\n",
"V_analytic = diffusion_analytic(0.5,0.04,V0,dy,viscosity)\n",
"plt.figure(figsize=(7,5))\n",
"plt.plot(y,V_analytic-V[0.5/dt],'--k',label='small s')\n",
"\n",
"dy = 0.0010\n",
"dt = 0.00254\n",
"y,V,r,s = diffusion_FTCS(dt,dy,t_max,y_max,viscosity,V0)\n",
"V_analytic = diffusion_analytic(0.5,0.04,V0,dy,viscosity)\n",
"V_numeric = V[r/2-1,:]\n",
"\n",
"plt.plot(y,V_analytic-V_numeric,'k',label='large s')\n",
"plt.xlabel('distance from wall (m)',fontsize=12)\n",
"plt.ylabel('velocity difference (m/s)',fontsize=12)\n",
"plt.title('difference between numerical and analytic \\n solutions for different \\'s\\' values',fontsize=14)\n",
"plt.axis([0,y_max,-4,4])\n",
"plt.legend();"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Laasonen implicit scheme"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.figure(figsize=(6,3))\n",
"plt.plot([0,2],[1,1],'k')\n",
"plt.plot([1,1],[0,1],'k')\n",
"plt.plot([0,1,2,1],[1,1,1,0],'ko',markersize=10)\n",
"plt.text(1.1,0.1,'T[n,j]')\n",
"plt.text(0.1,1.1,'T[n+1,j-1]')\n",
"plt.text(1.1,1.1,'T[n+1,j]')\n",
"plt.text(2.1,1.1,'T[n+1,j+1]')\n",
"plt.xlabel('space')\n",
"plt.ylabel('time')\n",
"plt.axis('equal')\n",
"plt.yticks([0.0,1.0],[])\n",
"plt.xticks([0.0,1.0],[])\n",
"plt.title('Laasonen scheme',fontsize=12)\n",
"plt.axis([-0.5,2.5,-0.5,1.5]);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Instead of estimating the velocity at time step $n+1$ with the curvature calculated at time step $n$, as it is done in the FTCS explicit scheme, we can also estimate the curvature at time step $n+1$, using the velocity change from time step $n$ to time step $n+1$:\n",
"\n",
"$$ s\\big(T(x+\\Delta x)-2T(x)+T(x-\\Delta x)\\big) = T(t+\\Delta t)-T(t) $$\n",
"\n",
"Written in matrix notation, this is equiavlent to\n",
"\n",
"$$ s\\big(T[n+1,j+1]-2T[n+1,j]+T[n+1,j-1]\\big) = T[n+1,j]-T[n,j] $$\n",
"\n",
"After some reshuffling we get\n",
"\n",
"$$ -sT[n+1,j+1] + (1+2s)T[n+1,j] - sT[n+1,j-1] = T[n,j] $$\n",
"\n",
"This is the Laasonen fully implicit scheme. Unlike the FTCS scheme, the Laasonen scheme is unconditionally stable. Let's try to write some Python code that implements this scheme. First it is useful for me to go through the logic of constructing the system of equations that needs to be solved. Let's consider a grid that only consists of 5 nodes in space and we are going to estimate the values of $T$ at the locations marked by the red dots in the figure below. Black dots mark the locations where we already know the values of $T$ (from the initial and boundary conditions)."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.figure(figsize=(6,3))\n",
"plt.plot([0,4,4,0],[0,0,1,1],'k')\n",
"for i in range(0,4):\n",
" plt.plot([i,i],[0,1],'k')\n",
"plt.plot([0,1,2,3,4,0,4],[0,0,0,0,0,1,1],'ko',markersize=10)\n",
"plt.plot([1,2,3],[1,1,1],'ro',markersize=10)\n",
"for i in range(0,5):\n",
" plt.text(i+0.1,0.1,'T[0,'+str(i)+']')\n",
" plt.text(i+0.1,1.1,'T[1,'+str(i)+']')\n",
"plt.xlabel('space')\n",
"plt.ylabel('time')\n",
"plt.axis('equal')\n",
"plt.yticks([0.0,1.0],['0','1'])\n",
"plt.title('first two time steps on a 1D grid of five points',fontsize=12)\n",
"plt.axis([-0.5,4.8,-0.5,1.5]);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"First we write the equations using the Laasonen scheme centered on the three points of unknown velocity (or temperature) -- these are the red dots in the figure above:\n",
"\n",
"$$ \\begin{array}{rrrrrcl} \n",
"-sT[1,0]&+(1+2s)T[1,1]&-sT[1,2]&+0T[1,3]&+0T[1,4]&=&T[0,1] \\\\\n",
"0T[1,0]&-sT[1,1]&+(1+2s)T[1,2]&-sT[1,3]&+0T[1,4]&=&T[0,2] \\\\\n",
"0T[1,0]&+0T[1,1]&-sT[1,2]&+(1+2s)T[1,3]&-sT[1,4]&=&T[0,3]\n",
"\\end{array} $$\n",
"\n",
"It may seem like we have five unknowns and only three equations but $T[1,0]$ and $T[1,4]$ are on the boundaries and they are known. Let's rearrange the equation system so that the left hand side has ony the unknowns:\n",
"\n",
"$$ \\begin{array}{rrrrcrr} \n",
"(1+2s)T[1,1]&-sT[1,2]&+0T[1,3]&=&T[0,1]&+sT[1,0] \\\\\n",
"-sT[1,1]&+(1+2s)T[1,2]&-sT[1,3]&=&T[0,2]& \\\\\n",
"0T[1,1]&-sT[1,2]&+(1+2s)T[1,3]&=&T[0,3]&+sT[1,4]\n",
"\\end{array} $$\n",
"\n",
"In matrix form this is equivalent to\n",
"\n",
"$$ \\begin{bmatrix} 1+2s & -s & 0 \\\\\n",
"-s & 1+2s & -s \\\\\n",
"0 & -s & 1+2s \\end{bmatrix} \\times \n",
"\\left[ \\begin{array}{c} T[1,1] \\\\ T[1,2] \\\\ T[1,3] \\end{array} \\right]\n",
"= \\left[ \\begin{array}{c} T[0,1]+sT[1,0] \\\\ T[0,2] \\\\ T[0,3]+sT[1,4] \\end{array} \\right] $$\n",
"\n",
"This of course can be extended to larger dimensions than shown here. \n",
"Now we are ready to write the code for the Laasonen scheme. One important difference relative to what I did in the explicit scheme example is that in this case we only keep the last two versions of the velocity distribution in memory, as opposed to preallocating the full array of $nt \\times ny$ size as we did before. This difference is not a significant time saver for simple problems like this but once you start dealing with more complicated tasks and code it is not possible and/or practical to keep the results of all time steps in memory."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from scipy.sparse import diags\n",
"def diffusion_Laasonen(dt,dy,t_max,y_max,viscosity,V0,V1):\n",
" s = viscosity*dt/dy**2 # diffusion number\n",
" y = np.arange(0,y_max+dy,dy) \n",
" t = np.arange(0,t_max+dt,dt)\n",
" nt = len(t) # number of time steps\n",
" ny = len(y) # number of dy steps\n",
" V = np.zeros((ny,)) # initial condition\n",
" V[0] = V0 # boundary condition on left side\n",
" V[-1] = V1 # boundary condition on right side\n",
" A = diags([-s, 1+2*s, -s], [-1, 0, 1], shape=(ny-2, ny-2)).toarray() # create coefficient matrix\n",
" for n in range(nt): # time is going from second time step to last\n",
" Vn = V #.copy()\n",
" B = Vn[1:-1] # create matrix of knowns on the RHS of the equation\n",
" B[0] = B[0]+s*V0\n",
" B[-1] = B[-1]+s*V1\n",
" V[1:-1] = np.linalg.solve(A,B) # solve the equation using numpy\n",
" return y,t,V,s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Because this is a stable scheme, it is possible to get reasonable solutions with relatively large time steps (which was not possible with the FTCS scheme):"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"dt = 0.01 # grid size for time (s)\n",
"dy = 0.0005 # grid size for space (m)\n",
"viscosity = 2*10**(-4) # kinematic viscosity of oil (m2/s)\n",
"y_max = 0.04 # in m\n",
"V0 = 10.0 # velocity in m/s\n",
"V1 = 0.0 # velocity in m/s\n",
"\n",
"plt.figure(figsize=(7,5))\n",
"for time in np.linspace(0,1.0,10):\n",
" y,t,V,s = diffusion_Laasonen(dt,dy,time,y_max,viscosity,V0,V1)\n",
" plt.plot(y,V,'k')\n",
"plt.xlabel('distance from wall (m)',fontsize=12)\n",
"plt.ylabel('velocity (m/s)',fontsize=12)\n",
"plt.axis([0,y_max,0,V0])\n",
"plt.title('Laasonen implicit scheme',fontsize=14);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Just for fun, let's see what happens if we set in motion the right side of the domain as well; that is, set $V_1$ to a non-zero value:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"dt = 0.01 # grid size for time (s)\n",
"dy = 0.0005 # grid size for space (m)\n",
"viscosity = 2*10**(-4) # kinematic viscosity of oil (m2/s)\n",
"y_max = 0.04 # in m\n",
"V0 = 10.0 # velocity in m/s\n",
"V1 = 5.0 # velocity in m/s\n",
"\n",
"plt.figure(figsize=(7,5))\n",
"for time in np.linspace(0,1.0,10):\n",
" y,t,V,s = diffusion_Laasonen(dt,dy,time,y_max,viscosity,V0,V1)\n",
" plt.plot(y,V,'k')\n",
"plt.xlabel('distance from wall (m)',fontsize=12)\n",
"plt.ylabel('velocity (m/s)',fontsize=12)\n",
"plt.axis([0,y_max,0,V0])\n",
"plt.title('Laasonen implicit scheme',fontsize=14);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Crank-Nicolson scheme"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Crank-Nicholson scheme is based on the idea that the forward-in-time approximation of the time derivative is estimating the derivative at the halfway point between times $n$ and $n+1$, therefore the curvature of space should be estimated there as well. The 'footprint' of the scheme looks like this:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"plt.figure(figsize=(6,3))\n",
"plt.plot([0,2],[0,0],'k')\n",
"plt.plot([0,2],[1,1],'k')\n",
"plt.plot([1,1],[0,1],'k')\n",
"plt.plot([0,1,2,0,1,2],[0,0,0,1,1,1],'ko',markersize=10)\n",
"plt.text(0.1,0.1,'T[n,j-1]')\n",
"plt.text(1.1,0.1,'T[n,j]')\n",
"plt.text(2.1,0.1,'T[n,j+1]')\n",
"plt.text(0.1,1.1,'T[n+1,j-1]')\n",
"plt.text(1.1,1.1,'T[n+1,j]')\n",
"plt.text(2.1,1.1,'T[n+1,j+1]')\n",
"plt.xlabel('space')\n",
"plt.ylabel('time')\n",
"plt.axis('equal')\n",
"plt.yticks([0.0,1.0],[])\n",
"plt.xticks([0.0,1.0],[])\n",
"plt.title('Crank-Nicolson scheme',fontsize=12)\n",
"plt.axis([-0.5,2.5,-0.5,1.5]);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The curvature at the halfway point can be estimated through averaging the curvatures that are calculated at $n$ and $n+1$:\n",
"\n",
"$$ 0.5s\\big(T[n+1,j+1]-2T[n+1,j]+T[n+1,j-1]\\big) + 0.5s\\big(T[n,j+1]-2T[n,j]+T[n,j-1]\\big) = T[n+1,j]-T[n,j] $$\n",
"\n",
"This can be rearranged so that terms at $n+1$ are on the left hand side:\n",
"\n",
"$$ -0.5sT[n+1,j-1]+(1+s)T[n+1,j]-0.5sT[n+1,j+1] = 0.5sT[n,j-1]+(1-s)T[n,j]+0.5sT[n,j+1] $$\n",
"\n",
"Just like we did for the Laasonen scheme, we can write the equations for the first two time steps:\n",
"\n",
"\\begin{array}{rrrrrcl} \n",
"-0.5sT[1,0] & +(1+s)T[1,1] & -0.5sT[1,2] & = & 0.5sT[0,0] & +(1-s)T[0,1] & +0.5sT[0,2] \\\\\n",
"-0.5sT[1,1] & +(1+s)T[1,2] & -0.5sT[1,3] & = & 0.5sT[0,1] & +(1-s)T[0,2] & +0.5sT[0,3] \\\\\n",
"-0.5sT[1,2] & +(1+s)T[1,3] & -0.5sT[1,4] & = & 0.5sT[0,2] & +(1-s)T[0,3] & +0.5sT[0,4]\n",
"\\end{array}\n",
"\n",
"Writing this in matrix form, with all the unknowns on the LHS:\n",
"\n",
"$$ \\begin{bmatrix} 1+s & -0.5s & 0 \\\\ -0.5s & 1+s & -0.5s \\\\ 0 & -0.5s & 1+s \\end{bmatrix} \\times \n",
"\\left[ \\begin{array}{c} T[1,1] \\\\ T[1,2] \\\\ T[1,3] \\end{array} \\right]\n",
"= \\begin{bmatrix} 1-s & 0.5s & 0 \\\\ 0.5s & 1-s & 0.5s \\\\ 0 & 0.5s & 1-s \\end{bmatrix} \\times\n",
"\\left[ \\begin{array}{c} T[0,1] \\\\ T[0,2] \\\\ T[0,3] \\end{array} \\right] +\n",
"\\left[ \\begin{array}{c} 0.5sT[1,0]+0.5sT[0,0] \\\\ 0 \\\\ 0.5sT[1,4]+0.5sT[0,4] \\end{array} \\right] $$\n",
"\n",
"Now we can write the code for the Crank-Nicolson scheme. We will use a new input parameter called $ntout$ that determines how many time steps we want to write out to memory. This way you don't have to re-run the code if you want to plot multiple time steps."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def diffusion_Crank_Nicolson(dy,ny,dt,nt,D,V,ntout):\n",
" Vout = [] # list for storing V arrays at certain time steps\n",
" V0 = V[0] # boundary condition on left side\n",
" V1 = V[-1] # boundary condition on right side\n",
" s = D*dt/dy**2 # diffusion number\n",
" A = diags([-0.5*s, 1+s, -0.5*s], [-1, 0, 1], shape=(ny-2, ny-2)).toarray() # create coefficient matrix\n",
" B1 = diags([0.5*s, 1-s, 0.5*s],[-1, 0, 1], shape=(ny-2, ny-2)).toarray()\n",
" for n in range(1,nt): # time is going from second time step to last\n",
" Vn = V\n",
" B = np.dot(Vn[1:-1],B1) \n",
" B[0] = B[0]+0.5*s*(V0+V0)\n",
" B[-1] = B[-1]+0.5*s*(V1+V1)\n",
" V[1:-1] = np.linalg.solve(A,B)\n",
" if n % int(nt/float(ntout)) == 0 or n==nt-1:\n",
" Vout.append(V.copy()) # numpy arrays are mutable, so we need to write out a copy of V, not V itself\n",
" return Vout,s"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"dt = 0.001 # grid size for time (s)\n",
"dy = 0.001 # grid size for space (m)\n",
"viscosity = 2*10**(-4) # kinematic viscosity of oil (m2/s)\n",
"y_max = 0.04 # in m\n",
"y = np.arange(0,y_max+dy,dy) \n",
"ny = len(y)\n",
"nt = 1000\n",
"plt.figure(figsize=(7,5))\n",
"V = np.zeros((ny,)) # initial condition\n",
"V[0] = 10\n",
"Vout,s = diffusion_Crank_Nicolson(dy,ny,dt,nt,viscosity,V,10)\n",
"\n",
"for V in Vout:\n",
" plt.plot(y,V,'k')\n",
"plt.xlabel('distance from wall (m)',fontsize=12)\n",
"plt.ylabel('velocity (m/s)',fontsize=12)\n",
"plt.axis([0,y_max,0,V[0]])\n",
"plt.title('Crank-Nicolson scheme',fontsize=14);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Fault scarp diffusion"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"So far we have been using a somewhat artificial (but simple) example to explore numerical methods that can be used to solve the diffusion equation. Next we look at a geomorphologic application: the evolution of a fault scarp through time. Although the idea that convex hillslopes are the result of diffusive processes go back to G. K. Gilbert, it was Culling (1960, in the paper [Analytical Theory of Erosion](http://www.jstor.org/stable/30059222)) who first applied the mathematics of the heat equation - that was already well known to physicists at that time - to geomorphology.\n",
"\n",
"Here I used the Crank-Nicolson scheme to model a fault scarp with a vertical offset of 10 m. To compare the numerical results with the analytical solution (which comes from Culling, 1960), I created a function that was written using a Python package for symbolic math called [sympy](http://sympy.org). One of the advantages of sympy is that you can quickly display equations in $\\LaTeX$."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/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YWNq/hXp6Ds5f6+/WTcTh0+n0t8bNCn4sTy2GkxlE2qmRncoW4AvEsR\nbddh0iPjMHXADufciuxTcfZFYuTESWkYo1AfIhHfyV6msWsGirQtOHihsbn0fhHXUnAS8EL/fWDp\nuZorw1t4OC+3sxt/oQLuCs66i/iLMd5aZRbZuEvBScBrs6bk6i6A+/HdZynPVubgMMAEWlkvhxYc\nZGLjUiEFJwGvEPrhmtIztXD4vq1VfMVZfp5VNIH9zn58FNQ3ohX6LxuLCXbJOYl4Lwb5zCe1DV8F\nqjg+8zh2zo94SG+ZuFGDwvkK+gn+ZBgFiTmJeJk6MYNNV8fLwVn0P7JoFikxJxmP3mnCTVPbauFp\n1wtrViUhJyEv49uS2FUV2Z3kzqLohBzO+x/uaYdL0M541wAAAABJRU5ErkJggg==\n",
"text/latex": [
"$$0.5 Y_{1} \\left(\\operatorname{erf}{\\left (\\frac{a - x}{2 \\sqrt{K t}} \\right )} + \\operatorname{erf}{\\left (\\frac{a + x}{2 \\sqrt{K t}} \\right )}\\right)$$"
],
"text/plain": [
" ⎛ ⎛ a - x ⎞ ⎛ a + x ⎞⎞\n",
"0.5⋅Y₁⋅⎜erf⎜─────────⎟ + erf⎜─────────⎟⎟\n",
" ⎜ ⎜ _____⎟ ⎜ _____⎟⎟\n",
" ⎝ ⎝2⋅╲╱ K⋅t ⎠ ⎝2⋅╲╱ K⋅t ⎠⎠"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import sympy\n",
"from sympy import init_printing\n",
"init_printing(use_latex=True)\n",
"x, t, Y1, a, K = sympy.symbols('x t Y1 a K')\n",
"y = (1/2.0)*Y1*(sympy.erf((a-x)/(2*sympy.sqrt(K*t))) + sympy.erf((a+x)/(2*sympy.sqrt(K*t))))\n",
"y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The variables in this equation are $x$ - horizontal coordinates, $t$ - time, $a$ - value of $x$ where fault is located, $K$ - diffusion coefficient, $Y_1$ - height of fault scarp."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from sympy.utilities.lambdify import lambdify\n",
"f = lambdify((x, t, Y1, a, K), y) # function for analytic solution"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"dt = 2.5 # time step (years)\n",
"dy = 0.1 # grid size for space (m)\n",
"D = 50E-4 # diffusion coefficient in m2/yr - e.g., Fernandes and Dietrich, 1997\n",
"h = 10 # height of fault scarp in m\n",
"y_max = 20 # length of domain in m\n",
"t_max = 500 # total time in years\n",
"y = np.arange(0,y_max+dy,dy) \n",
"ny = len(y)\n",
"nt = int(t_max/dt)\n",
"V = np.zeros((ny,)) # initial condition\n",
"V[:round(ny/2.0)] = h # initial condition\n",
"\n",
"Vout,s = diffusion_Crank_Nicolson(dy,ny,dt,nt,D,V,20)\n",
"\n",
"plt.figure(figsize=(10,5.2))\n",
"for V in Vout:\n",
" plt.plot(y,V,'gray')\n",
"\n",
"plt.xlabel('distance (m)',fontsize=12)\n",
"plt.ylabel('height (m)',fontsize=12)\n",
"plt.axis([0,y_max,0,10])\n",
"plt.title('fault scarp diffusion',fontsize=14);\n",
"plt.plot(y,np.asarray([f(x0, t_max, h, y_max/2.0, D) for x0 in y]),'r--',linewidth=2);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The numerical and analytic solutions (dashed red line) are very similar in this case (total time = 500 years). Let's see what happens if we let the fault scarp evolve for a longer time."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"dt = 2.5 # time step (years)\n",
"dy = 0.1 # grid size for space (m)\n",
"D = 50E-4 # diffusion coefficient in m2/yr - e.g., Fernandes and Dietrich, 1997\n",
"h = 10 # height of fault scarp in m\n",
"y_max = 20 # length of domain in m\n",
"t_max = 5000 # total time in years\n",
"y = np.arange(0,y_max+dy,dy) \n",
"ny = len(y)\n",
"nt = int(t_max/dt)\n",
"V = np.zeros((ny,)) # initial condition\n",
"V[:round(ny/2.0)] = h # initial condition\n",
"\n",
"Vout,s = diffusion_Crank_Nicolson(dy,ny,dt,nt,D,V,20)\n",
"\n",
"plt.figure(figsize=(10,5.2))\n",
"for V in Vout:\n",
" plt.plot(y,V,'gray')\n",
"\n",
"plt.xlabel('distance (m)',fontsize=12)\n",
"plt.ylabel('height (m)',fontsize=12)\n",
"plt.axis([0,y_max,0,10])\n",
"plt.title('fault scarp diffusion',fontsize=14);\n",
"plt.plot(y,np.asarray([f(x0, t_max, h, y_max/2.0, D) for x0 in y]),'r--',linewidth=2);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This doesn't look very good, does it? The reason for the significant mismatch between the numerical and analytic solutions is the fixed nature of the boundary conditions: we keep the elevation at 10 m on the left side and at 0 m on the right side of the domain. There are two ways of getting a correct numerical solution: we either impose boundary conditions that approximate what the system is supposed to do if the elevations were not fixed; or we extend the space domain so that the boundary conditions can be kept fixed throughout the time of interest. Let's do the latter; all the other parameters are the same as above."
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"dt = 2.5 # time step (years)\n",
"dy = 0.1 # grid size for space (m)\n",
"D = 50E-4 # diffusion coefficient in m2/yr - e.g., Fernandes and Dietrich, 1997\n",
"h = 10 # height of fault scarp in m\n",
"y_max = 40 # length of domain in m\n",
"t_max = 5000 # total time in years\n",
"y = np.arange(0,y_max+dy,dy) \n",
"ny = len(y)\n",
"nt = int(t_max/dt)\n",
"V = np.zeros((ny,)) # initial condition\n",
"V[:round(ny/2.0)] = h # initial condition\n",
"\n",
"Vout,s = diffusion_Crank_Nicolson(dy,ny,dt,nt,D,V,20)\n",
"\n",
"plt.figure(figsize=(10,5.2))\n",
"for V in Vout:\n",
" plt.plot(y,V,'gray')\n",
"\n",
"plt.xlabel('distance (m)',fontsize=12)\n",
"plt.ylabel('height (m)',fontsize=12)\n",
"plt.axis([0,y_max,0,10])\n",
"plt.title('fault scarp diffusion',fontsize=14);\n",
"plt.plot(y,np.asarray([f(x0, t_max, h, y_max/2.0, D) for x0 in y]),'r--',linewidth=2);"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now we have a much better result. The vertical dashed lines show the extent of the domain in the previous experiment. We have also gained some insight into choosing boundary conditions and setting up the model domain. It is not uncommon that setting up the initial and boundary conditions is the most time-consuming and difficult part of running a numerical model."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Further reading"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"R. Slingerland and L. Kump (2011) [Mathematical Modeling of Earth's Dynamical Systems](http://www.amazon.com/dp/0691145148/ref=cm_sw_r_tw_dp_iG3Wub0YJKYJK)\n",
"\n",
"W. E. H. Culling (1960) [Analytical Theory of Erosion](http://www.jstor.org/stable/30059222)\n",
"\n",
"L. Barba (2013) [12 steps to Navier-Stokes](https://github.com/barbagroup/CFDPython) - an excellent introduction to computational fluid dynamics that uses IPython notebooks\n",
"\n",
"I have blogged before about the geosciency aspects of the diffusion equation over [here](http://hinderedsettling.com/2009/11/26/hillslope-diffusion/).\n",
"\n",
"Questions or suggestions? Contact [@zzsylvester](https://twitter.com/zzsylvester)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}