Full Tutorials
Full Tutorials
Bahram Haddadi
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.
Tutorial Structure
Each case example follows a structured learning approach:
0. Background: overview of the key concepts covered in the tutorial and the
CFD principles related to the case.
1. Pre-processing: step-by-step setup of the case, including directory
structure, essential input files (dictionaries), and necessary modifications.
2. Running the simulation: instructions on executing the solver, running
necessary commands, and monitoring the progress of the simulation.
3. Post-processing: analyzing the simulation results using OpenFOAM®'s
built-in tools and the visualization software ParaView v5.x.
By following these tutorials, users will gain hands-on experience in setting up,
running, and analyzing CFD simulations in OpenFOAM®.
OpenFOAM® Basic Training
Table of Contents
Appendix D: ParaView
Tutorial One
Basic Case Setup
Bahram Haddadi
Tutorial One
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial One
Background
1. What is CFD?
Computational Fluid Dynamics (CFD) is a method used to analyze systems
involving fluid flow, heat transfer, and related phenomena such as heat and
mass transfer. This analysis is performed through computer-based simulations,
which help in understanding how fluids behave under different conditions. CFD
is a powerful tool used in a variety of fields, including aerospace, automotive,
chemical engineering, environmental studies, and biomedical applications.
The goal of CFD development is to create tools that are as reliable as other
computer-aided engineering (CAE) methods like stress analysis. However,
CFD is trickier due to the complex nature of fluid flow, which involves
turbulence, variable properties, and nonlinear behavior. The mathematical
foundation of CFD is based on the Navier-Stokes and continuity equations,
which describe the motion of fluid substances and are derived from
fundamental conservation laws (mass and momentum). These equations are
partial differential equations that represent how fluid velocity, pressure, and
density change over time and space.
While CFD offers many advantages, such as cost reduction in experimental
setups and the ability to simulate complex scenarios, it is not fully automated.
A good understanding of the underlying physics is necessary to set up a reliable
simulation and interpret results correctly. Additionally, even with advanced
computational resources, real-time simulations are still challenging due to the
intensive calculations required. CFD is typically used alongside experimental
methods like wind tunnel testing to validate and improve results.
CFD software comes in two main types:
• Open-source and free (e.g., OpenFOAM®): Offers flexibility for
modification and customization, making it popular in academic and
research environments.
• Commercial and closed source (e.g., ANSYS Fluent, COMSOL):
Provides user-friendly interfaces, technical support, and advanced
features, making it suitable for industrial applications.
In this guide, the focus will be on OpenFOAM®, an open-source CFD software
written in C++. It allows users to access, modify, and even develop custom
solvers to meet specific research or industrial needs. OpenFOAM® is widely
used due to its flexibility and extensive documentation, although it requires a
good understanding of both CFD principles and programming basics.
For beginners, it's helpful to think of CFD as a "virtual wind tunnel" where you
can simulate fluid flow without physically building models or conducting real-
world experiments. This makes it a cost-effective and versatile tool, especially
during the design and testing phases of engineering projects.
CFD is not only limited to air and water flow simulations, and it is extensively
used in modeling different sophisticated processes such as: weather patterns
(meteorology), blood flow in arteries (biomedical engineering), combustion
OpenFOAM® Basic Training
Tutorial One
2. Workflow of CFD
A typical CFD workflow consists of three main stages:
2.1 Pre-processing
This stage involves setting up the simulation, including:
• Geometry Definition: Creating the computational domain that
represents the physical system. This can be done using CAD
(Computer-Aided Design) software or built-in geometry tools in CFD
software. The accuracy of geometry affects how well simulation
represents the real-world scenario. Think of geometry as the "shape" or
"structure" through which the fluid will flow. Beginners can start with
simple geometries like pipes, ducts, or channels before progressing to
complex designs.
• Mesh Generation: Dividing the domain into smaller, non-overlapping
elements (cells) to form a grid. The quality and density of the mesh
significantly affect the accuracy of the simulation. Finer meshes are used
in regions with high gradients (e.g., near walls, sharp edges, or around
obstacles), while coarser meshes suffice for uniform flow areas. Meshes
can be structured (regular grids) or unstructured (irregular shapes),
depending on the complexity of the geometry. A structured mesh is
easier to generate and solve but less flexible for complex geometries,
while an unstructured mesh can fit intricate shapes better. Imagine the
mesh as a net spread over your geometry. The tighter the net (finer
mesh), the more detailed your simulation results will be. However, this
also increases computational effort, so there's a balance to be found.
• Model Selection: Choosing physical models to represent phenomena
such as turbulence (e.g., k-epsilon, k-omega models), heat transfer, and
chemical reactions. The selection depends on the flow regime (laminar
or turbulent) and the specific application.
• Fluid Properties: Defining parameters like density, viscosity, thermal
conductivity, and specific heat capacity. These properties vary with
temperature, pressure, or composition in complex simulations.
Incompressible flow assumes constant density, while compressible flow
accounts for changes in density due to pressure and temperature
variations.
• Boundary and Initial Conditions: Setting conditions at the domain's
boundaries (e.g., velocity at an inlet, pressure at an outlet, wall
conditions) and initial conditions for transient simulations. Proper
boundary conditions are crucial for accurate results.
The solution variables (e.g., velocity, pressure, temperature) are calculated at
specific points within each cell. The mesh's resolution influences the
OpenFOAM® Basic Training
Tutorial One
2.2 Solver
In this stage, numerical methods are applied to solve the governing equations
of fluid flow, including:
• Conservation Equations: Mass, momentum, and energy conservation
laws are integrated over each control volume. These equations are often
coupled, meaning changes in one variable affect others. For example,
changes in velocity can influence pressure and vice versa.
• Discretization: The continuous equations are converted into algebraic
forms using methods like the finite volume method (FVM), which ensures
conservation principles are maintained within each cell. Other methods
include the finite difference method (FDM) and finite element method
(FEM), though FVM is most common in CFD. Discretization involves
approximating derivatives with algebraic expressions, allowing the
equations to be solved numerically.
• Solution Techniques: The resulting algebraic equations are solved
iteratively until convergence is achieved. Common iterative solvers
include the SIMPLE (Semi-Implicit Method for Pressure-Linked
Equations) and PISO (Pressure-Implicit with Splitting of Operators)
algorithms. Convergence is determined when changes in the solution
between iterations fall below a predefined threshold.
The finite volume method is widely used because it ensures the conservation
of physical quantities within each control volume, making it both accurate and
robust. It is also flexible for handling complex geometries and boundary
conditions.
Think of the solver as the "engine" of CFD—it's where all the heavy lifting
happens to calculate how the fluid moves. Understanding how the solver works
helps in troubleshooting and optimizing simulations.
2.3 Post-processing
This stage involves analyzing and visualizing the simulation results. Key tasks
include:
• Visualization: Using cutting planes, contour plots, vector fields,
streamlines, and line plots to represent flow variables such as velocity,
pressure, and temperature distributions. Visualization helps in identifying
flow patterns, vortices, and areas of interest like high-pressure zones.
OpenFOAM® Basic Training
Tutorial One
• Data Analysis: Evaluating physical quantities like forces (drag, lift), heat
transfer rates, pressure drops, and flow rates. Quantitative analysis
helps validate the simulation results against experimental data or
theoretical predictions.
• Validation: Comparing simulation results with experimental data or
theoretical models to ensure accuracy. Sensitivity analysis may be
conducted to understand the influence of different parameters.
Popular post-processing tools include commercial software like TecPlot and
Ensight, as well as open-source tools such as ParaView and SALOME. These
tools allow for advanced visualization techniques, including 3D rendering and
time-dependent animations, making it easier to interpret complex flow
behaviors.
Tip: Post-processing is not just about making pretty pictures. It helps you
understand the flow physics and detect any errors or inconsistencies in your
simulation.
3. icoFoam Solver
icoFoam is an OpenFOAM® solver suitable for analyzing incompressible,
laminar flow of Newtonian fluids. It is based on the PISO algorithm (pressure-
implicit split-operator), which is essentially a pressure-velocity iterative
procedure for transient problems. In each iterative step, PISO solves the
momentum equation using one predictor step, with two further corrector steps
for both velocity and pressure.
OpenFOAM® Basic Training
Tutorial One
icoFoam – elbow
Tutorial outline
Using icoFoam solver, simulate 75 s of flow in an elbow for the following
GAMBIT® meshes:
• Tri-mesh (comes with OpenFOAM® tutorial)
• Hex-mesh coarse (check GAMBIT® “elbow 2D” tutorial)
• 2 times finer hex-mesh (refined previous step mesh)
Objectives
• Basic case setup in OpenFOAM®
• Setting up initial values of p and U
• Ensuring proper boundary definitions (imported boundaries from
GAMBIT®, additional surfaces during conversion and boundaries definition 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/legacy/incompressible/icoFoam/elbow
>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 Units (International System of 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 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
OpenFOAM® Basic Training
Tutorial One
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 (which is not the case in this tutorial):
There are three main directories (0, constant, system) in each case folder:
1.4.1. 0 directory
The 0 directory includes the initial and boundary 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
OpenFOAM® Basic Training
Tutorial One
p file includes pressure initial and boundary 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 p
Note: nano is the command line based text editor, which comes by default with
Ubuntu. You can use any other text editor (also graphical ones) for opening and
editing the files.
Note: You can use ctrl+x for closing and exiting the nano.
/*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Website: https://openfoam.org |
| \\ / A nd | Version: 12 |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
format ascii;
class volScalarField;
object 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;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
OpenFOAM® Basic Training
Tutorial One
Tutorial One
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
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;
}
)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Comparing the boundary names and types with the ones set in GAMBIT®, they
should be the same.
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 importing
the mesh to OpenFOAM®, modify that boundary in the file constant/polyMesh/
boundary, and change its type from wall to empty, and 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.
The files in the constant directory (usually) include material properties,
simulation physics and chemistry, e.g. by opening the physicalProperties file,
properties dimensions and the property value can be found and edited, 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.
1.4.3. system directory
Solver and finite volume methods settings can be found and changed in this
directory. There are three main files in this directory:
- fvSchemes: The discretization scheme used for each term of the
equations are set in this file (it will be discussed in more detail in the next
tutorials).
- fvSolution: Contains the settings to the coupling method of pressure
and velocity, the numerical methods, which are used for solving different
quantities, and the final tolerance for convergence of that quantity.
OpenFOAM® Basic Training
Tutorial One
startFrom latestTime;
startTime 0;
stopAt endTime;
endTime 75;
deltaT 0.05;
writeControl timeStep;
writeInterval 20;
purgeWrite 0;
writeFormat ascii;
writePrecision 6;
writeCompression off;
timeFormat general;
timePrecision 6;
runTimeModifiable true;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
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.
Note: Our first modification in the simulation is changing the endTime from the
original value of 10s to 75s, for running the simulation up to 75s.
OpenFOAM® Basic Training
Tutorial One
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: 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.
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
Tutorial One
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
Bahram Haddadi
Tutorial Two
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial Two
Background
1. What is Mesh?
When studying fluid flow and heat transfer, mathematical equations known as
partial differential equations (PDEs) describe how physical properties such as
mass, energy, and momentum change over space and time. However, solving
these equations directly (analytically) is extremely difficult unless the problem
is very simple.
To solve PDEs numerically, these equations are discretized and converted from
a set of PDEs to a set of algebraic equations. This involves breaking the entire
fluid domain into many smaller, manageable sections. These small sections are
called grid cells, and together they form a mesh.
A mesh is like a net or grid that covers the entire area where fluid behavior is
analyzed. The finer (smaller) the mesh, the more accurately flow details can be
captured, but at the cost of increased computational demand. Choosing the
right mesh ensures a balance between accuracy and efficiency in simulations.
One of the most common numerical methods for solving these equations is the
finite volume method (FVM), which is explained below.
The finite volume method works by applying and integrating this equation over
a control volume (CV), which is a small section of the mesh. A mathematical
technique called the Gauss divergence theorem helps converting volume
integral terms in the equation into surface integrals. This allows for the
calculation of the amount of a property entering and exiting each grid cell,
ensuring that all properties are conserved throughout the simulation.
𝜕
∫ (∫ 𝜌𝜑 𝑑𝑉) 𝑑𝑡 + ∫ ∫ 𝒏 ∙ (𝜌𝜑𝒖) 𝑑𝐴𝑑𝑡
∆𝑡 𝜕𝑡 𝐶𝑉 ∆𝑡 𝐴
= ∫ ∫ 𝒏 ∙ (𝛤∇𝜑) 𝑑𝐴𝑑𝑡 + ∫ ∫ 𝑆𝜑 𝑑𝑉 𝑑𝑡
∆𝑡 𝐴 ∆𝑡 𝐶𝑉
Tutorial Two
Tutorial Two
Tutorial outline
Using foamRun and fluid 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/fluid/forwardStep
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
OpenFOAM® Basic Training
Tutorial Two
In the thermoType, the models for calculating thermo physical properties of gas
are set:
- type: Specifies the underlying thermos-physical model, which in this
case is enthalpy based thermodynamics while incorporating the
equation of state using psi (compressibility)
- 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 transport model used. In this example a
constant value is used for viscosity.
- 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 momentumTransport 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)
OpenFOAM® Basic Training
Tutorial Two
(0 1 0.05)
(0.6 1 0.05)
(3 1 0.05)
);
blocks
(
hex (0 1 3 2 8 9 11 10) (25 10 1) simpleGrading (1 1 1)
hex (2 3 6 5 10 11 14 13) (25 40 1) simpleGrading (1 1 1)
hex (3 4 7 6 11 12 15 14) (100 40 1) simpleGrading (1 1 1)
);
defaultPatch
{
type empty;
}
boundary
(
inlet
{
type patch;
faces
(
(0 8 10 2)
(2 10 13 5)
);
}
outlet
{
type patch;
faces
(
(4 7 15 12)
);
}
bottom
{
type symmetryPlane;
faces
(
(0 1 9 8)
);
}
top
{
type symmetryPlane;
faces
(
(5 13 14 6)
(6 14 15 7)
);
}
obstacle
{
type patch;
faces
(
(1 3 11 9)
(3 4 12 11)
);
}
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Tutorial Two
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.
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.
Note: In OpenFOAM® (and C++) counting starts from 0 and not 1!
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 was explained in tutorial 1, 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.
The last part, simpleGrading(1 1 1) shows the size function, in this case 1
means there is no change in the cell size from one cell to another
In the boundary part, each boundary is defined by the vertices it is made of,
and 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:
Note: The solver can be also defined in the controlDict (which is the case here)
and then the simulation can be performed simply using foamRun command
without the solver flag.
OpenFOAM® Basic Training
Tutorial Two
3. Post-processing
The mesh is presented in the following way in ParaView, and you can easily
see the three blocks, which were created.
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”.
The simulation results are as follows:
0.5 s
1s
10 s
Bahram Haddadi
Tutorial Three
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial Three
Background
Tutorial Three
Tutorial Three
Tutorial outline
Use the “fluid” 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
• Learn how to specify initial and boundary conditions
• Investigate effect of grid resolution.
Data processing
Import your simulation into ParaView, and compare results.
OpenFOAM® Basic Training
Tutorial Three
1. Pre-processing
$FOAM_TUTORIALS/fluid/shockTube
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
>blockMesh
>setFields
Then run:
Tutorial Three
Note: Checking the information printed to the terminal (or log file) you can see
how by decreasing the cell size (e.g. by increasing the number of cells) or by
increasing the velocity (changing the pressure values) the Co number is
increasing at a constant time step. In case the Co is getting bigger than one,
the deltaT needs to be adopted accordingly to keep the Co below one.
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.007s
OpenFOAM® Basic Training
Tutorial Three
Pressure along tube axis for 10 bar/0.1bar and 10000 cells case at
t = 0.007s
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
Bahram Haddadi
Tutorial Four
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial Four
Background
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.
Choosing the right numerical scheme is essential for balancing accuracy and
stability in convection-dominated problems.
OpenFOAM® Basic Training
Tutorial Four
∫ 𝒏 ∙ (𝛤𝛻𝜑) 𝑑𝐴 = ∑ 𝛤𝑓 (𝒏 ∙ 𝛻𝑓 𝜑)𝐴𝑓
𝐴 𝑓
∫ 𝑆𝜑 𝑑𝑉 = 𝑆𝐼 𝑉𝑃 𝜑𝑃 + 𝑆𝐸 𝑉𝑃
𝑉
2. Discretization Schemes
Discretization schemes determine how values are interpolated between cell
centers and faces to compute fluxes accurately. The choice of scheme affects
solution accuracy, numerical diffusion, and computational stability. Below are
commonly used schemes and their respective advantages and limitations.
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
OpenFOAM® Basic Training
Tutorial Four
values in the neighboring cells using a variety of schemes. The flux satisfies
continuity constraints, which is prerequisite to obtaining the results.
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
𝑊ℎ𝑒𝑛 𝐹𝑒 > 0, 𝜑𝑒 = 𝜑𝑃 + 𝜑𝐸 − 𝜑𝑊
8 8 8
OpenFOAM® Basic Training
Tutorial Four
6 3 1
𝑊ℎ𝑒𝑛 𝐹𝑤 > 0, 𝜑𝑤 = 𝜑𝑊 + 𝜑𝑃 − 𝜑𝑊𝑊
8 8 8
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.
3. functions solver
Among foamRun solver modules functions solver, which is specifically
designed to execute function objects as defined in the system/controlDict or
system/functions files. Function objects are utilities within OpenFOAM that
facilitate workflow configurations and enhance simulations by generating
additional data during runtime or post-processing. By utilizing the functions
solver module with foamRun, users can automate the execution of these
function objects, streamlining processes such as data logging, field
calculations, and custom analyses without the need to run a full simulation. This
approach optimizes computational resources and simplifies the integration of
auxiliary calculations into the simulation workflow.
One of these functions is scalarTransport which resolves a transport equation
for a passive scalar. The velocity field and boundary condition need to be
provided by the user. It works by setting the source term in the transport
equation to zero (see equation below), and then solving the equation.
𝜕(𝜌𝜑)
+ 𝛻 ∙ (𝜌𝜑𝒖) − 𝛻 ∙ (𝛤𝛻𝜑) = 0
𝜕𝑡
OpenFOAM® Basic Training
Tutorial Four
Tutorial outline
Use the functions 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/fluid/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 physicalProperties file, and in
the system directory delete all the files except for blockMeshDict and
setFieldsDict files.
From the following case:
$FOAM_TUTORIALS/incompressibleFluid/pitzDailyScalarTransp
ort
Copy physicalProperties file to the constant folder in the newly created case
constant folder. Copy controlDict, fvSchemes, fvSolution and functions files
from the above case system directory to the created case system directory.
fieldValues
(
volScalarFieldValue T 1.0
);
}
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Tutorial Four
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
ddtSchemes
{
default Euler;
}
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.
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).
In the fvSolution file add pressure reference cell number and value to the
PIMPLE sub-dictionary, it should look like the following:
PIMPLE
{
nNonOrthogonalCorrectors 0;
pRefCell 0;
pRefValue 0;
}
OpenFOAM® Basic Training
Tutorial Four
Note: pRefCell and pRefValue are dummy values that solver can start the
calculations, since there is no pressure field available.
In the functions file, just keep the line for activating the scalar transport function.
In the functions file, different functions can be called, in this case the scalar
transport function is called with using “T” as the property (scalar) to be solved,
it uses a constant diffusivity model and set the value of it by setting D (in this
case it is 0.01).
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#includeFunc scalarTransport(T, diffusivity=constant, D = 0.01)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Note: By setting the diffusion coefficient “D” to zero, the case will be switched
to a pure advection simulation with no diffusion.
For part two:
• Set the diffusivity to 0, by setting the D in the functions file
• Set the velocity field to (1 0 0), either by using setFields utility or simply
in the 0/U file change the internalField to (1 0 0)
• Set different schemes in the fvSchemes file, for the div(phi, T)
2. Running simulation
>blockMesh
>setFields
3. Post-processing
Tutorial Four
Tutorial Four
Bahram Haddadi
Tutorial Five
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial Five
Background
1.1. Conservativeness
A discretization scheme is conservative if it ensures that the total amount of a
transported quantity (e.g., mass, momentum, energy) is preserved within the
solution domain. This property is fundamental for obtaining physically
meaningful results in fluid dynamics and preventing artificial gain or loss of the
transported variable.
To achieve conservativeness, the flux balance across each control volume
must be maintained. Mathematically, this means:
• The flux of φ leaving a control volume across a certain face must equal
the flux entering the adjacent control volume through the same face.
• The discretization scheme should represent the flux through a common
face consistently across adjacent control volumes.
A scheme that violates conservativeness can lead to unphysical results, such
as artificial creation or loss of mass or energy. Finite volume methods naturally
ensure conservation by integrating the governing equations over control
volumes, ensuring that what exits one control volume enters the next.
1.2. Boundedness
Most numerical solvers use iterative techniques to obtain the solution at each
node. The solver starts with an initial guess and updates the values until
convergence is achieved. To ensure a stable and physically meaningful
solution, the discretization scheme must satisfy boundedness criteria.
A bounded solution means that the numerical values of φ remain within
reasonable limits, avoiding unrealistic oscillations or negative concentrations,
which would be non-physical.
The sufficient condition for condition for boundedness is:
∑|𝑎𝑛𝑏 | ≤ 1 𝑎𝑡 𝑎𝑙𝑙 𝑛𝑜𝑑𝑒𝑠
{
|𝑎᾿𝑃 | < 1 𝑎𝑡 𝑜𝑛𝑒 𝑛𝑜𝑑𝑒 𝑎𝑡 𝑙𝑒𝑎𝑠𝑡
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
OpenFOAM® Basic Training
Tutorial Five
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
Transportiveness refers to the ability of a discretization scheme to correctly
account for the dominant transport mechanism in a problem. This is assessed
using the Peclet number (Pe), which measures the relative strength of
convection versus diffusion:
𝑁𝑐𝑜𝑛𝑣 𝐿𝑈
𝑃𝑒 = =
𝑁𝑑𝑖𝑓𝑓 𝐷
4. Transportiveness property
Tutorial Five
Conser- Trans-
Scheme Bounded Accuracy Remarks
vative portive
Less computationally
Unconditionally stable. Can give small
QUICK Yes Third order Yes
bounded undershoots and
overshoots
⃰ Pe should be less than 2.
Second-order
First-order upwind
upwind
8×8
64 × 64
Numerical diffusion
OpenFOAM® Basic Training
Tutorial Five
Tutorial Five
Tutorial outline
Use the functions 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.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.
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
defaultFieldValues (volScalarFieldValue T 0 );
regions
(
cylinderToCell
{
p1 ( 0 0 -1 );
p2 ( 0 0 1 );
radius 0.5;
fieldValues
(
volScalarFieldValue T 1
) ;
}
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
>blockMesh
>setFields
For running further parts (moving the circle to top, and then diagonally), in the
0 folder in the U file change the internalFiled velocity to (0 1 0) so the circle
moves up, and to (-1 -1 0) to move the circle diagonally back to the original
position.
Note: In the controdDict file, subSolverTime is set to 0 and therefore even if the
startTime is set to latestTime, the simulation will read the U file from time 0!
3. Post-processing
The simulation results are as follows:
OpenFOAM® Basic Training
Tutorial Five
1s 2s 3s
4s 5s 6s
7s 8s 9s
Bahram Haddadi
Tutorial Six
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial Six
Background
2. RANS-based models
The governing equations for a Newtonian fluid are:
• Conservation of mass
𝜕𝜌
+ ∇ ∙ (𝜌𝒖
̃) = 0
𝜕𝑡
• Conservation of momentum (Navier-Stokes equation)
𝜕(𝜌𝑢̃𝑖 ) 𝜕𝑝̃
+ ∇ ∙ (𝜌𝑢̃𝑖 𝒖
̃) = − + ∇ ∙ (𝜇∇𝑢̃𝑖 ) + 𝑆̃𝑀𝑖
𝜕𝑡 𝜕𝑥𝑖
OpenFOAM® Basic Training
Tutorial Six
Tutorial Six
Tutorial Six
incompressibleFluid – pitzDaily
Tutorial outline
Use incompressibleFluid solver, run a steady state simulation with following
turbulence models:
• kEpsilon (RAS)
• kOmega (RAS)
Objectives
• Understanding turbulence modeling
• Understanding steady state simulation
Data processing
Show the results of U and the turbulent viscosity in two separate contour plots.
OpenFOAM® Basic Training
Tutorial Six
1. Pre-processing
$FOAM_TUTORIALS/incompressibleFluid/pitzDaily
Replace the system directory with the system directory from the following
tutorial:
$FOAM_TUTORIALS/incompressibleFluid/pitzDailySteadyExperi
mentalInlet
Copy the pitzDaily file for the pitzDaily geometry from following directory to your
system directory:
$FOAM_TUTORIALS/resources/blockMesh
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;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
OpenFOAM® Basic Training
Tutorial Six
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
• kEpsilon (RAS): k and epsilon
• kOmega (RAS): k and omega
• LRR (RAS): k, epsilon and R
• Smagorinsky (LES): s
• kEqn (LES): k and s
• SpalartAllmaras (LES): nuSgs and nuTilda
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
{
model kEpsilon;
turbulence on;
printCoeffs on;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Note: For Boolean inputs in OpenFOAM either on/off, 1/0 or true/false can be
used.
Tutorial Six
In the fvSchemes files the ddtSchemes is set to steadyState which will set the
time derivative part of conservation equations to zero which is compatible with
the steady state assumption.
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
ddtSchemes
{
default steadyState;
}
gradSchemes
{
default Gauss linear;
}
divSchemes
{
default none;
div(phi,U) bounded Gauss Upwind;
div(phi,k) bounded Gauss Upwind;
div(phi,epsilon) bounded Gauss Upwind;
div(phi,R) bounded Gauss Upwind;
div(R) Gauss linear;
div(phi,nuTilda) bounded Gauss Upwind;
laplacianSchemes
{
default Gauss linear corrected;
}
interpolationSchemes
{
default linear;
}
snGradSchemes
{
default corrected;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
In case we are solving for property such as omega and it is not defined in the
schemes and there is no default schemes defined, it should be add to the
relevant schemes section, e.g. to the divSchemes (div(phi,omega)). Also,
fvSolution needs to be adopted based on the new parameters, e.g. omega.
Note: In the fvSolution the solver type and settings need to be defined or be
added to the others, e.g. for omega “(U|k|epsilon|R|nuTilda|omega)”).
2. Running simulation
Note: The default dictionary file for blockMesh is blockMeshDict in the system
directory. It is possible to use a different dictionary file by using the flag “-dict”
and the address of the file (dictionary), in this case system/pitzDaily.
Tutorial Six
3. Post-processing
The simulation results are as follows (all simulations scaled to the same range):
RAS
Velocity magnitude Turbulent viscosity
model
kEpsilon
kOmega
Bahram Haddadi
Tutorial Seven
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial Seven
Background
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:
𝜕𝑢𝑖 𝜕𝑢𝑖 1 𝜕𝑝 𝜕 𝜕𝑢𝑖
+ 𝑢𝑗 =− + (𝜐 )
𝜕𝑡 𝜕𝑥𝑗 𝜌 𝜕𝑥𝑖 𝜕𝑥𝑗 𝜕𝑥𝑗
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, because:
𝜕𝑢𝑖 𝜕𝑢̅𝑖
𝑢𝑗 ≠ 𝑢̅𝑗
𝜕𝑥𝑗 𝜕𝑥𝑗
OpenFOAM® Basic Training
Tutorial Seven
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 𝜕𝑥𝑗 𝜕𝑥𝑖
2. k-Eqn model
The governing equation for the SGS turbulence kinetic energy k in the kEqn
LES model is:
𝜕ρk 2 𝐶ₑ 𝜌 𝑘1.5
+ 𝛻 · (𝜌 𝑢 𝑘) = 𝛻 · (𝜌 𝐷ₖ 𝛻𝑘) + 𝜌𝐺 − 𝜌𝑘 (𝛻 · 𝑢) − + Sₖ
𝜕𝑡 3 Δ
This equation accounts for the transport, production, and dissipation of SGS
turbulence kinetic energy, providing a comprehensive representation of
turbulent flow dynamics.
3. Smagorinsky-Lilly model
One of the most widely used SGS models is the Smagorinsky-Lilly model, which
provides a simple way to estimate the sub-grid scale eddy viscosity:
1
𝜏𝑖𝑗 − τ𝑘𝑘 δ𝑖𝑗 = −2(C𝑠 ∆)2 |𝑆̅|S𝑖𝑗
3
In the Smagorinsky-Lilly model, the eddy viscosity is modeled by
OpenFOAM® Basic Training
Tutorial Seven
𝑆̅ = √2𝑆𝑖𝑗 𝑆𝑖𝑗
Tutorial Seven
incompressibleFluid – pitzDaily
Tutorial outline
Use the incompressibleFluid 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
• Transient vs steady state simulation
• Finding appropriate turbulence model
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/incompressibleFluid/pitzDailyLESDeveloped
Inlet
$FOAM_TUTORIALS/incompressibleFluid/pitzDaily
1.2. 0 directory
Set the proper turbulence model initial and boundary conditions and values.
Note: For different turbulent models, different files should be modified (check
Tutorial Six).
For kEpsilon model, the epsilon file need to be added and on the walls, for all
three properties: k, epsilon and nut, the wall-functions should be applied (based
on the y+ value) and proper initial values to be set. For more information:
https://www.openfoam.com/documentation/guides/latest/doc/guide-
turbulence.html
LES
{
LESModel kEqn;
turbulence on;
printCoeffs on;
delta cubeRootVol;
dynamicKEqnCoeffs
{
filter simple;
}
cubeRootVolCoeffs
{
deltaCoeff 1;
}
PrandtlCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
OpenFOAM® Basic Training
Tutorial Seven
deltaCoeff 1;
}
smoothCoeffs
{
delta cubeRootVol;
cubeRootVolCoeffs
{
deltaCoeff 1;
}
maxDeltaRatio 1.1;
}
Cdelta 0.158;
}
vanDriestCoeffs
{
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;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Note: For Smagorinsky, you can find the sample dictionary, including the
relevant settings in the following:
$FOAM_TUTORIALS/multiphaseEuler/LBend/constant/momentumTr
asport.gas
2. Running simulation
>blockMesh
Tutorial Seven
3. Post-processing
The simulation results are as follows:
For the kEpsilon model after 0.2 s the results are similar to the steady state
simulation. Therefore, it can be assumed it has reached the steady state. Other
models do not have a steady situation and are fluctuating all the time, so they
require averaging for obtaining steady state results.
kEpsilon and other RAS models use averaging to obtain the turbulence values,
but LES does not include any averaging by default. Therefore, LES simulations
should use a higher grid resolution (smaller cells) and smaller time steps (for
reasonable Co number). Contour plots or other LES results should be
presented time averaged over reasonable number of time steps (not done in
this tutorial).
OpenFOAM® Basic Training
Tutorial Seven
Smagorinsky
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
Bahram Haddadi
Tutorial Eight
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial Eight
Background
1. Multiphase flow
Multiphase flow refers to the simultaneous movement of two or more different
phases (solid, liquid, or gas). Each phase may contain one or more chemical
components. The common types of multiphase flows include:
• Gas-liquid flows (e.g., air bubbles in water, boiling liquids)
• Gas-solid flows (e.g., pneumatic transport, fluidized beds)
• Liquid-solid flows (e.g., sediment transport, slurry flows)
• Liquid-liquid flows (e.g., oil-water mixtures)
• Three-phase flows (e.g., water, gas, and solid mixtures in oil pipelines)
Multiphase flow can be further classified based on the flow regime:
• Separated flow: Distinct interfaces between phases (e.g., water flowing
under oil).
• Dispersed flow: One phase exists as discrete particles or droplets within
another continuous phase (e.g., bubbles in water, oil droplets in water).
• Mixed flow: A combination of separated and dispersed flow regions.
Multiphase flow is found in numerous applications, including chemical reactors
(bubble columns, distillation towers), oil and gas industries (flow through
pipelines, separation processes), environmental science (rain formation,
erosion due to sediment transport) and power plants (boiling in nuclear
reactors, cooling systems). Understanding and modeling multiphase flow is
crucial for improving efficiency, design optimization, and operational safety in
these applications.
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. Below we will cover some common modeling approaches of
multiphase flow.
Tutorial Eight
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 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 shared pressure and interphase exchange coefficients.
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.
Tutorial Eight
incompressibleVoF – damBreak
Tutorial outline
Use the incompressibleVoF 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/incompressibleVoF/damBreak
1.2. 0 directory
In the 0 directory, in the alpha.water.orig and p_rgh files, the initial values and
boundary conditions for water phase and 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 [];
internalField uniform 0;
boundaryField
{
#includeEtc “caseDicts/setConstrainTypes”
wall
{
type zeroGradient;
}
atmosphere
{
type inletOutlet;
inletValue uniform 0;
value uniform 0;
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
#includeEtc includes the etc folder in the OpenFOAM installation directory
and the path “caseDicts/setConstrainTypes” instruct it to include the
boundaries in this file also here. In this case the empty boundary is used for
this tutorial.
Checking the blockMeshDict file there is no boundary named wall, the wall in
the boundaryField section of files in the 0 is for using the same boundary
condition for the boundaries which have type wall.
Note: If in the files in 0 directory some not used boundaries are defined, as far
as their syntax is correct, OpenFOAM will ignore them, so you don’t need to
remove them!
Note: In the dimensions section [] is equal to [0 0 0 0 0 0 0] and it means
it is a dimensionless parameter.
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
sigma 0.07;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
and sigma is the surface tension between two phases, in this example it is the
surface tension between air and water.
For each phase, there is a dedicated physicalProperties.fileName file, in which
the properties of the relevant phase can be set. E.g. the
physicalProperties.water file looks as following:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
viscosityModel constant;
nu 1e-06;
rho 1000;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
In both phases the coefficients for different models of viscosity are given, e.g.
nu and rho. Depending on which model is selected, the corresponding
coefficients are read. In this simulation, the selected model is constant
(representing Newtonian model), therefore only the nu coefficient is needed.
Checking the g file, the gravitational field and 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
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
>blockMesh
>setFields
3. Post-processing
The simulation results are as follows (these are not the results for the original
mesh, but a 2x refined mesh):
OpenFOAM® Basic Training
Tutorial Eight
Bahram Haddadi
Tutorial Nine
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Tutorial Nine
Background
1. Parallel computing
Modern Computational Fluid Dynamics (CFD) problems often involve complex
geometries, turbulence, multiphase flows, and chemical reactions, making
simulations computationally expensive. Parallel computing reduces
computation time by distributing the workload across multiple processors,
enabling simulations that would otherwise be infeasible on a single machine.
Parallel computing involves dividing the computational domain into smaller sub-
domains, which are assigned to different processors. This step is known as
domain decomposition. These processors simultaneously perform
calculations and communicate with each other to synchronize data exchange.
This approach significantly reduces computational time, making it essential for
large-scale simulations in engineering and scientific research.
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.
Tutorial Nine
Tutorial Nine
Tutorial Nine
compressibleVoF – depthCharge3D
Tutorial outline
Use the compressibleVoF solver, simulate the example case for 0.5 s.
Objectives
• Understanding the difference between incompressible and compressible
solvers
• Understanding parallel processing and different discretization methods
Data processing
Investigate the results in ParaView.
OpenFOAM® Basic Training
Tutorial Nine
1. Pre-processing
$FOAM_TUTORIALS/compressibleVoF/depthCharge3D
1.2. 0 directory
In the 0 directory copy the alpha.water.orig, p.orig, p_rgh.orig and T.orig files to
alpha.water, p, p_rgh and T respectively.
Note: You can also skip copying the *.orig files, since running the setFields will
do it for you.
sigma 0.07;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
method hierarchical;
simpleCoeffs
{
n ( 1 4 1 );
}
hierarchicalCoeffs
{
n ( 1 4 1 );
order xyz;
}
manualCoeffs
{
dataFile "";
}
OpenFOAM® Basic Training
Tutorial Nine
distributed no;
roots ( );
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
>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
Tutorial Nine
<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.
Note: top command execution can be interrupted by typing q (or ctrl+c)
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
>foamToVTK
Tutorial Nine
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 “:”:
Tutorial Nine
0s 0.05 s 0.1 s
0.3 s 0.5 s
0.4 s
Tutorial Nine
4. Manual method
>decomposePar –cellDist
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
OpenFOAM® Basic Training
Tutorial Nine
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 &
Bahram Haddadi
Tutorial Ten
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek
• Clemens Gößnitzer
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.
Tutorial Ten
Background
In this tutorial, we will carry out Residence Time Distribution (RTD) analysis of
fluid flow through a T-junction pipe.
2. Tracer Analysis
Tracer analysis is a widely used technique for RTD measurement, where a
tracer substance (such as dye, salt, or radioactive material) is injected into the
system, and its concentration at the outlet is monitored over time. This provides
insight into how fluid elements move through the process unit and allows
engineers to quantify the RTD function.
Tutorial Ten
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
Tutorial Ten
Tutorial outline
Use the incompressibleFluid and functions 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:
• Inlet and outlet cross-sections: 1 × 1 m2
• Gas in the system: air at ambient conditions
• Operating pressure: 105 Pa
• Inlet 1: 0.1 m/s
• Inlet 2: 0.2 m/s
Objectives
• Understanding RTD calculation using OpenFOAM®
• Using multiple solvers for a simulation
Data processing
Plot the step response function and the RTD curve.
OpenFOAM® Basic Training
Tutorial Ten
1. Pre-processing
$FOAM_TUTORIALS/incompressibleFluid/pitzDaily
Replace the system directory with the system directory from the following
tutorial:
$FOAM_TUTORIALS/incompressibleFluid/pitzDailySteadyExperi
mentalInlet
Copy the pitzDaily file for the pitzDaily geometry from following directory to your
system directory:
$FOAM_TUTORIALS/resources/blockMesh
1.2. 0 directory
Update p, U, nut, nuTilda, k and epsilon files with the new boundary conditions
(in this simulation the following boundaries should be set inlet_one, inlet_two,
oulet and walls), e.g. for file 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)
}
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
Tutorial Ten
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
simulationType RAS
RAS
{
model kEpsilon;
turbulence on;
printCoeffs on;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
vertices
(
(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)
);
boundary
(
inlet_one
{
type patch;
faces
(
(0 10 11 1)
);
}
inlet_two
{
type patch;
faces
(
(7 6 16 17)
OpenFOAM® Basic Training
Tutorial Ten
);
}
outlet
{
type patch;
faces
(
(4 3 13 14)
);
}
walls
{
type wall;
faces
(
(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)
);
}
);
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
2. Running simulation
>blockMesh
Wait for simulation to converge. After convergence, check the results to make
sure about physical convergence of the solution.
>foamToVTK
OpenFOAM® Basic Training
Tutorial Ten
The simulation results are as follows (results are on the cut plane in the middle):
3. RTD calculation
$FOAM_TUTORIALS/incompressibleFluid/pitzDailyScalarTransp
ort
In the 0 directory, just keep the T file and delete all other files.
3.2. 0 directory
Copy and paste the U and p files from the latest time step of the simulation in
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.
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.
Tutorial Ten
4. Running Simulation
>blockMesh
>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.
Bahram Haddadi
Tutorial Eleven
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek
• Clemens Gößnitzer
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.
Tutorial Eleven
Background
In computational fluid dynamics (CFD) and chemical reaction modeling, two
commonly used approaches to simulate reactive flows are the Partially Stirred
Reactor (PaSR) Model and the Eddy Dissipation Concept (EDC) Model. These
models help in understanding and predicting how chemical reactions occur in
different flow environments, such as combustion, industrial chemical
processing, pollutant dispersion, and atmospheric chemistry.
Tutorial Eleven
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
multicomponentFluid – reactingElbow
Tutorial outline
Use the multicomponentFluid solver; simulate combustion of CH4 and O2 in a
mixing elbow:
• Use the two times finer Hex mesh from Example One
• Domain initially filled with N2
• velocity-inlet-5:
- Velocity: 1 m/s
- Mass fractions: 23 % O2, 77 % N2
- Temperature: 800 K
• velocity-inlet-6:
- Velocity: 3 m/s
- Mass fractions: 50 % CH4, 50 % N2
- Temperature: 293 K
• Operating pressure: 105 Pa
• Operating temperature: 298 K
• Isolated walls
Objectives
• Understanding multi-species and reaction modeling in OpenFOAM®
Data processing
Evaluate your results in ParaView.
OpenFOAM® Basic Training
Tutorial Eleven
1. Pre-processing
$FOAM_TUTORIALS/multicomponentFluid/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
OpenFOAM® Basic Training
Tutorial Eleven
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];
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.
Note: For the pressure-outlet-7 set the species boundary conditions to
zeroGradient.
Tutorial Eleven
defaultSpecie N2;
#include "thermo.compressibleGas"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
The mixture type is set to a multi-component mixture for calculating the mixture
properties and the heat capacities are calculated using “janaf polynomials”.
N2 is defines as defaultSpecie. In reaction solvers in OpenFOAM® the default
specie is calculated explicitly using the mass balance equation (to satisfy mass
conservation):
𝑚𝑎𝑠𝑠 𝑓𝑟𝑎𝑐𝑡𝑖𝑜𝑛 𝑜𝑓 𝑖𝑛𝑒𝑟𝑡 𝑠𝑝𝑒𝑐𝑖𝑒 = 1 − ∑ 𝑚𝑎𝑠𝑠 𝑓𝑟𝑎𝑐𝑡𝑖𝑜𝑛 𝑜𝑓𝑎𝑙𝑙 𝑜𝑡ℎ𝑒𝑟 𝑠𝑝𝑒𝑐𝑖𝑒𝑠
O2
{
specie
{
molWeight 31.9988;
OpenFOAM® Basic Training
Tutorial Eleven
}
thermodynamics
{
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.753e-06;
Ts 139;
}
}
…
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
application foamRun;
solver multicomponentFluid
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;
OpenFOAM® Basic Training
Tutorial Eleven
runTimeModifiable true;
adjustTimeStep yes;
maxCo 0.4;
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
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).
>foamToVTK
3. Post-processing
The simulation results at 120 s are as follows:
OpenFOAM® Basic Training
Tutorial Eleven
Bahram Haddadi
Tutorial Twelve
Contributors:
• Bahram Haddadi • Yitong Chen
• Christian Jordan
• Michael Harasek
• Philipp Schretter
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.
Tutorial Twelve
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.
2.1. GAMBIT®
GAMBIT® is a 3D unstructured tool, to specify the meshing scheme in it, two
parameters must be specified:
OpenFOAM® Basic Training
Tutorial Twelve
• Elements
• Type
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 (like snappyHexMesh). Currently cfMesh is capable of
producing mesh of Cartesian type in both 2D and 3D, tetrahedral and
polyhedral types.
OpenFOAM® Basic Training
Tutorial Twelve
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
Tutorial outline
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
functions solver
Objectives
• The aim of the tutorial is to introduce single region meshing with the
meshing tool snappyHexMesh
• Understanding the advantages of snappyHexMesh
• Understanding the three basic steps of 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/geometry of your running case directory.
$FOAM_TUTORIALS/resources/geometry/flange.stl.gz
Tutorial Twelve
includedAngle 150;
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * //
1.3.1. CASTELLATING
OpenFOAM® Basic Training
Tutorial Twelve
features
(
{
file "flange.extendedFeatureEdgeMesh";
level 0;
}
OpenFOAM® Basic Training
Tutorial Twelve
);
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!
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.
1.3.2. SNAPPING
Important parameters are number of mesh displacement iterations,
nSolveIter and the number of feature edge snapping iterations,
nFeatureSnapIter. The default values are fine for most of applications.
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * //
snapControls
{
nSmoothPatch 3;
tolerance 1.0;
nSolveIter 300;
nRelaxIter 5;
nFeatureSnapIter 10;
implicitFeatureSnap false;
explicitFeatureSnap true;
multiRegionFeatureSnap true;
}
// * * * * * * * ** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * //
1.3.3. LAYERING
The label for the layering is equal to the labeling of the Boundary surface in the
boundary file in the constant/polyMesh folder.
- nSurfaceLayers defines the number of surface layers
- expansionRatio defines the expansion ratio of the surface layers
- finalLayerThickness and minThickness define the min and the final
thickness of the surface layers
OpenFOAM® Basic Training
Tutorial Twelve
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
{
#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
The background mesh is created with the following command:
>blockMesh
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.
OpenFOAM® Basic Training
Tutorial Twelve
>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. The folders are created
based on the deltaT settings in the controlDict File (in this case it is 1, therefore
folders are 1, 2 and 3).
Tutorial Twelve
In order to avoid the creation of these folders and only keep the final mesh (to
be written directly in the constant folder), 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
>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.
Tutorial Twelve
Tutorial Twelve
>checkMesh
4. Running simulation
$FOAM_TUTORIALS/incompressibleFluid/pitzDailyScalarTransp
ort
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.
boundaryField
{
flange_patch1
OpenFOAM® Basic Training
Tutorial Twelve
{
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 and p files so that the velocity in the entire flange domain and at
the boundaries is zero.
Note: to set the initial fields to zero, remove the nonuniform filed and it values
and replace it with uniform field value, e.g. uniform (0 0 0 ).
In the constant directory
In the momentumTransport file, set the simulationType to laminar.
In the system directory
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
Bahram Haddadi
Tutorial Thirteen
Contributors:
• Bahram Haddadi • Yitong Chen
• Christian Jordan
• Michael Harasek
• Philipp Schretter
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.
Tutorial Thirteen
Background
Multi-region modeling is a computational approach used in CFD simulations
where the entire computational domain is divided into distinct regions, each
representing a specific phase or material. This method is particularly useful for
simulating conjugate heat transfer (CHT), fluid-structure interactions, and
multiphase flow scenarios.
1. Monolithic Approach
Tutorial Thirteen
The governing equations for mass, momentum, and energy are solved for each
individual region. For fluid regions, Navier-Stokes, continuity and energy
equations equations are solved while in the solid region’s equations such as
Fourier heat conduction equation for temperature distribution are normally
considred. Time-stepping is based on the smallest time-step for all the regions
and numerical schemes are managed separately for each region.
Tutorial Thirteen
snappyHexMesh - snappyMultiRegionHeater
Tutorial outline
Try to create a multi-region geometry and mesh and run a conjugate heat
transfer case using it.
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
https://github.com/OpenFOAM/OpenFOAM-
5.x/tree/master/tutorials/heatTransfer/chtMultiRegionFoam/snappyMultiRegionHeater
Either by creating the folders and then downloading the files and place them in
relevant folders or using following webpage:
https://download-directory.github.io/
Rename the constant/triSurface directory to constant/geometry directory. In the
system directory, change the name of surfaceFeatureExtractDict to
surfaceFeaturesDict.
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 (the folders can be created manually or will be generated
automatically after creating and splitting the mesh). 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.
thermoType
{
type heSolidThermo;
mixture pureMixture;
OpenFOAM® Basic Training
Tutorial Thirteen
transport constIsoSolid;
thermo eConst;
equationOfState rhoConst;
specie specie;
energy sensibleInternalEnergy;
}
mixture
{
specie
{
molWeight 12;
}
transport
{
kappa 80;
}
thermodynamics
{
Hf 0;
Cv 450;
}
equationOfState
{
rho 8000;
}
}
// ************************************************************************* //
Tutorial Thirteen
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 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.
Update the surfaceFeaturesDict file as following:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// ************************************************************************* //
// ************************************************************************* //
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 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;
OpenFOAM® Basic Training
Tutorial Thirteen
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 be also automated using 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
{
“.*”
{
OpenFOAM® Basic Training
Tutorial Thirteen
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”
Note: Add the missing “;” to the fvSolution files for bottomAir and topAir regions:
“(rho|rhoFinal)”
{
solver PCG;
preconditioner DIC;
tolerance 1e-7;
relTol 0;
}
>blockMesh
Equal to the single region case, the command surfaceFeatures 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 surfaceFeatures is not obligatory. This step
is only necessary, if certain edges need to be refined.
OpenFOAM® Basic Training
Tutorial Thirteen
>surfaceFeatures
>decomposePar
>reconstructPar –constant
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):
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’.
Tutorial Thirteen
Before running the simulations, the solver for each region needs to be defined,
in the controlDict file add the following lines:
regionSolvers
{
bottomAir fluid;
topAir fluid;
heater solid;
leftSolid solid;
rightSolid solid;
}
and also remove the rho files from 0/topAir and 0/bottomAir folders, now it is
ready to be run.
>foamMultiRun
Tutorial Thirteen
Bahram Haddadi
Tutorial Fourteen
Contributors:
• Bahram Haddadi • Yitong Chen
• Christian Jordan
• Michael Harasek
• Benjamin Piribauer
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.
Tutorial Fourteen
Background
2. Sampling in OpenFOAM®
This tutorial serves as a introduction to the sampling utility available in
OpenFOAM®. The sampling utility is a powerful feature that allows users to
extract data from specific surfaces or points within a simulation domain. This
extracted data can then be analyzed to understand the behavior of the
simulated flow, validate numerical results, or visualize specific regions of
interest.
By using the sampling utility, users can examine critical parameters such as
velocity, pressure, turbulence properties, and other field variables at selected
locations, which help in gaining insights into the correctness and stability of the
numerical solution.
OpenFOAM® Basic Training
Tutorial Fourteen
fluid – 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
$FOAM_TUTORIALS/compressible/fluid/shockTube
type sets;
libs (“libsampling.so”)
interpolationScheme cellPoint;
setFormat raw;
sets
(
data
{
type lineUniform;
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.
- 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.
OpenFOAM® Basic Training
Tutorial Fourteen
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 functions file (it can be also integrated into the controlDict) are
needed.
In this part one will change the functions file of the shockTube tutorial so that
our line- sampling from before will be executed while running, and per time step.
Modify the functions file as following:
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* * * * * *//
…
functions
{
#includeFunc mag(U)
linesample
{
type sets;
functionObjectLibs (“libsampling.so”);
writeControl timeStep;
outputInterval 1;
interpolationScheme cellPoint;
setFormat raw;
sets
(
data
{
type lineUniform;
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.
Inside our linesample sub-dictionary:
- type: sets or surfaces can be chosen. More types will be covered in a
later section.
- functionObjectLibs: provides the operations needed for the sampling
tasks.
- writeControl: specifies the intervals in which sampling data should be
collected in the case of timeStep, depending on the outputInterval,
sampling data will get saved in dependence of the timeStep. In the case
OpenFOAM® Basic Training
Tutorial Fourteen
>blockMesh
>setFields
3. Post-processing
After fluid solver finishes running, based on your sampling approach the
following steps should be performed:
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.
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.
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 us 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. lineUniform
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.
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 lineUniform;
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;
Tutorial Fourteen
4.1.3. cloud
The cloud type samples data at specific points defined in the point’s 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 surfaces. Inside the surfaces brackets one
can now sample an arbitrary number of surfaces, each in its own inner brackets.
The different types of 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
OpenFOAM® Basic Training
Tutorial Fourteen
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);
One can also set a new origin for the basePoint and normalVector with
coordinateSystem
{
origin (0.0501 0.0501 0.005);
}
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
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;
Tutorial Fourteen
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 does not already
exist 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;
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.
OpenFOAM® Basic Training
Tutorial Fourteen
//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 does not cross any cell with its surface and does not 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
Bahram Haddadi
Appendix A
Contributors:
• Bahram Haddadi • Sylvia Zibuschka
• Christian Jordan • Yitong Chen
• Michael Harasek • Vikram Natarajan
• Clemens Gößnitzer • Jozsef Nagy
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.
Appendix A
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.
cd, cd .. Changing the directory, cd .. goes one directory up and cd ~ moves to home
directory. Important to note is the space between cd and .. as opposed to DOS!
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.
ctrl+r Reverse search, for searching an already typed command in a terminal window.
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 systems provide the
du -k
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.
Appendix A
Nano, pico The command to run the nano text editor, a terminal based text editor.
| It is known as pipe and is used for merging two commands, redirecting one
command as input to another, e.g. less|grep searches a specified word in the
output of file opened with less.
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 display.
ps waux
rm, CAUTION: Deletes files. The option -r will also remove directories and files recursively and
rm -fr delete directories, f (force) prevents any further inquiry. - 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.
OpenFOAM® Basic Training
Appendix A
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®
Bahram Haddadi
Appendix B
Contributors:
• Bahram Haddadi • Yitong Chen
• Christian Jordan • Jozsef Nagy
• Michael Harasek
• Sylvia Zibuschka
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.
Appendix B
>. ./bashrc
2.1. Windows:
• Run PuTTY (search for: PuTTY windows).
• Set the following:
Category>Session
Category>Connection>Data
1 Display number
2 Session ID
OpenFOAM® Basic Training
Appendix B
your password. The password is not echoed to the screen and the
passwords are case sensitive.
• Immediately after entering your password, your computer will attempt to
establish a connection to your server. If it is your first time connecting to
that server, you will see a message asking you to confirm the identity of
the machine. Make sure you entered the address properly, and type
yes, followed by the return key, to proceed.
• Change to etc directory in OpenFOAM® installation directory
• Execute the following command:
>. ./bashrc
• To log out use whatever command is used to logout from the server you
are logged into (typically ctrl + d).
>. ./bashrc
Appendix B
>. ./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
Bahram Haddadi
Appendix C
Contributors:
• Bahram Haddadi • Yitong Chen
• Christian Jordan • Jozsef Nagy
• Michael Harasek
• Sylvia Zibuschka
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.
Appendix C
Q- How can I prevent typing long commands in the terminal for couple of times?
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]
OpenFOAM® Basic Training
Appendix C
A- Make sure OpenFOAM® and ParaView are installed correctly. Check Appendix B for
starting OpenFOAM®.
A- Use command:
>foamToVTK -region[REGION NAME]
A- Yes, by choosing .ogv file format from “file/save animation” menu. The output will be
a video file with .ogv format. In the new ParaView versions (newer than 4.3.0) the
animation can also be saved using .avi format.
A- During creating the geometry in the preprocessing software, e.g. GAMBIT, create
volume zones, which you will need to patch later (see software user manual for
creating regions in each software). For converting the mesh to the OpenFOAM ®
mesh use the appropriate tool with “-writeZones” flag to import zones to
OpenFOAM®, e.g.:
>fluentMeshToFoam -writeZones <your mesh>
regions
(
zoneToCell
{
name air; // region name which you assigned in gambit
fieldValues
(
volScalarFieldValue alpha.water 0 // the value of property
//which you want to patch
);
}
);
Then after running setFields tool, it will assign the values to that region.
OpenFOAM® Basic Training
Appendix C
Q- How can I create a bash scripting file for executing couple of command in series?
Instead of typing command sequences one by one after each other and executing
A-
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, setFields,
decomposePar, compressibleInterFoam in parallel mode and reconstructPar):
blockMesh
setFields
decomposePar
mpirun –np 4 compressibleInterFoam –parallel >log
reconstructPar
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
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.
Bahram Haddadi
Appendix D
Contributors:
• Bahram Haddadi • Yitong Chen
• Christian Jordan • Jozsef Nagy
• Michael Harasek
• Sylvia Zibuschka
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.
Appendix D
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.10.1 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.
For generation operations, use the OpenFOAM® command foamToVTK to
convert OpenFOAM® files into readable formats for ParaView. Then open the
.vtk file and press the green Apply button in the Properties panel. The reset
button is used for resetting the window and deleting the selected operation.
OpenFOAM® Basic Training
Appendix D
2. ParaView Interface
Properties panel
- 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].
OpenFOAM® Basic Training
Appendix D
- 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).
- 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.
OpenFOAM® Basic Training
Appendix D
Appendix D
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.
Appendix D
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.