project sg2212 development of a navier-stokes code as a

26
Computational Fluid Dynamics SG2212, Spring 2011 1 Project SG2212 Development of a Navier-Stokes code as a demonstration of concepts due 23/3-2011 Version 1.04 (10/3-2011) 1 Background The velocity and pressure fields for an incompressible fluid can be obtained by solving the Navier– Stokes equations numerically. Under the assumption of constant density (incompressible), the non-dimensional mass and momentum conservation equations are reduced to ∂u i ∂x i = 0 (1) ∂u i ∂t + (u i u j ) ∂x j = - ∂P ∂x i + 1 Re 2 u i ∂x j ∂x j + f i , (2) with u i denoting the velocity in the direction x i , P the pressure, and the Reynolds number Re. f i is a volume force. Note that the summation convention has been used. The corresponding transport equation for a scalar θ such as the temperature or pollutant concentration is ∂θ ∂t + (u j θ) ∂x j = 1 Pe 2 θ ∂x j ∂x j , (3) with the P´ eclet number Pe = Pr · Re. In the case of a so-called active scalar, the Boussinesq approximation can be used to model the influence of variable density onto the momentum equations by setting f 2 = Riθ. Here, we assume that the gravity acts in the y = x 2 direction, hence the force is applied onto the second component of f i . Finally, Ri denotes the Richardson number. As can be seen in the above equations, the continuity equation is not an evolution equation anymore as in the case of compressible fluids. This means that mass conservation becomes like an additional constraint for the momentum conservation equations. This requires extra attention when the equations are solved numerically. For time-dependent flows a common way to solve the discrete equations is the so-called projection or pressure correction method. Sometimes this method and its generalisations are also called splitting methods. A short description of this method is given next. Let us discretise the above equations using an explicit scheme for time derivatives (explicit Euler) U n+1 - U n Δt + N (U n )U n + GP n+1 = f (t n ) , (4) DU n+1 = 0 , (5) where N (U )U denotes the advective and viscous terms, GP the pressure gradient, Δt the time step and f (t) the forcing terms including the boundary conditions. Further, D stands for divergence operator. Note that the pressure term is discretized using the values at the time step n + 1. The reason for this will become clear later on. Applying the projection method to the set of equations

Upload: others

Post on 28-Feb-2022

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 1

Project SG2212

Development of a Navier-Stokes code as a demonstration of concepts

due 23/3-2011Version 1.04 (10/3-2011)

1 Background

The velocity and pressure fields for an incompressible fluid can be obtained by solving the Navier–Stokes equations numerically. Under the assumption of constant density (incompressible), thenon-dimensional mass and momentum conservation equations are reduced to

∂ui∂xi

= 0 (1)

∂ui∂t

+∂(uiuj)∂xj

= − ∂P∂xi

+1Re

∂2ui∂xj∂xj

+ fi , (2)

with ui denoting the velocity in the direction xi, P the pressure, and the Reynolds number Re. fi isa volume force. Note that the summation convention has been used. The corresponding transportequation for a scalar θ such as the temperature or pollutant concentration is

∂θ

∂t+∂(ujθ)∂xj

=1Pe

∂2θ

∂xj∂xj, (3)

with the Peclet number Pe = Pr · Re. In the case of a so-called active scalar, the Boussinesqapproximation can be used to model the influence of variable density onto the momentum equationsby setting f2 = Riθ. Here, we assume that the gravity acts in the y = x2 direction, hence the forceis applied onto the second component of fi. Finally, Ri denotes the Richardson number.

As can be seen in the above equations, the continuity equation is not an evolution equation anymoreas in the case of compressible fluids. This means that mass conservation becomes like an additionalconstraint for the momentum conservation equations. This requires extra attention when theequations are solved numerically. For time-dependent flows a common way to solve the discreteequations is the so-called projection or pressure correction method. Sometimes this method and itsgeneralisations are also called splitting methods. A short description of this method is given next.

Let us discretise the above equations using an explicit scheme for time derivatives (explicit Euler)

Un+1 − Un∆t

+N(Un)Un +GPn+1 = f(tn) , (4)

DUn+1 = 0 , (5)

where N(U)U denotes the advective and viscous terms, GP the pressure gradient, ∆t the time stepand f(t) the forcing terms including the boundary conditions. Further, D stands for divergenceoperator. Note that the pressure term is discretized using the values at the time step n + 1. Thereason for this will become clear later on. Applying the projection method to the set of equations

Page 2: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 2

above, one can rewrite them as follows. In the prediction step an intermediate flow field U∗ isintroduced which does not necessarily satisfy the continuity equation,

U∗ − Un∆t

+N(Un)Un = f(tn) . (6)

A correction step is then introduced in order to correct for the continuity equation,

Un+1 − U∗

∆t+GPn+1 = 0 . (7)

Applying the divergence operator D to equation (7) and using the divergence-free condition (5),one can derive the following Poisson equation for the pressure,

DGPn+1 = ∆Pn+1 =1

∆t(DU∗) , (8)

using the symbol ∆ for the Laplace operator. The computed pressure from this step can be insertedin equation (7) to obtain Un+1,

Un+1 = U∗ −∆tGPn+1 . (9)

As will be discussed later, in equation (8) homogeneous Neumann boundary conditions are em-ployed. Note that the pressure is only determined up to an additive constant (only pressurederivatives enter the evolution equations). This means that the pressure may be set explicitly inone point of the domain to avoid singular expressions.

The solution of the scalar transport equation (3) is simpler than the momentum equations, as thescalar θ does not need to sastisfy the divergence-free condition. Therefore, the integration can bedone in a straight-forward way using explicit time integration (velocity field from the previousetime step).

2 Simulation code

