(L) - 2015 - May - Introduction To Finite Element Modelling in Geosciences - ETH
(L) - 2015 - May - Introduction To Finite Element Modelling in Geosciences - ETH
Modelling in Geosciences
Dave A. May ([email protected])
Marcel Frehner ([email protected])
Mike Afanasiev (ETH Zürich)
Patrick Sanan (USI Lugano)
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
4 Numerical Integration 19
4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.2 Quadrature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
i
CONTENTS ii
7.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
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
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
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
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
• 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)
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
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
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
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
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
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)
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
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.
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).
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
where lx is the length of the spatial domain and dx is the element length. One can
create a similar vector for time.
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).
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).
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 ;
The variable iel is the current element number which varies within the loop from 1 to
nels.
where T is the vector (with dimensions nn × 1) of old temperatures and the other
vectors and matrices are described above.
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κ
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
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
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
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
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
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
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
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 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
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);
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.
5. Convert the derivatives from the local coordinates to the global coordinates by
performing the operation in Equation (5.24).
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).
10. The element matrices can then be added to the global element stiffness matrix.
This process is then continued for each element.
local node
numbering 1 2 3
2 3
1 2
4 5 6
1 4
3
7 8
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
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
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.
• 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.
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
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 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
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
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
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
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.
∂σ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
1 5 2
1 4
local degrees of freedom
(order: u1,v1,u2,v2,...,p1,p2,p3,p4)
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
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
B̂ = BN̂, (8.28)
σ̂ = 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.
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.
∂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.
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
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)
Ω
eu = u − uh , ev = v − v h ,
"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.
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:
4. Generate a new mesh, Ωh/2 by sub-dividing all the elements within the original
mesh Ωh ;
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.
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
4. Use all your skills and find a function u which satisfies the PDE and the boundary
conditions chosen.
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?
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.
and a 3 × 2 matrix D as
1 2
D = 4 3 .
5 6
61
APPENDIX A. MATLAB INTRODUCTION 62
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
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
7. Plot it:
>> plot (x , y )
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.
returns the transpose of the vector. The “dot” or scalar product of two matrices is given
by
>> x * y . ’
Some cool stuff (2): perform the example given at the end of
>> help coneplot ;
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
Loops
Create an array na=100; a=sin(5*[1:na]/na); plot(a).
15. Ask instructions on using “for”:
>> help for
17. Compare the result with the MATLAB inbuilt function sum
>> sum ( a )
A.3. EXPLORING MATLAB 65
Cumulative sum
19. Create a number of sedimentary layers with variable thickness:
>> thickness = rand (1 ,10); plot ( thickness )}
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
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
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,
A 3D tensor product can similarily be defined with the coordinates (ξ, η, ζ) via
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;
% BOUNDARY CONDITIONS
bc_dof = [ 1 n_tot ];
bc_val = [ 0 0 ];
% ELEMENT LOOP
for iel = 1: el_tot
69
APPENDIX C. 1D STEADY STATE DIFFUSION MATLAB EXAMPLE 70
end
end
% SOLVE
T = KG \ FG ;
% 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 ()
% 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
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];
% 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 ;
% 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 ;
% 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 );
%%
%% Script : M L_ FE M_O rd er OfA cc ur ac y . m
%%
%% MMS compute order of accuracy
%%
%
% 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 );
75
F
MMS SymPy Example
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
# =============================================
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