0% found this document useful (0 votes)
15 views81 pages

(L) - 2015 - May - Introduction To Finite Element Modelling in Geosciences - ETH

The document is a course outline for 'Introduction to Finite Element Modelling in Geosciences' held at ETH Zürich, focusing on the fundamentals of the Finite Element Method (FEM) and practical coding skills. It covers various topics including numerical integration, diffusion equations, elasticity, and code verification, with an emphasis on hands-on exercises using MATLAB. The course aims to equip participants with the necessary knowledge and skills to implement FEM for solving differential equations in geosciences.

Uploaded by

huchenglong564
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views81 pages

(L) - 2015 - May - Introduction To Finite Element Modelling in Geosciences - ETH

The document is a course outline for 'Introduction to Finite Element Modelling in Geosciences' held at ETH Zürich, focusing on the fundamentals of the Finite Element Method (FEM) and practical coding skills. It covers various topics including numerical integration, diffusion equations, elasticity, and code verification, with an emphasis on hands-on exercises using MATLAB. The course aims to equip participants with the necessary knowledge and skills to implement FEM for solving differential equations in geosciences.

Uploaded by

huchenglong564
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Introduction to Finite Element

Modelling in Geosciences
Dave A. May ([email protected])
Marcel Frehner ([email protected])
Mike Afanasiev (ETH Zürich)
Patrick Sanan (USI Lugano)

651-4144-00L Introduction to Finite Element Modelling in Geosciences


ETH Zürich, Sonneggstrasse 5, 8092 Zürich, Switzerland

July 27 - 31, 2015


Contents

Contents i

1 Preface 1

2 Basic Principles 3
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 The Finite Element Method . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3 One-dimensional, time dependent diffusion . . . . . . . . . . . . . . . . 4
2.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3 Time for Programming 13


3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2 The FE procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

4 Numerical Integration 19
4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.2 Quadrature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

5 The Diffusion Equation: From 1D to 2D 25


5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5.2 Derivation of the element matrices . . . . . . . . . . . . . . . . . . . . . 26
5.3 Integration of the element matrices . . . . . . . . . . . . . . . . . . . . . 29
5.4 Assembling the global stiffness matrix . . . . . . . . . . . . . . . . . . . 31
5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

6 The Weak Form 35


6.1 A prototype PDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.2 The weak form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.3 The discrete weak form . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.4 Further reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

7 Elasticity in Two Dimensions 39


7.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
7.2 Governing equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
7.3 FE discretisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
7.4 Matrix assembly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

i
CONTENTS ii

7.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

8 Stokes Flow in Two Dimensions 45


8.1 Governing equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
8.2 FE discretisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
8.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

9 Code Verification 51
9.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
9.2 Taylor series approximations . . . . . . . . . . . . . . . . . . . . . . . . 51
9.3 Errors and norms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
9.4 Measuring the order of accuracy . . . . . . . . . . . . . . . . . . . . . . 54
9.5 The Method of Manufactured Solutions (MMS) . . . . . . . . . . . . . . 55
9.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

A MATLAB Introduction 61
A.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
A.2 Useful linear algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
A.3 Exploring MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

B Useful Formulae 67

C 1D Steady State Diffusion MATLAB Example 69

D MMS 1D Diffusion Example 71

E MMS Order of Accuracy Example 75

F MMS SymPy Example 77


1
Preface

Objectives
The emphasis of this course is to learn the fundamentals of the Finite Element (FE)
method, and as importantly, that you learn to write a FE code from scratch. We present
what we regard as the minimum amount of theory necessary to understand and imple-
ment the FE method. As such, this class is definitely a “hands-on” practical introduction
to finite elements.
We encourage people to work on the exercises provided in these notes at their own
speed. It is common that not every one is able to complete all of the exercises within
a one week (all day) time period. In the past, we have had students take the class
two (or three) years in a row. Don’t be discouraged if your progress in completing the
exercises diminishes after day three.

Prerequisites
For teaching purposes, we advocate using MATLAB to implement your first FE code. If
you are new to MATLAB, or have forgotten some of the essentials, in Appendix A you
can find a small MATLAB refresher tutorial.
It is also highly advantageous if you already followed a class on programming the
finite difference method; e.g. 651-4273-00L: “Numerical Modelling in Fortran” (Paul
Tackley) or 651-4241-00L: “Numerical Modelling I and II: Theory and Applications”
(Taras Gerya)
Our rational to use MATLAB for teaching is based upon the following three facts:
1. MATLAB provides users with a complete development environment including:
(i) a text editor; (ii) run-time error checking of array indices; (iii) a powerful debug-
ger.
2. MATLAB contains a wide variety of visualisation routines.
3. MATLAB contains data-structures to describe sparse matrices and includes effi-
cient sparse-direct solvers.

Further Reading
In addition to these notes, we recommend the following textbooks:
• The Finite Element Method using MATLAB. Y. W. Kwon and H. Bang (1997), CRC
Press.

1
CHAPTER 1. PREFACE 2

• The Finite Element Method, Vol. 1. O. C. Zienkiewicz and R. L. Taylor (2000),


McGraw-Hill.

• Programming the Finite Element Method. I. M. Smith and D. V. Griffiths (1998),


John Wiley & Sons.

• The Finite Element Method. T. J. R. Hughes (2000), Prentice-Hall.

• Finite Elements and Fast Iterative Solvers. H. C. Elman, D. J. Silvester & A.


Wathan (2005), Oxford University Press.

• The Mathematical Theory of Finite Element Methods. S. C. Brenner & L. R. Scott


(2005), Springer.

• Computational Techniques for Fluid Dynamics, Vol. 1. C. A. J. Fletcher (2000),


Springer.

More background on finite elements and there application in computational geodynam-


ics, can be found in these references:

• Computational Geodyamics. A. Ismail-Zadeh and P. J. Tackley (2010), Cam-


bridge University Press.

• Numerical Modeling of Earth Systems: An introduction to computational methods


with focus on solid Earth applications of continuum mechanics. Lecture notes,
University of SouthernCalifornia, Becker and Kaus (2014). Available at http:
//geodynamics.usc.edu/~becker/preprints/Geodynamics557.pdf

• Finite Element block course: “Introduction to Finite Element Modelling in Geo-


sciences” - ETH Zürich. Lecture notes, available at http://jupiter.ethz.ch/
~gfdteaching/femblockcourse/2014/IntroToFEMForGeosciences.html

Acknowledgements
This class is built upon previous finite element classes taught at ETH which were es-
tablished by Guy Simpson (now at University of Geneva), Boris Kaus (now at Johannes
Gutenberg University Mainz) and Stefan Schmalholz (now at University of Lausanne).
2
Basic Principles

2.1 Introduction

The purpose of this course is to learn how to solve differential equations with the Finite
Element Method (FEM). For the most part we assume that the equations governing the
processes of interest are known and given. We will focus on the practical process of
how one goes from the equation, to obtaining an approximate (numerical) solution. Al-
though there are a variety of numerical techniques that one can use to obtain numerical
solutions, here we will focus solely on the FEM.
The process of obtaining a computational solution consists of two stages shown
schematically in Figure 2.1. The first stage converts the continuous partial differential
equation (PDE) and auxiliary (boundary and initial) conditions into a discrete system
of algebraic equations. This first stage is called discretisation. The second stage
involves solving the system of algebraic equations to obtain an approximate solution
to the original partial differential equation. The solution is approximate since errors
are introduced by the replacement of continuous differential terms in the governing
partial differential equation by algebraic expressions connecting nodal values on a finite
grid. Errors are also introduced during the solution stage but these tend to be small in
comparison to discretisation errors, unless the method failed to converge.
To convert the governing partial differential equation to a system of algebraic equa-
tions (or ordinary differential equations) a number of choices are available. The most
common are the finite difference, finite element, finite volume and spectral methods.
In principle, the solution does not depend on the method chosen. Each method has
its own advantages and disadvantages. The best approach is to choose the method
which best suits the problem being investigated. This course will only deal with the
finite element method, which is widely used in practice and is extremely powerful. The
technique is slightly harder to learn than, for example, the finite difference technique.
However, as you will see, the effort invested in initially learning the FEM pays of due to
the wide range of problems that the method is capable of solving. The FEM is espe-
cially well suited (though not restricted) to solving mechanical problems and problems
with domains which are geometrically complex. Another advantage of programming
in the finite element method is that the main structure of the code remains the same,
even when the method is applied to different physical problems. Thus, once you learn
this basic structure, you can modify it to solve a variety of problems with minimal effort.

3
CHAPTER 2. BASIC PRINCIPLES 4

Figure 2.1: Overview of the computational solution technique.

2.2 The Finite Element Method


The finite element method is a technique for solving partial differential equations. Usu-
ally, only the spatial derivatives are discretised with the finite element method whereas
finite differences are used to discretise time derivatives. Spatial discretisation is carried
out locally over small regions of simple but arbitrary shaped elements (the finite ele-
ments). This discretisation process results in matrix equations relating the loads (input)
at specified points in the element (called nodes) to the displacements (output) at these
same points. In order to solve equations over larger regions, one sums node-by-node
the matrix equations for the smaller sub-regions (elements) resulting in a global matrix
equation. This system of equations can then be solved simultaneously by standard
linear algebra techniques to yield nodal displacements. This last step completes the
numerical solution of the differential equation.

2.3 One-dimensional, time dependent diffusion


The various steps involved in performing the finite element method are best illustrated
with a simple example. Consider the following partial differential equation
 
∂T ∂ ∂T
= κ(x) + s(x), (2.1)
∂t ∂x ∂x
which governs transient heat conduction in one dimension with a source term s(x).
The dependent variable in this equation is the temperature T (x, t), the independent
variables are time t, distance x, κ(x) the thermal diffusivity and s(x) the source. We
are interested in computing the temperature function T (x, t) which satisfies Equation
(2.1) (i.e., the solution) over the domain Ω = [xA , xB ] subject to either (i) Dirichlet
boundary conditions of the form
T (xA , t) = TA
(2.2)
T (xB , t) = TB ,
where TA , TB are prescribed temperatures, or (ii) Neumann boundary conditions of the
form
∂T
κ = qA
∂x x=xA ,t
(2.3)
∂T
κ = qB ,
∂x x=xB ,t
where qA , qB are prescribed fluxes, or (iii) some mixture of Dirichlet and Neumann
conditions. We also require an initial condition
T (x, t = 0) = T0 (x). (2.4)
2.3. ONE-DIMENSIONAL, TIME DEPENDENT DIFFUSION 5

The first step of the finite element method involves choosing an element type which
defines where and how the discretisation is carried out. The simplest element for one
dimensional problems is a 2-node element (Figure 2.2a). As we will see, one can
use more nodes per element which will have the effect of increasing accuracy, but
also increasing the amount of equations and thus the cost of obtaining the numerical
solution.
The second step of the finite element method involves approximating the continu-
ous variable T in terms of nodal variables Ti using simple functions Ni (x) called shape
functions. If one focuses on one element (which contains 2 nodes), and one assumes
that temperature varies linearly between two nodes, one can write

T (x) ≈ N1 (x)T1 + N2 (x)T2 , (2.5)

or, using matrix notation


 
  T1
T (x) ≈ N1 (x) N2 (x) = NT. (2.6)
T2

In these equations, T is the continuous variable which we are approximating within


any given element in terms of the temperatures at the two nodes T1 and T2 . Since we
made the choice that temperature varies linearly between two nodes, we have to use
the following shape functions,
x x
N1 (x) = 1 − , N2 (x) = , (2.7)
L L
where L is the length of the element and x is the spatial variable which varies from 0
at node 1 to L at node 2 (Figure 2.2b). Note the following important properties of the
shape functions
• N1 = 1 at node 1 while N1 = 0 at node 2.

• N2 = 0 at node 1 while N2 = 1 at node 2.

• N1 (x) + N2 (x) = 1 (over the entire element).

• The functions are only local (i.e., they only connect adjacent nodes).
Note that the shape functions are simply interpolating functions (i.e., they are used
to interpolate the solution over a finite element). Also, as will become clear in the
following lectures, the choice of the shape functions is directly related to the choice of
an element type. For example in one-dimension, variation in a 2-node element cannot
be uniquely described by a function with an order greater than linear (two parameter
model), variation in a 3-node element cannot be uniquely described by a function with
an order greater than quadratic (three parameter model), etc.
The next step of the finite element method is to substitute our approximation for the
continuous variable into the governing differential equation. Thus, substituting Equation
(2.6) into Equation (2.1) leads to
      
∂   T1 ∂ ∂   T1
N1 (x) N2 (x) − κ(x) N1 (x) N2 (x) −s(x) = R, (2.8)
∂t T2 ∂x ∂x T2

where R (the residual) is a measure of the error introduced during discretisation. Note
that the original partial differential equation has now been replaced by an equation in
CHAPTER 2. BASIC PRINCIPLES 6

node 1 node 2
a) 1-D element
dx
x=0 x=dx

b) N(x) N1 N2

node 1 node 2

x=0 x=dx

c)

node 1 node 2 node 3 node 4 node 5

element 1 element 2 element 3 element 4

x=0 x=Lx
Figure 2.2: a) a 2-node, one dimensional finite element with b) linear shape functions,
and c) a small one dimensional mesh consisting of four elements and a total of five
nodes. See text for discussion.

the discretised (nodal) variables T1 and T2 . Thus, we now have one equation for two
unknowns, which obviously cannot be solved. The problem now reduces to finding
values for T1 and T2 such that the residual is minimized (ideally R is zero as in the
original equation). However to do so, we have to generate a system of equations
where the number of equations equals the number of unknowns.

In the finite element method, the unknown coefficients Ti are determined by requir-
ing that the integral of the weighted residual is zero on an element basis. To achieve
this step practically, one must multiply (or “weight”) the residual in Equation (2.8) by a
set of weighting functions (each in turn), integrate over the element volume and equate
to zero. Many methods (e.g., collocation, least squares and Galerkin) can be used
to achieve this process, the difference between which depends on the choice of the
weighting functions. In this course we will only consider the Galerkin method. In the
Galerkin method, the weighting functions are chosen to be identical to the shape func-
2.3. ONE-DIMENSIONAL, TIME DEPENDENT DIFFUSION 7

tions N . By carrying out the steps just described one obtains


Z L    
N1 ∂   T1
N1 N2 dx
0 N2 ∂t T2
Z L      Z L   
N1 ∂ ∂   T1 N1 0
− κ(x) N1 N2 dx − s(x) dx = . (2.9)
0 N2 ∂x ∂x T2 0 N 2 0

Note that in this example where the shape functions are linear, double differenti-
ation of these functions would cause them to vanish (obviously not very desirable).
This difficulty is resolved by applying Green’s theorem (integration by parts). In one
dimension, applied over the volume Ω = [xA , xB ] this yields
Z   Z xB
∂ ∂Nj ∂Ni ∂Nj ∂Nj
Ni κ(x) dx = − κ(x) dx + κ(x)Ni . (2.10)
Ω ∂x ∂x Ω ∂x ∂x ∂x xA

We note that the final term in the above expression which is evaluated at the end
points of the domain corresponds to a discrete flux. By invoking Green’s theorem, we
have implicitly introduced the Neumann boundary condition (see Equation (2.3)) into
our discretisation. We will assume that κ(x) and s(x) are constant over each element
volume [xA , xB ] and the constant values are denoted by κ̄ and s̄ respectively. Note
that these choices do not preclude using a spatially dependent value for κ or s over
the entire model domain, it only places a restriction on how these coefficients may vary
within an element. Under these assumptions and using Equation (2.10), we can write
Equation (2.9) as

L L
Z Z 
N1 N1 dx N1 N2 dx ∂  