Your task for this project is to develop a simulation programme that can solve the Navier–Stokesequations in a rectangular domain. This code should be written in MATLAB, based on the tem-plates given on the course homepage and in Appendix B (SG2212 template.m, DD template.m,avg template.m). To summarise, the features of the code are:

• Incompressible Navier-Stokes plus scalar equations (Boussinesq Approximation; only for PhDstudents)

• Second-order finite difference on a staggered grid

• Explicit Euler time integration for both advection and viscous terms

• Sparse matrices for the Poisson equation for the pressure correction

• Dirichlet and Neumann boundary conditions on a rectangular domain in two dimensions (2D)

Page 3: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 3

As this code is mainly used for educational purposes demonstrating the various concepts used inCFD, the complexity of the numerical method is intentionally kept on a low level. Therefore, anumber of features common in CFD software are not treated in the code:

• 3D formulation and implicit time stepping for viscous terms

• CFL condition for time stepping

• Higher order time integration methods

• Higher order spatial discretisation

• more efficient solution strategies, e.g. using a Cholesky decomposition

• More complex geometries, multiblock distributions, mappings etc.

In order to demonstrate the capabilities of your code we will consider two physical flow cases whichare introduced in the following sections 3 and 4. A detailed description of the numerical methodand its implementation is given in the Appendix.

3 Task 1: Lid-driven cavity (all course participants)

Consider the incompressible flow in a two-dimensional rectangular domain with side length lx andly. The side and lower walls are all solid and still, requiring no-slip boundary conditions. The topwall is moved with a constant speed u = 1 in the positive x-direction. This flow case is a commontest problem and usually called a lid-driven cavity. A sketch is given in Figure 1.

lx

ly

u=0, v=0

u=1, v=0

u=0,

v=

0

u=0,

v=

0

Figure 1: Sketch of the lid-driven cavity. The moving top wall is indicated in red.

Page 4: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 4

The mass and momentum conservation equations in non-dimensional form can be written as

∂u

∂x+∂v

∂y= 0 , (10)

∂u

∂t+∂P

∂x= −∂(u2)

∂x− ∂(uv)

∂y+

1Re

(∂2u

∂x2+∂2u

∂y2) , (11)

∂v

∂t+∂P

∂y= −∂(uv)

∂x− ∂(v2)

∂y+

1Re

(∂2v

∂x2+∂2v

∂y2) , (12)

with associated boundary conditions

x = 0 : u = v = 0 (13)x = lx : u = v = 0 (14)y = 0 : u = v = 0 (15)y = ly : u = 1, v = 0. (16)

You can optionally include also the advection of a passive scalar, governed by

∂θ

∂t= −∂(uθ)

∂x− ∂(vθ)

∂y+

1Pe

(∂2θ

∂x2+∂2θ

∂y2) , (17)

with Pe = Re · Pr. Choose Pr = 0.71 which is a good approximation for air. The boundaryconditions for the temperatur θ are

x = 0 : ∂θ/∂x = 0 (adiabatic) (18)x = lx : ∂θ/∂x = 0 (adiabatic) (19)y = 0 : θ = 0 (20)y = ly : θ = 1 . (21)

Initial conditions are at t = 0 non-moving fluid, i.e. u(t = 0) = v(t = 0) = 0. For the scalar, assumea linear profile in the vertical direction, i.e. θ(t = 0) = y/ly.

Your task is to write a Matlab code which solves the Navier–Stokes equations for the flow casedescribed above using the projection method on a staggered grid. The implementation of the scalarequation is only compulsive for PhD students. Run your code for cases given below (A-C).

A) Run the code for Re = 10, lx = ly = 1. Use a total of Nx = Ny = 30 grid cells and a timestep ∆t = 0.001. The flow will be stationary for t > 2.

For low values of Re, one gets a flow field which is symmetric in the x-direction, see Figure 2.

B) Run the code for Re = 100, lx = ly = 1, Nx = Ny = 50, ∆t = 0.001. The flow will bestationary for t > 10.

For moderate values of Re (≈ 100) the flow becomes asymmetric due to action of inertia, butit is still steady, see Figures 3. This can be clearly seen by means of a time series recorded inthe middle of the domain, see Fig. 5.

Page 5: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 5

C) (optional) Run the code for Re = 8000 or even higher Re, lx = ly = 1, Nx = Ny = 100,∆t = 0.001.

High values of Re lead to unsteady flow patterns (Re > 7500). Note also that increasingthe Reynolds number will give rise to thinner shear layers, which require more grid points toproperly resolve them. You can experiment with the combinations Re, Nx, Ny and ∆t, andobserve how the results (and stability) are affected.

You should deliver the Matlab code and a report with plots illustrating the flow field for the two(three) cases above. In order to give you an idea of how the flow is developping, consider Fig. 2 forcase A (Re = 10), Fig. 3 for case B (Re = 100) and Fig. 4 for case C (Re = 8000).

Figure 2: Simulation results for the lid-driven cavity, case A (Re = 10). Velocity field (left) andtemperature field (right) at t = 20. The colour scale ranges from 0 (blue) to 1 (red).

Figure 3: Simulation results for the lid-driven cavity, case B (Re = 100). Velocity field (left) andtemperature field (right) at t = 20. The colour scale ranges from 0 (blue) to 1 (red).

A detailed description of different steps of the algorithm and the boundary conditions is given inthe Appendix.

Page 6: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 6

Figure 4: Simulation results for the lid-driven cavity, case C (Re = 8000). Velocity field (left) andtemperature field (right) at t = 20. The colour scale ranges from 0 (blue) to 1 (red).

t

u(t)

0 5 10 15 200

0.05

0.1

0.15

0.2

0.25

0.3

Figure 5: Simulation results for the lid-driven cavity, case B (Re = 100). Transient behaviour ofthe velocity U at a velocity probe located at (x, y) = (0.5, 0.5).

