OFTutorialSeries PDF
OFTutorialSeries PDF
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
Editorial board:
• Bahram Haddadi
• Christian Jordan Technische Universität Wien
• Michael Harasek Institute of Chemical, Environmental
& Bioscience Engineering
Compatibility:
• OpenFOAM® 7
• OpenFOAM® v1906
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
This book has been used as a basis for preparing a series of video lectures
on youtube by Jozsef Nagy (JKU Linz):
www.youtube.com/channel/UCjdgpuxuAxH9BqheyE82Vvw
(Search for: Jozsef Nagy OpenFOAM at youtube.com)
OpenFOAM® Basic Training
Preface
In this OpenFOAM® tutorial series, we have prepared fourteen case examples that are designed to
help users to learn the key utilities and features within OpenFOAM®, including mesh generation,
multiphase modeling, turbulence modeling, parallel processing and reaction modeling. The base
tutorial examples can be imported directly from the OpenFOAM® installation directory.
The tutorials should be primarily used for OpenFOAM® versions 7.0 and v1906, with differences in
the running procedure between v1906 and 7.0 highlighted in blue boxes. So, simply ignore the blue
boxes if you are running in version 7.0! The structure of each case example follow the below
general structure:
Background: an introduction about the key topics explored in the tutorial and the relevant CFD
theory
1. Pre-processing: instructions on how to set up the correct case structure for a given problem
using base case tutorials, with explanations on relevant dictionaries
2. Running simulation: instructions on running the solver and its associated commands
3. Post-processing: examining the results in OpenFOAM®’s post-processing application,
ParaView V5.6.0
OpenFOAM® Basic Training
Table of Contents
Appendix D: ParaView
Tutorial One
Basic Case Setup
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial One
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. What is CFD?
Computational fluid dynamics or CFD is the analysis of systems involving fluid flow,
heat transfer and associated phenomena such as chemical reactions by means of
computer-based simulation. The technique is very powerful and its application spans a
wide range of industrial and non-industrial areas.
Although CFD has lots of advantages, it is not yet at the level where it can be blindly
used without a working knowledge of the physics involved, and despite the increasing
speed of computation available, CFD has not yet matured to a level where it can be
used for real time computation. Numerical analyses require significant time to be set
up and performed. CFD is still an aid to other analysis and experimental tools like
wind tunnel testing, and is used in conjunction with them. So be careful!
We will be focusing on OpenFOAM®, which is a free, open source CFD code, written
in C++. In addition, its source code is accessible and modifiable by its users. So, you
can even develop your own OpenFOAM® solver if you wish to!
2. Workflow of CFD
A CFD procedure is structured around the numerical algorithms that can tackle fluid
flow problems, and the workflow mostly contains three main elements:
2.1. Pre-processing
heavily on the number of cells in the grid. In general, the larger the number of cells,
the better the solution accuracy. Optimal meshes are often non-uniform: finer in areas
where large variations occur from point to point and coarser in regions with relatively
little change.
2.2. Solver
There are at least four distinct streams of numerical solution techniques: finite
difference, finite element, spectral methods and finite volume. We will only focus on
the finite volume method, as it is central to the most well-established CFD solvers. In
outline, the finite volume method consists of the following steps:
The first step, the control volume integration, makes the finite volume method
different from all other CFD techniques. It makes sure that a general flow variable,
e.g. momentum or enthalpy, is conserved in each finite size cell. This clear
relationship between the numerical algorithm and the underlying conservation
principle makes finite volume method popular and much simpler to understand.
2.3. Post-processing
This is where you take a look at the results and visualize them so that you can see
what happens in your model. Typical elements of post-processing are:
There are several post-processing tools; fluent built-in post-processing tool, ensight
and TecPlot are some well-known commercial examples. There are also some open
source tools such as Paraview and SALOME.
3. icoFoam solver
icoFoam – elbow
Tutorial outline
Using icoFoam solver, simulate 75 s of flow in an elbow for the following GAMBIT®
meshes:
Objectives
• Basic case setup in OpenFOAM®
Data processing
Import your simulation to ParaView, extract data to make two diagrams (using
spreadsheet calculators) of pressure and velocity magnitude along a line between two
tubes, do the same for all three simulations.
OpenFOAM® Basic Training
Tutorial One
1. Pre-processing
$FOAM_TUTORIALS/incompressible/icoFoam/elbow
Note: The ‘$’ sign allows the tutorial to be extracted from the installation directory
of OpenFOAM® under the current system environment.
>fluentMeshToFoam elbow.msh
Note: the ‘>’ sign is not part of the command. It is only used to show that the
command should be typed inside a terminal.
If the mesh was created in mm and is converted using the mentioned command it will
convert the mesh with wrong dimensions, since all the units in OpenFOAM® are SI 1
Units. There are different flags included with most of OpenFOAM® tools, for
checking them use the flag -help after the command, e.g.:
>fluentMeshToFoam -help
The output gives an overview of available options of the tool and also a short
description on how to use it:
Usage: fluentMeshToFoam [OPTIONS] <Fluent mesh file>
options:
-2D <thickness> use when converting a 2-D mesh (applied before scale)
-case <dir> specify alternate case directory, default is the cwd
-fileHandler <handler>
override the fileHandler
-libs <(lib1 .. libN)>
pre-load libraries
-noFunctionObjects
do not execute functionObjects
-scale <factor> geometry scaling factor - default is 1
-writeSets write cell zones and patches as sets
-writeZones write cell zones as zones
-srcDoc display source code in browser
-doc display application documentation in browser
-help print the usage
The -scale flag is used for converting the mesh dimensions from other units to SI
units, e.g. if the mesh was created in mm it will be converted to meter by using -
scale 0.001 and if the flag is omitted, uses 1:
Note: If there are internal boundaries in the mesh, there is another tool,
fluent3DMeshToFoam. Using this tool, the internal boundaries will be kept during
conversion.
There are three main directories (0, constant, system) in each case foloder:
1.4.1. 0 directory
The 0 directory includes the initial conditions for running the simulation. In each file
in this folder the initial conditions for one property can be set. The files are named
after the property they are standing for, e.g. usually T file includes temperature initial
OpenFOAM® Basic Training
Tutorial One
conditions. In the elbow example there are only two files inside the 0 directory, p and
U. p stands for pressure and U stands for velocity. Checking p:
>nano 1 p
dimensions [0 2 -2 0 0 0 0];
internalField uniform 0;
boundaryField
{
wall-4
{
type zeroGradient;
}
velocity-inlet-5
{
type zeroGradient;
}
velocity-inlet-6
{
type zeroGradient;
}
pressure-outlet-7
{
type fixedValue;
value uniform 0;
}
wall-8
{
type zeroGradient;
}
frontAndBackPlanes
{
type empty;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
1
nano is a text editor used in Linux OS (for closing and saving: ctrl+x)
OpenFOAM® Basic Training
Tutorial One
Note: As you can see the p unit is not the pressure unit (Pa). It is due to the fact that
in incompressible solvers in OpenFOAM® p is defined as “reduced” pressure divided
by density.
Note: In the dimension matrix the first number represents mass (kilogram), the second
one the length (meter), the third one time (second), the forth one the temperature
(Kelvin), the fifth one the quantity (mole), the sixth one current (ampere) and the last
one luminous intensity (candela).
The internalField sets the initial field of a specific quantity in the solution
domain. There are two types: uniform and non-uniform. Uniform field assigns a
single value to all elements, whereas non-uniform field specifies a unique value to
each field element.
The type of each of our boundaries as well as the value of this quantity on the
boundaries is defined in the boundaryField. There are different types of boundary
conditions in OpenFOAM®:
- empty: It is for sides, which are vertical to the direction that is not going to be
considered (e.g. in 2D simulations these boundaries are vertical to the third
dimension). In this boundary type both of the sides vertical to one dimension
should be selected together and named as one boundary.
The U file has to be defined via three components (since velocity is a vector): first one
stands for the x component, second one for the y component, and the third one for the
z component. For this case setup the z component is always zero because it is a 2D
simulation and no calculations will be done in the z direction. The boundaries vertical
to z direction have been already set to empty.
number (unique face IDs) for this boundary (for the sake of space, the dictionary
headers will not be included in this scope any more):
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
6
(
wall-4
{
type wall;
inGroups List<word> 1(wall)
nFaces 100;
startFace 1300;
}
velocity-inlet-5
{
type patch;
nFaces 8;
startFace 1400;
}
…
frontAndBackPlanes
{
type empty;
inGroups List<word> 1(empty);
nFaces 1836;
startFace 1454;
}
)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
OpenFOAM® v1906: the inGroups does not have the type “List<word>” in the front
of the group name.
Comparing the boundary names with the ones set in GAMBIT®, they should be the
same. Starting cell number and also number of each face cells can also be checked
here.
Note: However, in terms of boundary type, empty boundary condition does not exist in
GAMBIT®. All the faces perpendicular to the direction which is not going to be
considered are defined as a new boundary with type wall. After converting the mesh
to OpenFOAM® mesh, modify that boundary in the file constant/polyMesh/ boundary,
and change its type from wall to empty, and also change inGroups from wall to
empty. In this case, after converting the mesh, the face frontAndBackPlanes
needs to be modified for both hex-mesh and finer hex-mesh.
By opening the transportProperties file, properties dimensions and also the property
value can be found and edited (in v1906 no dimensions are listed), e.g.:
nu [ 0 2 -1 0 0 0 0 ] 0.01;
nu is the fluid kinematic viscosity, which is 0.01 m2/s for this example.
- fvSchemes: The discretization scheme which is used for each term of the
equations are set in this file.
- fvSolution: Contains the settings to the coupling method of pressure and velocity,
the numerical methods, which are used for solving different quantities, and also
the final tolerance for convergence of that quantity.
- controlDict: The time from where simulation starts (startFrom), the time when
the simulation finishes (stopAt), the time step (deltaT), the data saving interval
(writeInterval), the saved data file format (writeFormat), the saved file
data precision (writePrecision), and also if changing the files during the run
can affect the run or not (runTimeModifiable) are set in this file.
Note: If the write format is ascii, then the simulation data which is written to the file
can be opened and read using any text editor. If the format is binary, the data will
be written in binary style and is not readable by text editors. The advantage of
binary over ascii is the smaller file size, and consequently faster conversion and
writing to disk, for big simulations.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
application icoFoam;
startFrom latestTime;
startTime 0;
stopAt endTime;
writeControl timeStep;
writeInterval 20;
purgeWrite 0;
writeFormat ascii;
writePrecision 6;
writeCompression off;
timeFormat general;
timePrecision 6;
runTimeModifiable true;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
OpenFOAM® Basic Training
Tutorial One
Note: This simulation continues from the last time step data which is saved
(latestTime). If there was no saved data it will start from start time (startTime),
which is zero in this case.
2. Running simulation
The simulation can be run by typing the solver’s name and executing it:
>icoFoam
Note: For running the simulation the solver command (e.g. icoFoam) should be
executed inside the copy of the tutorial main folder. For example: The command
should be executed in the elbow folder, if it was run at some subfolders or somewhere
else, the simulation will fail.
3. Post-processing
>foamToVTK
where VTK is the ParaView data format. This command should be also executed in
the case main directory, e.g. elbow. Here, ParaView is used as the post-processing
tool, for running it
>paraview &
Note: There is also another option to open the OpenFOAM® simulation results with
ParaView without converting them to VTK; Create an empty text file in the main case
directory, name it <someName>.foam (e.g. foam.foam), and execute the following
command. This method is good for fast evaluation of the data in the middle of the
simulation or with a decomposed case in parallel simulations:
Note: By putting & at the end of command, the command line will remain active and
ready for further inputs while that program is running.
The comparisons of all three case results and charts are shown below.
OpenFOAM® Basic Training
Tutorial One
Pressure and velocity for different meshes at t=75 s, along the arc shown
OpenFOAM® Basic Training
Tutorial One
The comparison plots are along the line between points A (54 0 0) at the small tube
entrance and B (60 60 0) at the large tube exit part (length units are in meter) for Tri-
mesh, for other two meshes created using GAMBIT® the points are A (22 -33 0) and
B (27 30 0).
Tri
Hex
Hex
Fine
Note: For extracting data over a line, the line should be defined in ParaView using
“Plot Over Line”, then the data over this line can be exported by choosing Save Data
from File menu in ParaView.
Tutorial Two
Built in Mesh
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Two
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. What is mesh?
The partial differential equations that describe fluid flow and heat transfer are the conservation
equations of mass, energy and momentum. However we are usually unable to solve them
analytically, except in very simple cases. This is when discretization comes in. The flow region is
broken up into smaller sub-regions, with the equations solved in each sub-region. One of the
methods used to solve the equations is the finite volume method, which we will cover in detail
below. The sub-regions are later on referred to as grid cells, with a collection of grid cells forming a
mesh.
𝜕𝜕(𝜌𝜌𝜌𝜌)
+ ∇ ∙ (𝜌𝜌𝜌𝜌𝒖𝒖) = ∇ ∙ (𝛤𝛤∇𝜑𝜑) + 𝑆𝑆𝜑𝜑
𝜕𝜕𝜕𝜕
Rate of change of Net rate of flow Rate of change Rate of change
φ inside fluid + of φ out of = of φ due to + of φ due to
element fluid element diffusion sources
As you can see, the transport equation is essentially a manifestation of conservation of a fluid flow
property within the problem domain.
The key step of the finite volume method is the integration of the transport equation over a three-
dimensional control volume (CV). At discrete places values are calculated on a meshed geometry.
The small volume which surrounds each node of the mesh is the grid cell.
In each grid cell, the volume integral of the divergence term is replaced by a surface integral, using
the Gauss divergence theorem. These terms are then evaluated as fluxes at the surfaces. This not
only ensures the conservation of fluxes entering and exiting the grid cell, but allows for easy
formulation of the balances on unstructured meshes.
In time-dependent problems, it is also necessary to integrate with respect to time t over a small
interval ∆𝑡𝑡 from, say, 𝑡𝑡 until 𝑡𝑡 + ∆𝑡𝑡. This yields the most general integrated form of the transport
equation.
𝜕𝜕
� �� 𝜌𝜌𝜌𝜌 𝑑𝑑𝑑𝑑� 𝑑𝑑𝑑𝑑 + � � 𝒏𝒏 ∙ (𝜌𝜌𝜌𝜌𝒖𝒖) 𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑
∆𝑡𝑡 𝜕𝜕𝜕𝜕 𝐶𝐶𝐶𝐶 ∆𝑡𝑡 𝐴𝐴
The mesh used in OpenFOAM® can be simple grid structures based on the Cartesian co-ordinate
system, or complex unstructured grid arrangement that can handle curvature and geometric
complexity. The mesh is generated using the in-house OpenFOAM® tool (blockMesh and
snappyHexMesh) or external software, such as GAMBIT®. In this tutorial, we are going to learn
how to use the blockMesh tool in OpenFOAM®. Refer to Tutorial Twelve for information on the
snappyHexMesh tool.
For this tutorial, we chose to run the sonicFoam solver, which is slightly more complicated than
icoFoam, as it analyses the flow of a compressible gas/fluid.
4. rhoPimpleFoam solver
rhoPimpleFoam – forwardStep
Tutorial outline
Using rhoPimpleFoam solver, simulate 10 s of flow over a forward step.
Objectives
• Understand blockMesh
• Define vertices via coordinates as well as surfaces and volumes via vertices.
Data processing
Import your simulation into ParaView, and examine the mesh and the results in detail.
OpenFOAM® Basic Training
Tutorial Two
1. Pre-processing
$FOAM_TUTORIALS/compressible/rhoPimpleFoam/laminar/forwardStep
OpenFOAM® v1906:
$FOAM_TUTORIALS/compressible/sonicFoam/laminar/forwardStep
Note: As it can be seen, the p unit is the same as the pressure unit (kg m-1 s-2), because
rhoPimpleFoam/sonicFoam is a compressible solver.
Note: Do not forget that, this example is a purely numeric example (you might have noticed this
from the pressure values).
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
OpenFOAM® Basic Training
Tutorial Two
In the thermoType, the models for calculating thermo physical properties of gas are set:
- mixture: Is the model which is used for the mixture, whether it is a pure mixture, a
homogeneous mixture, a reacting mixture or ….
- transport: Defines the used transport model. In this example a constant value is used.
- thermo: It defines the method for calculating heat capacities, e.g. in this example constant heat
capacities are used.
- equationOfState: Shows the relation which is used for the compressibility of gases. Here
ideal gas model is applied by selecting perfectGas.
- energy: This key word lets the solver decide which type of energy equation it should solve,
enthalpy or internal energy.
After defining the models for different thermos-physical properties of gas, the constants and
coefficients of each model are defined in the sub-dictionary mixture. E.g. molWeight shows the
molecular weight of gas, Cp stands for heat capacity, Hf is the heat of fusion, mu is the dynamic
viscosity and Pr shows the Prandtl number.
By opening the turbulenceProperties the appropriate turbulent mode can be set (in this case it is
laminar):
simulationType laminar;
>nano blockMeshDict
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
convertToMeters 1;
vertices
(
(0 0 -0.05)
(0.6 0 -0.05)
(0 0.2 -0.05)
(0.6 0.2 -0.05)
(3 0.2 -0.05)
(0 1 -0.05)
(0.6 1 -0.05)
(3 1 -0.05)
(0 0 0.05)
(0.6 0 0.05)
(0 0.2 0.05)
(0.6 0.2 0.05)
(3 0.2 0.05)
(0 1 0.05)
(0.6 1 0.05)
(3 1 0.05)
);
blocks
(
OpenFOAM® Basic Training
Tutorial Two
mergePatchPairs
(
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
As noted before units in OpenFOAM® are SI units. If the vertex coordinates differ from SI, they can
be converted with the convertToMeters command. The number in the front of
convertToMeters shows the constant, which should be multiplied with the dimensions to change
them to meter (SI unit of length). For example:
convertToMeters 0.001;
shows that the dimensions are in millimeter, and by multiplying them by 0.001 they are converted
into meters.
OpenFOAM® Basic Training
Tutorial Two
In the vertices part, the coordinates of the geometry vertices are defined, the vertices are stored
and numbered from zero, e.g. vertex (0 0 -0.05) is numbered zero, and vertex (0.6 1 -0.05)
points to number 6.
In the block part, blocks are defined. The array of numbers in front each block shows the block
building vertices, e.g. the first block is made of vertices (0 1 3 2 8 9 11 10).
After each block the mesh is defined in every direction. e.g. (25 10 1) shows that this block is
divided into:
- 25 parts in x direction
- 10 parts in y direction
- 1 part in z direction
As it was explained before, even for 2D simulations the mesh and geometry should be 3D, but with
one cell in the direction, which is not going to be solved, e.g. here number of cells in z direction is
one and it’s because of that it’s a 2D simulation in x-y plane.
In the boundary part each boundary is defined by the vertices it is made of, and also its type and
name are defined.
Note: For creating a face the vertices should be chosen clockwise when looking at the face from
inside of the geometry.
2. Running simulation
Before running the simulation the mesh has to be created. In the previous step the mesh and the
geometry data were set. For creating it the following command should be executed from the case
main directory (e.g. forwardStep):
>blockMesh
After that, the mesh is created in the constant/polyMesh folder. For running the simulation, type the
solver name form case directory and execute it:
>rhoPimpleFoam
3. Post-processing
The mesh is presented in the following way in ParaView, and you can easily see the three blocks,
which were created.
OpenFOAM® Basic Training
Tutorial Two
Note: When a cut is created by default in ParaView, the program shows the mesh on that plane as a
triangular mesh even if it is a hex mesh. In fact, ParaView changes the mesh to a triangular mesh
for visualization, where every square is represented by two triangles. For avoiding this when
creating a cut in ParaView in the Slice properties window, uncheck “Triangulate the Slice”.
0.5 s
1s
10 s
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Three
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. Initial and Boundary Conditions
Before running the numerical solver, it is important to set up initial and boundary conditions
correctly for the problem. Ill-defined boundary conditions will result in non-convergence or
incorrect results.
The initial conditions provide the starting values for the solver and once specified, the value is put
into the center of every cell in the whole domain. As the solver starts to run, the initial values will
be replaced by newly calculated values. Any starting values can be used for 1st iteration. However
the better the initial values, the faster the convergence. Initial conditions are mandatory for transient
problems, but not absolutely required for steady state problems.
On the other hand we need to also provide boundary conditions. These will connect the simulation
models with its surroundings. The values specified are located at the boundary faces of the domain,
where their solution will be kept unchanged during the simulation, as the solver will not calculate
them. Most boundary conditions are either steady state or transient.
In OpenFOAM®, we can use the setFields utility to specify a non-uniform initial condition, and this
will be the focus of Tutorial Three. In addition, the boundary conditions are specified in the files in
the 0 directory.
In this tutorial, we will create meshes with 100, 1000 and 10000 cells in one dimension. However,
one cannot simply increase the number of cells (i.e. decrease the cell size) without changing the
time step size accordingly. This is because when running a numerical scheme (e.g. the Gauss linear
scheme; more details can be found in Tutorials Four and Five), the solution is reached using the
information propagated by waves or particles from one cell to the adjacent cell. To ensure a
physical solution it is essential that the physical flow information e.g. velocity, composition, etc. is
received by all cells within the calculation domain. It needs to be guaranteed that the information
transport does not “overtake” the physical transport, otherwise the scheme will be unable to access
the information required to form the solution.
The above criteria is known as the Courant-Friedrichs-Lewy (CFL) condition, and it is a necessary
condition for convergence. For one-dimensional problems, it can be written as:
𝑢𝑢∆𝑡𝑡
𝐶𝐶𝐶𝐶 = ≤1
∆𝑥𝑥
The key dimensionless number here is the Courant number, 𝐶𝐶𝐶𝐶, which needs to be less or equal to
one.
Note: u is the velocity magnitude of compound in the 1D direction, Δt is the simulation time step
size and Δx is the mesh size in the 1D direction.
As it is obvious from the equation by decreasing the mesh size (i.e. ∆𝑥𝑥), the time step size (∆𝑡𝑡)
should also be adjusted (decreased) for reaching a stable and convergent solution. Therefore the
CFL condition is useful in helping us choose a suitable time step size for our simulation. A common
OpenFOAM® Basic Training
Tutorial Three
way of selecting the time step size is to keep Courant number at 1, using the maximum possible u
and the smallest possible mesh size, a Δt that fits the criteria can be calculated.
OpenFOAM® Basic Training
Tutorial Three
rhoPimpleFoam – shockTube
Simulation
Use the rhoPimpleFoam solver; simulate 0.007 s of flow inside a shock tube, with a mesh with 100,
1000 and 10000 cells in one dimension, for initial values 1 bar/0.1 bar and 10 bar/0.1 bar.
Objectives
• To understand the setFields utility
Data processing
Import your simulation into ParaView, and compare results.
OpenFOAM® Basic Training
Tutorial Three
1. Pre-processing
Open tutorial
Copy the tutorial from the following directory to your working directory
$FOAM_TUTORIALS/compressible/rhoPimpleFoam/laminar/shockTube
system directory
Looking at the blockMeshDict file, it is obvious that it is a 1D mesh, because of the number of mesh
cells in y and z directions is one, and also in boundary section, plates vertical to these directions
are defined as empty. The mesh density can be set in the blocks part by changing x direction
mesh size (e.g. change it from 1000 to 100 or 10000).
Another important file is setFieldsDict, which is used by the tool setFields for patching (assign
an amount to a region) in the simulation. For example, here a pressure of 1 bar is set as the default
value for the entire region (from -5 to 5 in x direction), then half of the region (from 0 to 5) is
patched with a pressure of 0.1 bar.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
In the defaultFieldValues, a value is assigned to the whole domain, for example here, the
velocity has been set everywhere to zero, the temperature to 348.432 K, and the pressure to
100000 Pa. In the regions, a specific value is patched to a certain region of the domain. In this
example the region is defined as a cube, by the coordinates of one of its diagonals in boxToCell .
After choosing the region, the new values are assigned to the parameters (e.g. temperature at
278.746 K and pressure at 10000 Pa).
2. Running simulation
First the mesh needs to be created:
>blockMesh
>setFields
Then run:
OpenFOAM® Basic Training
Tutorial Three
>rhoPimpleFoam
Note: In the 10000 cell case with 10 bar and 0.1 bar, the simulation will crash with the default
deltaT (1e-5); after checking the same case with 1000 cells, you will find that the maximum Co is
around 0.6 (Time = 0.001):
Courant Number mean: 0.0508555 max: 0.589018
In the case with 10000 cells, the number of cells is increased by factor 10, so the cell size is reduced
by factor 10. For keeping the Courant number in the same range (around 0.6), according to the
“Background” section, deltaT should be decreased by factor 10. After reducing it to 1e-6 the
simulation will run smoothly.
Note: After running setFields for the first time, the files in the 0 directory are overwritten. If the
mesh is changed these files are not compatible with the new mesh and the simulation will fail. To
solve this problem replace the files in the 0 directory with the files in the 0.orig or the files with
suffix “.orig”, e.g. p.orig in the 0 directory. In the OpenFOAM® files or directories with suffix
“.orig” (“original”) usually contain the backup files. If a command changes the original files these
files can be replaced.
3. Post-processing
The simulation results are as follows:
OpenFOAM® Basic Training
Tutorial Three
Velocity along tube axis for 10 bar/0.1bar and 10000 cells case at t = 0.007 s
OpenFOAM® Basic Training
Tutorial Three
Pressure along tube axis for 10 bar/0.1bar and 10000 cells case at t = 0.007 s
OpenFOAM® Basic Training
Tutorial Three
Temperature along tube axis for 10 bar/0.1bar and 10000 cells case at t = 0.007 s
Tutorial Four
Discretization – Part 1
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Four
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. Discretizing general transport equation terms
Tutorial Four aims to help the users understand the different discretization schemes in
OpenFOAM®. But before that, it is important to understand the exact mathematical
procedures involved in discretization. Below is a detailed explanation of how each
term of the transport equation is discretized.
Where 𝜑𝜑𝑛𝑛 ≡ 𝜑𝜑 (𝑡𝑡 + ∆𝑡𝑡) stands for the new value at the time step we are solving for
and 𝜑𝜑0 ≡ 𝜑𝜑(𝑡𝑡) denotes old values from the previous time step.
Where F is the mass flux through the face 𝑓𝑓 defined as 𝐹𝐹 = 𝒏𝒏 ∙ (𝐴𝐴𝐴𝐴𝒖𝒖)𝑓𝑓 . The value 𝜑𝜑𝑓𝑓
on face f can be evaluated in a variety of ways which will be covered later in
section 2. The subscript 𝑓𝑓 refers to a given face.
Note that the above approximation is only valid if Γ is a scalar. Here, ∇𝑓𝑓 𝜑𝜑 denotes the
gradient at the face, 𝐴𝐴 denotes the surface area of the control volume and 𝐴𝐴𝑓𝑓 denotes
the area of a face for the control volume. It does not, however, imply a specific
OpenFOAM® Basic Training
Tutorial Four
discretization technique. The face normal gradient can be approximated using the
scheme:
𝜑𝜑𝑁𝑁 − 𝜑𝜑𝑃𝑃
𝒏𝒏 ∙ ∇𝑓𝑓 𝜑𝜑 =
|𝒅𝒅|
This approximation is second order accurate when the vector 𝒅𝒅 between the center of
the cell of interest P and the center of a neighboring cell N is orthogonal to the face
plane, i.e. parallel to A. In the case of non-orthogonal meshes, a correction term could
be introduced which is evaluated by interpolating cell centered gradients obtained
from Gauss integration.
where 𝑆𝑆𝐸𝐸 and 𝑆𝑆𝐼𝐼 may depend on φ. The term is then integrated over a control volume
as follows:
There is some freedom on exactly how a particular source term is linearized. When
deciding on the form of discretization (e.g. linear, upwind), its interaction with other
terms in the equation and its influence on boundedness and accuracy should be
examined.
2. Discretization Schemes
Since the results of CFD simulations are typically stored at the cell centers, it is
important to interpolate the results from cell centers to the face centers, to obtain the
fluxes for the surface integrals in the transport equation. For each term of the transport
equation, there is a variety of discretization/interpolation schemes available.
In general, interpolation needs a flux F through a general face f, and in some cases,
one or more parameters 𝛾𝛾. The face value 𝜑𝜑𝑓𝑓 can be evaluated from the values in the
neighboring cells using a variety of schemes. The flux satisfies continuity constraints,
which is prerequisite to obtaining the results.
Note: Here we define two faces, 𝑒𝑒 and 𝑤𝑤. To obtain flux through faces e and w, we
need to look its neighbouring values at P/E and W/P respectively. The subscripts
denote the face at which the face value 𝜑𝜑 or the flux F is located at.
𝜑𝜑𝑒𝑒 = 𝜑𝜑𝑃𝑃 𝑖𝑖𝑖𝑖, 𝐹𝐹𝑒𝑒 > 0
OpenFOAM® Basic Training
Tutorial Four
Here, we use linear interpolation for computing the cell face values.
𝜑𝜑𝐸𝐸 + 𝜑𝜑𝑃𝑃 𝜑𝜑𝑃𝑃 + 𝜑𝜑𝑊𝑊
𝜑𝜑𝑒𝑒 = , 𝜑𝜑𝑤𝑤 =
2 2
2.3. QUICK
QUICK stands for Quadratic Upwind Interpolation for Convective Kinetics. In the
QUICK scheme 3 point upstream-weighted quadratic interpolation are used for cell
face values.
6 3 1
When 𝐹𝐹𝑒𝑒 > 0, φ𝑒𝑒 = φ𝑃𝑃 + φ𝐸𝐸 − φ𝑊𝑊
8 8 8
6 3 1
When 𝐹𝐹𝑤𝑤 > 0, φ𝑤𝑤 = φ𝑊𝑊 + φ𝑃𝑃 − φ𝑊𝑊𝑊𝑊
8 8 8
OpenFOAM® Basic Training
Tutorial Four
QUICK scheme
Similar expressions can be obtained for 𝐹𝐹𝑒𝑒 < 0 and 𝐹𝐹𝑤𝑤 < 0.
Now that you know a bit more about discretization schemes, we can move on to the
tutorial. In this tutorial the scalarTransportFoam solver is used. More explanation of
this solver can be found below.
4. scalarTransportFoam solver
𝜕𝜕(𝜌𝜌𝜌𝜌)
+ ∇ ∙ (𝜌𝜌𝜌𝜌𝒖𝒖) − ∇ ∙ (𝛤𝛤∇𝜑𝜑) = 0
𝜕𝜕𝜕𝜕
OpenFOAM® Basic Training
Tutorial Four
scalarTransportFoam – shockTube
Simulation
Use the scalarTransportFoam solver, simulate 5 s of flow inside a shock tube, with 1D
mesh of 1000 cells (10 m long geometry from -5 m to 5 m). Patch with a scalar of 1
from -0.5 to 0.5. Simulate following cases:
• Set U to uniform (0 0 0). Vary diffusion coefficient (low, medium and high
value).
• Set the diffusion coefficient to zero and also U to (1 0 0) and run the
simulation in the case of pure advection using following discretization
schemes:
- upwind
- linear
- linearUpwind
- QUICK
- cubic
Objectives
• Understanding different discretization schemes.
Data processing
Import your simulation into ParaView, and plot temperature along tube length.
OpenFOAM® Basic Training
Tutorial Four
1. Pre-processing
>mkdir shockTube
$FOAM_TUTORIALS/compressible/rhoPimpleFoam/laminar/shockTube
OpenFOAM® v1906:
$FOAM_TUTORIALS/compressible/sonicFoam/laminar/shockTube
In the 0 directory, create a copy of T.orig and U.orig and rename them to T and U
respectively. In the constant directory delete the thermophysicalProperties and
turbulenceProperties files, and in the system directory delete all the files except for
blockMeshDict and setFieldsDict files.
OpenFOAM® v1906: Create a copy of 0.orig folder, rename it to 0 and delete the p
file in 0 directory!
Copy transportProperties file from constant folder in the newly created case constant
folder. Copy controlDict, fvSchemes and fvSolution from the above case system
directory to the created case system directory.
Note: By setting the diffusion coefficient to zero, the case will be switched to a pure
advection simulation with no diffusion.
volVectorFieldValue U ( 0 0 0 )
volScalarFieldValue T 0.0
);
regions
(
boxToCell
{
box ( -0.5 -1 -1 ) ( 0.5 1 1 );
fieldValues
(
volScalarFieldValue T 1.0
);
}
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
gradSchemes
{
default Gauss linear;
}
divSchemes
{
default none;
div(phi,T) Gauss linearUpwind grad(T);
}
laplacianSchemes
{
default none;
laplacian(DT,T) Gauss linear corrected;
}
interpolationSchemes
{
default linear;
}
snGradSchemes
{
default corrected;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
For each type of operation a default scheme can be set (e.g. for divSchemes is set to
none, it means no default scheme is set). Also a special type of discretization for each
element can be assigned (e.g. div(phi,T) it is set to linearUpwind). For each
element, where a discretization method has not been set, the default method will be
applied. If the default setting is none, no scheme is set for that element and the
simulation will crash.
OpenFOAM® Basic Training
Tutorial Four
Note: In fvSchemes, the schemes for the time term of the general transport equation
are set in ddtSchemes sub-dictionary. divSchemes are responsible for the
advection term schemes and laplacianSchemes set the diffusion term schemes.
Note: divSchemes should be applied like this: Gauss + scheme. The Gauss keyword
specifies the standard finite volume discretization of Gaussian integration which
requires the interpolation of values from cell centers to face centers. Therefore, the
Gauss entry must be followed by the choice of interpolation scheme
(www.openfoam.org).
2. Running simulation
>blockMesh
>setFields
>scalarTransportFoam
3. Post-processing
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Five
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. Properties of discretization schemes
Let’s explore some fundamental properties of discretization schemes. These properties are required
for our numerical results to be physically realistic. An understanding of these properties will help
the users to choose the appropriate discretization schemes for their model.
1.1. Conservativeness
Integration of the convection–diffusion equation over a finite number of control volumes yields a
set of discretized conservation equations involving fluxes of the transported property φ through
control volume faces. To ensure conservation of φ for the whole solution domain the flux of φ
leaving a control volume across a certain face must be equal to the flux of φ entering the adjacent
control volume through the same face. To achieve this flux through a common face must be
represented in a consistent manner – by one and the same expression – in adjacent control volumes
of each face.
1.2. Boundedness
Normally we use iterative numerical techniques to solve discretized equations at each nodal point.
The methods start with a guessed distribution of the initial conditions of the variable φ and perform
successive updates until a converged solution is obtained.
Here 𝑎𝑎᾿𝑃𝑃 is the net coefficient of the central node P (i.e. 𝑎𝑎᾿𝑃𝑃 − 𝑆𝑆𝑃𝑃 ), 𝑎𝑎𝑛𝑛𝑛𝑛 are the coefficient of the
neighbouring nodes. If the condition is satisfied, the resulting matrix of coefficients is diagonally
dominant. We need the net coefficients to be as large as possible, this means that 𝑆𝑆𝑃𝑃 should be
always negative. If this is the case, 𝑆𝑆𝑃𝑃 becomes positive due to the modulus sign and adds to 𝑎𝑎𝑃𝑃 .
1.3. Transportiveness
To understand transportiveness, one should look at a dimensionless number called the Peclet
number, 𝑃𝑃𝑃𝑃. It measures the relative strengths of convection, 𝑁𝑁𝑐𝑐𝑜𝑜𝑜𝑜𝑜𝑜 and diffusion, 𝑁𝑁𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑 .
𝑁𝑁𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐 𝐿𝐿𝐿𝐿
𝑃𝑃𝑃𝑃 = =
𝑁𝑁𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑 𝐷𝐷
Note: L is a characteristic length scale, U is the velocity magnitude, D is a characteristic diffusion
coefficient.
The primary goal is to ensure that the transportiveness is borne out of the discretization scheme.
Let’s consider the effect at a point P due to two constant sources of φ at nearby points W and E on
either side, in three cases.
OpenFOAM® Basic Training
Tutorial Five
Transportiveness property
It is useful to compare the different types of general discretization schemes covered in Tutorial Four
based on their conservativeness, boundedness and transportiveness properties.
Conser Trans-
Scheme Bounded Accuracy Remarks
-vative portive
Include false diffusion if
Upwind Unconditionally the velocity vector is not
Yes First order Yes
bounded parallel to one of the
coordinate directions
Central Conditionally Unrealistic solutions at
Yes Second order No
Differencing bounded⃰ large Pe number
Less computationally
Unconditionally stable. Can give small
QUICK Yes Third order Yes
bounded undershoots and
overshoots
⃰ Pe should be less than 2.
First-order Second-order
upwind upwind
8×8
64 × 64
Numerical diffusion
scalarTransportFoam – circle
Simulation
Use the scalarTransportFoam solver, do simulate the movement of a circular scalar spot region
(radius = 1 m) at the middle of a 100 × 100 cell mesh (10 m × 10 m), then move it to the right
(3 m), to the top (3 m) and diagonally.
Objectives
• Choosing the best discretization scheme.
Data processing
Examine your simulation in ParaView.
OpenFOAM® Basic Training
Tutorial Five
1. Pre-processing
1.1. Compile tutorial
Create the new case in your working directory like in tutorial four.
1.2. 0 directory
To move the circle to right change the internalField to (1 0 0) in the U file for setting the
velocity field towards the right. Modify U at suitable times, to obtain a velocity field which will
move the circle up and also diagonally.
vertices
(
(-5 -5 -0.01)
(5 -5 -0.01)
(5 5 -0.01)
(-5 5 -0.01)
(-5 -5 0.01)
(5 -5 0.01)
(5 5 0.01)
(-5 5 0.01)
);
blocks
(
hex (0 1 2 3 4 5 6 7) (100 100 1) simpleGrading (1 1 1)
);
edges
(
);
boundary
(
sides
{
type patch;
faces
(
(1 2 6 5)
(0 4 7 3)
(3 7 6 2)
(0 1 5 4)
);
}
empty
{
type empty;
faces
(
(5 6 7 4)
(0 3 2 1)
);
}
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
OpenFOAM® Basic Training
Tutorial Five
Choose a discretization scheme based on the results from the previous example and set it in the
fvSchemes.
In the setFieldsDict patch a circle to the middle of the geometry using the following lines.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
defaultFieldValues (volScalarFieldValue T 0 );
regions
(
cylinderToCell
{
p1 ( 0 0 -1 );
p2 ( 0 0 1 );
radius 0.5;
fieldValues
(
volScalarFieldValue T 1
) ;
}
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
cylinderToCell command is used to patch a cylinder to the region, p1 and p2 show the two
ends of cylinder center line, in the radius the radius is set.
Check controlDict, in the first part of simulation, where the circle should move to the right set the
startFrom to startTime and startTime to 0. By a simple calculation it can be seen that the
endTime should be 3 s (to move the circle from center to the right side). Similar calculations need
to be done for the two other parts, except the startTime is set to the endTime of previous part,
and new endTime should be that part “simulation time” plus endTime of the previous part.
2. Running Simulation
>blockMesh
>setFields
>scalarTransportFoam
For running the further parts (moving the circle to top, and then diagonally) change the velocity
field in the last time step directory, i.e. change the velocity in the time step directory 3 to (0 1 0) so
the circle moves up, further change the velocity in the directory 6 to (-1 -1 0) to move the circle
diagonally back to the original position.
After moving the circle to the right and changing the velocity field, the simulation is resumed. It can
be seen that the circle does not go up but moves to the right. This occurs due to the fact that
OpenFOAM® used the previous time step fluxes (phi) to do the calculations. We can solve this
problem by deleting phi file from the latest time step (of the previous part of simulation, e.g. 3). In
this way, OpenFOAM® creates new fluxes based on the new velocity field that we just updated. So,
easily delete phi and enjoy!
3. Post-processing
The simulation results are as follows:
OpenFOAM® Basic Training
Tutorial Five
1s 2s 3s
4s 5s 6s
7s 8s 9s
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Six
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. Why turbulence modeling?
In this tutorial, RANS-based model is explained in detail. In the next tutorial, large
eddy simulations (LES) and Smagorinsky-Lilly model will be covered.
2. RANS-based models
o Conservation of mass
𝜕𝜕𝜕𝜕
+ ∇ ∙ (𝜌𝜌𝒖𝒖
�) = 0
𝜕𝜕𝜕𝜕
o Conservation of momentum (Navier-Stokes equation)
𝜕𝜕(𝜌𝜌𝑢𝑢�𝑖𝑖 ) 𝜕𝜕𝑝𝑝�
+ ∇ ∙ (𝜌𝜌𝑢𝑢�𝑖𝑖 𝒖𝒖
�) = − + ∇ ∙ (𝜇𝜇∇𝑢𝑢�𝑖𝑖 ) + 𝑆𝑆̃𝑀𝑀𝑀𝑀
𝜕𝜕𝜕𝜕 𝜕𝜕𝑥𝑥𝑖𝑖
One of the solutions to the problem is to reduce the number of scales (from infinity to
1 or 2) by using the Reynolds decomposition. Any property (whether a vector or a
scalar) can be written as the sum of an average and a fluctuation, i.e. 𝜑𝜑� = Φ + φ where
the capital letter denotes the average and the lower case letter denotes the fluctuation
of the property. Using the Reynolds decomposition in the Navier-Stokes equations we
obtain RANS or Reynolds Averaged Navier Stokes Equations.
𝜕𝜕(𝜌𝜌𝑢𝑢𝑢𝑢
�����)
𝚤𝚤 𝜕𝜕(𝜌𝜌𝑣𝑣𝑢𝑢
�����)
𝚤𝚤 𝜕𝜕(𝜌𝜌𝑤𝑤𝑢𝑢
�����)
𝚤𝚤
−� + + � + S𝑀𝑀𝑀𝑀
𝜕𝜕𝜕𝜕 𝜕𝜕𝜕𝜕 𝜕𝜕𝜕𝜕
However, by using the Reynolds decomposition, there are new unknowns that were
introduced such as the turbulent stresses (𝜌𝜌𝑢𝑢𝑢𝑢 ����, 𝜌𝜌𝑣𝑣𝑣𝑣
����, 𝜌𝜌𝑤𝑤𝑤𝑤
����, 𝜌𝜌𝑢𝑢𝑢𝑢
����, 𝜌𝜌𝑣𝑣𝑣𝑣
���, 𝜌𝜌𝑤𝑤𝑤𝑤
����, 𝜌𝜌𝑢𝑢𝑢𝑢
����,
𝜌𝜌𝑣𝑣𝑣𝑣 �����) and turbulent fluxes (𝜌𝜌𝑢𝑢𝑢𝑢
����, 𝜌𝜌𝑤𝑤𝑤𝑤 ���, 𝜌𝜌𝑣𝑣𝑣𝑣 ����) and therefore, the RANS equations
���, 𝜌𝜌𝑤𝑤𝑤𝑤
describe an open set of equations (where the over bar denotes an average). The need
for additional equations to model the new unknowns is called Turbulence Modeling.
One possible approach to model the additional unknowns is to use the PDEs for the
turbulent stresses and fluxes as a guide to modeling. The turbulent models are as
follows, in order of increasing complexity:
• Two equation models: k‐ε, k‐kl, k‐ω, low Re k‐ε (first order model)
• Zero‐Equation Models
In OpenFOAM®, there are two simulation types for turbulence flow, RAS and LES.
As the name suggest, the RAS simulation is based on the RANS-based models
covered above and will be the sole focus of this tutorial. In the next tutorial, we will
move on to LES modeling and compare the results generated from these two
modeling types.
OpenFOAM® Basic Training
Tutorial Six
simpleFoam – pitzDaily
Simulation
Use simpleFoam solver, run a steady state simulation with following turbulence
models:
• kEpsilon (RAS)
• kOmega (RAS)
• LRR (RAS)
Objectives
• Understanding turbulence modeling
Data processing
Show the results of U and the turbulent viscosity in two separate contour plots.
OpenFOAM® Basic Training
Tutorial Six
1. Pre-processing
1.2. 0 directory
When a turbulent model is chosen, the value of its constants and its boundary values
should be set in the appropriate files. For example in kEpsilon model the k and
epsilon files should be edited. See below for the epsilon file (in the 0 folder):
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
dimensions [0 2 -3 0 0 0 0];
boundaryField
{
inlet
{
type fixedValue;
value uniform 14.855;
}
outlet
{
type zeroGradient;
}
upperWall
{
type epsilonWallFunction;
value uniform 14.855;
}
lowerWall
{
type epsilonWallFunction;
value uniform 14.855;
}
frontAndBack
{
type empty;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Note: Here is a list of files which should be available at 0 directory and need to be
modified for each turbulence model:
• laminar: no file
Some files are available, e.g. epsilon, k and nuTilda, some files should be created by
the user, e.g. R, nuSgs. Templates for these files can be also found in the examples of
older versions of OpenFOAM®, e.g. 1.7.1.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
simulationType RAS;
RAS
{
// Tested with kEpsilon, realizableKE, kOmega, kOmegaSST, v2F,
// ShihQuadraticKE, LienCubicKE.
RASModel kEpsilon;
turbulence on;
printCoeffs on;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Note: For the laminar model, set turbulence and printCoeffs to off.
For the LRR model, discretization model for the new variable R needs to be specified.
It is done through the fvSchemes file,
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
ddtSchemes
OpenFOAM® Basic Training
Tutorial Six
{
default steadyState;
}
gradSchemes
{
default Gauss linear;
}
divSchemes
{
default none;
div(phi,U) bounded Gauss linearUpwind grad(U);
div(phi,k) bounded Gauss limitedLinear 1;
div(phi,epsilon) bounded Gauss limitedLinear 1;
div(phi,omega) bounded Gauss limitedLinear 1;
div(phi,v2) bounded Gauss limitedLinear 1;
div(phi,R) bounded Gauss limitedLinear 1;
div(R) Gauss linear;
div((nuEff*dev2(T(grad(U))))) Gauss linear;
div(nonlinearStress) Gauss linear;
}
laplacianSchemes
{
default Gauss linear corrected;
}
interpolationSchemes
{
default linear;
}
snGradSchemes
{
default corrected;
}
wallDist
{
Method meshWave;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Furthermore, fvSolution needs to be changed due to the new R parameter. The solver
type for R is defined, in this case the solver used will be the same as the one for other
variables (U, k, epsilon, omega).
2. Running simulation
>blockMesh
>simpleFoam
Time = 298
3. Post-processing
The simulation results are as follows (all simulations scaled to the same range):
RAS
Velocity magnitude Turbulent viscosity
model
kEpsilon
kOmega
LRR
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Seven
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. Large eddy simulation (LES)
In LES models, it is assumed that large eddies of the flow are dependent on the
geometry, while the smaller eddies are more universal. One can then explicitly solve
for the large eddies in a calculation by resolving them in a grid and implicitly account
for the small eddies by using a sub grid-scale model (SGS model).
Mathematically, it is like separating the velocity field into a resolved and sub-grid part
using a filter function. The resolved part of the field represents the large eddies, while
the sub grid part of the velocity represents the small eddies whose effect on the
resolved field is included through the sub grid-scale model. Formally, one may think
of filtering as the convolution of a function with a filtering kernel 𝐺𝐺:
resulting in
Where 𝑢𝑢�𝑖𝑖 is the resolvable scale part and 𝑢𝑢, 𝑖𝑖 is the subgrid-scale part. However, most
practical (and commercial) implementations of LES use the grid itself as the filter and
perform no explicit filtering. The filtered equations are developed from the
incompressible Navier-Stokes equations of motion:
Substituting in the decomposition 𝑢𝑢𝑖𝑖 = 𝑢𝑢�𝑖𝑖 + 𝑢𝑢, 𝑖𝑖 and p = p� + p, and then filtering the
resulting equation gives the equations of motion for the resolved field:
We have assumed that the filtering operation and the differentiation operation
commute, which is not generally the case. It is thought that the errors associated with
this assumption are usually small, though filters that commute with differentiation
have been developed. The extra term 𝜕𝜕𝜏𝜏𝑖𝑖𝑖𝑖 /𝜕𝜕𝑥𝑥𝑗𝑗 arises from the non-linear advection
terms, due to the fact that:
𝜕𝜕𝑢𝑢𝑖𝑖 𝜕𝜕𝑢𝑢�𝑖𝑖
𝑢𝑢𝑗𝑗 ≠ 𝑢𝑢�𝑗𝑗
𝜕𝜕𝑥𝑥𝑗𝑗 𝜕𝜕𝑥𝑥𝑗𝑗
and hence
Similar equations can be derived for the sub grid-scale field. Sub grid-scale
turbulence models usually employ the Boussinesq hypothesis, and seek to calculate
(the deviatoric part of) the SGS stress using:
1
̅
𝜏𝜏𝑖𝑖𝑖𝑖 − τ𝑘𝑘𝑘𝑘 δ𝑖𝑖𝑖𝑖 = −2µ𝑡𝑡 𝑆𝑆𝑖𝑖𝑖𝑖
3
̅ is the rate-of-strain tensor for the resolved scale defined by
where 𝑆𝑆𝑖𝑖𝑖𝑖
1 𝜕𝜕𝑢𝑢�𝑖𝑖 𝜕𝜕𝑢𝑢�𝑗𝑗
̅ =
𝑆𝑆𝑖𝑖𝑖𝑖 � + �
2 𝜕𝜕𝑥𝑥𝑗𝑗 𝜕𝜕𝑥𝑥𝑖𝑖
and 𝜐𝜐𝑡𝑡 is the subgrid-scale turbulent viscosity. Substituting into the filtered Navier-
Stokes equations, we then have:
where we have used the incompressibility constraint to simplify the equation and the
pressure is now modified to include the trace term 𝜏𝜏𝑘𝑘𝑘𝑘 𝛿𝛿𝑖𝑖𝑖𝑖 /3.
2. Smagorinsky-Lilly model
A simple model for Sub grid-scale model is the Smagorinsky model, which can be
summarized as:
1
𝜏𝜏𝑖𝑖𝑖𝑖 − τ𝑘𝑘𝑘𝑘 δ𝑖𝑖𝑖𝑖 = −2(C𝑠𝑠 ∆)2 |𝑆𝑆̅|S𝑖𝑖𝑖𝑖
3
In the Smagorinsky-Lilly model, the eddy viscosity is modeled by
∆= (𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉𝑉)1/3
and
The Smagorinsky constant usually has the value: 𝐶𝐶𝑠𝑠 = 0.1 − 0.2
OpenFOAM® Basic Training
Tutorial Seven
pisoFoam – pitzDaily
Simulation
Use the pisoFoam solver, run a backward facing step case for 0.2 s with different
turbulence models:
• Smagorinsky (LES)
• kEqn (LES)
• kEpsilon (RAS)
Objectives
• Understanding turbulence models
Data processing
Display the results of U and the turbulent viscosity in two separate contour plots at
three different time steps. Compare with steady state simulation (Tutorial Six).
OpenFOAM® Basic Training
Tutorial Seven
1. Pre-processing
$FOAM_TUTORIALS/incompressible/pisoFoam/LES/pitzDaily
1.2. 0 directory
Set the turbulence model initial and boundary values.
Note: For different turbulent models, different files should be modified (check
Tutorial Six).
LES
{
LESModel kEqn;
turbulence on;
printCoeffs on;
delta cubeRootVol;
dynamicKEqnCoeffs
{
filter simple;
}
cubeRootVolCoeffs
{
deltaCoeff 1;
}
PrandtlCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
smoothCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
maxDeltaRatio 1.1;
}
Cdelta 0.158;
}
vanDriestCoeffs
OpenFOAM® Basic Training
Tutorial Seven
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
smoothCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
maxDeltaRatio 1.1;
}
Aplus 26;
Cdelta 0.158;
}
smoothCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
maxDeltaRatio 1.1;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
2. Running simulation
>blockMesh
>pisoFoam
3. Post-processing
0.01 s
0.05 s
0.2 s
kEqn
0.01 s
0.05 s
0.2 s
kEpsilon
0.01 s
0.05 s
0.2 s
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Eight
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
In this tutorial we are going to solve a problem of dam break using the interFoam solver. The main
feature of this problem is flow of water and air separated by a sharp interface. Before starting, let’s
cover some of the basics of multiphase flow.
1. Multiphase flow
Multiphase flow is simultaneous flow of materials in different phases. There can be multiple
components present in each phase. The common types of multiphase flows are: gas-liquid, gas-
solid, liquid-solid, liquid-liquid and three-phase flows.
Multiphase flow can be further categorized based on the visual appearance of the flow into
separated, mixed or dispersed flow. In dispersed flow, one phase exist as a continuous fluid, while
all other phases act as discontinuous particles flowing through the continuous fluid. In mixed flow
regions, dispersed particles as well as semi-continuous interfaces exist together.
So why is multiphase flow important? Multiphase flow is present in many industrial processes, such
as bubble columns, absorption, adsorption and stripping columns. Modeling of multiphase flow can
help maximizing contact between different phases, hence increasing the efficiency of the process.
2. Modeling approaches
Modeling of multiphase flow can be extremely complex, due to possible flow regime transitions. To
simplify the matter, different modeling approaches can be adopted and they generally fall into two
categories: lagrangian and Eulerian. In the case of dispersed configuration, Lagrangian approach is
more suitable. This involves tracking individual point particles during its movement. The other
approach is the Eulerian approach, which observes fluid behavior in a given control volume.
All phases are treated as continuous in the Euler-Euler approach. This approach is suitable for
separated flows where each phase behaves as a continuum, rather than being discrete. The phases
interact through the drag and lift forces acting between them, as well as through heat and mass
transfer. The Euler-Euler approach is also capable of modeling dispersed flow, where we are
interested in the overall motion of particles rather than tracking individual particles.
In the Euler-Euler approach, we introduce the concept of phasic volume fractions. These fractions
are assumed to be continuous functions of space and time, with their sum equal to one. For each
phase, a set of conservation equations for mass, momentum and energy is solved individually; in
addition, a transport equation for the volume fraction is solved. Coupling between the phases is
achieved through a shared pressure and interphase exchange coefficients.
The eddy lifetime (𝑡𝑡𝑒𝑒 ) and eddy length scale (𝑙𝑙𝑒𝑒 ) are estimated from the local turbulence properties.
From the length scale and the particle velocity, one can calculate the eddy transit time (𝑡𝑡𝑐𝑐 ), i.e. the
time taken for a particle to cross the eddy. The particle is then assumed to interact with the eddy for
a time which is the minimum of the eddy life time and the eddy transit time.
During that interaction the fluid fluctuating velocity is kept constant and the discrete particle is
moved with respect to its equation of motion. Then a new fluctuating fluid velocity is sampled and
the process is repeated.
The focus of the VOF method is to track the interface between phases. To do this, the transport
equations are solved for mixture properties, assuming that all field variables are shared between the
phases. Then an advection equation for the fraction function C is solved. The discretization of the
fraction function equation is crucial for obtaining a sharp interface.
The multiphase flow in this tutorial is analysed using the interFoam solver. Here is a brief
explanation of the solver below.
3. interFoam solver
interFoam is suitable for solving multiphase flow between 2 incompressible, isothermal immiscible
fluids. It is based on the Volume of Fluid (VOF) approach.
OpenFOAM® Basic Training
Tutorial Eight
interFoam – damBreak
Simulation
Use the interFoam solver to simulate breaking of a dam for 2s.
Objectives
• Understanding how to set viscosity, surface tension and density for two phases
Data processing
See the results in ParaView.
OpenFOAM® Basic Training
Tutorial Eight
1. Pre-processing
$FOAM_TUTORIALS/multiphase/interFoam/laminar/damBreak/damBreak
1.2. 0 directory
In the 0 directory the following files exist:
alpha.water.orig p_rgh U
In the alpha.water.orig and p_rgh files the initial values and also boundary conditions for water
phase and also pressure are set. Copy alpha.water.orig to alpha.water (remember: the *.orig files are
back up files, and solvers do not use them). E.g. in alpha.water:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
dimensions [0 0 0 0 0 0 0];
internalField uniform 0;
boundaryField
{
leftWall
{
type zeroGradient;
}
rightWall
{
type zeroGradient;
}
lowerWall
{
type zeroGradient;
}
atmosphere
{
type inletOutlet;
inletValue uniform 0;
value uniform 0;
}
defaultFaces
{
type empty;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
Note: The inletOutlet and the outletInlet boundary conditions are used when the flow
direction is not known. In fact, these are derived types and are a combination of two different
boundary types.
OpenFOAM® Basic Training
Tutorial Eight
- inletOutlet: When the flux direction is toward the outside of the domain, it works like a
zeroGradient boundary condition and when the flux is toward inside the domain it is like a
fixedValue boundary condition.
- outletInlet: This is the other way around, if the flux direction is toward outside the
domain, it works like a fixedValue boundary condition and when the flux is toward inside
the domain, it is like a zeroGradient boundary condition.
E.g. if the velocity field outlet is set as inletOutlet and the inletValue is set to (0 0 0), it
avoids backflow at the outlet! The “inletValue” or “outletValue” are values for
fixedValue type of these boundary conditions and “value” is a dummy entery for OpenFOAM®
for finding the variable type. Using (0 0 0), OpenFOAM® understands that the variable is a
vector.
water
{
transportModel Newtonian;
nu 1e-06;
rho 1000;
}
air
{
transportModel Newtonian;
nu 1.48e-05;
rho 1;
}
sigma 0.07;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
In both phases the coefficients for different models of viscosity are given, e.g. nu and rho.
Depending on which model is selected, the coefficients from the corresponding sub-dictionary are
read. The selected model is Newtonian, only the nu coefficient is used.
sigma is the surface tension between two phases, in this example it is the surface tension between
air and water.
Checking the g file, the gravitational field and also its direction are defined, it is 9.81 m/s2 in the
negative y direction.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
dimensions [0 1 -2 0 0 0 0];
value ( 0 -9.81 0 );
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
OpenFOAM® Basic Training
Tutorial Eight
2. Running simulation
>blockMesh
>setFields
>interFoam
3. Post-processing
The simulation results are as follows (these are not the results for the original mesh, but a 2x refined
mesh):
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Nine
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
In this tutorial we will analyze compressible fluid flow in OpenFOAM®. Parallel
processing is utilized to speed up the simulation. In this introduction part, theory
behind compressible flow, solvers for compressible flow and parallel computing will
be explained in detail.
𝑢𝑢 𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙𝑙 𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣𝑣
𝑀𝑀𝑀𝑀 = =
𝑐𝑐 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 𝑜𝑜𝑜𝑜 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠
When a fluid flow is compressible, temperature and pressure are affected strongly by
variations in density. It is therefore important to take into account the linkage between
pressure, temperature and density in compressible flow, usually by applying an
equation of state from thermodynamics (e.g. the ideal gas equation).
There are two general types of solution schemes for compressible flow: pressure-
based and density-based.
In general, density based solvers are more suitable for high speed compressible flows
with shocks. This is because density based solvers solve for conserved quantities
across the shock, so the discontinuities will not affect the results.
3. Parallel computing
comes in. Parallel computing is defined as the simultaneous use of more than one
processor to execute a program. The geometry of the domain will be partitioned into
sub-domains, with each sub-domain assigned to a single processor. Furthermore data
and computational tasks will be partitioned and divided amongst the processors. This
step is known as domain decomposition.
Parallel computing can be carried out in two ways. One is done on a single computer
with multiple internal processors, known as a Shared Memory Multiprocessor. The
other way is achieved through a series of computers interconnected by a network,
known as a Distributed Memory Multicomputer.
compressibleInterFoam – depthCharge3D
Simulation
Use the compressibleInterFoam solver, simulate the example case for 0.5 s.
Objectives
• Understanding the difference between incompressible and compressible
solvers
Data processing
Investigate the results in ParaView.
OpenFOAM® Basic Training
Tutorial Nine
1. Pre-processing
$FOAM_TUTORIALS/multiphase/compressibleInterFoam/laminar/depth
Charge3D
1.2. 0 directory
In the 0 directory copy the alpha.water.orig, p.orig and p_rgh.orig files to
alpha.water, p and p_rgh respectively.
pMin 10000;
sigma 0.07;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
method hierarchical;
simpleCoeffs
{
n ( 1 4 1 );
delta 0.001;
}
hierarchicalCoeffs
{
n ( 1 4 1 );
delta 0.001;
order xyz;
}
manualCoeffs
{
OpenFOAM® Basic Training
Tutorial Nine
dataFile "";
}
distributed no;
roots ( );
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
OpenFOAM® v1906: In this file just the coefficients for hierarchical method are
listed!
If the simple method is being used, the parameter n must be changed accordingly.
The three numbers (1 4 1) indicate the number of pieces the mesh is split into in
the x, y and z directions, respectively. Their multiplication result should be equal to
numberOfSubdomains.
If the hierarchical method is being used, these parameters and also the order in
which the mesh should be split up in each direction should be provided.
If the scotch method is being used, then no user-supplied parameters are necessary
except for the number of subdomains.
There is also a parameter delta, known as the cell skew factor. This factor is set to a
default value of 0.001, and measures to what extent skewed cells should be
accounted for.
Note: In order to check the quality of the mesh, the checkMesh tool can be used (run it
from main case directory). If the message “Mesh OK” is displayed – the mesh is fine
and no corrections need to be done.
If the mesh fails in one or more tests, try to recreate or refine the mesh for a better
mesh quality (less non-orthogonally and skewness). If the error exists after correcting
the mesh then a possible course of action is to increase the delta parameter (for
example: to 0.01) and then rerun the blockMesh and checkMesh tools.
2. Running simulation
>blockMesh
>setFields
For running the simulation in parallel mode the computing domain needs to be
divided into subdomains and a core should be assigned to each subdomain. This is
done by following command:
>decomposePar
OpenFOAM® Basic Training
Tutorial Nine
This decomposes the mesh according to the supplied instructions. One possible source
of error is the product of the parameters in n does not match up to the number of the
subdomains. This appears for the simple and hierarchical methods.
After executing this command four new directories will be made in the simulation
directory (processor0, processor1, processor2 processor3), and each subdomain
calculation will be saved in the respective processor directory.
<No of cores> is the number of cores being used. solver is the solver for this
simulation. For example, if 4 cores are desired, and the solver is
compressibleInterFoam following command is used:
> log is the filename for saving the simulation status data, instead of printing them
to the screen. For checking the last information which is written to this file the
following command can be used during the simulation running:
>tail -f log
Note: Before running any simulation, it is important to run the top command (type the
‘top’ command in the terminal), to check the number of cores currently used on the
machine. Check the load average. This is on the first line and shows the average
number of cores being used. There are three numbers displayed, showing the load
averages across three different time scales (one, five and 15 minute respectively).
Add the number of cores you plan to use to this number – and you will get the
expected load average during your simulation. This number should be less than the
total number of cores in the machine – or the simulation will be slowed or the
machine will crash (if you run out of memory). If you are running on a multi user
server it is recommended to leave at least a few cores free, to allow for any
fluctuations in the machine load.
The simulation can take several hours, depending on the size of the mesh and time
step size.
3. Post-processing
For exporting data for post processing, at first all the processors data should be put
together and a single combined directory for each time step was created. By executing
the following command all the cores data will be combined and new directories for
each time step will be created in the simulation main directory:
>reconstructPar
OpenFOAM® Basic Training
Tutorial Nine
>foamToVTK
Using above commands without entering end time will do the reconstruction or
conversion from start time to the end of available data:
For reconstructing or converting only one time step the commands should be used
without end time and “:”:
0s 0.05 s 0.1 s
0.3 s 0.5 s
0.4 s
4. Manual method
The manual method for decomposition is slightly different from the other three. In
order to use it:
After running the blockMesh and setFields utilities, set the decomposeParDict file as
any other simulation. For decomposition method, choose either simple, hierarchical or
scotch. Set the number of cores to the same number which is going to be used for
manual.
>decomposePar -cellDist
Once the decomposition is done, check the cellDecomposition file in the constant
directory. It should have a format similar to:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
1024000
(
0
0
0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
1
1
1 ...)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Note: If the above output is not displayed, but a stream of NUL characters, your text
editor is probably printing binary. To fix this, open system/controlDict, and change
the writeFormat field from binary to asci and rerun the previous command.
The first number n after the header, but before the opening brackets, 1024000 in this
example, refers to the number of points in the mesh. Within the brackets, n lines
follow. Each line contains one number between 0 and n-1, where n is the number of
cores to be used for the computation. This number refers to the core being used to
compute the corresponding cell in the points file in the constant directory. For
example, if the second line in the points file brackets reads (0.125 0 0) and the
OpenFOAM® Basic Training
Tutorial Nine
second line in the cellDecomposition directoy reads 0, this means that the cell
(0.125 0 0) will be processed by processor 0.
This cellDecomposition file can now be edited. Although this can be done manually,
it is probably not feasible for any sufficiently large mesh. The process must thus be
automated by writing a script to populate the cellDecomposition file according to the
desired processor breakdown.
Now, edit the decomposeParDict file. Select decomposition method manual, and for
the dataFile field in the manual coeffs range, specify the path to the file which
contains the manual decomposition. Note that OpenFOAM® searches in the constant
directory by default, in case relative paths are being used:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
numberOfSubdomains 4;
method manual;
simpleCoeffs
{
n ( 1 4 1 );
delta 0.001;
}
hierarchicalCoeffs
{
n ( 1 4 1 );
delta 0.001;
order xyz;
}
manualCoeffs
{
dataFile "manFile";
}
distributed no;
roots ( );
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Delete the old processor directories, decompose the case with the new decomposition
settings and run the simulation.
>cd processor<n>
OpenFOAM® Basic Training
Tutorial Nine
>foamToVTK
>paraview &
- The part of the mesh decomposed by that core will appear, in grey.
- Change the color in the drop-down menus in the toolbar. This is to ensure that each
individual part can be easily seen.
Once this is done for all processors, the entire mesh will appear. However, the
processor regions can now easily be seen in a different color.
In order to save this, there are two options. The first option is to take a screenshot:
File > Save a screenshot
The second option is to save the settings and modifications as a ParaView state file.
File > Save State
The current settings and modifications can then be easily recovered by:
File > Load State
Saving the state allows changes to be made afterwards. Saving a screenshot keeps
only a picture, while losing the ability to make changes after exiting ParaView. Doing
both is recommended.
Tutorial Ten
Residence Time Distribution
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Ten
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
In this tutorial we will carry out Residence Time Distribution (RTD) analysis of fluid flow through
a T-junction pipe.
Residence time distribution is a probability distribution function that provides information about the
amount of time a tracer element spends within a process unit, such as a reactor or a column. RTD
analysis is important because in almost all real-life processes, the mixing is not ideal and chemical
engineers will need RTD to analyze the real mixing characteristics, for example inside a
continuously stirred reactor. They can also use RTD analysis to obtain information about the flow
pattern, back mixing and bypassing behavior of a process unit.
2. Tracer Analysis
Radioactive tracers are usually used to determine RTD of a process unit. Based on the above
diagram, first the tracer is injected into the inlet, and then the exit tracer concentration, 𝐶𝐶(𝑡𝑡), is
measured at regular time intervals. This allows the exit age distribution, 𝐸𝐸(𝑡𝑡), to be calculated.
It is clear from the above equation that the fraction of tracer molecules exiting the reactor that have
spent a time between 𝑡𝑡 and 𝑡𝑡 + 𝑑𝑑𝑑𝑑 in the process unit is 𝐸𝐸(𝑡𝑡)𝑑𝑑𝑑𝑑. Since all tracer elements will leave
the unit at some point, RTD satisfies the following relationship:
∞
� 𝐸𝐸(𝑡𝑡) 𝑑𝑑𝑑𝑑 = 1
0
OpenFOAM® Basic Training
Tutorial Ten
Simulation
Use the simpleFoam and scalarTransportFoam to simulate the flow through a square cross section T
pipe and calculate RTD (Residence Time Distribution) for both inlets using a step function
injection:
Objectives
Data processing
Plot the step response function and the RTD curve.
OpenFOAM® Basic Training
Tutorial Ten
1. Pre-processing
$FOAM_TUTORIALS/incompressible/simpleFoam/pitzDaily
1.2. 0 directory
Update p, U, nut, nuTilda, k and epsilon files with the new boundary conditions, e.g. U:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
dimensions [0 1 -1 0 0 0 0];
boundaryField
{
inlet_one
{
type fixedValue;
value uniform (0.1 0 0)
}
inlet_two
{
type fixedValue;
value uniform (-0.2 0 0)
}
outlet
{
type zeroGradient;
}
walls
{
type fixedValue;
value uniform (0 0 0)
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
turbulence on;
printCoeffs on;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
vertices
(
OpenFOAM® Basic Training
Tutorial Ten
(0 4 0) // 0
(0 3 0) // 1
(3 3 0) // 2
(3 0 0) // 3
(4 0 0) // 4
(4 3 0) // 5
(7 3 0) // 6
(7 4 0) // 7
(4 4 0) // 8
(3 4 0) // 9
(0 4 1) // 10
(0 3 1) // 11
(3 3 1) // 12
(3 0 1) // 13
(4 0 1) // 14
(4 3 1) // 15
(7 3 1) // 16
(7 4 1) // 17
(4 4 1) // 18
(3 4 1) // 19
);
blocks
(
hex (0 1 2 9 10 11 12 19) (10 30 10) simpleGrading (1 1 1)
hex (9 2 5 8 19 12 15 18) (10 10 10) simpleGrading (1 1 1)
hex (8 5 6 7 18 15 16 17) (10 30 10) simpleGrading (1 1 1)
hex (2 3 4 5 12 13 14 15) (30 10 10) simpleGrading (1 1 1)
);
edges
(
);
patches
(
patch inlet_one
(
(0 10 11 1)
)
patch inlet_two
(
(7 6 16 17)
)
patch outlet
(
(4 3 13 14)
)
wall walls
(
(0 1 2 9)
(2 5 8 9)
(5 6 7 8)
(2 3 4 5)
(10 19 12 11)
(19 18 15 12)
(18 17 16 15)
(15 14 13 12)
(0 9 19 10)
(9 8 18 19)
(8 7 17 18)
(2 1 11 12)
(3 2 12 13)
(5 4 14 15)
(6 5 15 16)
)
);
mergePatchPairs
(
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
OpenFOAM® Basic Training
Tutorial Ten
2. Running simulation
>blockMesh
>simpleFoam
Wait for simulation to converge. After convergence, check the results to make sure about physical
convergence of the solution.
>foamToVTK
The simulation results are as follows (results are on the cut plane in the middle):
3. RTD calculation
$FOAM_TUTORIALS/basic/scalarTransportFoam/pitzDaily
3.2. 0 directory
Delete the U file and replace it with the calculated velocity field from the first part of the tutorial
(use the latest time step velocity field from previous part of simulation to calculate RTD for this
geometry). There is no need to modify or change it. The solver will use this field to calculate the
scalar transportation.
OpenFOAM® Basic Training
Tutorial Ten
Update T (T will be used as an inert scalar in this simulation) file boundary conditions to match new
simulation boundaries, to calculate RTD of the inlet_one set the internalField value to 0, T
value for inlet_one to 1.0 and T value for inlet_two to 0.
4. Running Simulation
>blockMesh
>scalarTransportFoam
>foamToVTK
5. Post-processing
>foamToVTK
Load the outlet VTK file into paraview using following path:
File > Open > VTK > outlet > outlet_..vtk > OK > Apply
Select T from variables menu, and then integrate the variables on the outlet:
Filters > Data Analysis > Integrate Variables > Apply
The values given in the opened window are integrated values in this specific time step. By changing
the time step values for different time steps are displayed. As mentioned before, the average value
of the property is needed. Therefore, these values should be divided by outlet area to get average
values (1m × 1m).
After finishing the RTD calculations for inlet_one, the same procedure should be followed for
calculating RTD of inlet_two, except T value for inlet_one should be 0 and for inlet_two it
should be 1.0.
OpenFOAM® Basic Training
Tutorial Ten
The average value of T for each outlet approaches a certain constant value, which is the ratio of that
scalar mass inlet to the whole mass inlet. For plotting data over time “Plot Selection Over Time”
option in ParaView can be used, in the opened SpreadSheetView window (IntegrateVariables)
select the set of data which you want to plot over time and then:
Filters > Data Analysis > Plot Selection Over Time > Apply
Next, to obtain the RTD plots, export the data to a spreadsheet program (e.g. Excel), calculate and
plot the gradient of changes in average value of T on the outlet from time 0 to 120s for both inlets.
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Eleven
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
There are two common approaches in modeling reactions:
Partially stirred rector (PaSR) model is used to model thermodynamic and chemical reactions
numerically, for example, combustion. In the PaSR approach, a computational cell is split into two
different zones: a reacting zone and a non-reacting zone. The reacting zone is modeled as a
perfectly stirred reactor (PSR), and all reactants are assumed to be perfectly mixed with each other.
For the reactor, we are interested in three concentrations, 1) mean concentration of key component
in the feed, 𝑐𝑐𝑖𝑖𝑖𝑖 ; 2) mixture concentration in the reacting zone, 𝑐𝑐; 3) concentration at the reactor
exit𝑐𝑐𝑒𝑒𝑒𝑒𝑒𝑒𝑒𝑒 .
In the reacting zone, reaction occurs for a duration of 𝜏𝜏𝑐𝑐 , so the concentration of mixture changes
from 𝑐𝑐𝑖𝑖𝑖𝑖 to 𝑐𝑐. In the non-reacting zone, the reacted mixture is getting mixed up with the non-reacted
mixture for a duration of 𝜏𝜏𝑚𝑚𝑚𝑚𝑚𝑚 , resulting in the final exit concentration, 𝑐𝑐𝑒𝑒𝑒𝑒𝑒𝑒𝑒𝑒 .
A key parameter to be calculated in this model would be the reaction rate, and it is clear that the
reaction rate is proportional to the ratio of the chemical reaction time to the total conversion time in
the reactor (i.e. sum of reacting and mixing time), 𝜅𝜅𝑘𝑘 :
𝜏𝜏𝑐𝑐
𝜅𝜅𝑘𝑘 =
𝜏𝜏𝑐𝑐 + 𝜏𝜏𝑚𝑚𝑚𝑚𝑚𝑚
The Eddy Dissipation Concept (EDC) model looks at the interaction between reaction and
turbulence, where the overall reaction rate is controlled by turbulent mixing. It is widely used for
combustion modeling for a great variety of combustion environments with great success.
It is assumed in the model that most reaction takes place within fine turbulence structures, which
are modeled as perfectly-mixed reactors. We need to know the reaction mass fraction and the mass
transfer rate between the fine structures and its surrounding fluid.
∗
𝑢𝑢∗ 2
𝛾𝛾 = � �
𝑢𝑢′
Where 𝑢𝑢∗ is the mass average fine structure velocity. The fine structures are located in regions with
nearly constant turbulent kinetic energy given by 𝑢𝑢′2 .
The mass transfer rate between fine structure and surrounding fluid per unit of fluid and per unit of
time is modeled as:
𝑢𝑢∗ ∗
𝑚𝑚̇ = 2 ⋅ ⋅ 𝛾𝛾
𝐿𝐿∗
where 𝐿𝐿∗ is the characteristic length of the fine structure.
OpenFOAM® Basic Training
Tutorial Eleven
reactingFoam – reactingElbow
Simulation
Use the reactingFoam solver, simulate combustion of CH4 and O2 in a mixing elbow:
• Use the two times finer Hex mesh from Example One
• velocity-inlet-5:
- Velocity: 1 m/s
- Temperature: 800 K
• velocity-inlet-6:
- Velocity: 3 m/s
- Temperature: 293 K
• Isolated walls
Objective
Data processing
Evaluate your results in ParaView.
OpenFOAM® Basic Training
Tutorial Eleven
1. Pre-processing
$FOAM_TUTORIALS/combustion/reactingFoam/laminar/counterFlowFlame2D
Copy the GAMBIT® mesh from Tutorial One (two times finer mesh) to the case main directory.
1.2. 0 directory
Update all the files in 0 directory with new boundary conditions, e.g. U:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
dimensions [0 1 -1 0 0 0 0];
boundaryField
{
wall-4
{
type fixedValue;
value uniform (0 0 0);
}
velocity-inlet-5
{
type fixedValue;
value uniform (1 0 0);
}
velocity-inlet-6
{
type fixedValue;
value uniform (0 3 0);
}
pressure-outlet-7
{
type zeroGradient;
}
wall-8
{
type fixedValue;
value uniform (0 0 0);
}
frontAndBackPlanes
{
type empty;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
The reaction taking place in this simulation CH4 combusting with O2 creating CO2 and H2O. N2 is
the non-reacting species. The boundary conditions and initial value of all species should be defined
in the 0 directory. These values are mass fractions (between 0 and 1) and dimension less, e.g. CH4:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
OpenFOAM® Basic Training
Tutorial Eleven
boundaryField
{
wall-4
{
type zeroGradient;
}
velocity-inlet-5
{
type fixedValue;
value uniform 0; //no CH4 at this inlet
}
velocity-inlet-6
{
type fixedValue;
value uniform 0.5; //50% CH4 mass fraction at this inlet
}
pressure-outlet-7
{
type zeroGradient;
}
wall-8
{
type zeroGradient;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
Note: If the file for a species does not exist in the 0 directory, the values from Ydefault will be used
for that species.
inertSpecie N2;
chemistryReader foamChemistryReader;
foamChemistryFile "$FOAM_CASE/constant/reactions";
foamChemistryThermoFile "$FOAM_CASE/constant/thermo.compressibleGas";
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
OpenFOAM® Basic Training
Tutorial Eleven
The mixture type is set to a reacting mixture for calculating the mixture properties and the heat
capacities are calculated using “janaf polynomials”.
𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚 𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓 𝑜𝑜𝑜𝑜 𝑖𝑖𝑖𝑖𝑖𝑖𝑖𝑖𝑖𝑖 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠 = 1 − � 𝑚𝑚𝑚𝑚𝑚𝑚𝑚𝑚 𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓𝑓 𝑜𝑜𝑜𝑜𝑜𝑜𝑜𝑜𝑜𝑜 𝑜𝑜𝑜𝑜ℎ𝑒𝑒𝑒𝑒 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠
The species and the reactions are addressed using foamChemistryFile. In this simulation
reactions and species are read from reactions file in the constant directory:
species
(
O2
H2O
CH4
CO2
N2
);
reactions
{
methaneReaction
{
type irreversibleArrheniusReaction;
reaction "CH4 + 2O2 = CO2 + 2H2O";
A 5.2e16;
beta 0;
Ta 14906;
}
}
OpenFOAM® v1906: Also the elements are listed in the reactions file and an element balance is
performed in the calculations!
The species in this simulation are O2, H2O, CH4, CO2 and N2. They are defined in the species
sub-dictionary. In the reactions sub-dictionary, reactions are specified. The reaction of methane
combustion is defined and it is of type irreversible Arrhenius reaction,
irreversibleArrheniusReaction.
In the Tutorial Two it was explained that the coefficients for calculating gas mixture properties are
defined in the mixture sub-dictionary because it was a homogeneous mixture. But in this example
the mixture is not homogenous so coefficients for calculating properties of each species are needed
separately to calculate mixture properties based on each cell composition. The coefficients of each
species are defined in the foamChemistryThermoFile, which reads the file thermos.compressibleGas
from the constant directory (this step is outlined in the thermophysicalProperties file). For example,
the O2 coefficients for each model are shown below:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
O2
{
specie
{
molWeight 31.9988;
}
thermodynamics
{
OpenFOAM® Basic Training
Tutorial Eleven
Tlow 200;
Thigh 5000;
Tcommon 1000;
highCpCoeffs ( 3.69758 0.00061352 -1.25884e-07 1.77528e-11 -
1.13644e-15 -1233.93 3.18917 );
lowCpCoeffs ( 3.21294 0.00112749 -5.75615e-07 1.31388e-09 –
8.76855e-13 -1005.25 6.03474 );
}
transport
{
As 1.67212e-06;
Ts 170.672;
}
}
…
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
In the thermodynamics sub-dictionary the janaf polynomial model coefficients for calculating the
heat capacity can be found and in transport the sutherland model coefficients for viscosity are
stored.
application reactingFoam;
startFrom startTime;
startTime 0;
stopAt endTime;
endTime 120;
deltaT 1e-6;
writeControl adjustableRunTime;
writeInterval 10;
purgeWrite 0;
writeFormat ascii;
writePrecision 6;
writeCompression off;
timeFormat general;
timePrecision 6;
runTimeModifiable true;
adjustTimeStep yes;
maxCo 0.4;
OpenFOAM® Basic Training
Tutorial Eleven
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
2. Running simulation
>fluentMeshToFoam fineHex.msh
After converting the mesh, check the boundary file in the constant/polyMesh directory and change
the type and inGroups of boundary frontAndBackPlanes from wall to empty (it is a 2D
simulation).
>reactingFoam
>foamToVTK
3. Post-processing
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Twelve
Compatibility:
• OpenFOAM® 7
• OpenFOAM® v1906
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
In this tutorial, we will familiarize ourselves with the snappyHexMesh tool in OpenFOAM®. This
utility generates 3D meshes containing hexahedra and split-hexahedra. We will also introduce
different types of meshes with complex geometries and compare the snappyHexMesh tool with
other mesh generation tools.
So far we have only worked with meshes in Cartesian co-ordinates, however, many engineering
problems involve complex geometries that do not fit exactly in Cartesian co-ordinates. In such
cases, it would be much more advantageous to work with grids that can handle curvature and
geometric complexity more naturally.
CFD methods for complex geometries are classified into two groups:
• Cells center points can be mapped into a matrix based on their location in the grid
• Structure and position in the matrix is given by indices (I, J in two dimensions and I, J, K in
three dimensions)
For the most complex geometries it may be necessary to sub-divide the flow domain into several
different blocks, where each mesh cell is a block, this is known as block-structured grids. The
next level of complexity is the unstructured grids. It gives unlimited geometric flexibility, here the
limitations of structured grids do not apply – but at the cost of higher programming and
computational efforts. Unstructured grids also allow the most efficient use of computing resources
for complex flows, so this technique is now widely used in industrial CFD.
There are a number of advanced meshing tools available, both commercial and free source. The
major mesh generators are ANSYS GAMBIT®, ICEM, Salome, snappyHexMesh and cfMesh. Here
we will learn about GAMBIT®, snappyHexMesh and cfMesh tools in detail.
2.1. GAMBIT®
GAMBIT® is a 3D unstructured tool, to specify the meshing scheme in it, two parameters must be
specified:
• Elements
• Type
OpenFOAM® Basic Training
Tutorial Twelve
The Elements parameter defines the shape(s) of the elements that are used to mesh the object. The
Type parameter defines the pattern of mesh elements on the object. It has a single graphical user
interface which brings geometry creation and meshing together in one environment.
2.2. snappyHexMesh
In contrast to GAMBIT®, which incorporates both mesh generation and refinement, the
snappyHexMesh tool built within OpenFOAM® requires an existing geometry base mesh to work
with. The base mesh usually comes from the blockMesh tool. This utility has the following key
features:
• allow parallel execution to speed up the process
• supports geometry data from STL/OBJ files
• addition of internal and wall layers
• zonal meshing
The key steps involved when running snappyHexMesh are:
• Castellation: The cells which are beyond a region set by a predefined point are deleted
• Snapping: Reconstructs the cells to move the edges from inside the region to the required
boundary
• Layering: Creates additional layers in the boundary region.
The advantages of snappyHexMesh over the other mesh generation tools are as follows:
• No commercial software package is ultimately necessary. For the meshing, the OpenFOAM®
environment is sufficient and no further software is necessary.
• The geometry can be created with any CAD program like CATIA®, FreeCAD, etc. As the
geometry is to be only surface data, the files need to be in .stl, .nas or .obj. format.
• The meshing process can be run in parallel mode. If high computational capabilities are
available, high quality meshes can be generated in little time.
2.3. cfMesh
cfMesh is an open-source library for mesh generation implemented within the OpenFOAM®
framework (similar to snappyHexMesh). Currently cfMesh is capable of producing mesh of
Cartesian type in both 2D and 3D, tetrahedral and polyhedral types.
The fundamental work-flow of the tool starts from a mesh template, then followed by a mesh
modifier. The modifier allows for efficient parallelization using shared memory parallelization
(SMP) and distributed memory parallelization using MPI.
OpenFOAM® Basic Training
Tutorial Twelve
snappyHexMesh – flange
Simulation
The procedure described in this tutorial is structured in the following order:
• Creation of the geometry data
• Meshing a geometry with one single region
• Run an OpenFOAM® simulation with the generated mesh using scalarTransportFoam
Objectives
• The aim of the tutorial is to give a basic introduction to single region meshing with the meshing
tool snappyHexMesh
Data processing
Import your simulation to ParaView and analyze the heat distribution in the flange.
OpenFOAM® Basic Training
Tutorial Twelve
1. Pre-processing
$FOAM_TUTORIALS/mesh/snappyHexMesh/flange
Normally the .stl files are created using CAD software, such as CATIA® and freeCAD. stl files
contain information about the solid geometry. However, in this tutorial the stl files are available to
be copied from the OpenFOAM® tutorials folder. To do this, copy the stl files from the below
location to the constant/triSurface of your running case directory.
$FOAM_TUTORIALS/resources/geometry/flange.stl.gz
- triSurface:
The folder triSurface should contain a file with the geometry data to be meshed (stl, nas, obj).
The file name is to be used as a reference pointer in later stages.
Note: The stl file should be in ascii format. All the stl files (different boundaries stl files) should
form a closed geometry together.
For creating a mesh using snappyHexMesh the following files should be present in system
directory:
- blockMeshDict
For meshing using snappyHexMesh a background mesh is needed, which should surround the
geometry surface (e.g. stl file) file. The background mesh will be refined based on the settings in
the snappyHexMeshDict and the extra parts will be removed. Usually the background mesh is
crated using blockMesh. Here we define a base mesh.
Note: To ensure that the sharp edges are refined properly, it is very important to create perfect
cube cells in the background mesh using blockMesh utility.
- decomposeParDict
The meshing using snappyHexMesh can be also performed in parallel mode. If the mesh is to be
run in parallel using the decomposePar utility, this file defines the parameters for distributed
processors
- meshQualityDict
Parameters to be checked for mesh quality and their values are defined in this file.
OpenFOAM® Basic Training
Tutorial Twelve
- surfaceFeatureExtractDict:
Using surfaceFeatures utility prior to meshing with snappyHexMesh helps to extract the sharp
edges and have a better mesh with snappyHexMesh on these edges. All edges are marked,
whose adjacent surfaces normal are at an angle less than the angle specified in includedAngle
in the surfaceFeaturesDict. The extracted edges are written to “*.extendedFeatureEdgeMesh”
files in constant/extendedFeatureEdgeMesh folder to be treated later in the meshing process.
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Surfaces (“flange.stl”);
includedAngle 150;
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
OpenFOAM® v1906: the utility surfaceFeatureExtract should be used for extracting sharp edges,
the setup file is surfaceFeatureExtractDict!
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
flange.stl
{
extractionMethod extractFromSurface;
extractFromSurfaceCoeffs
{
includedAngle 150;
}
writeObj yes;
}
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
- snappyHexMeshDict:
This file includes the settings for running the snappyHexMesh. As mentioned in the Background
section meshing using this tool has three steps:
1 – Castellating
2 – Snapping
3 – Layering
In the first section of this file, castellatedMesh, snap, addLayers can be set to true or
false depending on the stages required.
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
castellatedMesh true;
snap true;
addLayers true;
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
The Geometry sub-dictionary lists all surfaces used by snappyHexMeshDict, except the
blockMesh geometry, and defines a name for each of them to be used as a reference.
OpenFOAM® Basic Training
Tutorial Twelve
Then we specify a region of the domain that we want to refine. The refined region is given an
arbitrary name; in this case, it is refineHole, which is a sphere with its center and radius
defined.
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
geometry
{
flange
{
type triSurfaceMesh;
file “flange.stl”;
}
refineHole
{
type searchableSphere;
centre (0 0 -0.012);
radius 0.003;
}
};
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
CASTELLATING
In the castellating step based on the settings in the snappyHexMeshDict file the created
background mesh (in this case using blockMesh) cells are cut into sub-cells and the unneeded
part of the mesh will be deleted. The background mesh is known as mesh “level 0”, by setting
the “level” to 1 the background mesh at the position of features or defined refinements will be
cut into half in each direction (creating 8 sub-cells for a 3D mesh). Therefor by each level of
refinement number of cells increases by factor 8!
refinementSurfaces are for surface based refinement. Every surface is specified with two
levels. The first level is the minimum level that every cell intersecting the surface gets refined
up to. The second level is the maximum level of refinement.
locationInMesh: Important coordinate for single region cases, to define which part of the
mesh should be kept, inside or outside the geometry.
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
castellatedMeshControls
{
maxLocalCells 100000;
maxGlobalCells 2000000;
minRefinementCells 0;
nCellsBetweenLevels 1;
features
(
{
file "flange.extendedFeatureEdgeMesh";
level 0;
}
);
refinementSurfaces
{
flange
{
level (2 2);
}
}
resolveFeatureAngle 30;
refinementRegions
{
refineHole
{
mode inside;
levels ((1E15 3));
}
locationInMesh (-9.23149e-05 -0.0025 -0.0025);
allowFreeStandingZoneFaces true;
}
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Note: The locationInMesh point should never be on a face of the mesh, even after refinement.
It should always be inside a cell or the meshing will fail!
OpenFOAM® Basic Training
Tutorial Twelve
In the castellated step, the background mesh will be refined based on the defined refinement levels
at features, surfaces or regions and the unneeded part of the mesh will be removed.
SNAPPING
Important parameters are number of mesh displacement iterations, nSolveIter and the number of
feature edge snapping iterations, nFeatureSnapIter.
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
snapControls
{
nSmoothPatch 3;
tolerance 1.0;
nSolveIter 300;
nRelaxIter 5;
nFeatureSnapIter 10;
implicitFeatureSnap false;
explicitFeatureSnap true;
multiRegionFeatureSnap true;
}
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
LAYERING
The label for the layering is equal to the labeling of the Boundary surface in the boundary file in the
constant/polyMesh folder.
finalLayerThickness 0.3;
minThickness 0.25;
nGrow 0;
featureAngle 30;
nRelaxIter 5;
nSmoothSurfaceNormals 1;
nSmoothNormals 3;
nSmoothThickness 10;
maxFaceThicknessRatio 0.5;
maxThicknessToMedialRatio 0.3;
minMedianAxisAngle 90;
nBufferCellsNoExtrude 0;
nLayerIter 50;
nRelaxedIter 20;
}
meshQualityControls
{
OpenFOAM® Basic Training
Tutorial Twelve
#include "meshQualityDict"
relaxed
{
maxNonOrtho 75;
}
nSmoothScale 4;
errorReduction 0.75;
}
writeFlags
(
scalarLevels
layerSets
layerFields
);
mergeTolerance 1e-6;
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Note: Only the relevant changes, which were used in the sample flange case, are commented in
the snappyHexMeshDict.
2. Running snappyHexMesh
According to the settings in the blockMeshDict, the mesh was created with 20 cells in x direction,
16 cells in y direction and with 12 cells in z direction.
>surfaceFeatures
>snappyHexMesh
Note: The meshing process with snappyHexMesh can also be run in parallel. To run the command
on several processors, refer to Tutorial Eight for more information.
The command snappyHexMesh creates a folder with the mesh files for each mesh step. If, for
example, in the snappyHexMeshDict, only castellatedMesh is set to true and snap and addLayers
are set to false, only one folder is created. If also snap is set to true, 2 folders are created and if also
addLayers is set to true, 3 folders with 3 polyMesh folders are created.
In order to avoid the creation of these folders and only keep the final mesh, the following command
can be used to overwrite the previous meshing steps. In this case, only one polyMesh folder exits in
the /constant directory.
>snappyHexMesh -overwrite
However, sometimes it is useful to run snappyHexMesh without the overwrite option, as it allows
the user to make changes to a specific time step without having to run all the other steps again, thus
reducing computational time.
To examine, what each of the steps in the snappyHexMeshDict really does, we need to turn off the
overwrite feature in snappyHexMesh command and generate VTK files to be opened in ParaView.
OpenFOAM® Basic Training
Tutorial Twelve
>foamToVTK
Simply change the time in Paraview to see the effect of snappyHexMesh steps on the mesh, i.e. time
1 corresponds to the mesh after castellating step, time 2 for the mesh after snapping step, time 3 for
the mesh after the layering step.
The slice views taken with ParaView from the center of the flange. The slices are depicted by the
red plain in the following figure:
You can review the mesh quality with the tool checkMesh.
>checkMesh
4. Running simulation
The flange mesh files need to be transferred to the running case directory. To achieve this, copy the
polyMesh folder from the latest time step file of the flange folder into the constant directory of the
pitzDaily folder. If the overwrite function is activated when running snappyHexMesh, copy the
polyMesh folder from constant directory of the flange folder.
OpenFOAM® Basic Training
Tutorial Twelve
boundaryField
{
flange_patch1
{
type fixedValue;
value uniform 350;
}
flange_patch2
{
type fixedValue;
value uniform 293;
}
flange_patch3
{
type fixedValue;
value uniform 293;
}
flange_patch4
{
type fixedValue;
value uniform 350;
}
}
- Update the U file in the 0 directory so that the velocity in the entire flange domain and at the
boundaries is zero
- Update the controlDict file in the system directory by changing the endTime to 0.0005,
deltaT to 0.000001 and writeInterval to 100.
4.4. Results
Convert the results to VTK files with
>foamToVTK
OpenFOAM® Basic Training
Tutorial Twelve
0.00004s 0.00005s
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Thirteen
Compatibility:
• OpenFOAM® 7
• OpenFOAM® v1906
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. Multi-region modeling & why do we need it?
In multi-region modeling, the entire computational domain is divided into individual regions, with
each region representing a coherent continuum of the same phase. The key feature of this type of
modeling is that separate governing transport equations are solved for each region.
In general, two different approaches have been adopted in the past to solve multi-region problems:
• Monolithic: solve using a single coupled matrix equation system
• Partitioned: solve using separate matrix equation systems
In this OpenFOAM® tutorial, we are focusing on the partitioned approach. The fundamental steps in
this approach are outlined below:
1. Define the whole mesh domain and the separate regions within it. Assign cells into each
region
2. Specify field variables in each region
3. Solve the transport equation in each individual region
4. Multiregional coupling at the interface between different regions
5. Iteration to achieve fully/coupled solution
2. chtMultiRegionFoam solver
This solver is developed to solve heat transfer problems between multiple regions.
OpenFOAM® Basic Training
Tutorial Thirteen
snappyHexMesh - snappyMultiRegionHeater
Simulation
Objectives
• Understanding multi region meshing with the meshing tool snappyHexMesh
Data processing
Import your simulation to ParaView. Analyze the flow field through the flange and the heat
distribution in the flange.
OpenFOAM® Basic Training
Tutorial Thirteen
1. Pre-processing
Download the following tutorial to your working directory (the folders should be created by user
and then download the files and place them in relevant folders):
https://github.com/OpenFOAM/OpenFOAM-
5.x/tree/master/tutorials/heatTransfer/chtMultiRegionFoam
1.2. 0 directory
Unlike the single region simulations in the 0 directory an individual folder per region exist which
stores the files including initial and boundary conditions for that region. Also in the 0 directory
some files exists which are just dummy files that will not be used in the simulations. The initial and
boundary conditions for each region are changed and updated using the changeDictionary utility
which will be explained later.
OpenFOAM® v1906: Copy the file g from constant/topAir to the constant directory!
Like constant directory also in system directory a folder per region can be found and all the settings
for that region are stored in the corresponding folder, e.g. fvSolution, fvSchemes and
decomposeParDict. The fvSchemes file in the system directory is a dummy file while the fvSolution
includes the number of outer correctors setting for PIMPLE algorithm. There is also just one
controlDict file and it is in main system folder.
Note: For running the simulations in parallel the decomposeParDict files for all the regions should
OpenFOAM® Basic Training
Tutorial Thirteen
have the same settings as the main one in the system directory. This is not valid for parallel meshing
using snappyHexMesh while it just uses the decomposeParDict file in the main system directory.
The files needed for creating a multi-region mesh are the same as the mesh for single-region, except
for slight differences in snappyHexMeshDict file:
locationInMesh: In a multi-region mesh this point is not used but it should be defined just as
a place holder.
refinementSurfaces: Different regions are defined in here. E.g. for the region BottomAir
all the faces and cells inside the bottomAir stl (each region stl should be a closed volume) file
are marked with bottomAir flag (in faceZone and cellZone).
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
castellatedMeshControls
{
maxLocalCells 100000;
maxGlobalCells 2000000;
minRefinementCells 10;
nCellsBetweenLevels 2;
features
(
{
file "bottomAir.eMesh";
level 1;
}
…
{
file "topAir.eMesh";
level 1;
}
);
refinementSurfaces
{
bottomAir
{
level (1 1);
faceZone bottomAir;
cellZone bottomAir;
cellZoneInside inside;
}
…
rightSolid
{
level (1 1);
faceZone rightSolid;
cellZone rightSolid;
cellZoneInside inside;
}
}
resolveFeatureAngle 30;
refinementRegions
{
}
locationInMesh (0.01 0.01 0.01);
allowFreeStandingZoneFaces false;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
After creation of the mesh and splitting to different regions the initial and boundary conditions
for each region can be manually set in the relevant region folders in 0 directory. This process can
OpenFOAM® Basic Training
Tutorial Thirteen
be also automated usind the changeDictionary utility. The dictionary file for this utility for each
region is in the relevant region folder in the system directory: changeDictionaryDict.
See below the changeDictionaryDict file for the heater region. In the boundary sub-dictionary
type of boundaries for minY, MinZ and maxZ are set to patch. Then for T the internal field will
be overwritten with uniform 300. In the next step all the boundaries in the T file for heater
region will be set to zeroGradient (“.*” means all the boundaries with any name) and after
that the bounadries with the name “heater_to_.*” will be changed to
turbulentTemperatureCoupledBaffleMixed and minY will be changed to fixedValue.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
boundary
{
minY
{
type patch;
}
minZ
{
type patch;
}
maxZ
{
type patch;
}
}
T
{
internalField uniform 300;
boundaryField
{
“.*”
{
type zeroGradient;
value uniform 300;
}
“heater_to_.*”
{
type compressible::turbulentTemperatureCoupledBaffleMixed;
Tnbr T;
knappaMethod solidThermo;
value uniform 300;
}
minY
{
type fixedValue;
value uniform 500;
}
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *//
to
#includeEtc “caseDicts/mesh/generation/meshQualityDict.cfg”
OpenFOAM® v1906: Add the pRefCell/pRefValue lines to the fvSolution file for the bottomAir
region:
PIMPLE
{
momentumPredictor yes;
nCorrectors 2;
nNonOrthogonalCorrectors 0;
pRefCell 0;
pRefValue 1e5;
}
Add the missing “;” to the fvSolution files for bottomAir and topAir regions:
Note: Add the missing “;” to the fvSolution files for bottomAir and topAir regions:
“(rho|rhoFinal)”
{
solver PCG;
preconditioner DIC;
tolerance 1e-7;
relTol 0;
}
Equal to the single region case, the command surfaceFeatureExtract creates the eMesh files
from the stl files with the geometry data. Also the folder extendedFeatureEdgeMesh is created in
the constant directory. The creation of eMesh files with the command surfaceFeatureExtract
is not obligatory. This step is only necessary, if certain edges need to be refined.
>surfaceFeatureExtract
For performing the meshing in parallel, the geometry needs to be decomposed prior to running
snappyHexMesh. Depending on the number of subdomains, defined in the decomposeParDict, the
processor folders are created accordingly.
>decomposePar
Note: It is recommended, not to use the scotch method to decompose the region. Rather, the
hierarchical or the simple method should be used. In case of scotch method, errors can occur while
executing snappyHexMesh or while reconstructing the mesh.
In order to prevent the creation of the folders 1, 2 (castellation and snapping features are turned on
while layering is turned off) and only keep the final time step folder with the final mesh, the
command -overwrite can be added after snappyHexMesh. In this case, only one folder, 0, is created
with the files pointLevel and cellLevel. The mesh data in this case is located in constant/polyMesh.
>mpirun -np 4 snappyHexMesh -parallel -overwrite
Note: If castellatedMesh and snap are set on true in the snappyHexMeshDict, only the snapped
mesh is stored, whereas the intermediate step castellatedMesh is overwritten. If castellatedMesh,
snap and addLayers are set on true in the snappyHexMeshDict, only the layered mesh is stored and
the previous intermediate steps castellatedMesh and snap are overwritten.
OpenFOAM® Basic Training
Tutorial Thirteen
In this case only the steps castellatedMesh and snap are set to true, as these steps are applied to the
whole mesh. The following command reconstructs the final mesh:
>reconstructParMesh -constant
After running the command reconstructParMesh, the following message appears in the
terminal window, which can be ignored:
This is an experimental tool, which tries to merge individual processor meshes back into one master
mesh. ...
Not well tested & use at your own risk!
After this step all the regions are meshed but the meshes are connected and needs to be split. In the
meshing step each region cells are marked with a flag and this flag will be used in the next step to
split the mesh. Mesh regions can be split using the following command which split the mesh based
on the flagged cellZones and overwrite the old meshes in the polyMesh directories in the region
folders (if any exist):
>splitMeshRegions -cellZones -overwrite
With the mesh ready, the next step is to apply appropriate field values to each region, according to
the changeDictionaryDict. This command needs to be repeated for each region, with the name of
the region specified after the prefix ‘–region’.
>chtMultiRegionFoam
The results need to be converted to VTK files for each region with flag -region.
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Tutorial Fourteen
Compatibility:
• OpenFOAM® 7
• OpenFOAM® v1906
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Background
1. Introduction to sampling
This tutorial is an introduction to the OpenFOAM® sampling utility. With this utility
one can extract sample data from certain selected surfaces or points in ones simulation
after or while running the simulation. If data is sampled while running one can use
sampling to observe the progress of the simulation and the correctness of the solution
without even reaching a write-interval.
Using a sample file in the system directory data can be sampled after the simulation or
by adding the needed functions to the controlDict it can be done while running a
simulation.
At the beginning of this tutorial the implementation for sampling using the sample
and the controlDict will be introduced and afterwards the different sampling options
in OpenFOAM® will be discussed.
OpenFOAM® Basic Training
Tutorial Fourteen
sonicFoam – shockTube
Tutorial outline
Simulate the flow along a shock tube for 0.007 s and use OpenFOAM® sampling
utility for extracting the data along a line during the simulation and after the
simulation.
Objectives
• Understand the function of sampling and how to use the sampling utility
Data processing
Import your simulation to ParaView to visualize it and analyze the extracted data with
sampling tool.
OpenFOAM® Basic Training
Tutorial Fourteen
1. Pre-processing
1.1.Copying tutorial
To test the sampling feature, we will use the shockTube tutorial covered in Tutorial
Three and extract data over a line between (-5 0 0) and (5 0 0).
$FOAM_TUTORIALS/compressible/rhoPimpleFoam/laminar/shockTube
OpenFOAM® v1906:
$FOAM_TUTORIALS/compressible/sonicFoam/laminar/shockTube
1.2.system directory
1.2.1.sample dictionary
The sample file can be found in the system directory.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
type sets;
libs (“libsampling.so”)
interpolationScheme cellPoint;
setFormat raw;
sets
(
data
{
type uniform;
axis x;
start (-4.995 0 0);
end (4.995 0 0);
nPoints 1000;
}
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
In the type the type of data to be sampled is defined, e.g. sets or surfaces. The
different options for interpolationScheme and setFormat will be discussed in a
later section.
In the sets sub-dictionary each set of data should be given a name, which is freely
chosen by the user, in this case the name is simply ‘data’. In the bracket for the set of
data, we need to specify the following criteria:
- type: specifies the method of sampling. Here uniform was chosen to make a
sample on a line with equally distributed number of points.
OpenFOAM® Basic Training
Tutorial Fourteen
- axis: to define how the point coordinates are written. In this case, x means that
only the x coordinate for each point will be written.
- Start/end: the endpoints of the line-sample are defined
- nPoints: number of points on our line
Outside of the data and sets bracket in the fields we have to define which fields we
want to sample.
1.2.2.controlDict
To have the option to sample for each time step instead of each write-interval or
sampling while the solver is running; instead of the sample dictionary additions in the
controlDict are needed.
In this part one will change the controlDict of the shockTube tutorial so that our line-
sampling from before will be executed while running, and per time step.
Add the following code to the end of the function sub-dictionary in the controlDict.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
…
functions
{
#includeFunc mag(U)
linesample
{
type sets;
functionObjectLibs (“libsampling.so”);
writeControl timeStep;
outputInterval 1;
interpolationScheme cellPoint;
setFormat raw;
sets
(
data
{
type uniform;
axis x;
start (-4.995 0 0);
end (4.995 0 0);
nPoints 1000;
}
);
linesample sub-dictionary includes the settings for the sampling tool. Any arbitrary
name can be chosen instead of linesample. The chosen name will be the name of
the folder in the postProcessing directory after running the solver.
2. Running simulation
To run the Tutorial go to your case directory in the terminal and use the following
commands:
>blockMesh
>setFields
>sonicFoam
3. Post-processing
After sonicFoam solver finishes running, based on your sampling approach the
following steps should be performed:
3.1.sample dictionary
use the sample command to extract your sample-data.
A new folder will appear in your case directory named postProcessing and in it a
folder named sample. In this folder all the sampling data will be stored in separate
folders for each write-interval.
3.2.controlDict
The postProcessing directory and all its subdirectories have been generated after the
first time step. Now it can be seen that for every time step a folder is generated instead
of only every write interval.
OpenFOAM® Basic Training
Tutorial Fourteen
4. Types of sampling
There are 2 main types of sampling. The sets type, which was used in our example
above, and the surfaces type.
In the sets type of sampling different kinds of point samplings, like the line sampling
we used before, or some kind of cloud sampling are included. In the surface type
whole surfaces are sampled, like near a patch, or on a plane defined by a point and a
normal vector.
Let’s discuss the similarities between the set and surface types. If the sampling
happens in the controlDict the 4 entries discussed in the controlDict section of this
tutorial need to be included for both types. On top of that both types need an
interpolation scheme. Here only two of the schemes: cell and cellPoint will be
discussed. The cell scheme assumes that the cell centre value as constant in the whole
cell. The cellPoint scheme will carry out linear interpolation between the cell
centre and vertex values. Lastly the field bracket looks the same for both cases.
4.1. sets
All sets need a setFormat, for example csv which needs to be included after the
interpolationScheme.
After that the sets sub-dictionary begins where a bracket with an arbitrary name
begins in which the sets sampling type and the geometrical location of the sampling
points will be chosen. In the following a few of sampling types will be discussed.
4.1.1. uniform
This one was used in the above example. A line from a start point to an end point with
a fixed number of points evenly distributed along it.
OpenFOAM® Basic Training
Tutorial Fourteen
axis determines what is written for the point coordinate in the output file. distance
means it will only write the distance between sampled point and start point in the file.
lineX1
{
type uniform;
axis distance;
4.1.2. face
This type also samples along a line from a defined start to endpoint, but only writes in
the log file for every face the line cuts.
lineX2
{
type face;
axis x;
4.1.3. cloud
The cloud type samples data at specific points defined in the points bracket.
somePoints
{
type cloud;
axis xyz;
points ((0.049 0.049 0.00501)(0.051 0.049 0.00501));
}
4.1.4. patchSeed
The patchSeed sampling type is used for sampling patches of the type wall. One can
for example sample the surface adsorption on a wall with this type.
patchSeed
{
type patchSeed;
axis xyz;
patches (".*Wall.*");
maxPoints 100;
}
Please note that for patches only a patch of type wall can be used. If you choose a
wrong type, nothing will be sampled and you receive no error message.
4.2. surfaces
All surfaces need a surfaceFormat specified. Practical formats would be the vtk
format which can be opened with paraview and the raw format which can be used for
gnuplots. Instead of the sets bracket now a surfaces bracket must be used and the
type is of course also surfaces. Inside the surfaces brackets one can now sample
an arbitrary number of surfaces, each in its own inner brackets. The different types of
OpenFOAM® Basic Training
Tutorial Fourteen
surface sampling like the plane in the example below will be discussed in the next
sections.
type surfaces;
interpolationScheme cellPoint;
surfaceFormat vtk;
fields
(
U
);
surfaces
(
yoursurfacename
{
type plane;
basePoint (0.1 0.1 0.1);
normalVector (0.1 0 0);
triangulate false;
}
);
4.2.1. plane
The type plane creates a flat plane with an origin in the basePoint normal to the
normalVector. This normalvector starts in the origin, not in the basePoint. To
turn the triangulation of the surface off one has to add triangulate false.
constantPlane
{
type plane; // always triangulated
basePoint (0.0501 0.0501 0.005);
normalVector (0.1 0.1 1);
4.2.2. patch
A sampling of type patch can sample data on a whole patch. Please note that while
the syntax looks the same as in the patchSeed case, also patches that are not of type
wall work. Default option will triangulate the surface, this can be turned off with
triangulate false.
walls_interpolated
{
type patch;
patches ( ".*Wall.*" );
//interpolate true;
// Optional: whether to leave as faces (=default) or triangulate
// triangulate false;
}
4.2.3. patchInternalField
OpenFOAM® Basic Training
Tutorial Fourteen
Similar to the patch type, this type needs a patch on which it samples. It will sample
data that’s a certain distance away in normal direction (offsetMode normal). There
is also the option to define the distance in other ways seen in the commented section
of the code.
Note: While the sampling happens not on the patch but a distance away from it, the
geometric position of the sampled values in the output file will be written as the
position of the patch.
Once again the default triangulation can be turned off with triangulate false.
nearWalls_interpolated
{
// Sample cell values off patch.
// Does not need to be the near-wall
// cell, can be arbitrarily far away.
type patchInternalField;
patches ( ".*Wall.*" );
interpolate true;
4.2.4. triSurfaceSampling
With the triSurfaceSampling type data can be sampled in planes which are
provided as a trisurface stl file. To create such a file one can use the command below.
The command will generate a .stl file of one (or more) of your patches.
Here your patch needs to be replaced with the name of one of your patches defined in
the constant/polyMesh/boundary file. Starting the command without the patches
option will generate a stl file of your whole mesh boundary. Next make a directory in
the constant folder named triSurface if it doesnt already exis t and copy the .stl file
there. In the code you now have to specify your stl file as the surface. For the source
the use of boundaryFaces seems to be a good option of the stl file is one of your
patches.
triSurfaceSampling
{
// Sampling on triSurface
type sampledTriSurfaceMesh;
OpenFOAM® Basic Training
Tutorial Fourteen
surface integrationPlane.stl;
source boundaryFaces;
// What to sample: cells (nearest cell)
// insideCells (only triangles inside cell)
// boundaryFaces (nearest boundary face)
interpolate true;
}
Note: Most CAD software can export the surface of 3D drawings as stl files.
4.2.5. isoSurface
The isoSurface sampling type is quite different to what was discussed before in
this tutorial. Until now all the sampling types had a constant position in space and
changing field values at that position were extracted. With the isoSurface sampling
one tracks the position of a defined value in space. The example below can be copied
into the shocktube tutorials sample file (of course it needs all the other options needed
for surface type sampling).
Using vtk for the surfaceFormat one can visualize the moving shockwave in
space. Note that both the vtk of the sampling and the whole shocktube case can be
opened together in paraview to compare the results.
Note that the isoField needs to be a scalarfield.
interpolatedIso
{
// Iso surface for interpolated values only
type isoSurface;
// always triangulated
isoField p;
isoValue 9e4;
interpolate true;
//zone ABC;
// Optional: zone only
//exposedPatchName fixedWalls;
// Optional: zone only
// regularise false;
// Optional: do not simplify
// mergeTol 1e-10;
// Optional: fraction of mesh bounding box
// to merge points (default=1e-6)
}
4.2.6. isoSurfaceCell
The isoSurfaceCell type is very similar to the one we discussed before, but this
one doesn’t cross any cell with its surface and doesn't interpolate values.
constantIso
{
// Iso surface for constant values.
// Triangles guaranteed not to cross cells.
type isoSurfaceCell;
// always triangulated
isoField rho;
isoValue 0.5;
interpolate false;
regularise false;
// do not simplify
// mergeTol 1e-10;
// Optional: fraction of mesh bounding box
// to merge points (default=1e-6)
}
Appendix A
Linux Commands
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Appendix A
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
cat, more, less File viewer with pure read function - in order of ease of operation. In
less with pagedown/pageup you can navigate within the file, with / and
? can look for strings, q can be used for closing less. cat is back for
universally available on Unix.
cp, cp -r Copying files or entire directory trees (with -r option). Caution: There is
no warning or prompt when overwriting existing files! The important
thing is that a target has to be always given, at least one . which means,
copy to the current directory.
du, du -s, Calculates the amount of space consumed in a directory. For safety
reasons you should use the -k option (output in kilobytes), since some
du -k
systems provide the space in blocks that include only 512 bytes ...
gedit Text editor with graphical user interface. When working with gedit
some temporary files (originalFileName~) are created, they can be
deleted after saving.
grep Search command for plain-text data sets for lines matching a regular
expression.
kill, kill -9 Stopping processes. For this the process ID is required, which can be
found with top or ps. The Exit is irrevocable course - but you cannot
shoot processes, if you are not the "owner".
ls, ls –la Lists the contents of a directory, with option -la also hidden files are
displayed, as well as the file size and characteristics.
OpenFOAM® Basic Training
Appendix A
Nano, pico The command to run the nano text editor, a terminal based text editor.
ps, ps –A Lists all the processes that were started in the respective command
window with the options are all running processes on the system
ps waux
display.
rm, Deletes files. The option -r will also remove directories and files
CAUTION: recursively and delete directories, f (force) prevents any further inquiry.
rm -fr - Incorrectly applied, this command can lead to irreversible loss of all
(private) data. There is no undelete or undo!
scp The copy command over the network - as secure FTP replacement. Also
dominates the -r (recursive) option. Usage: scp source file destination
file with source and the destination format can be USERNAME@
COMPUTER.DOMAIN:PATH/TO/FILE. Source or target can of course
also be created locally, then (your) user name and computer are not
required.
tail, tail -f File viewer, the default outputs the last 10 lines of a file. With option -
n XX can spend the last XX lines, with the -f option, the command is
running from those lines, which are attached to a file. The command is
therefore perfect for watching log files.
top Displays a constantly updated list of all running processes, with process
ID, memory and CPU usage. For processes of one user top [username]
should be used, and for quitting q or ctrl+c should be applied.
vi, vim File editor. For forward searching use /, for backward searching use ?.
For exiting esc+:x. nano or pico are recommended for beginners, which
are easier to handle.
Appendix B
Running OpenFOAM®
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Appendix B
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
>. ./bashrc
Category>Session
Category>Connection>SSH>Tunnels
Destination: localhost:59** 1
Category>Session
• Press Save.
• Now choose from “saved sessions” your session (openFoamUser) and press
Open. In the opened Command (Prompt) window, it prompts for your
1 Display number
2 Session ID
OpenFOAM® Basic Training
Appendix B
password. The password is not echoed to the screen and the passwords are
case sensitive.
>. ./bashrc
• To log out use whatever command is used to logout from the server you are
logged into (typically ctrl + d).
• Open your Terminal application. You will see a window with a $ or > symbol
and a blinking cursor. From here, you may issue the following command to
establish the SSH connection to your server (be careful about upper case ‘L’ in
the -gL).
• You will then be prompted to enter your password. Type or copy/paste your
SSH user password into the Terminal. You will not see the cursor moving
while entering your password. This is normal. Once you are finished inputting
your password, press return on your keyboard. At this point, you will be
connected to your server remotely through SSH.
>. ./bashrc
• Make sure VNC Server is installed on the remote machine and it is started (ask
administrator for display number, port and other information, for starting
VNC Server check FAQ)
• Install the appropriate VNC Viewer and run it (search for: vnc viewer):
• Press Connect
• Press Continue
• Press Ok
>. ./bashrc
• If a new terminal in the VNC desktop is opened, the last two steps should be
done in that to activate OpenFOAM® in there.
Appendix C
Frequently Asked Questions
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Appendix C
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
Q - How can I prevent typing long commands in the terminal for couple of times?
A - Using curser keys to navigate line by line.
Type beginning of the command and use Tab (auto completion).
By using reverse search, use ctrl+r to search for previous commands typed in
the terminal, e.g. typing a part of command show the suggestions and you can
navigate through them.
A - Use command:
>vncviewer :[NUMBER OF LOCAL PORT, e.g. 1 or 2]
Then after running setFields tool, it will assign the values to that region.
Q - How can I create a bash scripting file for executing couple of command in
series?
A - Instead of typing command sequences one by one after each other and executing
them. It is possible to put all those commands in a file and execute that file to
run them. This is known as “bash scripting”.
Bash scripting is typically used in the cases when the same simulation should be
run with identical settings a couple of times, but with a few changes. For bash
scripting create an empty file (e.g. using nano editor creating text file “go”):
> nano go
Add the commands to this file (e.g. commands for running blockMesh,
OpenFOAM® Basic Training
Appendix C
Exit the editor and save the file (ctrl+x , y, enter for nano editor).
For changing this file to an executable file, file permissions should be set. By
using this command file permissions are displayed:
>ls -la go
-rw-r--r-- 1 e166**** E020D166 73 Aug 23 9:15 go
The first ‘r’ shows that this text file can be read by user, the ‘w’ shows that user
has the permission to write this file, but the ‘–‘ sign shows that this file is not
executable by the user. To change this permissions execute following command:
>chmod u+x go
After executing the file, the commands added to the file will be executed one by
one. In most of the OpenFOAM® tutorials there are Allrun and Allclean files,
which are bash scripts for running the case and cleaning a case, respectively.
This offering is not approved or endorsed by ESI® Group, ESI-OpenCFD® or the OpenFOAM®
Foundation, the producer of the OpenFOAM® software and owner of the OpenFOAM® trademark.
OpenFOAM® Basic Training
Appendix D
ISBN 978-3-903337-00-8
Publisher: chemical-engineering.at
1. Introduction to ParaView
The post-processing application for OpenFOAM® is ParaView, which is a free, open
source program. In this tutorial, different features and tools available in ParaView
5.6.0 will be explored.
ParaView Interface
The tree structure (“pipeline”) of ParaView helps the user to easily choose and display
suitable sub-models for creating the desired image or animation. Adding a mesh or
velocity vectors to a contour plot of pressure is an example of this functionality.
2. ParaView Interface
2.1. Properties Panel
Properties panel
OpenFOAM® Basic Training
Appendix D
- Colouring
The drop-down menu for solid colour allows different field variables to be chosen
and viewed, for example, pressure and velocity magnitude.
The Rescale button allows the data range to be adjusted to fit the data, as
sometimes the max/min data range are not updated automatically.
- Scalar Coloring
The ‘Map Scalars’ option allows the scalar values to be mapped to a specific
colour using a lookup table.
Turning the option ‘Interpolate Scalars Before Mapping’ on or off will affect the
way the scalar data is visualized with colours. According to the ParaView
documentation, if it is turned on, scalars will be interpolated within polygons and
colour mapping will happen on a per-pixel basis; if off, color mapping occurs at
polygon points and colors are interpolated, which is generally less accurate[1].
- Styling
The opacity of the image can be set (1 = solid, 0 = invisible) in the Opacity option.
- Lighting
There are two options for Interpolation, Gouraud or Flat. With Gouraud shading
enabled, normals are defined only per point and no face normal is needed. If the
Interpolation is changed to Flat, only the face normals will be computed and used
for lighting, note that this option is not suitable for objects with smooth surfaces
[2]
.
- Backface Styling
This is an advanced feature in ParaView that enables the backface style of a wire
frame object to be changed.
- Transforming
The Transform filter allows you to translate, rotate and change the size and the
origin of the data sets.
- Miscellaneous
By default ParaView triangulate the cells and shows them as triangles. For
disabling this uncheck the “Triangulate” option in the Miscellaneous section of
the Properties panel.
- Glyph Parameters
The Glyth Parameters filter generates a glyph, which can be arrow, cone, box,
cylinder, line, sphere or a 2D glyph. The glyth is generated at each point in the
input dataset[3]. Depending on the type of glyph chosen, different options are
available to orientate, scale and size the glyph.
- Orientation Axes
The Orientation Axes feature controls an axes icon in the image window (e.g. to
set the color of the axes labels x, y and z).
OpenFOAM® Basic Training
Appendix D
- Lights
The lighting controls options appear when clicking on the Edit button. For
producing images with strong bright colors (e.g. isosurface) Headlight of strength
1 is appropriate.
- Background
The background color of the layout can be chosen from the drop-down menu, with
types Single color, Gradient and Image available.
Button toolbars
Pull-down menus at the top of the main window and the major panels, in the toolbars
below the main pull-down menus increase the functionality of ParaView. The
function of each button can be easily understood by its icon, also any button
description can be found in the Help menu (keeping the mouse over an icon without
clicking on it will also give a short explanation on its functionality).
A feature worth mentioning is the drop-down menu next to the Reset button, this
provides the options of the different ways of presenting the mesh. To see the structure
of the mesh, use Surface with Edges; and to see both the cell structure and the interior
of the mesh, use Wireframe.
2.3. Color Map Editor Panel
The chosen scalar field can be selected from a pull down menu. If the case is a 3D
case module, the contours will be a set of 2D surfaces that represent a constant value.
The Isosurfaces list in the Properties panel allows the user to specify the values at
which the isosurfaces are computed.
By default ParaView triangulate the cells and shows them as triangles. For disabling
this uncheck “triangulate the slice” option in the Properties panel of the slice.
3.3. Streamlines
To create tracer lines, click on the Stream Tracer button in the Button Toolbars.
Tracer points can be along a line or points, and this can be chosen in the Seed Type
drop-down menu in the Seeds section of the Properties panel. Usually, some trial and
error is needed for achieving the desired streamlines. The length of steps tracer takes
can be changed in the Streamline Parameters section of the Properties panel. A
smaller length increases calculation time but increases smoothness. For having high
quality images Tubes filter can be used after tracer lines have been created. There are
different types of tubes, not only cylindrical.
3.4. Vector plots
The Glyph filter is used for creating vector plots. Scale Mode menu in the properties
panel is used for:
4. Data Analysis
4.1. Plot over time
This option is available by clicking the Plot Selection Over Time button in the Button
Toolbars. This allows the data at one point to be plotted over the entire time range.
4.2. Plot over line
This option allows the data points to be plotted along a line at a specific time step.
Click on the Plot Over Line button. The Cartesian coordinates of the beginning and
ending points of the line can be specified in the Properties panel. Several variables
OpenFOAM® Basic Training
Appendix D
can be plotted at the same time, to turn each variable on or off and to change its
legend name, use the Series Parameters section in the Properties panel.
4.3. Integrate Variables
The Integrate Variables option is selected from the Filters menu. This tool integrates
point and cell data over lines and surfaces. It also computes length of lines, area of
surface, or volume[4]. Different data types available are Point Data, Cell Data, or
Field Data; this can be chosen in the Field Association section in the Properties panel.
5. Exporting Data
5.1. Image Output
For creating a screenshot of the graphs the easiest way is Save Screenshot from File
menu. After selecting it in the opened window the picture resolution can be set, and
by locking the aspect ratio, changing image resolution in one direction cause change
in its resolution in the other direction respectively. For high quality images a
resolution of more than 1000 pixels is a good choice.