Z0 L 0
T1
L
Z 
  ∂t T2
N2 N1 dx N2 N2 dx
0 0
Z L Z L 
∂N1 ∂N1 ∂N1 ∂N2
dx dx  
∂x ∂x ∂x ∂x  T1

0
+ κ̄ Z L
 0
Z L
∂N2 ∂N1 ∂N2 ∂N2  T2
dx dx
0 ∂x ∂x ∂x ∂x
0Z L   
N 1 dx N q
  1 A xA 
 
 0
− s̄  L
 0
−
 = . (2.11)
0
Z
N2 dx N2 qB
x B
0

Note that one now has two equations for the two unknowns T1 and T2 as desired. On
evaluating the integrals (using N defined in Equation (2.7)), Equation (2.11) becomes
"L L
# " # " 1 # "L# " #
∂ T1 − L1 N1 qA
  
T1 xA 0
3 6
+ κ̄ L1 − s̄ L2 − = , (2.12)
L L ∂t T2 −L 1 T2 N2 qB 0
6 3 L 2 xB

which can be simplified using matrix notation to the following


 
∂T
MM + KM T = F, (2.13)
∂t
CHAPTER 2. BASIC PRINCIPLES 8

where
L L
 

MM =  3 6  , (2.14)
 
L L
6 3
1 1
 

KM = κ̄  L L , (2.15)

1 1 

L L
L
   
N q
   1 A xA 
F = s̄  2  +  , (2.16)
L N2 qB
2 xB

and  
T
T= 1 . (2.17)
T2

Remark: We note that our notation for matrices is somewhat unconventional in


that two letters are used to define a matrix. This notation style is purely historical.
Please do not ever assume that MM implies raising the matrix M to the power 2,
e.g. it does not mean M2 .

The next step we perform is to discretise the time derivative. Here this is achieved
using a finite difference approximation. Assuming an implicit time discretisation, one
approximates Equation (2.13) as

Tn+1 − Tn
 
MM + KM Tn+1 = F, (2.18)
∆t

where Tn+1 is the future temperature at the nodes (i.e., the unknowns) and Tn is the
vector of old (i.e., known) temperatures. Rearranging, one can write this as
 
1 1
MM + KM Tn+1 = MM Tn + F, (2.19)
∆t ∆t

or more compactly as
KL Tn+1 = KR Tn + F, (2.20)
where
L κ̄ L κ̄
 
+ −
KL =  3∆t L 6∆t L  (2.21)

L κ̄ L κ̄

− +
6∆t L 3∆t L
and
L L
 

KR =  3∆t 6∆t  (2.22)



L L

6∆t 3∆t
2.3. ONE-DIMENSIONAL, TIME DEPENDENT DIFFUSION 9

and the F vector is


1
 
" #
2 qA
F = s̄L   + .
1 qB
2
In Equation (2.20), everything appearing on the right hand side is known (and it
combines to form a vector). The matrix KL is referred to as the element stiffness matrix
whereas T is the unknown element vector (and the subscript n+1 has been dropped for
clarity). For the purposes of following discussions we introduce the following notation:
 
KL11 KL12
KL = .
KL21 KL22
L
Thus, for example, the term KL11 has the value 3∆t + Lκ̄ . Similar notation is assumed
for KR.
Remember that so far we have only carried out discretisation for a single element,
whereas we generally want to divide the solution domain into many elements so as
to obtain an accurate solution. Accordingly, let us consider a small one-dimensional
mesh, consisting of four elements (once you get the idea you can easily consider more
elements). This situation is depicted in Figure 2.2c. Now, instead of having just two
unknowns, we have five, related to the five nodes in the mesh. One now generates
a global matrix equation by summing node-by-node the matrix equation derived for
a single element (i.e., Equation (2.12)). Thus, for example, note that whereas node
1 contains a contribution only from element 1, node 2 has contributions from both
elements 1 and 2 (Figure 2.2c). Performing this process (using the notation introduced
above and assuming that each element matrix is the same) leads to

   n+1
KL11 KL12 0 0 0 T1
KL21 KL22 + KL11 KL 0 0
12  T2 
  

 0 KL21 KL22 + KL11 KL12 0  T3 
 
 
 0 0 KL21 KL22 + KL11 KL12  T4 
0 0 0 KL21 KL22 T5
   n
KR11 KR12 0 0 0 T1
KR21 KR22 + KR11 KR 0 0
12  T2 
  

= 0
 KR21 KR22 + KR11 KR12 0  T3 
 

 0 0 KR21 KR22 + KR11 KR12  T4 
0 0 0 KR21 KR22 T5
1  
2 qA
1  0 
   
 1  +  0  , (2.23)
+ sL    
1  0 
1
2 qB

which, using matrix notation, becomes

KLG Tn+1 = KRG Tn + FG , (2.24)

where the subscript G indicates that the matrices and vectors refer to the entire “global”
or assembled problem and not simply to a single element. Note that the matrices KLG
CHAPTER 2. BASIC PRINCIPLES 10

and KRG are symmetric which is an important (though not a necessary) property
when it comes to solving the system of equations. Note that most non-zero terms are
clustered near the main diagonal – a property which can be exploited when solving the
system of linear equations. Also, note that the two imposed boundary fluxes, qA and
qB , only appear in rows 1 and 5. The reason for this is that the row 1 corresponds to
node 1, which is located at the left hand side of the boundary (xA = 0) and row 5 is
related to node 5, which is located on the right most side of the boundary (xB = Lx ).
Equation (2.24) can also be written in the form
KLG Tn+1 = b, (2.25)
which is the classic form for a system of linear equations. In this last expression, KLG
is referred to as the stiffness (or coefficient) matrix (and is known), b is referred to as
the “right hand side vector” or “load vector” and Tn+1 is the unknown “solution vector”
or “reaction vector”.
The final step before one can solve the linear system of equations represented by
Equation (2.25) is to impose boundary conditions. There are several possible choices;
fixed temperature, fixed temperature gradient, or some combination of the two. Fixed
temperature boundaries may be implemented by performing the following steps: (1)
zeroing the entries in the relevant equation (2) placing a 1 on the diagonal entry of the
stiffness matrix and (3) setting the value at the correct position of the right hand side
vector equal to the desired value. Alternatively, if one wishes to implement zero-flux
boundary conditions one does not have to do anything explicitly (i.e., it is the default
boundary condition created when one ignored the boundary terms in Equation (2.10)).
Non zero flux boundary conditions are slightly more complex to evaluate. In this class,
if boundary fluxes are imposed, they will always be equal to zero. These will be referred
to as the natural boundary condition.
You are now ready to compute the solution to Equation (2.25). The basic steps that
need to be incorporated into a computer program can be summarized as follows:
1. Define all physical parameters (e.g., diffusivity, source term, length of spatial do-
main) and numerical parameters e.g., number of elements and nodes).
2. Define the spatial coordinates xi for your nodes, and specify the time domain
where you want to obtain the discrete solution.
3. Within an element loop, define the element matrices MM and KM and the ele-
ment load vector F (see Equations (2.14) to (2.16)). Use these to compute KL
and KR (see Equations (2.21) & (2.22)). Sum these matrices node-by-node to
form the global matrices KLG and KRG and the global vector FG (see Equations
(2.23)). If the element properties do not depend on time these global matrices
only need to be calculated once and can be saved for later use.
4. Within a time loop, perform the operations on the right hand side of Equation
(2.25) (i.e., firstly multiply KRG with the old temperature vector Tn and then add
the resulting vector to FG ) to form the right-hand-side vector b. Note that the
vector T0 must contain the discrete form of your initial condition, T (x, 0).
5. Apply boundary conditions.
6. Solve Equation (2.25) for the new temperature, and then continue to the next time
step.
2.4. EXERCISES 11

2.4 Exercises
1. Read the text above and try to understand it.

2. We solved the system for second order derivatives. Can we employ linear shape
functions if we want to solve, for example, the bending equation for a thin plate,
which has fourth order derivatives? If no, which shape functions should be em-
ployed?
3
Time for Programming

3.1 Introduction
The purpose of this session is to learn how to program the finite element method (FEM)
in one dimension using MATLAB. To illustrate this we use the diffusion equation (dis-
cretised in Chapter 2) which is governed by the following element equations
 
MM MM n
+ KM Tn+1 = T + F, (3.1)
∆t ∆t

where " ∆x #
∆x
3 6
MM = ∆x ∆x
, (3.2)
6 3

−1
" 1
#
∆x ∆x
KM = κ −1 1
, (3.3)
∆x ∆x
" ∆x # " #
2
N1 qA xA
F=s ∆x
+ , (3.4)
2
N2 qB xB

and  
T
T= 1 . (3.5)
T2
The superscripts n and n + 1 refer to the old (known) and future (unknown) tempera-
tures, respectively. These equations can be written more compactly as

KL Tn+1 = KR Tn + F, (3.6)

where the element stiffness matrix KL is


MM
KL = + KM (3.7)
∆t
and the element right hand side matrix KR is

MM
KR = . (3.8)
∆t
Remember that for a 2-node element, these relations form a system of two equa-
tions for the two unknown node temperatures T1 and T2 . It is important to distinguish

13
CHAPTER 3. TIME FOR PROGRAMMING 14

these element equations from the global equations formed by summing the element
equations node-by-node within a finite element mesh, denoted as

KLG Tn+1 = KRG Tn + FG = b, (3.9)

where the subscript G indicates that the matrices and vectors are global matrices. The
size of the matrices KLG and KRG are nn × nn (where nn is the number of nodes in
the finite element mesh) whereas the matrices MM and KM have dimensions 2 × 2.

3.2 The FE procedure


The basic steps that must be performed in order to solve these equations within a
computer program can be summarized as follows:

1. Define all physical parameters (e.g., diffusivity, source term, length of spatial do-
main) and numerical parameters e.g., number of elements and nodes).

2. Define the spatial coordinates xi for your nodes, and specify the time domain
where you want to obtain the discrete solution.

3. Define the relationship between the element node numbers and the global node
numbers.

4. Define boundary node indices and the values of the potential (e.g., temperature)
at the boundary nodes.

5. Initialise the global matrices KLG , KRG and FG so that their dimensions are
defined and that the matrices are filled with zeros.

6. Within an element loop, define the element matrices MM and KM and the ele-
ment load vector F (see Equations (3.2), (3.3) and (3.4)). Use these to compute
KL and KR. Sum these matrices (and F) node-by-node to form the global stiff-
ness matrices KLG and KRG and the global vector FG (see Equation (3.9)). If
the element properties do not depend on time these global matrices only need to
be calculated once and can be saved for later use.

7. Within a time loop, perform the operations on the right hand side of Equation
(3.9) (i.e., firstly multiply KRG with the old temperature vector Tn and then add
the resulting vector to FG to form the right hand side vector b). Note that the
vector T0 must contain the discrete form of your initial condition, T (x, 0).

8. Apply boundary conditions.

9. Solve Equation (3.9) for the new temperature, and then continue to the next time
step.

We will now describe each of these steps in more detail. In the following, we will
indicate where MATLAB commands are used via the syntax
>> alpha = 1.0;
3.2. THE FE PROCEDURE 15

[1] Parameter definitions


This step requires little further explanation. All physical (e.g., κ, domain length, etc.)
and numerical (number of nodes, timestep) parameters must be defined in this section
using commands of the form
>> kappa = 10.0;

[2] Define spatial and time domain


Similarly this step requires little further explanation. The spatial coordinate vector x
can be defined in MATLAB using the command
>> x = [ 0 : dx : lx ];

where lx is the length of the spatial domain and dx is the element length. One can
create a similar vector for time.

[3] Local to global mapping


In order to sum the element equations node-by-node to form the global matrices one
must define the relationship between local node numbers and global node numbers.
We achieve this by creating a matrix called g num which has the following form for a
5-node (4 element) finite element mesh constructed with 2-node (linear) elements:
 
1 2 3 4
g num = ,
2 3 4 5

which in MATLAB is defined via the command,


>> g_num = [ 1 , 2 , 3 , 4 ; 2 , 3 , 4 , 5 ];

The matrix g num has the dimensions nod × nels where nod is the number of nodes
per element and nels is the total number of elements in the mesh (both of which must
be defined in “[1] Parameter definitions” - see above). Thus, for example, the two local
node numbers 1 and 2 in element 3 correspond to the global node numbers 3 and 4
respectively (i.e., g num(1,3) = 3 and g num(2,3) = 4).

[4] Define boundary conditions


One must define to which global nodes boundary conditions are to be applied (and
what the boundary value is). This can be done with the following commands:
>> bcdof = [ 1 , nn ];

and
>> bcval = [ 0.0 , 0.0 ];

The array bcdof specifies which which nodes, namely the first (1) and last (nn), in the
mesh are to be constrained. The array bcval defines the value of the temperature
constraint we wish to apply at each boundary node.
CHAPTER 3. TIME FOR PROGRAMMING 16

[5] Initialisation
One must initialise the global matrices KLG , KRG and global vector FG using com-
mands of the form
>> KLG = zeros ( nn , nn );

and
>> FG = zeros ( nn , 1 );

where nn is the number of equations in the finite element mesh (which also equals the
total number of nodes in this problem).

[6] Element matrix assembly


The element matrices MM and KM can be formed using commands of the form
>> MM = [ dx /3.0 , dx /6.0 ; dx /6.0 , dx /3.0 ];

whereas the vector F can be formed with the command


>> F = s *[ dx /2.0 ; dx /2.0 ];

Once these are defined, the matrices KL and KR can be computed according to
Equations (3.7) and (3.8). The next task is, within a loop over all elements, to sum
the element matrices node-by-node to form the global matrices. This step is achieved
using the matrix g num just described. For example, in order to form the matrix KLG
one can use the following commands:
>> KLG ( g_num (: , iel ) , g_num (: , iel ))
= KLG ( g_num (: , iel ) , g_num (: , iel )) + KL ;

whereas to form the vector FG one can use


>> FG ( g_num (: , iel )) = FG ( g_num (: , iel )) + F ;

The variable iel is the current element number which varies within the loop from 1 to
nels.

[7] Form right hand side vector


Within a time loop one can now form the global right hand side vector b with the com-
mand
>> b = KRG * T + FG ;

where T is the vector (with dimensions nn × 1) of old temperatures and the other
vectors and matrices are described above.

[8] Implement boundary conditions


The boundary conditions can be imposed using the following sequence of commands:
>> for i =1: length ( bcdof )
>> KLG ( bcdof ( i ) , : ) = 0.0;
>> KLG ( bcdof ( i ) , bcdof ( i )) = 1.0;
>> b ( bcdof ( i ) ) = bcval ( i );
>> end
3.3. EXERCISES 17

The above piece of MATLAB code does the following. First we loop over all nodes that
have a (fixed or Dirichlet) boundary condition. We place zeros throughout the entire
row where the boundary conditions should be imposed. These row indices are listed
in the array bcdof. Following that, we place a value 1.0 on the diagonal of that row,
and place the corresponding value of the Dirichlet boundary condition in the right hand
side vector b.

[9] Solution
The final step which must be carried out is to solve the system of equations (i.e., Equa-
tion (3.9)) simultaneously, which can be performed using the MATLAB command
>> T = KLG \ b ;

This operation will compute the solution vector T, which contains the temperature
within the domain at the n + 1 timestep. A new time step can be computed by re-
peating Steps 7,8,9.

3.3 Exercises
1. Write a code that can solve the 1D diffusion problem with the finite element
method. For simplicity we will assume that the boundary integral term is zero.
Note that this assumption implies that we are solving the diffusion with zero flux
boundary conditions.

2. Modify the code, to take into account source terms, variable grid spacing, and
variable thermal diffusivity (assume properties to be constant within one ele-
ment).