Page 7: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 7

4 Task 2: Rayleigh-Benard problem (only for PhD students)

The flow induced by small density variations due to temperature differences between two walls iscalled Rayleigh-Benard convection. The control parameter is the so-called Rayleigh number Rawhich describes the ratio of bouyancy to viscous forces acting on the flow.

Depending on Ra, various flow regimes can be studied, ranging from stable flow configuration forlow Ra, two-dimensional convection rolls (i.e. large counter-rotating vortices, see below), hexagonalconvection cells, and finally for high Ra fully turbulent flow. The major relevance for us to studythis flow is that using comparably simple tools from linear stability analysis the changeover fromstable to unstable (i.e. amplifying) flow can be exactly determined. To numerically check thisso-called critical Rayleigh number Rac provides a very useful validation of the numerical code.

lx

ly

u=0, v=0, !=!B

u=0, v=0, !=!T

u=0,

v=

0, !

x=0

u=0,

v=

0, !

x=0

Figure 6: Close cavity with non-isothermal walls.

If the flow field is subjected to a temperature gradient between the two walls, density variationin the flow may be generated. These density variations, due to buoyancy forces, induce motionin the fluid. The corresponding force in the momentum equations can be modelled by means ofthe Boussinesq approximation. In order to tackle this flow problem, the governing equations (1)-(2) are thus coupled to the temperature equation (3) using the forcing term f2. Then, a slightlydifferent non-dimensionalisation has to be employed, essentially based on a convective velocity scale.The only non-dimensional numbers in the equations are the Rayleigh number Ra and the Prandtlnumber Pr. For a two-dimensional flow the final non-dimensional equations can be written as

∂u

∂x+∂v

∂y= 0 , (22)

∂u

∂t+∂P

∂x= −∂(u2)

∂x− ∂(uv)

∂y+

1Pr

(∂2u

∂x2+∂2u

∂y2

), (23)

∂v

∂t+∂P

∂y= −∂(uv)

∂x− ∂(v2)

∂y+

1Pr

(∂2v

∂x2+∂2v

∂y2

)+ f2 , (24)

∂θ

∂t= −∂(uθ)

∂x− ∂(vθ)

∂y+

1Pr

(∂2θ

∂x2+∂2θ

∂y2

). (25)

(26)

Page 8: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 8

The forcing in the normal direction, caused by buoyancy forces, is f2 = RaPrθ.

The original formulation of the Rayleigh-Benard convection problem is considered as the flowbetween two infinte parallel walls, see the sketch in Fig. 7. However, for the present project, weconsider a two-dimensional cavity where the top and bottom walls are kept at different temperaturesand the side-walls are assumed to be adiabatic ( ∂θ∂n = 0). A sketch of the geometry is given in figure6. Here, the boundary conditions are

x = 0 : u = v = 0,∂θ

∂x= 0 , (27)

x = lx : u = v = 0,∂θ

∂x= 0 , (28)

y = 0 : u = v = 0, θ = θB , (29)y = ly : u = v = 0, θ = θT . (30)

Initial conditions are at t = 0 non-moving fluid, i.e. u(t = 0) = v(t = 0) = 0. For the scalar, assumea linear profile in the vertical direction,

θ(x, y, t = 0) = θB +y

ly(θT − θB) . (31)

For cases where θT > θB, the density is decreasing with increasing height. This corresponds to astate with is called stable stratification, which means that the flow is stable and all disturbances willdecay eventually. However, if θT < θB, corresponding to unstable stratification, for large enoughvalues of Ra the flow becomes unstable. A stability diagram for this case is shown in Fig. 7. Itcan be seen that the first instability appears for Rac = 1708 with a wavenumber Kc = 3.12, whichcorresponds to a wavelength of λc = 2.01.

Your task is to include the forcing f2 and the energy equation to the code developed in Task 1 andrun it for cases given below.Choose the Prandtl number Pr = 0.71, the box size lx = 10, ly = 1, and the resolution Nx = 200,Ny = 20. The domain is thus elongated in the x-direction, imitating an infinite domain. As initialconditions random noise of moderate amplitude (±0.1(θB − θT )) should be used in order to triggerthe instability.

A) Run the code for Ra = 100, 1000, 5000, θT = 1 and θB = 0.

These parameters correspond to stable flow. You should observe that initial disturbances willdecay due to viscosity.

B) Run the code for θT = 0 and θB = 1.

Here, if the value of Rayleigh number is large enough (Ra > 1708) flow instability will beobserved. Run the code for different values of Ra and try to find “experimentally” the criticalvalue Rac. To determine the stability of a specifc run, consider the time evolution of a probein the flow, see Fig. 8. If you observe exponential growth (solid line in Fig. 8), you are in theunstable regime, otherwise the flow is stable.

the

Page 9: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 9

! h

"="B

"="T

Stable (σ < 0)

Unstable (σ > 0)

← Neutral curve (σ =0)

← (1708,3.12)

Ra

K

1000 2000 3000 4000 5000 6000 7000 8000

1

2

3

4

5

6

7

8

Figure 7: Top: Sketch of the flow structure (convection cells). Bottom: Stable and unstable(shaded) regions for Rayleigh-Benard problem. Here, λ = 2π/K is the wavelength of the unstableperturbation. The critical Rayleigh number is Rac = 1708 with associated spatial wavenumberK = 2π/λc = 3.12.

t

u(x=

5,y=

0.5,

t)

0 5 10 15 2010

−4

10−3

10−2

Ra=1715Ra=1700

Figure 8: Temporal evolution of the probe signals for two Rayleigh numbers close to the neu-trally stable state (Rac = 1708). It can clearly be seen that the supercritical trajectory leads toexponential growth, whereas the subcritical case eventually will exponetially decay.

Page 10: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 10

Figure 9: Stationary flow patterns for large times corresponding to Ra = 1700, Ra = 1715, Ra =2700 and Ra = 50000 (from top to bottom). Both the velocity distribution and the temperaturefield are shown for each Rayleigh number.

Page 11: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 11

A Solution procedure and implementation

A.1 Grid

In order to avoid spurious checkerboard solution the equations are discretized on a staggered grid.Figure 10 shows the numerical domain where the pressure p is defined in cell centres and thevelocities u and v are defined in the centre of the vertical and horizontal cell faces, respectively.Table 1 gives the number of unknowns for each of the flow variables to solve for. Here, nx and ny

Table 1: Resolution for the various solution variables.

Variable Interiour resolution Boundary conditions includedP nx× ny (nx+ 2)× (ny + 2)U (nx− 1)× ny (nx+ 1)× (ny + 2)V nx× (ny − 1) (nx+ 2)× (ny + 1)

are the number of cells in the x and y directions, respectively. The coordinates of the grid pointsare given as

Xi = ilxnx

, i = 0, · · · , nx , (32)

Yj = jlyny

, j = 0, · · · , ny , (33)

where lx and ly are the lengths in x and y directions. Note that number of grid points (includingthe boundary points) is nx+ 1 and ny + 1, respectively.

A.2 Boundary conditions

A.2.1 Velocity

Boundary conditions for both velocity components are given all around the rectangular domain.In the following, these vectors are denoted US for U at the lower boundary (south), VW for Von the left boundary (west), etc. Thus, on each side a total of (nx + 1) or (ny + 1) boundaryvalues are specified on the cell corners. The Dirichlet boundary condition for U on the left and theright boundaries of computational domain can be directly applied as the velocity nodes lie on thoseboundaries, see Fig. 10. The same is valid for V on the top and the bottom boundaries. However,the boundary conditions for U on top and bottom boundaries should be imposed by chosing thecorrect values for dummy cells (cells outside the domain), i.e.,

Ui+ 12,0 = 2US

i+12

− Ui+ 12,1 . (34)

This expression corresponds to taking the average between the interiour and exteriour points atindex i+ 1

2 . Furthermore, linear interpolation can be used to go from USi+1

2

to USi , etc. Similarly

Page 12: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 12

i=0 1 nx nx+1

ny+1

ny

1

j=0

puv

WES

T

NORTH

EAST

SOUTH

Figure 10: Sketch of the staggered grid. Circles are pressure nodes, squares U -velocity, and tri-angles V -velocity. Filled symbols corresond to interiour points, whereas open symbols representthe dummy values. The domain boundary is indicated by the thick blue line, on which also theboundary conditions are given.

for V on the left and the right boundaries

V0,j+ 12

= 2VWj+1

2

− V1,j+ 12. (35)

A.2.2 Pressure

As it was shown during the lecture, we have the choice to specify a Neumann boundary conditionfor pressure. In other words the normal derivative at the boundaries should be equal to zero forpressure, i.e.,

∂P

∂n= 0 . (36)

This means that the pressure values in the dummy cells have to be set equal to the value in theadjacent pressure node in the interiour of the domain. For example

P1,j − P0,j

hx= 0 ⇒ P0,j = P1,j . (37)

Page 13: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 133.2. FINITE-VOLUME DISCRETIZATIONS OF 2D NS 63

PSfrag replacementsx, x1

y, x2

z, x3

u, u1

v, u2

w, u3

x1

x2

x 0i

ri

(x 0

i , t)

ui

(x 0

i , t)

P(t = 0

)

xu1

u2 > u1

x1

x2

x3

x 0i

ui dtdx 0

i

dui dtri

(dt

)

dri

(dt

)

P1

P2

x1

x2

x3

R3

R2

R1

r3

r2

r1π2 + dϕ12

V (t)S (t)

V (t + ∆t)− V (t)S (t + ∆t)

un

V (t + ∆t)p

T0, U0

Tw

LT0

U0

Gradient fieldswi∂p∂xi

ui

Divergence free vectorfields // to boundaryLh

x1

x2

p0 > p1

p1

un

dSu · n∆t

xy

u0

p0

η = y√4νt

uu0

y = η√

4νt

tηy

ωz = ω(η)·u0√πνt

tL}δ

ω ≈ 0U →y, vx, u

LUδ

u0η = y√

νx/u0

f ′ = uu0

Blasius profileδ∗

xSeparation point⇐= Pressure force

xy

luT

xy

dxdy

− dxdl = (dx, dy)

n dl = (dy,− dx)i− 1, j + 1

i, j + 1i + 1, j + 1

cc′

bb′

i− 1, ji + 1, j

i, j

Aabcd

dd′

aa′

i− 1, j − 1i, j − 1

i + 1, j − 1j

ii + 1ui,j

vi,j

pi,j

pi,j

vi,j+1/2

vi,j−1/2

ui−1/2,j

i− 12 i i + 1

2 i + 1 i + 32

j + 12

j

j − 12

j − 1

PSfrag replacementsx, x1

y, x2

z, x3

u, u1

v, u2

w, u3

x1

x2

x 0i

ri

(x 0

i , t)

ui

(x 0

i , t)

P(t = 0

)

xu1

u2 > u1

x1

x2

x3

x 0i

ui dtdx 0

i

dui dtri

(dt

)

dri

(dt

)

P1

P2

x1

x2

x3

R3

R2

R1

r3

r2

r1π2 + dϕ12

V (t)S (t)

V (t + ∆t)− V (t)S (t + ∆t)

un

V (t + ∆t)p

T0, U0

Tw

LT0

U0

Gradient fieldswi∂p∂xi

ui

Divergence free vectorfields // to boundaryLh

x1

x2

p0 > p1

p1

un

dSu · n∆t