3. A simple (time-dependent) analytical solution for the diffusion equation exists for
the case when the forcing term s = 0, and the initial temperature distribution is
given by  2
x
T (x, t = 0) = Tmax exp − 2 .
σ
Here σ is the half-width of the distribution and Tmax is the maximum amplitude of
the temperature perturbation at x = 0. The solution for this problem is given by

−x2
 
Tmax
T (x, t) = p exp 2 .
1 + 4tκ/σ 2 σ + 4tκ

This solution is derived assuming that T → 0 at x = ±∞. Program the analytical


solution and compare the analytical solution with the numerical solution with the
same initial condition. Use Tmax = 100, σ = 1 and −5 ≤ x ≤ 5.
4
Numerical Integration

4.1 Overview
In Chapter 3 we saw that 1D finite element discretisation of the diffusion equation may
lead to the element matrices
Z L Z L 
 N1 N1 dx N1 N2 dx
 0 0
MM = Z L (4.1)

Z L 
 
N2 N1 dx N2 N2 dx
0 0
and  Z L Z L 
∂N1 ∂N1 ∂N1 ∂N2
κ dx κ dx
 0 ∂x ∂x 0 ∂x ∂x
KM =  Z L (4.2)

Z L 
 ∂N2 ∂N1 ∂N2 ∂N2 
κ dx κ dx
0 ∂x ∂x 0 ∂x ∂x
and element force vector (assuming zero flux Neumann boundary conditions)
Z L 
 N1 dx
F = s L
 Z 0 , (4.3)

N2 dx
0
where the shape functions N1 and N2 were defined as
x x
N1 (x) = 1 − , N2 (x) = . (4.4)
L L
As we will see later, many different partial differential equations (elasticity, viscous
fluid flow) lead to these same (or at least very similar) set of matrices. A mass ma-
trix MM is always associated with discretisation of a first-order time derivative (e.g.,
∂T /∂t) whereas the KM matrix comes from the discretisation of second-order spatial
derivatives (e.g., ∂ 2 T /∂x2 ). In the example we considered it was possible to evalu-
ate the integrals in Equations (4.1) & (4.2) analytically. This was largely facilitated by
the fact that we (i) considered a 1D problem using (ii) linear basis functions and (iii)
we assumed that κ was constant over each element. Using analytically derived ele-
ment stiffness matrices can be advantageous as it avoids the need to approximate the
integrals which removes one source of numerical error and may also be much more
efficient than an approximate technique. However, in general, if any of the above three
assumptions are violated, using analytically derived stiffness matrices is not feasible.
In such circumstances one must approximate the integrals appearing within the stiff-
ness matrix. Throughout the remainder of this course, we will utilise integrals which
have been approximated numerically using an optimal and efficient technique.

19
CHAPTER 4. NUMERICAL INTEGRATION 20

4.2 Quadrature
The method we will employ to perform numerical integration is a type of quadrature
rule. In general, a quadrature rule replaces the integral by a weighted sum over a set
of n quadrature points. For example, the function f (ξ) integrated over the range [a, b]
is approximated via
Z b n
X
f (ξ) dξ ≈ f (ξi )wi . (4.5)
a i=1

In Equation (4.5), ξi is the coordinate (or abscissa) of the ith quadrature point and
wi is the quadrature weight associated with the ith quadrature point. Note that the
quadrature rule only requires one to evaluate the integrand f (·) at the location of each
quadrature point.
The choice of quadrature scheme defines the values of n, ξi and wi . The type of
quadrature scheme which should be used is entirely dependent on the nature of the
integrand f (·). In finite element analysis, the integrand is defined via products of the
basis functions N (see MM) or from products of the derivative of the basis functions
(see KM). In general, integrands of this type are polynomials of some order k, i.e. they
contain terms like ξ s where s = 1, 2, . . . , k. The family of Gauss-Legendre quadrature
schemes have been specifically designed to exactly evaluate polynomial integrands in
one dimension. We will denote the n-point Gauss-Legendre (GLg), as the rule which
uses n quadrature points. In 1D, the n-point GLg rule exactly integrates polynomials of
order ≤ (2n − 1). Tabulated values of n, ξi and wi for GLg rules which are suitable for
polynomials up to third order can be found in most finite element books. In Table 4.1
we provide the Gauss-Legendre quadrature rules for 1D from n = 1 → 4.

n ξi wi k

1 0.0 2.0 1
q
2 ± 13 1.0 3

3 0.0 0.88888888888889
±0.774596669241483 0.55555555555556 5

4 ±0.339981043584859 0.65214515486255
±0.861136311594053 0.34785484513745 7

Table 4.1: A selection of different order accuracy 1D Gauss-Legendre quadrature rules.


n denotes the number of quadrature points. The quantities wi , ξi indicate the weight
and coordinate of the ith quadrature point respectively. k is the polynomial order for
which the integration rule is exact.

To be used in a general manner, tabulated quadrature rules assume an integration


domain. GLg rules typically assume that the integration is performed over the domain
[−1, 1]. The choice of integration domain is arbitrary. To use the tabulated rule in prac-
tice, one needs to define a coordinate transform from the domain of interest (say [a, b] in
Equation (4.5), or [0, L] in Equation (4.1)) to the domain used by the tabulated quadra-
4.2. QUADRATURE 21

ture rule. To illustrate the necessary steps to numerically evaluate a finite element
stiffness matrix via GLg quadrature, we now consider evaluating
Z L
N1 (x)N1 (x) dx. (4.6)
0

The first task is to transform the limit of integration, from what we will refer to as the
global coordinate system 0 ≤ x ≤ L to local coordinate system used by the quadrature
rule given by −1 ≤ ξ ≤ 1. Note that the shape functions defined in Equation (4.4)
are written in terms of the global coordinate x varying over the interval [0, L]. We can
linearly map the [0, L] interval for x onto the [−1, 1] interval for ξ using the following
transformation:
L
x = (ξ + 1) . (4.7)
2
The reader should check that this transformation gives us the desired limits of [−1, +1].
This is achieved by inserting x = 0 (and x = L) into Equation (4.7) and solving for ξ.
Substituting Equation (4.7) into Equation (4.4) leads to the shape functions defined in
terms of local coordinates
1 1
N1 (ξ) = (1 − ξ) , N2 (ξ) = (1 + ξ) . (4.8)
2 2
To perform the integration over the local coordinate system [−1, +1], we must first
transform the variable of integration. This is obtained by differentiating Equation (4.7)
with respect to ξ and rearranging to yield
L
dx = dξ. (4.9)
2
Thus, one can rewrite the integral in Equation (4.6) as
Z L Z 1
L
N1 (x)N1 (x) dx = N1 (ξ)N1 (ξ) dξ. (4.10)
0 −1 2

As will be seen in the following lectures, the term L2 appearing in Equation (4.10), which
is responsible for converting the integral from the global to the local coordinate system,
is referred to as the determinant of the Jacobian, det(J).
Now we are ready to numerically approximate the integral using the summation
formula in Equation (4.5). For example, using the 2 point Gauss-Legendre rule (i.e.,
n = 2, see Table 4.1) the integral can be computed as
Z 1
L  p   p  L
N1 (ξ)N1 (ξ) dξ ≈ N1 − 1/3 N1 − 1/3 × × 1.0
−1 2 2
p  p  L
+ N1 1/3 N1 1/3 × × 1.0
2
L
= (0.6220084681 × 1.0 + 0.04465819869 × 1.0)
2
= 0.333L,
p
p that N1 (ξ)N1 (ξ) evaluated at 1/3 is 0.04465819869 and N1 (ξ)N1 (ξ) at ξ =
noting
− 1/3 is 0.6220084681 and the weighting factors are both 1.0 (see Table 4.1). Note
that this result is identical to the result obtained by the analytic calculation (i.e., L/3).
CHAPTER 4. NUMERICAL INTEGRATION 22

As a second example, consider calculation of the term


Z L
∂N1 ∂N1
dx, (4.11)
0 ∂x ∂x
appearing in Equation (4.2). Note firstly that, by using the chain rule,
∂N1 ∂N1 ∂ξ
= . (4.12)
∂x ∂ξ ∂x
In general, the derivative of the global coordinate with respect to local coordinate (i.e.,
∂x/∂ξ) is known as the Jacobian (denoted J). The inverse relation, ∂ξ/∂x (appearing
in Equation (4.12)) is known as the inverse of the Jacobian, and this must always be
calculated to convert derivatives from global coordinates to local coordinates.
Therefore, one can rewrite Equation (4.11) as
Z L Z L  
∂N1 ∂N1 ∂N1 ∂ξ ∂N1 ∂ξ
dx = dx
0 ∂x ∂x 0 ∂ξ ∂x ∂ξ ∂x
Z 1  
∂N1 ∂ξ ∂N1 ∂ξ L
= dξ (4.13)
−1 ∂ξ ∂x ∂ξ ∂x 2
Z 1
∂N1 ∂N1 2
= dξ,
−1 ∂ξ ∂ξ L

where we used the fact that ∂x/∂ξ = L2 (see Equation (4.9)). Note that ∂N1 /∂ξ = −1/2,
which is constant (see Equation (4.8)). Thus by using the 2-point GLg quadrature rule,
the term represented by Equation (4.13) can be integrated to give
Z 1        
∂N1 ∂N1 2 2 1 1 1 1
dξ ≈ − − × 1.0 + − − × 1.0
−1 ∂ξ ∂ξ L L 2 2 2 2 (4.14)
1
= ,
L
which is once again the exact result.
From these simple examples, we see that numerical integration gives very accu-
rate results with minimal computation (in this case using only 2 integration points).
This accuracy is due the strength of the Gauss-Legendre method and the fact that the
functions being integrated are polynomials of a known order.
For the remainder of this course we will assume that shape functions and their
derivatives are given in terms of the local coordinates on the interval [−1, 1]. Moreover,
we will use Gauss-Legendre quadrature which also requires integration over the inter-
val [−1, 1]. Based on these assumptions, the following steps must be carried out in
order to perform numerical integration of the terms in the element matrices:

1. Define the number of integration points and obtain the integration points and
weights. Evaluate the shape functions and their derivatives (defined in terms of
local coordinates) at each integration point, and save the results for later use.
2. Do a loop over all elements and initialize the element matrices MM, KM and
element vector F.
3. Within the element loop, start a loop over all integration points. One must convert
derivatives from the local coordinates to the global coordinates using the inverse
of the Jacobian, by performing an operation such as that in Equation (4.12).
4.3. EXERCISES 23

4. Perform the vector multiplication involving the shape functions or their derivatives
(evaluated at integration points), multiplied by the relevant weight, and multiplied
by the determinant of the Jacobian (to convert integrals from global to local coor-
dinates, see Equation (4.10)), which leads to the matrices MM, KM and F. The
result should be added to the multiplication from proceeding integration points.

5. Once one has exited the loop over integration points, the integration is complete
(i.e., the element matrices have been integrated).

6. The element matrices can then be added to the global element stiffness matrix.
This process is then continued for each element.

In the 1D example discussed here, it might seem like “overkill” to use numerical
integration. However, as you will soon see, utilising quadrature rules to evaluate ele-
ment stiffness matrices and force vectors has immense advantages when (i) using high
order elements (e.g. quadratic), and or (ii) when considering 2D and 3D problems. An
immediate advantage in 2D (and 3D) which comes from using quadrature rules, is that
we can deform the finite element mesh and still easily evaluate the integrals, without
having to modify our code. Therefore it is good to practice using quadrature rules within
the context of this 1D example.

4.3 Exercises
1. Perform the numerical integration of Equation (4.11) with a 3-point quadrature
rule, instead of 2-point rule. How do the results differ?

2. Using the program developed in the last session, write a FE code which solves
the diffusion equation in 1D where the element matrices and vectors are inte-
grated numerically. Check that the results are identical to those obtained when
using analytically computed element matrices/vectors.

3. Read chapter six from the book of Kwon & Bang (see website). Explain which
order quadrature rule should be used if one was to use quadratic elements to
solve the diffusion equation? Modify your code to solve the 1D diffusion equation
with quadratic elements, instead of linear elements. The 1D quadratic shape
functions defined in the local coordinates system are given by
1
N1 (ξ) = ξ (ξ − 1) (4.15)
2
N2 (ξ) = 1 − ξ 2 (4.16)
1
N3 (ξ) = ξ (ξ + 1) . (4.17)
2
Note that each 1D quadratic element is composed of three nodes, instead of two
nodes (as with the linear elements). Compare the results of the solution obtained
using a 3-point GLg quadrature rule and a 2-point GLg quadrature rule.
5
The Diffusion Equation: From 1D to 2D

5.1 Introduction
One of the strengths of the finite element method is the relative ease with which it is
possible to extend your code from one dimension to two (or three) dimensions. To
demonstrate the finite element method in two-dimensions, we once again use the ex-
ample of the diffusion equation. Remember that the diffusion equation is derived by
combining a statement for the conservation of energy

∂T h i q 
∂ ∂ x
ρcp = −∇T q + s = − ∂x ∂y + s, (5.1)
∂t qy

with a general anisotropic constitutive relationship


   " ∂ #
qx kxx kxy ∂x
q= =− ∂
T = −D∇T, (5.2)
qy kyx kyy
∂y

to yield
∂T
ρcp = ∇T (D∇T ) + s. (5.3)
∂t
This equation governs transient heat conduction in two-dimensions with a source term
s(x, y). The dependent variable in this equation is the temperature T , the independent
variables are time t and distance x, and kij (x, y) are the components of the thermal
conductivity tensor, ρ(x, y) is density and cp (x, y) heat capacity. If the thermal conduc-
tivity is isotropic and constant in space, Equation (5.3) in 2D reduces to

∂2T ∂2T
 
∂T
=κ + + s, (5.4)
∂t ∂x2 ∂y 2

where κ = k/(ρcp ) is the thermal diffusivity. For the isotropic case, we have that
 
κ 0
D= . (5.5)
0 κ

Nevertheless, as we will see, it is more natural and general to leave the equation in the
form shown in Equation (5.3). In fact one of the benefits of the finite element method
is that introducing an anisotropic diffusivity tensor does not introduce any additional
complexity to the discretisation procedure.

25
CHAPTER 5. FROM 1D TO 2D 26

5.2 Derivation of the element matrices


As in our one dimensional example, the first step of the finite element method is to
choose an element type. We choose here one of the simplest two-dimensional el-
ements which is the 4-node quadrilateral (see Figure 5.1) element. The four shape
functions Ni (x, y) which go together with this type of element are polynomials of the
form
Ni (x, y) = ai + bi x + ci y + di xy,
where ai , bi , ci , di are coefficients which relate to each node i. This element appears to
be linear, but due to the presence of the cross term xy, the quadrilateral basis functions
in 2D are referred to as bilinear. For the moment we shall simply refer to the shape
functions using the following notation
 
N(x, y) = N1 (x, y) N2 (x, y) N3 (x, y) N4 (x, y) , (5.6)

and we note that the shape functions are expressed in terms of the global coordinate
system (i.e., they are a function of x and y). The second step of the finite element
method involves approximating the continuous variable T in Equation (5.3) in terms of
nodal variables Ti using the shape functions just defined, i.e.,
 
T1
  T2 
T (x, y) ≈ N1 (x, y) N2 (x, y) N3 (x, y) N4 (x, y)  
T3  (5.7)
T4
= NT.

Substituting this approximation for T into Equation (5.3) yields the following equation


ρcp (NT) = ∇T (D∇N)T + s. (5.8)
∂t
Multiplying this equation by the weighting functions (the shape functions) and integrat-
ing over the element volume Ωe leads to
ZZ ZZ ZZ

ρcp NT (NT) dxdy = NT ∇T (D∇N)T dxdy + NT s dxdy. (5.9)
Ωe ∂t Ωe Ωe