xy

u0

p0

η = y√4νt

uu0

y = η√

4νt

tηy

ωz = ω(η)·u0√πνt

tL}δ

ω ≈ 0U →y, vx, u

LUδ

u0η = y√

νx/u0

f ′ = uu0

Blasius profileδ∗

xSeparation point⇐= Pressure force

xy

luT

xy

dxdy

− dxdl = (dx, dy)

n dl = (dy,− dx)i− 1, j + 1

i, j + 1i + 1, j + 1

cc′

bb′

i− 1, ji + 1, j

i, jAabcd

dd′

aa′

i− 1, j − 1i, j − 1

i + 1, j − 1j

ii + 1ui,j

vi,j

pi,j

pi,j

vi,j+1/2

vi,j−1/2

ui−1/2,j

i− 12

ii + 1

2

i + 1i + 3

2j + 1

2

jj − 1

2

j − 1control volume for divergence condition.

PSfrag replacementsx, x1

y, x2

z, x3

u, u1

v, u2

w, u3

x1

x2

x 0i

ri

(x 0

i , t)

ui

(x 0

i , t)

P(t = 0

)

xu1

u2 > u1

x1

x2

x3

x 0i

ui dtdx 0

i

dui dtri

(dt

)

dri

(dt

)

P1

P2

x1

x2

x3

R3

R2

R1

r3

r2

r1π2 + dϕ12

V (t)S (t)

V (t + ∆t)− V (t)S (t + ∆t)

un

V (t + ∆t)p

T0, U0

Tw

LT0

U0

Gradient fieldswi∂p∂xi

ui

Divergence free vectorfields // to boundaryLh

x1

x2

p0 > p1

p1

un

dSu · n∆t

xy

u0

p0

η = y√4νt

uu0

y = η√

4νt

tηy

ωz = ω(η)·u0√πνt

tL}δ

ω ≈ 0U →y, vx, u

LUδ

u0η = y√

νx/u0

f ′ = uu0

Blasius profileδ∗

xSeparation point⇐= Pressure force

xy

luT

xy

dxdy

− dxdl = (dx, dy)

n dl = (dy,− dx)i− 1, j + 1

i, j + 1i + 1, j + 1

cc′

bb′

i− 1, ji + 1, j

i, j

Aabcd

dd′

aa′

i− 1, j − 1i, j − 1

i + 1, j − 1j

ii + 1ui,j

vi,j

pi,j

pi,j

vi,j+1/2

vi,j−1/2

ui−1/2,j

i− 12

ii + 1

2

i + 1i + 3

2j + 1

2

jj − 1

2

j − 1control volume for divergence condition.

control volume for streamwise momentum equation (u) .

PSfrag replacementsx, x1

y, x2

z, x3

u, u1

v, u2

w, u3

x1

x2

x 0i

ri

(x 0

i , t)

ui

(x 0

i , t)

P(t = 0

)

xu1

u2 > u1

x1

x2

x3

x 0i

ui dtdx 0

i

dui dtri

(dt

)

dri

(dt

)

P1

P2

x1

x2

x3

R3

R2

R1

r3

r2

r1π2 + dϕ12

V (t)S (t)

V (t + ∆t)− V (t)S (t + ∆t)

un

V (t + ∆t)p

T0, U0

Tw

LT0

U0

Gradient fieldswi∂p∂xi

ui

Divergence free vectorfields // to boundaryLh

x1

x2

p0 > p1

p1

un

dSu · n∆t

xy

u0

p0

η = y√4νt

uu0

y = η√

4νt

tηy

ωz = ω(η)·u0√πνt

tL}δ

ω ≈ 0U →y, vx, u

LUδ

u0η = y√

νx/u0

f ′ = uu0

Blasius profileδ∗

xSeparation point⇐= Pressure force

xy

luT

xy

dxdy

− dxdl = (dx, dy)

n dl = (dy,− dx)i− 1, j + 1

i, j + 1i + 1, j + 1

cc′

bb′

i− 1, ji + 1, j

i, jAabcd

dd′

aa′

i− 1, j − 1i, j − 1

i + 1, j − 1j

ii + 1ui,j

vi,j

pi,j

pi,j

vi,j+1/2

vi,j−1/2

ui−1/2,j

i− 12

ii + 1

2

i + 1i + 3

2j + 1

2

jj − 1

2

j − 1control volume for divergence condition.

control volume for streamwise momentum equation (u) .control volume for normal momentum equation (v) .

Figure 3.4: Cartesian finite-volume grid where the velocity components and the pressure uses staggeredgrids.

which satisfies the divergence constraint. If it is input into the equation for u and v we find the expression

dg

dt+

8Re · ∆x2

g = 0 ⇒ g = e−8t

Re·∆x2

Thus we have a spurious solution consisting of checkerboard modes which are damped slowly for velocityand constant in time for the pressure. This mode will corrupt any true numerical solution and yields thisdiscretization unusable as is. These modes are a result of the very weak coupling between nearby finitevolumes or grid points, and can be avoided if they are coupled by one sided differences or if they are dampedwith some type of artificial viscosity.

Staggered cartesian grid

To eliminate the problem with spurious checkerboard modes, we can use a staggered grid as in figure 3.4,where the control volumes for the streamwise, spanwise and pressure are different.

The control volume for the continuity equation is centered abound the pressure point and the discretiza-tion becomes

(ui+ 1

2 ,j − ui− 12 ,j

)∆y +

(vi,j+ 1

2− vi,j− 1

2

)∆x = 0

orui+ 1

2 ,j − ui− 12 ,j

∆x+

vi,j+ 12− vi,j− 1

2

∆y= 0

The control volume for the streamwise velocity is centered around the streamwise velocity point andthe discretization becomes

∂ui+1/2,j

∂t+

u2i+1,j − u2

i,j

∆x+

(uv)i+1/2,j+1/2 − (uv)i+1/2,j−1/2

∆y+

pi+1,j − pi,j

∆x−

1Re

ui+3/2,j − 2ui+1/2,j + ui−1/2,j

∆x2− 1

Re

ui+1/2,j+1 − 2ui+1/2,j + ui+1/2,j−1

∆y2= 0

Figure 11: Sketch of the staggered grid. Hollow symbols indicate dummy cells situated outside thecomputational domain.

Consequently the discretisation of the Laplace operator at nodes (1, j) will be

∇2P1,j =P2,j − P1,j

h2x

+P1,j+1 − 2P1,j + P1,j−1

h2y

, for j = 2, · · · , ny − 1. (38)

A.3 Data structure

All the variables are stored as a matrix. Note that the first index in MATLAB is the row and thesecond index the column, which means that the direction of increasing x is from top to bottom ofthe matrices. Similarly, increasing the y direction is from left to right in the matrix. Therefore,the storage of variables in the matrices corresponds to the transpose of the “physical” domain.

We introduce matrices U and V which only contain the unknown velocity values at inner cells,and not the (known) boundary values. Their sizes are for the matrix U containing the u velocity:(nx− 1)× ny. Similarly, V containing the v velocity: nx× (ny − 1).

At t = 0 they can be initiated with zeros (i.e. fluid at rest) in MATLAB as

U=zeros(nx-1,ny);

Page 14: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 14

V=zeros(nx,ny-1);

To perform central difference over the inner points, we need to include the boundary points in U andV. These extended marices are called Ue and Ve. They can be created by adding the approperiaterows and columns to the U and V matrices. For example for the u velocity this is done as follows

1) Add vectors uE and uW containig boundary values at right and left boundaries of the physicaldomain, respectively, (all transposed in MATLAB)

In MATLAB:

Ue=[uW ; U ; uE];

Extrapolation

Extrapolation

Figure 12: Boundary condition treatment of velocity

2) Introduce dummy cells with values which give the correct boundary conditions on the topand bottom boundaries of the physical domain. The boundary values are stored in vectorsuN and uS as described above.

In MATLAB:

Ue=[2uS’-Ue(:,1) Ue 2uN’-Ue(:,end)];

The matrix Ve is build in similar way. Then, size of the new matrices will be

Ue: (nx+ 1)× (ny + 2)Ve: (nx+ 2)× (ny + 1)

The advective (non-linear) terms are calculated using the values of the velocity field on the bound-aries of the control volumes which are different from the locations the discrete velocity field isdefined. Therefore, we introduce matrices which contain an averaged value of u and v on theboundaries of the control volumes. For that Ue and Ve should be averaged in x or y directiondepending on the term to be evaluated. Here, we define the averaging function avg( ) such that

Page 15: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 15

[avg(f)]i =12

(fi−1 + fi) . (39)

Note that the length of the resulting vector avg(f) is one element less than the length of f .Furthermore, avg(f) can be applied in both the x- and y-directions. In the example below, thefunction makes the averaging in either x or y direction.

In MATLAB:

function B=avg(A,idim)if(idim==1)

B=1/2 [ A(2:end,:) + A(1:end-1,:) ];elseif(idim==2)

B=1/2 [ A(:,2:end) + A(:,1:end-1) ];end

Applying this function to average the u velocity in the y direction can be achieved as follows inMATLAB:

Ua=avg(Ue,2)

After averaging the size of the matrix Ua will be (nx+ 1)× (ny + 1).

1/2 1/2

1/2

1/2

Figure 13: Averaging of velocities.

A.4 Construction of Laplace (Lp) operator

One of the most crucial steps of the code is the implementation of the Laplace operator. Weneed to construct that in a efficient way. To save memory and gain speed when the equations

Page 16: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 16

are solved we make use of sparse matrix storage in MATLAB. This can be done in a smart butslightly complicated way in MATLAB. Let us first define the Laplace operator for a one-dimensionalcase. Using centeral finite differences second order, with Neumann boundary condition at the twoboundaries we can define a derivative matrix with the following structure,

D2

=1h2

−1 11 −2 1

. . . . . . . . .1 −1

. (40)

This is implemented in function DD(n,h) (available as template).

To extended this operator for a two-dimensional case, one can use the kron operator in MATLABto perform a Kronecker tensor product,

kron(A,B) =

A(1, 1) ·B A(1, 2) ·B · · ·A(2, 1) ·B A(2, 2) ·B · · ·

......

. . .

. (41)

Then one can compute the derivative matrix to compute Uxx = LP · U by choosing

A = Iny×ny, B = D

2,

and Uyy by choosing

A = D2, B = I

nx×nx .

In MATLAB:

Lp=kron(speye(ny),DD(nx,hx))+...

The actual level of the pressure is not determined since only the pressure gradient enters theNavier–Stokes equations, i.e. both P + const. and P satisfy the Poisson equation. Therefore, oneneeds to fix the value of the pressure at one node, e.g. P1,1 = 0. This is achived by the followingmodification of the equation system

Lp(1, :) = 0, Lp(1, 1) = 1, R(1) = 0 .

Ignoring this gives singular matrices! This is of course a general feature. For any incompressibleflow, the pressure is only determined up to a constant.

A.5 Outline of required steps

The iterations start at t = tn with Un, V n and march towards t = tn+1 = tn + ∆t.

Page 17: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 17

1. Compute non-linear advective terms, namely NLxn, NLxn :

NLxn = −((Un)2)x − (UnV n)y (42)

NLyn = −(UnV n)x − ((V n)2)y. (43)

The derivatives in the terms NLx and NLy are computed as differences between the functionvalues at the pressure nodes (see Fig. 11) and therefore the derivatives should be calculatedbased on the average of the velocity values at neighboring velocity nodes. For example for(UnV n)x we proceed as follows:

((UnV n)x)i,j+ 12

=1hx

[Ui+ 1

2,j+ 1

2Vi+ 1

2,j+ 1

2− Ui− 1

2,j+ 1

2Vi− 1

2,j+ 1

2

](44)

where Ui+ 12,j+ 1

2=

12

[Ui+ 1

2,j+1 + Ui+ 1

2,j

](45)

and Vi+ 12,j+ 1

2=

12

[Vi+1,j+ 1

2+ Vi,j+ 1

2

]. (46)

In MATLAB:

Ua=avg(Ue,2);Va=avg(Ve,1);UVx = 1/hx * diff( Ua.*Va, 1 , 1);

2. Compute viscous diffusion terms, namely DIFFnx, DIFFny

DIFFnx =1Re

[Unxx + Unyy] (47)

DIFFny =1Re

[V nxx + V n

yy]. (48)

For example

[DIFFnx]i+ 12,j =

1Re

(Ui− 1

2,j − 2Ui+ 1

2,j + Ui+ 3

2,j

h2x

+Ui+ 1

2,j−1 − 2Ui+ 1

2,j + Ui+ 1

2,j+1

h2y

)(49)

use the extended grid and store only interior points.

In MATLAB:

viscu= diff( Ue(:,2:end-1),2,1 )/hx^2 + diff( Ue(2:end-1,:),2,2 )/hy^2;

The command diff( ) is a built-in MATLAB operator which takes the difference betweenadjacent components. The first argument is the matrix to operate on, the second is the orderof the difference (here 2 for the second derivative) and the third is specifying along whichmatrix dimension the derivative is taken (1 for x-direction and 2 for y-direction).

3. Compute forcing terms if required, Fnx , Fny .

Page 18: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 18

4. Advance the solution to an intermediate time level (U∗ and V ∗) using explicit Euler

U∗ − Un∆t

= NLnx +DIFFnx + Fnx , (50)

V ∗ − V n

∆t= NLny +DIFFny + Fny . (51)

5. Solve the Poisson equation for the pressure

∆Pn+1 =1

∆t(DxU

∗ +DyV∗) . (52)

Now, we need to solve the Poisson equation with the homogeneous Neumann conditions forPn+1. Construct the disctretised Laplace operator Lp (for details on the structure of theoperator Lp see Section A.4) and evaluate DxU

∗+DyV∗ with central difference second order.

LpPn+1 = R with R =

1∆t

(DxU∗ +DyV

∗). (53)

⇒ Pn+1 = Lp−1R . (54)

Here, Pn+1 and R are of size nx× ny, containing the unkown pressure and the r.h.s. at thecell centres, respectively.

In MATLAB:

R=diff([uW ; U ; uE])/hx + ...;R=reshape(R,nx*ny,1);P=Lp\R;P=reshape(P,nx,ny);

6. Compute the velocity field at time step n+ 1 according to

Un+1 = U∗ −∆tGPn+1 . (55)

Page 19: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 19

B Code

B.1 SG2212 template.m

% Navier-Stokes solver,% adapted for course SG2212% KTH Mechanics%% Depends on avg.m and DD.m%

clear all

%------------------------------------------

lid_driven_cavity=1;

if (lid_driven_cavity==1)% Parameters for test case I: Lid-driven cavity% The Richardson number is zero, i.e. passive scalar.

Pr = 0.71; % Prandtl numberRe = 100.; % Reynolds numberRi = 0.; % Richardson number

dt = 0.001; % time stepTf = 20; % final timeLx = 1; % width of boxLy = 1; % height of boxNx = 50; % number of cells in xNy = 50; % number of cells in yig = 200; % number of iterations between output

% Boundary and initial conditions:Utop = 1.;% IF TEMPERATURE: Tbottom = 1.; Ttop = 0.;% IF TEMPERATURE: namp = 0.;

else% Parameters for test case II: Rayleigh-Bnard convection% The DNS will be stable for Ra=1705, and unstable for Ra=1715% (Theoretical limit for pure sinusoidal waves% with L=2.01h: Ra=1708)% Note the alternative scaling for convection problems.

Pr = 0.71; % Prandtl number

Page 20: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 20

Ra = 2715; % Rayleigh number

Re = 1./Pr; % Reynolds numberRi = Ra*Pr; % Richardson number

dt = 0.0005; % time stepTf = 20; % final timeLx = 10.; % width of boxLy = 1; % height of boxNx = 200; % number of cells in xNy = 20; % number of cells in yig = 200; % number of iterations between output

% Boundary and initial conditions:Utop = 0.;% IF TEMPERATURE: Tbottom = 1.; Ttop = 0.;namp = 0.1;

end

%------------------------------------------

% Number of iterationsNit = ...% Spatial grid: Location of cornersx = linspace( ... );y = linspace( ... );% Grid spacing

hx = ...hy = ...% Boundary conditions:uN = x*0+Utop; vN = avg(x,2)*0;uS = ... vS = ...uW = ... vW = ...uE = ... vE = ...tN = ... tS = ...% Initial conditionsU = zeros(Nx-1,Ny); V = zeros(Nx,Ny-1);% linear profile for T with random noise% IF TEMPERATURE: T = ... + namp*rand(Nx,Ny)% Time seriestser = [];Tser = [];

Page 21: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 21

%-----------------------------------------

% Compute system matrices for pressure% First set homogeneous Neumann condition all around% Laplace operator on cell centres: Fxx + FyyLp = kron(speye(Ny), ... ) + kron( ... ,speye(Nx));% Set one Dirichlet value to fix pressure in that pointLp(1,:) = ... ; Lp(1,1) = ... ;

%-----------------------------------------