Integration by parts over the domain Ωe and denoting the element boundaries lying on
the domain boundary via Γe gives
Z Z   Z Z 
T ∂T T
ρcp N N dxdy + ∇(N) (D∇N) dxdy T
Ωe ∂t e
ZZ Ω I (5.10)
T T T
= N s dxdy + N qb n dS,
Ωe Γe

where qb is an applied flux and n is the outward point normal to the boundary ∂Ω. Recall
that the boundary integral term corresponds to the Neumann boundary condition. This
equation can be simplified to
 
∂T
MM + KM T = F, (5.11)
∂t
5.2. DERIVATION OF THE ELEMENT MATRICES 27

where ZZ
MM = ρcp NT N dxdy, (5.12)
Ωe
ZZ
KM = (∇N)T D∇N dxdy (5.13)
Ωe
and ZZ I
F= NT s dxdy + NT q
bT n dS. (5.14)
Ωe Γe
Note that we leave p, cp , D and s inside the integrals as we have not assumed anything
about how these coefficients vary within the domain, or within the element.
Note that the element matrices and vectors have a virtually identical form to those
derived in Chapter 3 in one dimension. In fact, there are only two significant differences.
First, the integration domain is now defined in two-dimensions. As we shall see, one
can use the same numerical integration as used in the 1D problems. Second, the
shape functions have derivatives in both the x and y directions.
Before continuing it is useful to explicitly define the form (i.e., the dimensions) of
some of the matrices defined above. For example, the shape functions N are defined
as  
N(x, y) = N1 (x, y) N2 (x, y) N3 (x, y) N4 (x, y) , (5.15)
and the shape function derivatives are defined as
 
∂N1 ∂N2 ∂N3 ∂N4
 ∂x ∂x ∂x ∂x 
∇N(x, y) =   ∂N1 ∂N2 ∂N3
. (5.16)
∂N4 
∂y ∂y ∂y ∂y

The conductivity matrix is defined as 1 :


 
kxx kxy
D= . (5.17)
kyx kyy

Thus, one can see that the dimensions of the element matrices MM and KM are 4×4
whereas the element vector F has dimensions 4 × 1.
The next step is to discretise the time derivative in Equation (5.11) using finite
differences. This is carried out in an identical manner to that already performed in 1D
(see script 1) leading to
 n+1
− Tn

T
MM + KM Tn+1 = F, (5.18)
∆t

where Tn+1 is the new temperature at the nodes (i.e. the unknowns) and Tn is the
vector of the old (known) temperatures. Rearranging, one can write this as
 
MM MM n
+ KM Tn+1 = T + F, (5.19)
∆t ∆t
or more compactly as
KL Tn+1 = KR Tn + F, (5.20)
where MM, KM and F have been previously defined.
1
We note that to be physically valid we require that kxx kyy − kxy kyx > 0 and that kxy = kyx .
CHAPTER 5. FROM 1D TO 2D 28

2-D FEM MESH - one degree of freedom per node

local node local coordinate


numbering system
2 3 2 h=1
3

x=-1 x=1
integration
h points
h=-1
1 4 1 4
x
Global node and element numbering
13 14 15 16

7 8 9
9 10 11 12

x=0 Ly=9
4 5 6
5 6 7 8

1 2 3
1 2 3 4
y=0
Lx=9

g_num= 1 2 3 5 6 7 9 10 11 Relationship between


567 9 10 11 13 14 15 elements and global
678 10 11 12 14 15 16 node numbers
234 6 7 8 10 11 12

Global coordinates of nodes


g_coord= 0.0 3.0 6.0 9.0 0.0 3.0 6.0 9.0 0.0 3.0 6.0 9.0 0.0 3.0 6.0 9.0
0.0 0.0 0.0 0.0 3.0 3.0 3.0 3.0 6.0 6.0 6.0 6.0 9.0 9.0 9.0 9.0
Figure 5.1: A two-dimensional finite element mesh with one degree of freedom on each
node.
5.3. INTEGRATION OF THE ELEMENT MATRICES 29

5.3 Integration of the element matrices


The element matrices just derived contain integrals of the shape functions, or deriva-
tives of the shape functions, both expressed in terms of global coordinates (x and y).
To evaluate such matrices two transformations are required. First, since we will provide
shape functions (and their derivatives) in terms of local coordinates, it is necessary to
devise some means of expressing the shape functions (and their derivatives) appear-
ing in the integrals in terms of local coordinates. Second, the area over which the
integration has to be carried out must be expressed in terms of local coordinates (with
an appropriate change in the limits of integration).
As in one dimension, we will use Gauss-Legendre quadrature to approximate the
integrals defining the element stiffness matrices. The formula for Gauss-Legendre
quadrature in two-dimensions is
Z 1 Z 1 X ny
nx X nip
X
f (ξ, η) dξdη ≈ f (ξi , ηj )wi wj = f (ξn , ηn )Wn (5.21)
−1 −1 i=1 j=1 n=1

where nx and ny are number of integration points in each direction, ξi and ηj are the
local spatial coordinates of the integration points, and wi and wj , or Wn are the weights.
The quadrature weights and locations of the integration points are once again obtained
from a table such as that provided in Chapter 4, Table 4.1. Note that the integration in
two dimensions is very similar to the integration in one dimension. One simply sums
over the total number of integration points nip = nx × ny and multiplies by the weights
W n = wi wj .
Derivatives are converted from one coordinate system to another by means of the
chain rule, expressed in matrix form as
∂ ∂x ∂y
      
∂ ∂
 ∂ξ   ∂ξ ∂ξ   ∂x   ∂x 
 =
 ∂   ∂x ∂y   ∂  = J  ∂  , (5.22)
   

∂η ∂η ∂η ∂y ∂y
where J is the Jacobian matrix. The Jacobian matrix can be found by differentiating
the global coordinates with respect to the local coordinates. In practice this requires
one to multiply the coordinates of a particular element with the derivatives of the shape
functions. For example, if we considered the 4 node quadrilateral element we would
have:
∂N1 ∂N2 ∂N3 ∂N4
  
x1 y1
 ∂ξ ∂ξ ∂ξ ∂ξ 
 x2 y2 
 
J=  ∂N1 ∂N2 ∂N3 ∂N4  x3 y3  , (5.23)

∂η ∂η ∂η ∂η x4 y4
where (x1 , y1 ) is the x, y coordinates of node 1, etc. The derivatives of the shape
functions with respect to the global coordinates can thus be found via

   

  = J−1  ∂ξ  ,
 ∂x   
∂  ∂  (5.24)
∂y ∂η
where J−1 is the inverse of the Jacobian matrix. The shape functions themselves do not
have to be converted from the local to the global coordinate system. This is because
CHAPTER 5. FROM 1D TO 2D 30

we have chosen a special type of “isoparametric” element (which essentially means


that the shape functions defining the geometry are the same as those interpolating the
unknown function).
Transformation of integration from the global to local coordinate system is per-
formed using the determinant of the Jacobian, det(J), according to the following re-
lation ZZ Z Z 1 1
f (x, y) dxdy = f (ξ, η) det(J(ξ, η)) dξdη. (5.25)
−1 −1

We note that in contrast to the one dimensional example, the Jacobian J is in general
not a constant. Only under special conditions is J a constant. Such conditions for
bilinear basis functions include when the elements have edges which are parallel to
the x and y axis, or the elements define parallelograms. Combining this result with
Equation (5.21) yields the final integration formula
ZZ nip
X
f (x, y) dxdy ≈ f (ξi , ηi ) det(J(ξi , ηi ))Wi . (5.26)
i=1

Again we emphasize that det(J) should be evaluated at the quadrature point.


Finally, to complete the definition of the element stiffness matrices, we provide the
definition for the shape functions associated with a bilinear, 2D quadrilateral element
such as is shown in Figure 5.1. In local coordinates, they are defined via

1
N1 (ξ, η) = (1 − ξ) (1 − η) (5.27)
4
1
N2 (ξ, η) = (1 − ξ) (1 + η) (5.28)
4
1
N3 (ξ, η) = (1 + ξ) (1 + η) (5.29)
4
1
N4 (ξ, η) = (1 + ξ) (1 − η) , (5.30)
4
and their derivatives with respect to ξ and η are (computed by hand, or with MAPLE);

∂N1 (ξ, η) 1 ∂N1 (ξ, η) 1


= − (1 − η) , = − (1 − ξ)
∂ξ 4 ∂η 4
∂N2 (ξ, η) 1 ∂N2 (ξ, η) 1
= − (1 + η) , = (1 − ξ)
∂ξ 4 ∂η 4
(5.31)
∂N3 (ξ, η) 1 ∂N3 (ξ, η) 1
= (1 + η) , = (1 + ξ)
∂ξ 4 ∂η 4
∂N4 (ξ, η) 1 ∂N4 (ξ, η) 1
= (1 − η) , = − (1 + ξ) .
∂ξ 4 ∂η 4

In summary, the following steps must be carried out to perform integration of the
element matrices:

1. Define the number of integration points (nip) and obtain and save the integration
points and weights.
5.4. ASSEMBLING THE GLOBAL STIFFNESS MATRIX 31

2. Perform a loop over all elements and initialize the element matrices MM and
KM.

3. Within the element loop, do a loop over each integration point. Evaluate the
shape functions and their derivatives at the relevant integration point.

4. Calculate the Jacobian matrix by performing the operation in Equation (5.23).

5. Convert the derivatives from the local coordinates to the global coordinates by
performing the operation in Equation (5.24).

6. Calculate the determinant of the Jacobian.

7. Perform the vector multiplication involving the shape functions or their derivatives
(evaluated at integration points), multiplied by the relevant weights, which leads
to the matrices MM and KM. The result should be added to the multiplication
from proceeding integration points.

8. Once one has exited the loop over integration points, the integration is complete
(i.e., the element matrices have been integrated).

9. Form the matrices KL and KR defined in Equation (5.20)

10. The element matrices can then be added to the global element stiffness matrix.
This process is then continued for each element.

5.4 Assembling the global stiffness matrix