% Progress barfprintf(...

’[ | | | | ]\n’)

%-----------------------------------------

% Main loop over iterations

for k = 1:Nit

% include all boundary points for u and v (linear extrapolation% for ghost cells) into extended array (Ue,Ve)Ue = ...Ve = ...

% averaged (Ua,Va) and differentiated (Ud,Vd) of u and v on cornersUa = ...Ud = ...Va = ...Vd = ...

% construct individual parts of nonlinear termsdUVdx = ...dUVdy = ...Ub = ...Vb = ...dU2dx = ...dV2dy = ...

% treat viscosity explicitlyviscu = ...viscv = ...

% buoyancy term

Page 22: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 22

% IF TEMPERATURE: fy = ...

% compose final nonlinear term + explicit viscous termsU = U + dt/Re*viscu - dt*(...);V = V + dt/Re*viscv - dt*(...) + % IF TEMPERATURE: dt*fy;

% pressure correction, Dirichlet P=0 at (1,1)rhs = diff( ... )/hx + diff( ... )/hy;rhs = reshape(rhs,Nx*Ny,1);rhs(1) = ...P = Lp\rhs;P = reshape(P,Nx,Ny);

% apply pressure correctionU = U - ...V = V - ...

% Temperature equation% IF TEMPERATURE: Te = ...% IF TEMPERATURE: Tu = ...% IF TEMPERATURE: Tv = ...% IF TEMPERATURE: H = ...% IF TEMPERATURE: T = T + dt*H;

%-----------------------------------------

% progress barif floor(51*k/Nit)>floor(51*(k-1)/Nit), fprintf(’.’), end

% plot solution if neededif k==1|floor(k/ig)==k/ig

% compute divergence on cell centresif (1==1)div = diff([uW;U;uE])/hx + diff([vS’ V vN’],1,2)/hy;

figure(1);clf; hold on;contourf(avg(x,2),avg(y,2),div’);colorbaraxis equal; axis([0 Lx 0 Ly]);title(sprintf(’divergence at t=%g’,k*dt))drawnow

end

% compute velocity on cell cornersUa = ...

Page 23: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 23

Va = ...Len = sqrt(Ua.^2+Va.^2+eps);

figure(2);clf;hold on;%contourf(avg(x,2),avg(y,2),P’);colorbarcontourf(x,y,sqrt(Ua.^2+Va.^2)’,20,’k-’);colorbarquiver(x,y,(Ua./Len)’,(Va./Len)’,.4,’k-’)axis equal; axis([0 Lx 0 Ly]);title(sprintf(’u at t=%g’,k*dt))drawnow

% IF TEMPERATURE: % compute temperature on cell corners% IF TEMPERATURE: Ta = ...

% IF TEMPERATURE: figure(3); clf; hold on;% IF TEMPERATURE: contourf(x,y,Ta’,20,’k-’);colorbar% IF TEMPERATURE: quiver(x,y,(Ua./Len)’,(Va./Len)’,.4,’k-’)% IF TEMPERATURE: axis equal; axis([0 Lx 0 Ly]);% IF TEMPERATURE: title(sprintf(’T at t=%g’,k*dt))% IF TEMPERATURE: drawnow

% Time historyif (1==1)figure(4); hold on;tser = [tser k*dt];Tser = [Tser Ue(ceil((Nx+1)/2),ceil((Ny+1)/2))];plot(tser,abs(Tser))title(sprintf(’Probe signal at x=%g, y=%g’,...

x(ceil((Nx+1)/2)),y(ceil((Ny+1)/2))))set(gca,’yscale’,’log’)xlabel(’time t’);ylabel(’u(t)’)

endend

endfprintf(’\n’)

%-----------------------------------------

Page 24: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 24

B.2 DD template.m

function A = DD(n,h)% DD(n,h)%% One-dimensional finite-difference derivative matrix% of size n times n for second derivative:% h^2 * f’’(x_j) = -f(x_j-1) + 2*f(x_j) - f(x_j+1)%% Homogeneous Neumann boundary conditions on the boundaries% are imposed, i.e.% f(x_0) = f(x_1)% if the wall lies between x_0 and x_1. This gives then% h^2 * f’’(x_j) = + f(x_0) - 2*f(x_1) + f(x_2)% = + f(x_1) - 2*f(x_1) + f(x_2)% = f(x_1) + f(x_2)%% For n=5 and h=1 the following structure is recovered:%% A =%% -1 1 0 0 0% 1 -2 1 0 0% 0 1 -2 1 0% 0 0 1 -2 1% 0 0 0 1 -1%% This function belongs to SG2212.m

A = spdiags( ... )’/h^2;

Page 25: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 25

B.3 avg template.m

function B = avg(A,idim)% AVG(A,idim)%% Averaging function to go from cell centres (pressure nodes)% to cell corners (velocity nodes) and vice versa.% avg acts on index idim; default is idim=1.%% This function belongs to SG2212.m

if nargin<2, idim = 1; end

if (idim==1)B = (A( ... , ... )+A( ... , ... ))/2;

elseif (idim==2)B = (A( ... , ... )+A( ... , ... ))/2;

elseerror(’avg(A,idim): idim must be 1 or 2’)

end

Page 26: Project SG2212 Development of a Navier-Stokes code as a

Computational Fluid Dynamics SG2212, Spring 2011 26

C Revision history

%------------% Version 1.00 3/3/2011%% Version 1.01 6/3/2011% . error in matrix for Laplace operator, eq. (39)% . error in equation (48)% Version 1.02 8/3/2011% . error in pressure constant% . missing Re in eq. (48)% . index in equations (33) and (34)% Version 1.03 9/3/2011% . text in section 1% . equation (48) rewritten% Version 1.04 10/3/2011% . initial conditions for the scalar given (new eq.31)%------------