The final step that needs to be performed is the node-by-node summing-up of the
element matrices to form the global stiffness matrices. Once again, this is carried out
in a manner very similar to that already done in one dimension. The only difference
is that now one has to make more decisions in how the unknowns in the mesh are
numbered globally. An example of a small 2D finite element mesh is shown in Figure
5.1. Note that each node represents one unknown (i.e. temperature) and is given a
global index (and a global coordinate).
The global numbering of the equations used in your finite element is not unique.
There are no strict rules as to how one should order the global indices. On structured
grids with quadrilateral elements (like in our example) the traditional rule of thumb was
to begin numbering in the direction with the fewest nodes in an effort to minimise the
bandwidth of the global matrix and thus yield more efficient solves. In practice, when
using modern factorisation techniques such as those employed in MATLAB, this rule
of thumb is no longer applicable. Furthermore it does not generalise to unstructured
meshes. Here we advocate using the numbering scheme which is most convenient to
implement. The relationship between the elements and global node numbers should
be specified early in the program and saved in a matrix (for example in g num. This
matrix is then used to “steer” the entries within each element stiffness matrix into the
correct position within the global matrix.
To illustrate this process with an example, we return to the 2D diffusion equation
and consider assembling the global stiffness matrix which corresponds to a very small
CHAPTER 5. FROM 1D TO 2D 32

2-D FEM MESH - one degree of freedom per node

local node
numbering 1 2 3
2 3

1 2
4 5 6

1 4
3
7 8

Relationship between elements


and global node numbers
g_num= 4 5 7
124
235
568
Figure 5.2: A small three element finite element mesh. In the text the diffusion equation
is discretised for this mesh. The corresponding system of global equations are shown
in Equation (5.33).

mesh which is illustrated in Figure 5.2. Referring to the element matrices defined in
Equation (5.20), we introduce the following notation
 e
Le12 Le13 Le14

L11
L e Le22 Le23 Le24 
Le = 
 21 ,
Le31 Le32 Le33 Le34 
Le41 Le42 Le43 Le44

where the superscript e is introduced to represent the element number. Thus, for ex-
ample, the term L311 is the term L11 from element 3. Similar notation is assumed for
RG (refer to Equation (5.20)). The matrix g num for the mesh in Figure 5.2 is given by:
 
4 5 7
1 2 4
g num = 
2
. (5.32)
3 5
5 6 8
5.4. ASSEMBLING THE GLOBAL STIFFNESS MATRIX 33

Note that there are three columns, one for each element, while there are four rows,
one for each node. As already stated, g num is used to place the entries from element
matrices in the correct position within the global matrix. As an example, consider the
term L113 . Since the term is from element 1, we must look at the first column of g num
where we see that the local nodes 1 and 3 (i.e., the first and third row) map to the global
indices 4 and 2 respectively. This indicates that the entry L113 will be inserted (summed)
within the global matrix LG at the position (4, 2). Repeating this process for all terms
leads to the global equations which will be denoted via
LG Tn+1 = RG Tn + FG , (5.33)
where
 k
T1
T2 
 
T3 
 
k
T4 
T =
T5  ,
 (5.34)
 
T6 
 
T7 
T8
 1
L123 0 L121 L124 0 0 0

L22
L32 L33 + L222
1 1 2
L23 1
L31 L34 + L221
1 L224 0 0 
L232 L233 L231 L234
 
 0 0 0 0 
 1
L113 1 3 L14 + L323
1 L321 L324 

L12 0 L11 + L22 0
LG = 
L1 L1 + L2
 (5.35)
 42 43 12 L213 L141 + L332 L144 + L211 + L333 L214 L331 L334 

 0 L2 L243 0 L241 L244 0 0 
 42 
 0 0 0 3
L12 L313 0 L311 L314 
0 0 0 L342 L343 0 L341 L344
and
 1 1 1 1
0 0 0 0

R22 R23 R21 R24
1 1 2
R32 R33 + R22 2
R23 1
R31 1 2
R34 + R21 2
R24 0 0 
2 2 2 2
 
 0 R32 R33 0 R31 R34 0 0 
 1 1 1 3 1 3 3 3 

R12 R13 0 R11 + R22 R14 + R23 0 R21 R24
RG = 
R1 R1 + R2 2 1 3 1 2 3 2 3 3 .

 42 43 12 R13 R41 + R32 R44 + R11 + R33 R14 R31 R34 
 0 2
R42 2
R43 0 2
R41 2
R44 0 0 
 
 0 0 0 3
R12 3
R13 0 3
R11 R3 14
0 0 0 3
R42 3
R43 0 3
R41 3
R44
(5.36)
The process of summing the element matrix into the global matrix is easily achieved
in a computer program. For example, once the matrix Le for a certain element e has
been integrated, it is added to the global matrix using a command such as
>> LG ( g_num ( : , iel ) , g_num ( : , iel ) ) = ...
LG ( g_num ( : , iel ) , g_num ( : , iel ) ) + L ;

where iel is the current element index. Now that the global equations have been
constructed all that remains is to apply boundary conditions and solve the system of
equations. This is carried out in the same manner as the one dimensional problem
considered earlier.
CHAPTER 5. FROM 1D TO 2D 34

5.5 Exercises
1. Write a 2D FE code that solves the diffusion equation using bilinear, quadrilateral
elements. Assume a constant, isotropic conductivity tensor. Apply constant tem-
perature at the top and bottom boundaries, and zero flux at the side boundaries
(i.e. set no boundary condition here).

2. Confirm that the code works when the grid is deformed (if not, it is likely that you
made a mistake defining the Jacobian or your global derivatives). Define a mesh
which has significant topography on the upper surface. Compute the temperature
distribution within this domain.

3. Modify the code to take into account (i) a spatially variable, anisotropic conduc-
tivity tensor, (ii) variable grid spacing and (iii) a spatially variable heat source.
6
The Weak Form

6.1 A prototype PDE


Consider the Poisson equation
∇2 u + f = 0. (6.1)
In order to obtain a unique solution of Equation (6.1) in some domain Ω, we require
the prescription of the boundary conditions. We will denote the boundary of Ω via ∂Ω
and the interior of the domain as Ω̄ = Ω \ ∂Ω. Dirichlet boundary conditions specify the
value of u along some region of the boundary which we denote by ∂ΩD . A Neumann
boundary specifies the value of ∇u along some boundary segment ∂ΩN . At every point
in space x along the entire boundary of Ω, a boundary condition must be specified.
That is, ∂Ω = ∂ΩD ∪ ∂ΩN and these segments do not overlap, i.e. ∂ΩD ∩ ∂ΩN = ∅.
Formally we can state this problem as:
Find u such that
∇2 u + f = 0 in Ω̄ (6.2)
subject to
u = gD on ∂ΩD and ∇u · n = gN on ∂ΩN , (6.3)
where n is the outward pointing normal to the boundary ∂Ω.

6.2 The weak form


To construct the weak form we introduce a test function v and we will require that
Z
∇2 u + f v dV = 0.

(6.4)

Using Green’s theorem, the above can be equivalently stated as


Z Z I
∂u
∇u · ∇v dV = vf dV + v dS. (6.5)
Ω Ω ∂Ω ∂n

We now discuss some details related to the weak form defined in Equation (6.5).
From Equation (6.4) it is apparent that any solution u which satisfies Equation (6.1) sat-
isfies Equation (6.4) for any choice of v. To consider whether the converse is true, we
first observe that the required smoothness of u has been reduced, that is the derivative
operating on u has changed from second order to first order. Thus Equation (6.5) may
have a solution say u0 , but u0 may not be smooth enough to also be a solution of Equa-
tion (6.1). For this reason, solutions of Equation (6.5) are referred to as weak solutions.

35
CHAPTER 6. THE WEAK FORM 36

Given their weak nature, many possible weak solutions will exist which satisfy Equation
(6.5). We will discuss the class of functions from which weak solutions live within in the
following paragraphs.
As of yet we have not discussed what types of functions are valid choices for u
and v. One restriction on selecting v comes from the observation that the weak form
∂u
in Equation (6.5) contains a flux term ∂n = ∇u · n, defined over the entire bound-
ary. Recalling the problem statement required to obtain a solution to the PDE (see
Equation (6.3)), we observe that the flux term in the weak form exactly matches the
Neumann boundary condition, except that that Neumann condition is only enforced
over the boundary segment ∂ΩN and not over all ∂Ω. Therefore, to enforce that the
weak form is consistent with the boundary conditions of the PDE we require that v = 0
along the Dirichlet boundary ∂ΩD . Thus, for solutions of the PDE which only possess
Dirichlet boundaries, i.e. ΩN = ∅, the surface integral in the weak form vanishes as v is
constructed to be identically zero along this boundary region. The Dirichlet boundary
also provides a restriction on the choice of u, name that any function used to define the
weak solution must satisfy u = gD on ∂ΩD . Using this restrictions on u, v, we can state
the weak form problem as:
Find u such that
Z Z I
∇u · ∇v dV = vf dV + v gN dS in Ω̄. (6.6)
Ω Ω ∂ΩN

Another property to consider in choosing a valid v, and in defining the class of


permissible functions within which weak solutions to Equation (6.6) live within, come
from the consideration of function smoothness. To define smoothness, we use an L2
measure defined as Z  1/2
2
||u||2 := u dV . (6.7)

Any function u which satisfies
||u||2 < ∞
is said to live within the space (i.e. the set of all functions) of L2 functions. Consider-
ing the left hand side of Equation (6.6) we observed that the equation is well-defined
(doesn’t blow up) if all the derivatives of u and v are in L2 . Accordingly, if this true and
both f and gN also live within L2 , then the right hand side of Equation (6.6) will also be
well bounded.

6.3 The discrete weak form


We will assume that the problem domain Ω, has been partitioned into M e elements
and N n nodes. One each node, i we will define a test function v(x) = φ̂i (x). Inserting
this expression into Equation (6.6) yields
Nn Z
X Nn Z
X I
∇u · ∇φ̂i dV = φ̂i f dV + φ̂i gN dS. (6.8)
i Ω i Ω ∂ΩN

The discrete solution space is then defined via


Nn
X
u(x) = φ1 (x)u1 + φ2 (x)u2 + · · · = φi (x)ui ,
i=1
6.4. FURTHER READING 37

where each ui represents the approximate to u at the node i. Upon substitution we


have
XNn X
Nn Z Nn Z
X I
∇φ̂i · ∇φj uj dV = φ̂i f dV + φ̂i gN dS. (6.9)
i j Ω i Ω ∂ΩN

By making the choice that the trial functions should be identical to the discrete solution
space, that is choosing φ̂i = φi , we obtain the Galerkin approximation,
Nn X
X Nn Z Nn Z
X I
∇φi · ∇φj uj dV = φi f dV + φi gN dS. (6.10)
i j Ω i Ω ∂ΩN

The equation above defines a system of linear equation which can be more compactly
expressed via a matrix-vector form.

6.4 Further reading


• For a discussion about the weak form, see sections 1.1 to 1.3 of Elman, Silvester
& Wathan.

• For a discussion about evaluating the discrete weak form, see sections 1.4 of
Elman, Silvester & Wathan.

• For a discussion on the same concepts with, read and work through pages 1-13
of Hughes.
7
Elasticity in Two Dimensions

7.1 Introduction
Up to now we have only considered PDE’s which involve scalar unknowns (i.e. tem-
perature). When discretised, such problems possess one degree of freedom (i.e., one
unknown) per node. However, many PDE’s such as those describing the behaviour
of elastic solids or viscous fluids, have vector unknowns (e.g., the displacement or ve-
locity in each direction). When discretised these PDE’s translate to FE problems with
multiple degrees of freedom per node. The purpose of this script is to introduce you
the finite element programming of problems having two-degrees of freedom per node.
This approach is illustrated by solving a solid mechanics problem.

7.2 Governing equations


The equations governing the two-dimensional displacement of a solid are derived
by combining the conservation of momentum and a constitutive relationship relating
stresses and strain. The conservation of momentum defined in a domain Ω with bound-
ary ∂Ω is given by:
∂σxx ∂σxy
+ =0
∂x ∂y
∂σxy ∂σyy
+ = 0, (7.1)
∂x ∂y
where σxx , σyy and σxy are stresses (gravity is ignored). In case of an elastic medium,
the constitutive relation is
    
σxx 1−ν ν 0 xx
E
σyy  =  ν 1−ν 0   yy  , (7.2)
(1 + ν)(1 − 2ν) 1
σxy 0 0 2 (1 − 2ν) γ xy

where E is the Youngs modulus, ν the Poisson’s ratio and xx , yy , γxy are strains. In
this case we assumed a linear elastic material subjected to plane strain conditions. In
the more general case, the constitutive relationship becomes more complex (one can,
for example, incorporate anisotropy by changing the constitutive matrix in Equation
(7.2)). The relationship between strain and displacement is given by
∂ 
 
∂x 0  
xx
 ux ,
∂ 

 yy  =  0 ∂y (7.3)
  uy
γxy ∂ ∂
∂y ∂x

39
CHAPTER 7. 2D ELASTICITY 40

where ux , uy are displacements in the x and y direction, respectively. Using matrix


notation, these three relations can be written as

BT σ̂ = 0,
σ̂ = Dˆ, (7.4)
ˆ = Be,

where

 
  ∂x 0
ux  ∂ 
e= , 0
B= ∂y  , (7.5)

uy
∂ ∂
∂y ∂x
 
1−ν ν 0
E
D=  ν 1−ν 0 , (7.6)
(1 + ν)(1 − 2ν) 1
0 0 2 (1 − 2ν)

and    
xx σxx
ˆ =  yy  , σ̂ = σyy  .
 (7.7)
γxy σxy
In the displacement formulation, such as the one presented here, one eliminates σ̂ and
ˆ in the following steps:

BT σ̂ = 0
BT Dˆ = 0 (7.8)
BT DBe = 0

This last relation is a pair or partial differential equations for the two unknowns, ux and
uy (i.e., the two components of the vector e).

7.3 FE discretisation
To proceed with a finite element discretisation one introduces an element type and
set of shape functions. We use 4-node quadrilaterals and the corresponding bilinear
shape functions. Thus, ux and uy within a single element are approximated as
 
ux(1)
  ux(2) 
ux (x, y) ≈ N1 (x, y) N2 (x, y) N3 (x, y) N4 (x, y) ux(3)  = Nux
 (7.9)
ux(4)

and
 
uy(1)
  uy(2) 
uy (x, y) ≈ N1 (x, y) N2 (x, y) N3 (x, y) N4 (x, y) uy(3)  = Nuy .
 (7.10)
uy(4)
7.4. MATRIX ASSEMBLY 41

Substituting these approximations into Equation (7.8), weighting each equation with
the shape functions, integrating over the element volume Ωe and integrating by parts
where necessary yields the following set of discrete element equations:

KM r = F, (7.11)

where Z
KM = B̂T DB̂ dV, (7.12)
Ωe
 
∂N1 ∂N2 ∂N3 ∂N4
 ∂x 0 0 0 0 
 ∂x ∂x ∂x 
 ∂N1 ∂N2 ∂N3 ∂N4 
B̂ =  0 0 0 0 (7.13)
 
 ∂y ∂y ∂y ∂y 

 ∂N ∂N1 ∂N2 ∂N2 ∂N3 ∂N3 ∂N4 ∂N4 
 1 
∂y ∂x ∂y ∂x ∂y ∂x ∂y ∂x

and
 I   I 
T
− N (σxx nx + σxy ny ) dS − NT tx dS
 ∂Ωe ∩∂Ω
 =  I∂Ωe ∩∂Ω
  
F=
 I
, (7.14)
T T
  
− N (σyx nx + σyy ny ) dS − N ty dS
∂Ωe ∩∂Ω ∂Ωe ∩∂Ω

where ti = σij nj is an applied traction along the piece of the element edge ∂Ωe con-
tained on the boundary of the domain ∂Ω and the element displacement vector r is
given by
ux(1)
 
uy(1) 
 
ux(2) 
 
uy(2) 
r=  . (7.15)
ux(3) 

u 
 y(3) 
u 
x(4)
uy(4)
The terms within the element matrix KM can be integrated via Gauss-Legendre
quadrature rules using the same procedure as was utilised for the diffusion equation.

7.4 Matrix assembly


In the diffusion problem we considered previously, each node represented only one un-
known and it was reasonably straightforward to “steer” the element matrices to the cor-
rect location in the global matrix. Now that we have two degrees of freedom per node
we have to perform some additional steps to define how we assemble the global ma-
trix. Namely, we will require the specification of three matrices, denoted g num, nf and
g g. We have already encountered g num; this matrix defines the relationship between
global element numbers and global node numbers. The matrix nf is used to specify
the relationship between the global node numbers and the global equation numbers.
Lastly, the matrix g g defines the relationship between the global element numbers and
the global equation numbers. Examples of these matrices for a small mesh are shown
CHAPTER 7. 2D ELASTICITY 42

2-D FEM MESH - two degrees of freedom per node

Global node and element numbering


13 14 15 16
local node
(25,26) (27,28) (29,30) (31,32) numbering
2 3

7 8 9
9 10 11 12
(17,18) (19,20) (21,22) (23,24) 1 4
x=0 Ly=9 local coordinate
4 5 6
system
5 6 7 8 2 h=1
3

(9,10) (11,12) (13,14) (15,16) x=-1 x=1

1 2 3 h
h=-1
1 4
1 2 3 4
x
(1,2) (3,4) (5,6) (7,8)
y=0
Lx=9

g_num= 1 2 3 5 6 7 9 10 11 Relationship between


567 9 10 11 13 14 15 elements and global
678 10 11 12 14 15 16 node numbers
234 6 7 8 10 11 12

Relationship between
nf = 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 nodes and equation
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 numbers

g_g= 1 3 5 9 11 13 17 19 21 Relationship between elements


2 4 6 10 12 14 18 20 22 and equation numbers
9 11 13 17 19 21 25 27 29
10 12 14 18 20 22 26 28 30
11 13 15 19 21 23 27 29 31
12 14 16 20 22 24 28 30 32
3 5 7 11 13 15 19 21 23
4 6 8 12 14 16 20 22 24

Figure 7.1: A small finite element mesh with two degrees of freedom per node. Global
space numbering for nodes and displacements is shown in upper left image. Upper
right panel shows the local space numbering of the nodes and the reference element.
Lower panels indicate element-node map (g num), the node-equation map (nf) and the
element-equation map (g g).

in Figure 7.1. Once these matrices are constructed, then the assembly of the global
matrix is straightforward. Within the main element loop, g num is used to retrieve the
nodes within a particular element, which is necessary for example to obtain the global
7.5. EXERCISES 43

node coordinates of each element (e.g., coord = g coord(:,g num(:,iel))’). The


matrix nf is used if one wishes to refer to a specific degree of freedom. For example,
say our solution is stored in the array displ. Then displ(nf(1, :)) can be used
to refer to the first degree of freedom (i.e, ux ) for each node in the mesh whereas
displ(nf(2, :)) can be used to refer to the second degree of freedom (i.e, uy ). Fi-
nally, the matrix g g is used to “steer” the integrated element matrix KM to the correct
position in the global matrix LG , e.g.
>> LG ( g_g (: , iel ) , g_g (: , iel ) ) = ...
LG ( g_g (: , iel ) , g_g (: , iel ) ) + KM ;

Now that the global matrix has been assembled, one can impose any Dirichlet bound-
ary conditions and solve the system of equations.

7.5 Exercises
1. Write a 2D, plane strain, elastic code to solve the equations above. Test it with
a pure-shear setup, in which you prescribe ux at the left and right boundaries
and set uy = 0 at the lower boundary. Leave all other boundaries unconstrained,
implying the traction ti = 0. If you choose ν = 0.49, the material behaves almost
incompressibly and you should see a pure shear displacement field.

2. Model the deformation of a thin elastic beam under the influence of gravity. To do
this, you will need to add gravity to the force balance equations (which will result
in right-hand side terms in your equations). Create a setup in which you keep the
left boundary of the domain fixed (ux = uy = 0) and all other boundaries free (i.e.
enforce zero normal stress). Introduce time-evolution into the model by updating
the global coordinates with gcoord = gcoord + displacement * dt, where dt
is the time step.

3. Examine the stress field obtained from your FE solution. Plot the components of
the stress at each integration plot. Plot σxx at the nodal points of your deformed
mesh.

4. Repeat the exercises above using 2D biquadratic shape functions (instead of


bilinear shape functions). You will need to use at least 3 × 3 integration points
with the biquadratic shape functions. Once this element type is added to your
code and you have verified the correctness of the implementation (e.g you obtain
very similar looking results as when using bilinear elements), you will be well
prepared to tackle the Stokes equations (next exercise).
8
Stokes Flow in Two Dimensions

8.1 Governing equations


Many problems in Earth science involve the flow of fluids. One of the most important
examples of which is the slow viscous deformation of rock. The purpose of this script
is to present an introduction to the equations which govern the motion of very viscous
fluid and to study how these equations can be solved using the finite element method.
The mechanics of a fluid is governed by four sets of equations, conservation of
mass (continuity), conservation of momentum, a relationship between strain rate and
velocity and a constitutive relationship. The force balance in two dimensions is gov-
erned by the equations

∂σxx ∂σxy
+ =0
∂x ∂y
∂σxy ∂σyy
+ − ρg = 0, (8.1)
∂x ∂y

where σij is the stress tensor, ρ is density and g is gravitational acceleration (note
inertial terms are ignored). We assume a coordinate system in which the direction of
gravity acts in the negative y direction The equation for the conservation of mass of an
incompressible fluid is
∂u ∂v
+ = 0, (8.2)
∂x ∂y

where u and v are velocities in x and y direction respectively. The constitutive relation-
ship for an incompressible, Newtonian viscous material is
      
σxx 1 2η 0 0 ˙xx
σyy  = −p 1 +  0 2η 0  ˙yy  , (8.3)
σxy 0 0 0 2η ˙xy

where η is the viscosity, ˙ij are strain rates and p is the pressure. Finally, the kinematic
relationship between strain rates and velocities is defined as

∂u
 
 
˙xx ∂x

˙yy  =  ∂v 
  ∂y  .
 (8.4)
˙xy 1 ∂u
+ ∂v
2 ∂y ∂x

45
CHAPTER 8. 2D STOKES FLOW 46

When written out in full, these equations in 2D have the form


    
∂p ∂ ∂u ∂ ∂u ∂v
− + 2η + η + = 0 (8.5)
∂x ∂x ∂x ∂y ∂y ∂x
    
∂p ∂ ∂v ∂ ∂u ∂v
− + 2η + η + = ρg (8.6)
∂y ∂y ∂y ∂x ∂y ∂x
∂u ∂v
+ = 0. (8.7)
∂x ∂y
This set of coupled partial differential equations are commonly known as the Stokes
equations. Using matrix notation, Equations (8.1), (8.2), (8.3) & (8.4) can be written
compactly as
BT σ̂ = f (8.8)
T
m Bu = 0 (8.9)
σ̂ = −mp + Dė (8.10)
ė = Bu, (8.11)
where     

u 0 f
u= , f= = x , (8.12)
v ρg fy
∂ 
  0
1 ∂x
∂ 
0 ∂y

m = 1 , B=
,
 (8.13)
0 ∂ ∂
∂y ∂x
 
2η 0 0
D =  0 2η 0 , (8.14)
0 0 η
and    
˙xx σxx
ė =  ˙yy  , σ̂ = σyy  . (8.15)
γ̇xy σxy
Note in the above equation that γ̇xy = 2˙xy and that we have generalised the definition
of the force to allow for non-zero contributions to the x-momentum equation. The
reader should verify that Equations (8.8) - (8.9) are consistent with Equations (8.5),
(8.6) and (8.7). In the Stokes formulation considered here, one eliminates σ̂ and ė in
the following manner
BT σ̂ = f (8.16)
T T
B Dė − B (mp) = f (8.17)
T T
B DBu − B (mp) = f , (8.18)
to obtain an expression only in terms of the velocity u and pressure p. Thus, the
governing equations are
BT DBu − BT (mp) = f (8.19)
and
mT Bu = 0, (8.20)
which is a set of three equations (remember that Equation (8.19) consists of two equa-
tions), for the three unknowns u, v and p.
8.2. FE DISCRETISATION 47

local node numbering


4 7 3
Pressure nodes
2 3
velocity nodes
8 9 6

1 5 2

1 4
local degrees of freedom
(order: u1,v1,u2,v2,...,p1,p2,p3,p4)

7,8,20 13,14 5,6,21

15,16 17,18 11,12

1,2,19 9,10 3,4,22

Figure 8.1: A single finite element illustrating the Q2 -Q1 velocity-pressure formulation
used to solve Stokes flow. A biquadratic shape function (Q2 ) is used for velocity and
a bilinear shape function (Q1 ) for pressure. The nodes associated with velocity (solid
circles) possess two degrees of freedom (for u, v) and the nodes associated with the
pressure (open circles) possess one degree of freedom.

8.2 FE discretisation

One simple and (barely) adequate method for discretising Equations (8.5), (8.6) and
(8.7) with quadrilateral elements is to use the 9 node biquadratic shape functions (Q2 )
for velocities and the 4 node bilinear shape function (Q1 ) for the pressure. This config-
uration is depicted in Figure 8.1. Note that the same quadrilateral geometry is used to
define the approximation for both velocity and pressure. We also note that the corners
of the velocity element coincide with the corners of the pressure element. The two
velocities are approximated as

u1
 
u2 
 
u3 
 
 u4 
 
e

u(x, y) ≈ N1 N2 N3 N4 N5 N6 N7 N8 N9 u5  = Nu ,
 (8.21)
u6 
 
u7 
 
u8 
u9
CHAPTER 8. 2D STOKES FLOW 48

v1
 
v2 
 
v3 
 
 v4 
 
e

v(x, y) ≈ N1 N2 N3 N4 N5 N6 N7 N8 N9 v5  = Nv ,
 (8.22)
v6 
 
v7 
 
v8 
v9
or
N 0 ue
    
u
≈ = N̂Ue . (8.23)
v 0 N ve
The pressure is approximated via
 
p1
  p2  e
p(x, y) ≈ N̄1 N̄2 N̄3 N̄4 p3  = Np p .
 (8.24)
p4

Note in the above that we denote the basis functions for the velocity via Ni and those
for pressure via N̄i .
First we consider the weak form of the momentum equations. To simplify the deriva-
tion, we multiply the stress gradient (in Voigt notation) by the velocity basis functions
for u and v and integrate over the element volume Ωe . In 2D this yields
 
Z  T " ∂ 0 ∂ # σxx Z  T  
N 0 ∂x ∂y N 0 fx
T ∂ ∂
 σyy dV =
 T dV. (8.25)
Ωe 0 N 0 ∂y ∂x Ωe 0 N fy
σxy

Then applying integration by parts yields


 T  
∂N ∂NT σxx
Z 0
 ∂x ∂y
σyy  dV =
∂NT ∂NT
 
Ωe 0 ∂y ∂x σxy (8.26)
Z  T   I  T 
N 0 fx N (σxx nx + σxy ny )
− dV + dS.
Ωe 0 NT fy T
∂Ωe N (σyx nx + σyy ny )

Denoting the Neumann boundary conditions as ti = σij nj and the boundary segment
of each element as Γe , we can simplify the weak form above to
 T  
∂N ∂NT σxx
Z 0 Z  T 
N fx
I  T 
N tx
 ∂x T
∂y
T
  σyy dV = −
 T dV + T dS. (8.27)
∂N ∂N
Ωe 0 ∂y ∂x σxy Ωe N fy Γe N ty

To complete the derivation, we introduce the discrete strain rate operator

B̂ = BN̂, (8.28)

and then insert the definition of the discrete stress

σ̂ = DB̂Ue − mNp pe ,
8.3. EXERCISES 49

to give
 
∂NT ∂NT
Z
∂x 0 ∂y
 
 DB̂Ue − mNp pe dV =
∂NT ∂NT

Ωe 0 ∂y ∂x (8.29)
 T 
Z I  T 
N fx N tx
− T dV + T dS,
Ωe N fy Γe N ty

or
Ke Ue + Ge pe = f e , (8.30)
in which Z
e
K = B̂T DB̂ dV, (8.31)
Ωe
Z
e
G =− B̂T mNp dV (8.32)
Ωe
and
NT fx
Z   I  T 
e N tx
f =− dV + dS. (8.33)
Ωe NT fy T
Γe N ty

In comparison, the weak form of the continuity equation is much simpler to derive.
All that is required is to multiply the continuity equation by NTp and integrate over the
element volume to yield Z
− NTp mT B̂Ue dV = 0, (8.34)

or
(Ge )T Ue = 0. (8.35)
Note that we multiplied the weak continuity equation by minus one simply to make
formulation symmetric (The reader should verify the system is symmetric). This doesn’t
change the system of equations as the right side of the continuity equations is the
zero vector. The complete discretised Stokes problem (on the element level) can be
compactly expressed via

Ke Ge Ue
     e
f
= . (8.36)
(Ge )T 0 pe 0

One should note that the element matrices all have different dimensions. Using the
9-noded biquadratic elements for velocity, there are 18 velocity unknowns per element.
The bilinear pressure element results in 4 pressure degrees of freedom per element.
Consequently, Ke has dimensions 18 × 18 and Ge has dimensions 18 × 4. Care should
be taken in carrying out the matrix-vector products as the discrete velocity and pressure
vectors are of different length. All the element matrices defined above can be integrated
and assembled in the standard finite element fashion.

8.3 Exercises
1. Write a FE code to solve the Stokes equations for the unknowns u, v and p using
boundary conditions and the Rayleigh-Taylor setup shown in Figure 8.2. Use
biquadratic shape functions for velocity and continuous bilinear shape functions
CHAPTER 8. 2D STOKES FLOW 50

for pressure. Free slip conditions are implemented by only setting the boundary-
normal velocities to zero (so e.g., u = 0 on the left and right boundary). Model
time evolution by advecting the grid, and also study what happens if the upper
boundary is a free surface, σ ·n = 0. To introduce this boundary condition, simply
do not set any Dirichlet boundary conditions on the upper boundary.

2. Plot the second invariant of the strain rate tensor (˙II = 12 (˙2xx + ˙2yy + 22xy )0.5 ) for
the previous model.

3. Create a code to simulate viscous detachment folding subjected to a background


pure shear deformation. Ask the instructors for hints.

Figure 8.2: Rayleigh Taylor setup in which a fluid of higher density is superposed on
top of a fluid with lower density and the interface between the two fluids is perturbed
in a sinusoidal manner. Employ λ = H = 1, h = 0.5, A0 = 10−2 , g = 1, µ1 = 1, µ2 =
1, ρ1 = 1, ρ2 = 0.
9
Code Verification

9.1 Introduction
The purpose of this session is to learn how to determine if your implementation of the
finite element method (i.e. your MATLAB code) is “working correctly”. By “working cor-
rectly” we mean that your FE code is solving the partial differential equations (PDE’s)
accurately, and most importantly that the numerical errors associated with the discrete
solution of the PDE decrease at the expected rate when the grid is refined.

9.2 Taylor series approximations


Suppose we had a smooth, infinitely differentiable function f (x), then we can locally
approximate the function via an infinite Taylor series expansion

∂f h2 ∂ 2 f h3 ∂ 3 f
f (x + h) = f (x) + h + + + ...
∂x 2 ∂x2 6 ∂x3
N (9.1)
X hn ∂ n f
= ,
n! ∂xn
i=0

where h is a small perturbation. The more terms N we include, the more accurate the
expansion is. For example, consider the truncated Taylor series expansion

∂f h2 ∂ 2 f h3 ∂ 3 f
f (x + h) = f (x) + h + + , (9.2)
∂x 2 ∂x2 6 ∂x3

where all terms with powers ≥ 4 have been neglected. We will use the notation O(hk ) to
indicate the order of accuracy of discrete solutions. We can express the approximation
error in Equation (9.2) which results from dropping the terms with order hα , α ≥ 4 via

∂f h2 ∂ 2 f h3 ∂ 3 f
f (x + h) = f (x) + h + + + O(h4 ), (9.3)
∂x 2 ∂x2 6 ∂x3
which indicates that the truncated Taylor series is fourth order accurate.

9.3 Errors and norms


Consider the PDE
∇2 u = f, (9.4)

51
CHAPTER 9. CODE VERIFICATION 52

where we denote by u, the exact solution. If we apply the FE method to the above we
obtain the following matrix problem

Lh uh = F h . (9.5)

Here Lh is the discrete Laplacian and F h is the discrete right hand side of the PDE. We
denote by uh the solution of the discrete problem. Note that in general, uh will only ever
by an approximate solution to the PDE. Accordingly, we can define the discretisation
error e, as
e = u − uh . (9.6)
The superscript h notation is frequently used to indicate that the discrete solution is a
function of the grid resolution h. In the above, e is function of space. In practice, it is
more convenient to quantify the error via a single number, i.e. via some measure of
the global discretisation error. Possible choices for global error measure include the L1
measure Z
E(Ω)L1 = u − uh dV (9.7)

and the L2 measure sZ
2
E(Ω)L2 = |u − uh | dV . (9.8)

Sources of errors
We consider that there are two main sources of error in the FE implementations dis-
cussed in this course. These can be classified as discretisation errors or numerical
errors. Errors associated with discretisation related to the size of the element used
h, and the order of the polynomial used p. For example, the first exercise used ten
(h = 10/10), 1D linear elements (p = 1). Numerical errors relate to round-off (i.e.
due to finite precision arithmetic) and the accuracy of the solver used to obtain uh in
Equation (9.5). In all the examples we considered in this course, the solver employed
by MATLAB is an exact LU factorisation - which for the purpose of this class we will
regard as having zero numerical error.

Expected errors
The FE method benefits from having a very solid and rigorous mathematical back-
ground. This mathematical foundation provides many results regarding the errors we
can expect from finite element calculations. We will not derive the errors estimates for
the discretisation errors here, but rather state them and leave the interested reader to
discover the world of finite element analysis in their own time.
In the following error estimates the coefficients Ci are constants which are indepen-
dent of the grid resolution h, and the polynomial order of the basis function p. Note that
a linear element implies p = 1, quadratic implies p = 2, cubic implies p = 3, etc. Each
error estimate is associated with a different constant Ci . In general, the constants Ci
cannot be derived analytically as they are problem dependent (e.g. there depend on
the domain geometry, boundary conditions, coefficients in the PDE), thus if desired,
they must be computed from numerical experiments. In practical computations we are
usually less interested in the specific value of Ci and are primarily concerned with only
the order of accuracy of the method.
9.3. ERRORS AND NORMS 53

STEADY STATE DIFFUSION (1D, 2D, 3D)


In the exercise considered in previous lessons, we used linear-1D (bilinear-2D, trilinear-
3D) elements to solve the steady diffusion equation. In this case, the polynomial order
of the shape function p, was p = 1. Using this element, the errors expected are given
by Z
T − T h dV ≤ C1 h,

in the L1 norm and


Z 1/2
2
h
T −T dV ≤ C2 h2 ,

in the L2 norm. In general, for a shape function of order polynomial p, we expect the
following: Z
T − T h dV ≤ C3 hp , (9.9)

Z 1/2
2
h
T −T dV ≤ C4 hp+1 . (9.10)

ELASTICITY (2D)
Z
u − uh + v − v h dV ≤ C5 hp (9.11)

Z 1/2
2 2
h h
u−u + v−v dV ≤ C6 hp+1 (9.12)

STOKES FLOW - MIXED METHOD (2D)


For convenience we will define the error of each velocity component as

eu = u − uh , ev = v − v h ,

then the expected errors for pressure are given by


Z 1/2
2
p − ph dV ≤ C7 hq+1 (9.13)

and for the velocity we have


Z 1/2
2 2
|eu | + |ev | dV ≤ C8 hp+1 . (9.14)

"Z #1/2
2 2 2 2
∂eu ∂eu ∂ev ∂ev
+ + + dV ≤ C9 hp (9.15)
Ω ∂x ∂y ∂x ∂y

Note that for the mixed method (used when solving Stokes flow), the pressure basis
function usually employs a different order polynomial to the velocity basis, which here
we denote via q.
CHAPTER 9. CODE VERIFICATION 54

Limitations
The mathematical analysis performed to obtain the above error estimates required nu-
merous assumptions to be made. The assumptions include: homogenous material
properties (diffusivity, viscosity, density, etc.); that the model domain Ω can be com-
pletely resolved by the element with zero discretisation error (i.e. the domain Ω is a
rectangle and a structured grid of quadrilateral elements was used to discretise it);
there is zero error associated with the boundary conditions; there is zero error associ-
ated with the matrix solver.
Thus, we emphasize very strongly, that the results above are by no means com-
pletely universal. Whilst some of the assumptions can be relaxed and the error esti-
mates above will remain valid - however, violating these assumptions can sometimes
result in completely different (usually lower) error estimates.

9.4 Measuring the order of accuracy


To keep the discussion general, let’s assume that the problem of interest can be de-
scribed by the abstract PDE
Lu = f,
which is valid over the domain of interest Ω. For this problem, we will consider that u is
subject to the following Dirichlet boundary condition

u(x) = g(x) for x ∈ ∂Ω,

where the boundary of Ω is denoted by ∂Ω and g(x) is a prescribed function (i.e. it’s
known). Furthermore we will assume that given f , g and the differential operator L,
we have (by some means) obtained a function u which satisfies the boundary and the
PDE above, i.e. we have a solution to the problem of interest.
The procedure to measure the order of accuracy of the discretisation error can be
summarised as follows:

1. Define a mesh on your domain Ωh , with a mesh resolution of h;

2. Discretise the differential operator L and f , and solve for uh ;

3. Compute a global error measure, say E(Ωh )L2 for example;

4. Generate a new mesh, Ωh/2 by sub-dividing all the elements within the original
mesh Ωh ;

5. Repeat the steps above.

If the sequence above is repeated for say 4-8 different meshes, each with successively
higher resolution, the results of E (the error measured in some norm) versus h should
be plotted on a log10 − log10 graph. If the meshes used in the study are suitably fine
and resolve the analytic solution well, then the plotted data in log-log space should
lie along a straight line. Performing a linear regression should result in a correlation
coefficient very close of 1.0. The gradient of the this log-log plot will define the order of
accuracy of our numerical solution.
9.5. THE METHOD OF MANUFACTURED SOLUTIONS (MMS) 55

To understand this result, recall that the error one a given mesh domain Ωh is
assumed to vary with h according to
E(Ωh ) ≈ Chk , (9.16)
where C is a constant independent of h. C is considered a function of the model prob-
lem, i.e. it relates to the shape of the domain used, the choice of boundary conditions
and material properties used in the PDE. On a finer mesh, Ωh/r , we have
 k
h/r h
E(Ω ) ≈ C , (9.17)
r
where r is a refinement factor. For simplicity in the steps 1-5 above we considered a
refinement factor of r = 2. Combining Equations (9.16) & (9.17) we have
E(Ω1 )
= rk (9.18)
E(Ω2 )
and now taking the log10 of both sides yields an expression for the order of accuracy k:
 
E(Ω1 )
k = log10 . [log10 (r)]−1 . (9.19)
E(Ω2 )
Note that we are most interested in the behaviour of the error in the asymptotic limit,
h → 0. If your initial mesh was too coarse and failed to resolve the analytic solution,
the computed errors may not lie along a straight line. In this case, one should consider
only using the errors associated with the finest meshes considered.

Asymptotic behaviour
Measuring the order of accuracy k of a method only provides information concerning
how the error changes (ideally decreases) as the mesh resolution h is decreased. For
example, if a method is second order accurate O(h2 ) (in some norm), ie. k = 2, then
we can expect that the error (measure in the appropriate norm) obtained on a grid
with resolution h, will reduce be a factor of four if we solve then solve on grid with
resolution h/2. The order of accuracy tells us nothing about the absolute value of the
error. Another way of stating this, is the order of accuracy gives us information about
the slope of the log(E) − log(h) graph, but doesn’t provide us with the offset, i.e. the
constant C in Equation (9.16) is unknown.
In the asymptotic limit of h → 0, then a fourth order method will always be more
accurate than a second order method. However, in practice we are often far from
this asymptotic limit, thus the question of which method is better cannot be answered
with only knowing the order of accuracy. This point is illustrated in Figure 9.1. Pure
analysis may provide upper bounds on what the constant C might be (under quite
strict assumptions), but for all practical purposes the constant C must be determined
via numerical experiments.

9.5 The Method of Manufactured Solutions (MMS)


In all the previous sections it was taken for granted that we also had an analytic solution
u which we could use to measure the error within our numerical solution, uh . The clas-
sical approach to obtain an analytic solution is as follows. Given the PDE of interest,
Lu = f :
CHAPTER 9. CODE VERIFICATION 56

Discretisation error
10
Method A : k = 2.0
Method B : k = 6.0
5

0
log10 (E2 )

−5

−10

−15

−20
−4.0 −3.5 −3.0 −2.5 −2.0 −1.5 −1.0 −0.5 0.0
log10 (h)

Figure 9.1: Discretisation errors for two methods with an order of accuracy of 6 (Method
B) and 2 (Method A). Note the cross over point at h ≈ 1/56

1. Choose a simple domain Ω (i.e. a box/cube);

2. Define the right hand side f ;

3. Select your Dirichlet or Neumann boundary conditions;

4. Use all your skills and find a function u which satisfies the PDE and the boundary
conditions chosen.

In general, analytic solutions for multi-dimensional problems can be difficult to obtain.


The complexity of the obtaining analytic solutions continues to increase if we wish to
consider coefficients (i.e. diffusivity, viscosity) which vary as a function of space, or if we
were to consider a domain which was no longer naturally defined in the chosen coordi-
nate system (i.e. a rectangle/cube in x, y, z). Up to this point, we have only considered
linear problems. The problem is compounded if one seeks an analytic solution for non-
linear problems. Frequently researchers have to resort to using analytic solutions for
1D, homogenous coefficient problems to verify their numerical model (e.g. Poiseuille
flow). Using the solution from 1D Poiseuille flow is hardly appropriate to verify a code
designed to solve 3D, variable viscosity Stokes flow. An alternative approach must be
employed - this approach is called the Method of Manufactured Solutions (MMS).
The basic idea to constructed manufactured solutions is completely general and
extremely versatile. The concepts can be applied to arbitrarily complex PDE’s (linear,
non-linear, time dependent) and to arbitrarily complex domains and boundary condi-
tions. The basic process of manufacturing a solution are described below. Given the
PDE, Lu = f :
9.5. THE METHOD OF MANUFACTURED SOLUTIONS (MMS) 57

1. Choose the solution uM S ;


2. Define any coefficients within L;
3. Compute fM S = LuM S and define the result to be your right hand side, i.e.
f = fM S ;
4. Given any domain Ω, evaluate uM S or ∂uM S /∂n to define any Dirichlet or Neu-
mann boundary conditions respectively.
The procedure only requires to choose a function for the solution, and then apply the
action of the differential operator L. Whilst the algebra involved may be somewhat te-
dious to define the right hand side function f , we are only required to perform differenti-
ation. The action of differentiation is easy (compared to integration) and can be readily
performed by symbolic algebra packages such as Maple, MATLAB (using the symbolic
toolbox) Mathematica, Maxima (http://maxima.sourceforge.net) or SymPy (sym-
bolic python, http://http://sympy.org).
It is important to emphasize that the function chosen for u does not have to be
physically meaningful. It is not important whether u “looks” like a solution you would
typically obtain from your application. The purpose of manufacturing solutions is solely
to ascertain that what is implemented in your code is producing discrete solutions of
the quality expected by that particular numerical method.
There are some limitations to the method of manufactured solutions which should
be mentioned. The function chosen for u and the coefficients in the operator L, must be
smooth and differentiable. Care should also be exercised that the constructed function
fM S is “well behaved”, in the sense that it doesn’t contain any singularities. This is
easily confirmed by simply plotting the function. Furthermore, fM S should be able
to be resolved on the grid sequence you use when computing the order of accuracy.
The coefficients should be chosen so that are physically reasonable, e.g. coefficients
representing viscosity should not be negative.

Example: A linear PDE


The linear differential operator associated with the 1D diffusion equation, with a spa-
tially variable coefficient is given by
 
∂ ∂
Lu := κ(x) T. (9.20)
∂x ∂x
First I choose the coefficient for the diffusivity to be
κ(x) = (4 tanh(10x) + 6) exp(0.8x), (9.21)
and the temperature to be
TM S (x) = 8 sin(x)x4 + 20. (9.22)
Using sympy (see mms-linear-Diffusion1D.py), I obtain the following right hand side
 
∂ ∂
fM S = κ(x) TM S
∂x ∂x
= [6 + 4 tanh(10x)][−8x4 sin(x) + 64x3 cos(x) + 96x2 sin(x)] exp(0.8x) (9.23)
2 4 3
+ [40 − 40(tanh(10x) )][8x cos(x) + 32x sin(x)] exp(0.8x)
+ 0.8[6 + 4 tanh(10x)][8x4 cos(x) + 32x3 sin(x)] exp(0.8x)
CHAPTER 9. CODE VERIFICATION 58

The manufactured functions κ(x) and uM S , together with fM S are shown in Figure 9.2.
This example is demonstrated in the script ML FEM 1D DiffusionVariableCoeff MMS.m
and the order of accuracy is determined using the resulting output. The output is
processed in the script ML FEM OrderOfAccuracy.m.

Manufactured solution
30 3000
κ(x) fM S
uM S
2500
25

2000
20

1500
uM S , κ M S

fM S
15

1000

10
500

5
0

0 −500
−1.0 −0.5 0.0 0.5 1.0
x

Figure 9.2: Manufactured solution for the 1D diffusion equation with a spatially variable
diffusivity.

9.6 Exercises
1. Verify your 2D steady state, diffusion code which uses Q1 (bilinear) elements.
Choose a smooth, differentiable function for uM S for the temperature. Use (i) a
mesh of uniform quadrilateral elements, (ii) constant thermal diffusivity κ = 13.4
and (iii) the manufactured solution to specify Dirichlet boundary conditions every-
where. Use the global error measure in Equation (9.10). Follow the programming
style in the example script ML FEM 1D DiffusionVariableCoeff MMS.m. One im-
portant difference to note is that the example script uses 1-point Gauss quadra-
ture to evaluate the error. In this example, you should use the 2 × 2 Gauss
quadrature rule to evaluate Equation (9.10). Follow steps 1-5 in Section 9.4
and measure the order of accuracy of your FE solution by modify the script
ML FEM OrderOfAccuracy.m. Deform the grid so that the elements are no longer
uniform quadrilaterals and measure the order of accuracy. Does the order of
accuracy change?

2. Verify your 2D elasticity code which uses Q2 (biquadratic) elements. Choose a


function for the displacement solution (uM S , vM S ) and use (i) a mesh of uniform
quadrilateral elements, (ii) constant elastic parameters and (iii) the manufactured
9.6. EXERCISES 59

solution to specify Dirichlet boundary conditions for both the displacement de-
grees of freedom (u, v). Use the error defined in Equation (9.12). Evaluate this
integral using the 3 × 3 Gauss quadrature rule. Compute the order of accuracy
of your FE solution. As an additional test, make the elasticity coefficients vary
in space and see if the order of accuracy changes. Note that you will have to
re-compute fM S .
A
MATLAB Introduction

A.1 Introduction
This main goal of this part of the course is to learn how to solve the partial differential
equations we spoke about earlier in the lecture. Most of the equations that are of
interest to you as an Earth ccientist are known. However, they can typically not be
solved analytically (or if they can - it is a very complicated). At the same time, however,
it is relatively straightforward to solve them with the aid of a computer. Although there
are a variety of numerical techniques that one can use, the main focus here is on the
Finite Element Method.

The focus here is on the practical problem of going from an equation to a solution.
At the beginning of each lecture, a short introduction will be given and the rest of the
lecture consists in writing code and solving exercises. The computer language we will
use is MATLAB, which has a number of neat features, such as plotting or solving of
linear systems of equations.

A.2 Useful linear algebra


MATLAB is entirely vector or linear algebra based. It is therefore useful to remind you
of some of the linear algebra that you learned a long time ago.
Let’s define a vector b as

b= 5 10 17

and a 3 × 2 matrix D as
 
1 2
D =  4 3 .
5 6

The transpose (denoted with T ) of D and b is given by:


 
T 1 4 5
D = ,
2 3 6
 
5
bT =  10  .
17

61
APPENDIX A. MATLAB INTRODUCTION 62

An example of matrix-vector multiplication:


 
  5  
1 4 5  10  = 130 .
DT bT =
2 3 6 142
17

An example of vector-vector multiplication (e.g. scalar product or dot product):


 
5
bbT =
 
5 10 17  10  = 414 .
17

An example of matrix-matrix multiplication:


 
  1 2  
1 4 5  42 44
DT D = 4 3 = .
2 3 6 44 49
5 6

In numerical modelling, after discretisation we will frequently end up with a system of


linear equations of the form:

Ax = f ,

where A is an n × m matrix and f is a n × 1 vector. The coefficients Aij and fi are all
known, however the m × 1 vector x is unknown. If we take A = D and f = bT , x is
(check!):
 
1
x = .
2

A.3 Exploring MATLAB


MATLAB is a vector based computer language, which is available for Windows, Apple
and Unix operating systems. It comes with its own programming language, which whilst
can be slow, it is extremely useful due to its simplicity.

Getting started
To start the program, type matlab at the unix prompt. The MATLAB command window
starts.
1. Type 2+3. You’ll get the answer. Type 2 + 3*9 + 5^2.
2. Type
>> x =3
>> y=x.
>> z=x*y
>> pi
>> a = x * pi

3. Type demo and explore some examples.


4. Type help. You see a list of all help functions. Type help log10 to get information
about the log10 command.
A.3. EXPLORING MATLAB 63

Vectors/arrays and plotting


5. Create an array of x-coordinates:
>> dx =2
>> x =[0: dx :10]

6. Define a set of y-coordinates as a function of x:


>> y = x .^2 + exp ( x /2)

7. Plot it:
>> plot (x , y )

8. Exercise: Make a plot of a parametric function. What does it look like?


>> t =0:.1:2* pi
>> x = sin ( t ); y = cos ( t ); plot (x ,y , ’o - ’)
>> xlabel ( ’x ’)
>> ylabel ( ’y ’)
>> axis image , title ( ’ fun with plotting ’)

Exercise: Make an ellipse out of it with a short radius of 1 and a long radius of 2.
Change the colour of the curve to red.

Matrices and 3D plotting


First create x and y arrays, for example: x=[1:5];y=x;
9. Play with matrix products of x and y. Perform an element by element product of the
two vectors (note the dot) via,
>> x .* y

The following command


>> x . ’

returns the transpose of the vector. The “dot” or scalar product of two matrices is given
by
>> x * y . ’

The matrix product


>> x ’* y

returns a matrix. Some commands (try them):


>> ones (1 ,5) , ones (6 ,1)
>> length ( x )
>> whos

10. Creating 2D matrices.


A useful function is meshgrid, which creates 2D arrays:
>> [ x2d , y2d ] = meshgrid (0:.1:5 ,1:.1:8)

You can obtain the size of an array using:


>> size ( x2d )
APPENDIX A. MATLAB INTRODUCTION 64

11. Plot the function sin(x2d.*y2d).


>> z2d = sin ( x2d .* y2d )
>> surf ( x2d , y2d , z2d )
>> mesh ( x2d , y2d , z2d )
>> contour ( x2d , y2d , z2d ) , colorbar
>> contourf ( x2d , y2d , z2d ) , colorbar

Some cool stuff (1)


>> [ x2d , y2d , z2d ] = peaks (30);
>> surf ( x2d , y2d , z2d ); shading interp
>> light ; lighting phong

Some cool stuff (2): perform the example given at the end of
>> help coneplot ;

Some additional useful commands:


clf: clear current active figure
close all: close all figure windows

MATLAB scripting
By now you must be tired of typing all those commands all the time. Luckily, there is a
MATLAB script language which allows you to type the commands in a text editor, save
the result and re-use it later. MATLAB scripts are text files which end with the suffix
“.m”.
12. Open a text editor (e.g. emacs, vi, Xcode) and create a file “mysurf.m”.
13. Type the plotting commands from the last section in the text file. A good program-
ming convention is to start the script with clear, which clears the memory of MATLAB.
Another good programming practice is to include lots of comments within your MATLAB
script which describe what each line/block of code actually does. A comment can be
placed after %, e.g.
% This is my first matlab script

14. Start the script from within MATLAB by going to the directory where the text file is
saved. Type
>> mysurf

from within MATLAB and you should see the plot.

Loops
Create an array na=100; a=sin(5*[1:na]/na); plot(a).
15. Ask instructions on using “for”:
>> help for

16. Compute the sum of an array:


>> mysum =0; for i =1: length ( a ) , mysum = mysum + a ( i ); end ; mysum

17. Compare the result with the MATLAB inbuilt function sum
>> sum ( a )
A.3. EXPLORING MATLAB 65

18. Exercise. Create an x-coordinate array: dx=0.01; y=cos([0:dx:10]). Compute


the integral of y = cos(x) on the x-interval 0 ≤ x ≤ 10. Use sum(y) and write a MATLAB
script. Compare it with sin(10), the analytical solution.

Cumulative sum
19. Create a number of sedimentary layers with variable thickness:
>> thickness = rand (1 ,10); plot ( thickness )}

20. Compute the depth of the interface between different layers:


>> depth (1)=0;
>> for i =2: length ( thickness )
>> depth ( i ) = depth (i -1)+ thickness ( i );
>> end ;
>> plot ( depth )

21. Compare the results with the built in MATLAB function cumsum:
>> bednumber =1: length ( depth )
>> plot ( bednumber , depth , bednumber , cumsum ( thickness ))

22. What causes the discrepancy? Try to remove it, read the description of the function
>> help cumsum

IF command
23. Ask MATLAB for information;
>> help if

Find maximum value within the above array thickness, and compare it with the built-in
MATLAB function max(thickness).

FIND command
24. Ask MATLAB for information;
>> help find

Find which layer has the maximum thickness: find(thickness==max(thickness)).


25. Find the number of beds with a maximum thickness less than 0.5.

Matrix operations
26. Exercise: Reproduce the linear algebra exercises in the beginning of this docu-
ment. Hint: If you want to solve the system of linear equations A x = f for x, you can
use the backslash operator: x = A\f.
B
Useful Formulae

Vector operations

" #
∂x
grad(u) = ∇u = ∂
u (B.1)
∂y
h
∂ ∂
i ∂v1 ∂v2
div(v) = ∂x ∂y · v = ∇T v = + (B.2)
∂x ∂y

Integration by parts (1D)


Z b Z b
dg(x) df (x)
f (x) dx = − g(x) dx + [f (x)g(x)]ba (B.3)
a dx a dx

Integration by parts (higher dimensions)


Z Z I
∂g ∂f
f dV = − g dV + f g ni dS (B.4)
Ω ∂xi Ω ∂xi ∂Ω
Z Z I
f · ∇g dV = − g∇ · f dV + gf · n dS (B.5)
Ω Ω ∂Ω
Z Z I
2
∇f · ∇g dV = − f ∇ g dV + f ∇g · n dS (B.6)
Ω Ω ∂Ω

Tensor products
Given a vector of 1D functions, P (s) = (P1 (s), P2 (s), . . . , Pm (s)), we can define a 2D
tensor product with the coordinates (ξ, η)
N11 (ξ, η) = P1 (ξ)P1 (η)
N21 (ξ, η) = P2 (ξ)P1 (η)
N31 (ξ, η) = P3 (ξ)P1 (η)
..
.
Nm1 (ξ, η) = Pm (ξ)P1 (η)
N12 (ξ, η) = P1 (ξ)P2 (η) (B.7)
..
.
Nm2 (ξ, η) = Pm (ξ)P2 (η)
..
.
Nmm (ξ, η) = Pm (ξ)Pm (η)

67
APPENDIX B. USEFUL FORMULAE 68

In general we have,

Nij = Pi (ξ)Pj (η), for all 1 ≤ i, j ≤ m (B.8)

A 3D tensor product can similarily be defined with the coordinates (ξ, η, ζ) via

Nijk = Pi (ξ)Pj (η)Pk (ζ), for all 1 ≤ i, j, k ≤ m (B.9)

We note that the 1D basis used need not be the same length, for example one could
define
Nijk = Ui (ξ)Vj (η)Wk (ζ), (B.10)
where U (s) = (U1 (s), . . . , Um (s)), V (s) = (V1 (s), . . . , Vn (s)), W (s) =
(W1 (s), . . . , Wp (s)) and where m 6= n 6= p.
C
1D Steady State Diffusion Example

%%
%% Script : F E M _ 1 D _ 2 n d _ o r d e r _ s t e a d y s t a t e . m
%%
%% FE code for 1D , 2 nd order steady state
%% diffusion equation with a non - zero source term
%% Marcel Frehner , ETH Zurich , 2012
%%

% GENERAL STUFF
clear all
close all
clc

% GEOMETRICAL PARAMETERS
Lx = 10;

% PHYSICAL PARAMETERS
kappa = 1;
source = -1;

% NUMERICAL PARAMETERS
el_tot = 10;
n_tot = el_tot +1;
n_per_el = 2;

% calculated from above


dx = Lx / el_tot ;
GCOORD = 0: dx : Lx ;

% LOCAL - TO - GLOBAL MAPPING


EL_N = [ 1: n_tot -1 ; 2: n_tot ];

% BOUNDARY CONDITIONS
bc_dof = [ 1 n_tot ];
bc_val = [ 0 0 ];

% INITIALIZE GLOBAL STIFFNESS MATRIX AND GLOBAL FORCE VECTOR


KG = zeros ( n_tot , n_tot );
FG = zeros ( n_tot ,1);

% ELEMENT LOOP
for iel = 1: el_tot

% GET NODE INDICES FOR ELEMENT iel


el_nodes = EL_N (: , iel );

69
APPENDIX C. 1D STEADY STATE DIFFUSION MATLAB EXAMPLE 70

% DEFINE ELEMENT STIFFNESS MATRIX AND VECTOR


Kloc = kappa / dx *[1 -1; -1 1];
Floc = source * dx /2;

% INSERT / SUM LOCAL ELEMENT STIFFNESS MATRICES


% INTO GLOBAL STIFFNESS MATRIX
KG ( el_nodes , el_nodes ) = KG ( el_nodes , el_nodes ) + Kloc ;
FG ( el_nodes ) = FG ( el_nodes ) + Floc ;

end

% APPLY BOUNDARY CONDITIONS


for ibc = 1: length ( bc_dof )

% GET NODE INDICES FOR BOUNDARY CONDITION AT NODE ibc


bc_idx = bc_dof ( ibc );

% ZERO ROW AND INSERT 1 ON THE DIAGONAL


KG ( bc_idx ,:) = 0;
KG ( bc_idx , bc_idx ) = 1;

% FORCE DIRICHLET VALUE INTO RHS VECTOR


FG ( bc_idx ) = bc_val ( ibc );

end

% SOLVE
T = KG \ FG ;

% COMPUTE ANALYTICAL SOLUTION


x_ana = 0: Lx /1000: Lx ;
T_ana = -1/2* source / kappa .* x_ana .^2 + 1/2* source * Lx / kappa * x_ana ;

% PLOT SOLUTIONS
plot ( x_ana , T_ana , ’k - ’ , GCOORD ,T , ’ ro ’);
xlim ([0 Lx ])
xlabel ( ’x - coordinate [ m ] ’)
ylabel ( ’ T [ ] ’)
legend ( ’ analytical solution ’ , ’ fem solution ’)
drawnow
D
MMS 1D Diffusion Example

%%
%% Script : M L _ F E M _ 1 D _ D i f f u s i o n V a r i a b l e C o e f f _ M M S . m
%%
%% FE code for solving steady state , 1 D diffusion equation
%% with variable coefficient ( diffusivity ).
%% Demonstration of the Method of Manufactured Solutions ( MMS )
%% 26.07.2011 , Dave May , ETH Zurich
%%

function [] = main ()

clear all , close all , clc

% Numerical parameters
% Mesh sequence used ,
% no_elements = { 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 }
no_el = 128;
no_nodes = no_el + 1;
no_nodes_el = 2;
width = 2;
X = [ -1: width /( no_el ): -1+ width ];
dx = X (2) - X (1);
% Initialization of matrices and vectors
KK = zeros ( no_nodes , no_nodes );
u = zeros ( no_nodes ,1);
F = zeros ( no_nodes ,1);

% Node numbering
for i =1: no_el
iel = i ;
nodes ( iel ,1) = i ;
nodes ( iel ,2) = i +1;
end

% Setup system matrix


for iel =1: no_el
ileft = nodes ( iel ,1);
iright = nodes ( iel ,2);
x_centroid = 0.5 * ( X ( iright ) + X ( ileft ) );

% Physical parameters evaluated at the element centroid


A = MMS_Coefficient ( x_centroid );
B = MMS_RightHandSide ( x_centroid );

% Setup element matrix


% Matrix for conductive terms , see Maple script

71
APPENDIX D. MMS 1D DIFFUSION EXAMPLE 72

K_loc = [ - A / dx A / dx ; A / dx -A / dx ];
% Right hand side vector
F_loc = [ B * dx /2 B * dx /2];

for i =1: no_nodes_el


ii = nodes ( iel , i );
for j =1: no_nodes_el
jj = nodes ( iel , j );
KK ( ii , jj ) = KK ( ii , jj ) + K_loc (i , j );
end
F ( ii ) = F ( ii ) + F_loc ( i );
end
end

% Boundary conditions
% Evaluate the manufactured solution at the end points
KK (1 ,:) = 0; KK (1 ,1) = 1;
F (1) = MMS_Solution ( X (1) ); % Left boundary
KK ( end ,:) = 0; KK ( end , end ) = 1;
F ( end ) = MMS_Solution ( X ( end ) ); % Right boundary

% Solve matrix
u = KK \ F ;

% Compute the L2 error using a 1 - point quadrature over each element


L2_error = 0.0;
for iel =1: no_el
ileft = nodes ( iel ,1);
iright = nodes ( iel ,2);

% element volume
dV = X ( iright ) - X ( ileft );
% coordinate of element centroid
x_centroid = 0.5 * ( X ( iright ) + X ( ileft ) );
% FE solution at centroid
T_fem_centroid = 0.5 * ( u ( iright ) + u ( ileft ) );
% MMS at centroid
T_mms = MMS_Solution ( x_centroid );
% Discretisation error at centroid
T_error = T_mms - T_fem_centroid ;

L2_error = L2_error + T_error * T_error * dV ;


end
L2_error = sqrt ( L2_error );
fprintf (1 , ’ h = E_2 = \n ’ );
fprintf (1 , ’%1.4 e , %1.6 e ; \n ’ , dx , L2_error );

% Evaluate the analytical solution and plot


L = width ;
x = [ -1: dx /2.0: -1+ L ];
for i =1: length ( x )
u_mms ( i ) = MMS_Solution ( x ( i ) );
end

% Graphics
plot (X ,u , ’ - ok ’ ,x , u_mms , ’ -b ’);
xlabel ( ’x ’); ylabel ( ’u ’); grid on ;
legend ( ’ finite element soln . ’ , ’ manufactured soln . ’ ,4); drawnow ;
73

% ===========================================================
%
% Manufactured coefficients , solution and right hand side
%
function val = MMS_Coefficient ( x )
val = ( 4.0 * tanh (10.0 * x ) + 6.0 ) * exp (0.8 * x );

function val = MMS_Solution ( x )


val = 8.0 * sin ( x )* x ^4 + 20.0;

function val = MMS_RightHandSide ( x )


val = (6 + 4* tanh (10* x ))*( -8* x ^4* sin ( x ) + 64* x ^3* cos ( x ) ...
+ 96* x ^2* sin ( x ))* exp (0.8* x ) ...
+ (40 - 40* tanh (10* x )^2)*(8* x ^4* cos ( x ) ...
+ 32* x ^3* sin ( x ))* exp (0.8* x ) ...
+ 0.8*(6 + 4* tanh (10* x ))*(8* x ^4* cos ( x ) ...
+ 32* x ^3* sin ( x ))* exp (0.8* x );
E
MMS Order of Accuracy Example

%%
%% Script : M L_ FE M_O rd er OfA cc ur ac y . m
%%
%% MMS compute order of accuracy
%%

clear all , close all , clc

%
% Data obtained from running
% ML_FEM_1D_DiffusionVariableCoeff_MMS .m
% with the following mesh sequence
% no_elements = { 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 }
%

data = [
5.0000 e -01 , 2.375693 e +00;
2.5000 e -01 , 6.843966 e -01;
1.2500 e -01 , 1.770845 e -01;
6.2500 e -02 , 4.460979 e -02;
3.1250 e -02 , 1.117224 e -02;
1.5625 e -02 , 2.794296 e -03;
7.8125 e -03 , 6.986512 e -04;
3.9062 e -03 , 1.746675 e -04;
1.9531 e -03 , 4.366748 e -05;
];

h = data (: ,1);
E = data (: ,2);

logh = log10 ( h );
logE = log10 ( E );

% plot log ( h ) vs log ( E )


plot ( logh , logE , ’ - ok ’ , logh , logE , ’ -b ’);
xlabel ( ’ log10 ( h ) ’); ylabel ( ’ log10 ( E ) ’); grid on ;
legend ( ’ convergence ’ ,4); drawnow ;

% perform linear regression and obtain the correlation coefficient


p = polyfit ( logh , logE ,1);
R = corrcoef ( logh , logE );

fprintf (1 , ’ Order of accuracy : %1.4 f \n ’ , p (1) );


fprintf (1 , ’ Correlation coefficient : %1.4 f \n ’ , R (1 ,2) );

75
F
MMS SymPy Example

from sympy import *


from sympy import var , Plot

x = Symbol ( ’x ’)

# Chosen solution
T = 8* sin ( x ) * x **4 + 20

# Chosen coefficient
kappa = ( 4* tanh (10* x ) + 6 ) * exp (0.8* x )

# Compute , fMS = Lu
# = d / dx ( kappa ( x ). dT / dx )
dT_dx = diff ( T , x )
kappa_dT_dx = kappa * dT_dx

fMS = diff ( kappa_dT_dx , x )

print ( ’[ MMS chosen solution ] ’)


print ( ’\ tT = ’)
print ( ’\t ’ + ccode ( T ))

print ( ’[ MMS chosen coefficients ] ’)


print ( ’\ tkappa = ’)
print ( ’\t ’ + ccode ( kappa ))

print ( ’[ MMS right hand side ] ’)


print ( ’\ tf_MS = ’)
print ( ’\t ’ + ccode ( fMS ))

print ( ’[ MMS boundary conditions ] ’)


print ( ’ Dirichlet : ’)
T_eval = T . subs ({ x : ’ -1.0 ’})
result = T_eval . evalf ()
print ( ’\ tT ( x )|( x = -1.0) = ’ + str ( result ))

T_eval = T . subs ({ x : ’1.0 ’})


result = T_eval . evalf ()
print ( ’\ tT ( x )|( x =+1.0) = ’ + str ( result ))

# =============================================
print ( ’ Neumann : ’)
kgradT_eval = kappa_dT_dx . subs ({ x : ’ -1.0 ’})
result = kgradT_eval . evalf ()
print ( ’\ tkappa ( x ). dT ( x )/ dx |( x = -1.0) = ’ + str ( result ))

77
APPENDIX F. MMS SYMPY EXAMPLE 78

kgradT_eval = kappa_dT_dx . subs ({ x : ’1.0 ’})


result = kgradT_eval . evalf ()
print ( ’\ tkappa ( x ). dT ( x )/ dx |( x =+1.0) = ’ + str ( result ))

You might also like