Module'0' 1'
These lectures notes are licensed under the Creative Commons
Attribution-ShareAlike 4.0 International License.
Module'0' 2'
Introductory OpenFOAM® Course
Module'0' 3'
Training agenda
Module 0.
• Training agenda
• Housekeeping issues
Module 1.
• Introduction to OpenFOAM®
• Library organization
• My first tutorial
Module'0' 4'
Training agenda
Module 2.
• CFD workflow
• Geometry generation
• Getting more productive using a GUI
Module 3.
• Meshing preliminaries
• Mesh quality assessment
• Mesh conversion and manipulation
• Meshing in OpenFOAM®
• Meshing with cfMesh
• Meshing with open-source tools
Module'0' 5'
Training agenda
Module 4.
• Scientific visualization
• Post-processing and plotting
• Co-processing
• Scripting
• Data analytics
Module 5.
• Running in parallel
• GPU
Module'0' 6'
Training agenda
Module 6.
• The finite volume method. A crash introduction
• On the CFL number
• Boundary conditions and initial conditions
• Unsteady and steady simulations
• Assessing convergence
Module'0' 7'
Training agenda
Module 7.
• Programming in OpenFOAM® - Building blocks
• Programming in OpenFOAM® - Implementing boundary
conditions and applications
• Implementing boundary conditions using swak4foam
• Field initialization using swak4foam
Module'0' 8'
Training agenda
Module 8.
• Advanced modeling capabilities:
• Turbulence modeling
• Multiphase flows
• Source terms
• Heat-transfer and conjugate heat transfer
• Discrete particle modeling
• Moving reference frames and sliding grids
• Moving bodies and rigid body motion
Module'0' 9'
Training agenda
Module 9.
• Tips and tricks
Module 10.
• Conclusions and wrap-up session
Module'0' 10'
The Team
Joel GUERRERO
joel.guerrero@unige.it
'
'
guerrero@wolfdynamics.com'
Module'0' 11'
The Team
Damiano NATALI
damiano.natali@unige.it
'
'
natali@wolfdynamics.com '
Module'0' 12'
Before we begin
Housekeeping issues
Module"0" 1"
Before we begin
Who does not have a working installation of
OpenFOAM®?
Module"0" 2"
Before we begin
What about your OpenFOAM® skills?
• Totally new.
• Beginner.
• Intermediate.
• Advanced.
• Guru.
Module"0" 3"
Before we begin
Any clue on the FVM, CFD, multi-physics
simulations, scientific computing, or numerical
methods?
• Not a clue.
• Guitar hero.
Module"0" 4"
Before we begin
You are in Linux, you see this nice window that
everybody calls terminal. Now what?
Module"0" 5"
Before we begin
How confortable are you with Linux?
• If you are new to Linux, do not worry, we are going to give you a crash
introduction to the basic Linux commands.
• Also, if you installed our Linux version, we are going to show how to use
it and what applications are installed.
Module"0" 6"
Afternoon Session Morning Session
(1:30 pm – 4:30 pm) (9:00 am – 12:30 am)
• More on geometry generation, mesh generation, • Advanced mesh generation with blockMesh and
and post-processing using Open Source tools. snappyHexMesh.
• Advanced post-processing with paraview and • Geometry generation, mesh generation and
visit. post-processing using Open Source tools.
The above outline is a guide only and every attempt will beModule"0"
• How to setup a case from scratch using • Python scripting and automation.
Day 3
•
• Hands-on tutorials. • Implementing boundary and initial conditions
End of the day. Last minute issues and additional questions.
Module"0" 8"
Before we begin
Linux for open source CFD
• First at all and in order to avoid compatibility issues during the course, I
highly advise you to install our custom made Linux version. You can find it in
the following:
https://susestudio.com/a/XrxjaO/joel-s-opensuse-13-2-kde-4-desktop
• In the provided USB key you will find the virtual machine distribution.
• I also remind you that it is a fully working Linux OpenSUSE 13.2 version
(with KDE 4), that you can modify or upgrade to fit your needs.
• So if you do not like KDE, you can install Gnome or whatever you want to
use.
Module"0" 9"
Before we begin
Linux for open source CFD
• This Linux version was created with CFD applications in mind for CFD
users. It comes with many CFD, CAD, mesh generation, visualization,
numerical libraries, optimization, plotting applications and editing utilities pre-
installed. It also comes with all the compilers and libraries necessary to
compile most of the applications.
• In the version available for download you have all the applications necessary
for this course.
Module"0" 10"
Before we begin
Linux for open source CFD
• The OpenFOAM® version installed is 2.3.x, which you can update by using
the Git revision control system.
Module"0" 11"
Before we begin
Training material
Module"0" 12"
Before we begin
Training material
• In the USB key you will also find all the training material (tutorials, slides,
quick reference guides, OpenFOAM® user guide, OpenFOAM®
programmers manual, and lectures notes).
• You can extract the training material wherever you want. However, I highly
recommend you to extract all the training material in your OpenFOAM® user
directory. From now on, this directory will become
• $PTOFC
(abbreviation of path to OpenFOAM® course).
• You can add this alias to your .bashrc file by adding the following line,
Module"0" 13"
Before we begin
Training material
• By the way, to uncompress the tutorials go to the directory where you copied
the training material and then type in the terminal,
• On the other side, if you are interested in compressing a directory, you can
proceed as follows,
Module"0" 14"
Before we begin
Module"0" 15"
Before we begin
Module"0" 16"
Before we begin
Installing OpenFOAM® - Working on your own
• If for any reason you do not want to use our Linux version, you are free
to install any Linux version you like.
• My instructions are exactly the same as the one you will find in
http://www.openfoam.org/, I only added a few tips and comments.
Module"0" 17"
Before we begin
Additional Tools
Module"0" 18"
Before we begin
For geometry generation, mesh generation, and visualization, the following open source
applications might come in handy:
Mesh Generation
• Salome (http://www.salome-platform.org/). *
• Engrid (http://engits.eu/en/engrid). *
• GMSH (http://www.geuz.org/gmsh/). *
• Triangle (http://www.cs.cmu.edu/~quake/triangle.html).
• Tetgen (http://tetgen.berlios.de/).
• cfMesh " "(http://www.c-fields.com/).
• Overture (http://www.overtureframework.org/).
Module"0" 20"
Before we begin
For geometry generation, mesh generation, and visualization, the following open source
applications might come in handy:
Module"0" 21"
Before we begin
For geometry generation, mesh generation, and visualization, the following open source
applications might come in handy:
Visualization
• Visit (https://wci.llnl.gov/codes/visit/). *
• Paraview (http://www.paraview.org/). *
• Mayavi (http://code.enthought.com/projects/mayavi/) . *
Module"0" 22"
Before we begin
For geometry generation, mesh generation, and visualization, the following open source
applications might come in handy:
Module"0" 23"
Before we begin
For geometry generation, mesh generation, and visualization, the following open source
applications might come in handy:
OpenFOAM® GUI
• Helyx-os (http://engys.com/products/helyx-os).
Module"0" 24"
Before we begin
And of course we will need,
OpenFOAM® solver
• OpenFOAM® (http://www.openfoam.org/).
Module"0" 25"
Before we begin
Also, the following OpenFOAM® utilities might come in handy
OpenFOAM® utilities
• PyFoam (http://openfoamwiki.net/index.php/Contrib_PyFoam).
• swak4foam (http://openfoamwiki.net/index.php/Contrib/swak4Foam).
• setDiscreteFields (http://openfoamwiki.net/index.php/Contrib_setDiscreteFields).
Module"0" 26"
Before we begin
Additionally, to deal with numerical optimization the following applications might come in
handy
Optimization Frameworks
• DAKOTA (http://dakota.sandia.gov/).
• OpenMDAO (http://www.openmdao.org/).
Module"0" 27"
Before we begin
By the way, you do not need to install all these tools. These are tools that I often use or
I feel confortable with.
Module"0" 28"
Course objectives
Introduce the CFD simulation lifecycle by using
open source tools.
“From geometry generation, to mesh generation, to
governing equations solution, to post-processing”.
Geometry description
Mesh generation
Visualization
Module"0" 29"
Course objectives
Module"0" 30"
Course objectives
Module"0" 31"
Course objectives
Module"0" 32"
Prerequisites
Module"0" 33"
What I will try to keep to a minimum
Module"0" 34"
What I need from you
Module"0" 35"
What I need from you
Module"0" 36"
What I need from you
• If you have a case of your own, let me know and I will try to do
my best to help you to setup your case. But remember,
Module"0" 37"
What I need from you
Module"0" 39"
What about OpenFOAM® documentation?
Module"0" 40"
What about OpenFOAM® documentation?
Module"0" 41"
What about OpenFOAM® documentation?
Remember,
Module"0" 42"
How to learn more about OpenFOAM®
Module"0" 43"
How to learn more about OpenFOAM®
Module"0" 44"
How to learn more about OpenFOAM®
Module"0" 45"
10 steps to get functional with OpenFOAM®
• Learn by doing.
• Learn from an OpenFOAM® case or course tutorial.
• Try to change the case and study the outcome.
• Introduce errors in the case and try to understand OpenFOAM® output.
• Make a totally different case using the same solver.
• Learning C++ is extremely beneficial.
• Learning Python will not hurt you, specially for data analytics
• Understand the solver. For this you will need some C++ skills and finite
volume method theoretical background.
• Top level development, make your own solver or modify and existing
one and setup the case.
• Try to do some debugging and profiling. For profiling you can use
Valgrind, it is an amazing tool.
• Very important, understand the theory.
Module"0" 46"
Useful links
• User manual, programmer manual and source code.
Module"0" 47"
CFD/FVM/C++ Bibliographical references
• Numerical Heat Transfer and Fluid Flow.
S. Patankar. 1980, Taylor & Francis
• An Introduction to Computational Fluid Dynamics.
H. K. Versteeg, W. Malalasekera. 2007, Prentice Hall.
• Computational Methods for Fluid Dynamics.
J. H. Ferziger, M. Peric. 2001, Springer.
• Computational Fluid Dynamics: Principles and Applications.
J. Blazek. 2006, Elsevier Science.
• Computational Techniques for Multiphase Flows
G. H. Yeoh, J. Tu. 2009, Butterworth-Heinemann
• Turbulence Modeling for CFD
D. Wilcox. 2006, DCW Industries.
• A Finite Volume Method for the Prediction of Three-Dimensional Fluid Flow in Complex
Ducts.
M. Peric. PhD Thesis. 1985. Imperial College, London.
• Error analysis and estimation in the Finite Volume method with applications to fluid
flows.
H. Jasak. PhD Thesis. 1996. Imperial College, London.
• Computational fluid dynamics of dispersed two-phase flows at high phase fractions
H. Rusche. PhD Thesis. 2002. Imperial College, London.
Module"0" 48"
CFD/FVM/C++ Bibliographical references
• The C++ Programming Language.
B. Stroustrup. 2013, Addison-Wesley.
• The C++ Standard Library.
N. Josuttis. 2012, Addison-Wesley.
• C++ for Engineers and Scientists.
G. J. Bronson. 2012, Cengage Learning.
• Sams Teach Yourself C++ in One Hour a Day.
J. Liberty, B. Jones. 2004, Sams Publishing.
• C++ Primer.
S. Lippman, J. Lajoie, B. Moo. 2012, Addison-Wesley.
• http://www.cplusplus.com/
• http://stackoverflow.com/
Module"0" 49"
Module 1
Module'1')'Lecture'1' 1'
Today’s lecture
Module'1')'Lecture'1' 2'
OpenFOAM® brief overview
General description:
• OpenFOAM® stands for Open Source Field Operation and
Manipulation.
Module'1')'Lecture'1' 3'
OpenFOAM® brief overview
General description:
• It can be used in massively parallel computers. No need to pay
for separate licenses.
Module'1')'Lecture'1' 4'
OpenFOAM® brief overview
General description:
• It has extensive multi-physics capabilities:
• Computational fluid dynamics.
• Heat transfer and conjugate heat transfer.
• Combustion and chemical reactions.
• Multiphase flows and mass transfer.
• Stress analysis and fluid-structure interaction.
• Particle methods (DEM, DSMC, MD) and lagragian particles
tracking.
• Dynamic mesh handling, 6 DOF solvers, and adaptive mesh
refinement.
• Computational aero-acoustics, computational
electromagnetics, computational
Module'1')'Lecture'1'
solid mechanics, etc. 5'
OpenFOAM® brief overview
Brief overview – Description and implementation:
• Finite Volume Method (FVM) based solver.
Module'1')'Lecture'1' 6'
OpenFOAM® brief overview
Brief overview – Description and implementation:
• Massive parallelism through domain decomposition.
Module'1')'Lecture'1' 7'
OpenFOAM® brief overview
Brief overview – Physical models:
• Physical modeling library:
Module'1')'Lecture'1' 8'
OpenFOAM® brief overview
Brief overview – Physical models:
• Physical modeling library:
Module'1')'Lecture'1' 9'
OpenFOAM® brief overview
Brief overview – Solvers:
• OpenFOAM® comes with several ready-to-use or out-of-the-
box solvers:
Module'1')'Lecture'1' 10'
OpenFOAM® brief overview
Brief overview – Solvers:
• OpenFOAM® comes with several ready-to-use or out-of-the-
box solvers:
Module'1')'Lecture'1' 11'
OpenFOAM® brief overview
Brief overview – Solvers:
• And if this is not enough for you, you can implement your own
solvers.
Module'1')'Lecture'1' 12'
OpenFOAM® brief overview
Brief overview – Equation mimicking:
• The equation,
@⇢U
+r· U r · µrU = rp
@t
can be written in OpenFOAM® as follows,
solve
(
fvm::ddt(rho,U)
+ fvm::div(phi,U)
- fvm::laplacian(mu,U)
==
- fvc::grad(p)
);
Module'1')'Lecture'1' 14'
OpenFOAM® brief overview
Brief overview – Customizing solvers:
• OpenFOAM® design encourages code and libraries re-use.
• Top level solvers are written in few 100s lines of code, and are
optimized for efficiency.
Module'1')'Lecture'1' 15'
OpenFOAM® brief overview
Brief overview – Core technology:
• OpenFOAM® is assembled from components: foundations
libraries (vectors and tensors algebra, mesh handling,
discretization, boundary conditions, linear solvers, parallel
computing, etc.), physical modeling libraries, utilities and
solvers.
Module'1')'Lecture'1' 16'
OpenFOAM® brief overview
Brief overview – Core technology:
• This ensures consistency across the whole of the OpenFOAM®
distribution, rather than having a suite of packages compiled
from entirely separate source code.
Module'1')'Lecture'1' 17'
OpenFOAM® brief overview
Module'1')'Lecture'1' 18'
Module 1
Module'1')'Lecture'2' 1'
Today’s lecture
Module'1')'Lecture'2' 2'
Today’s lecture
Module'1')'Lecture'2' 3'
OpenFOAM® directory organization
bin
$HOME/OpenFOAM/OpenFOAM-2.3.x
doc
In this directory you will find all the directories
etc containing OpenFOAM® installation. In this
directory you will also find additional files (such as
platforms
README.org, COPYING, etc.), but the most
src important one is Allwmake, which compiles
OpenFOAM®.
tutorials
$WM_PROJECT_DIR
platforms
If you use OpenFOAM® version 2.3.0, the
src environment variable $WM_PROJECT_DIR will
point to
tutorials
wmake $HOME/OpenFOAM/OpenFOAM-2.3.0
Allwmake
Additional
files
Module'1')'Lecture'2' 5'
OpenFOAM® directory organization
$WM_PROJECT_DIR
OpenFOAM® environment variables
applications
platforms
echo $WM_PROJECT_DIR
src
Allwmake
To see all the environment variables type env.
Additional
files
Module'1')'Lecture'2' 6'
OpenFOAM® directory organization
$WM_PROJECT_DIR
OpenFOAM® aliases
applications
platforms
alias foam='cd $WM_PROJECT_DIR'
src alias app='cd $FOAM_APP'
tutorials alias src='cd $FOAM_SRC'
alias tut='cd $FOAM_TUTORIALS’
wmake
Allwmake
For a complete list type alias in the terminal.
Additional
files
Module'1')'Lecture'2' 7'
OpenFOAM® directory organization
Module'1')'Lecture'2' 8'
OpenFOAM® directory organization
$WM_PROJECT_DIR
applications
solvers
test
utilities
Module'1')'Lecture'2' 10'
OpenFOAM® directory organization
$WM_PROJECT_DIR
bin
Module'1')'Lecture'2' 11'
OpenFOAM® directory organization
Module'1')'Lecture'2' 12'
OpenFOAM® directory organization
$WM_PROJECT_DIR
doc
Module'1')'Lecture'2' 13'
OpenFOAM® directory organization
$WM_PROJECT_DIR
doc
• Documentation usage:
acroread $WM_PROJECT_DIR/doc/Guides-a4/UserGuide.pdf
acroread $WM_PROJECT_DIR/doc/Guides-a4/ProgrammersGuide.pdf
firefox file://$WM_PROJECT_DIR/doc/Doxygen/html/index.html
• Notice that I am using acroread for opening the *.pdf files and firefox for
the *.html files.
Module'1')'Lecture'2' 14'
OpenFOAM® directory organization
Module'1')'Lecture'2' 15'
OpenFOAM® directory organization
$WM_PROJECT_DIR
etc
• It also contains the super dictionary controlDict, where you can set
several debug flags and the defaults units.
Module'1')'Lecture'2' 16'
OpenFOAM® directory organization
Module'1')'Lecture'2' 17'
OpenFOAM® directory organization
$WM_PROJECT_DIR
platforms
linux64GccDPOpt
bin
lib
Module'1')'Lecture'2' 19'
OpenFOAM® directory organization
$WM_PROJECT_DIR
src/ …
src/ …
In this directory you will also find the Allwmake script, which will compile all the
content of the src directory.
To compile a specific library, go to the desired sub-directory and compile it by
typing wmake.
Module'1')'Lecture'2' 21'
OpenFOAM® directory organization
Module'1')'Lecture'2' 22'
OpenFOAM® directory organization
$WM_PROJECT_DIR
tutorials
• The tutorials directory contains example cases for each solver. These
are the tutorials distributed with OpenFOAM®.'
Module'1')'Lecture'2' 23'
OpenFOAM® directory organization
Module'1')'Lecture'2' 24'
OpenFOAM® directory organization
$WM_PROJECT_DIR
wmake
wmake understands the file structure in OpenFOAM® and has some default
compiler directives that are set in the wmake directory. There is also a command,
wclean, that cleans up the output from the wmake command.
If you add a new compiler name in the bashrc file, you should also tell wmake
how to interpret that name. In wmake/rules you will find the default settings for
the available compilers.
You can also find a few scripts that are useful when organizing your files for
compilation, or for cleaning up. Module'1')'Lecture'2' 25'
OpenFOAM® directory organization
• Tip of day,
Module'1')'Lecture'2' 26'
OpenFOAM® directory organization
Module'1')'Lecture'2' 28'
OpenFOAM® directory organization
$HOME/OpenFOAM
$WM_PROJECT_DIR
$WM_PROJECT_USER_DIR
Environment variables
• $HOME/OpenFOAM/OpenFOAM-2.3.x/etc
Module'1')'Lecture'2' 32'
OpenFOAM® directory organization
Environment variables
• If you are running bash or ksh (if in doubt type echo $SHELL),
you sourced the $WM_PROJECT_DIR/etc/bashrc file by
adding the following line to your $HOME/.bashrc file:
• source $HOME/OpenFOAM/OpenFOAM-2.3.x/etc/
bashrc
source $HOME/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc
WARNING
Remember, when you use OpenFOAM® you are using its
environment settings, that is, path to libraries and
compilers.
Module'1')'Lecture'2' 35'
Directory structure of an OpenFOAM® solver
Module'1')'Lecture'2' 36'
Directory structure of an OpenFOAM® solver
$WM_PROJECT_DIR/applications/solvers
REMEMBER
For your own applications, it is recommended to put the source code in
$WM_PROJECT_USER_DIR following the same structure as in $WM_PROJECT_DIR/
applications. Also, you will need to modify Make/files and Make/options to show
the new name and location of the compiled binaries and libraries to link the solver against.
This is done so you do not modify anything in the original installation,
except for updates!. You can do anything you want to your own copies,
so you do not risk messing things up.
Module'1')'Lecture'2' 38'
Directory structure of an OpenFOAM® utility
Module'1')'Lecture'2' 39'
Directory structure of an OpenFOAM® utility
$WM_PROJECT_DIR/applications/utilities
REMEMBER
For applications of your own, it is recommended to put the source code in
$WM_PROJECT_USER_DIR following the same structure as in $WM_PROJECT_DIR/
applications. Also, you will need to modify Make/files and Make/options to show
the new name and location of the compiled binaries and libraries to link the utility against.
This is done so you do not modify anything in the original installation,
except for updates!. You can do anything you want to your own copies,
so you do not risk messing things up.
Module'1')'Lecture'2' 41'
Directory structure of an OpenFOAM® utility
REMEMBER
You can put your OpenFOAM® cases, solvers, utilities
and libraries in any directory, but it is highly advisable to
save everything in your OpenFOAM® user directory or
$WM_PROJECT_USER_DIR.
Module'1')'Lecture'2' 42'
Today’s lecture
Module'1')'Lecture'2' 43'
Solvers in OpenFOAM®
• In $FOAM_SOLVERS (use alias sol to go there) you will find the directories
containing the source code for the solvers available in the OpenFOAM® installation
(version 2.3.x):
• basic
• combustion
• compressible
• discreteMethods
• DNS
• electromagnetics
• financial
• heatTransfer
• incompressible
• lagrangian
• multiphase
• stressAnalysis
Module'1')'Lecture'2' 44'
Solvers in OpenFOAM®
• For example, in the sub-directory incompressible you will find several sub-
directories containing the source code of the following solvers:
• adjointShapeOptimizationFoam
• boundaryFoam
• icoFoam
• nonNewtonianIcoFoam
• pimpleFoam
• pisoFoam
• shallowWaterFoam
• simpleFoam
• Inside each directory you will find a *.C file with the same name as the directory.
This is the main file, where you will find the top-level source code and a short
description of the solver. In incompressible/icoFoam/icoFoam.C you will find
the following description:
Transient solver for incompressible, laminar flow of
Newtonian fluids. Module'1')'Lecture'2' 45'
Solvers in OpenFOAM®
REMEMBER
Module'1')'Lecture'2' 46'
Utilities in OpenFOAM®
• In $FOAM_UTILITIES (use alias util to go there) you will find the directories
containing the source code for the utilities available in the OpenFOAM® installation
(version 2.3.x):
• mesh
• miscellaneous
• parallelProcessing
• postProcessing
• preProcessing
• surface
• thermophysical
As for the solver, take your time and dig into each directory to get a
complete description of each utility.
Module'1')'Lecture'2' 47'
Utilities in OpenFOAM®
• For example, in the sub-directory mesh/generation you will find several sub-
directories containing the source code of the following utilities:
• blockMesh
• extrude
• extrude2DMesh
• foamyHexMesh
• foamyQuadMesh
• snappyHexMesh
• Inside each utility directory you will find a *.C file with the same name as the
directory. This is the main file, where you will find the top-level source code and a
short description of the utility. In snappyHexMesh/snappyHexMesh.C you will find
the following description:
• Co • Q
• enstrophy • streamFunction
• flowType • streamFunction
• Lambda2 • uprime
• Mach • vorticity
• Pe
• Inside each utility directory you will find a *.C file with the same name as the
directory. This is the main file, where you will find the top-level source code and a
short description of the utility. In Q/Q.C you will find the following description:
REMEMBER
Module'1')'Lecture'2' 50'
Applications and libraries in OpenFOAM®
• acroread $WM_PROJECT_DIR/doc/Guides-a4/
UserGuide.pdf
acroread $WM_PROJECT_DIR/doc/Guides-a4/UserGuide.pdf
Module'1')'Lecture'2' 51'
Applications and libraries in OpenFOAM®
• If you have internet access you can read the online user guide. Go to the link
http://www.openfoam.org/docs/user/, then go to chapter 3 (applications and libraries), and then
go the sub-sections, 3.5 Standard solvers, 3.6 Standard utilities, and/or 3.7 Standard libraries.
Module'1')'Lecture'2' 52'
Applications and libraries in OpenFOAM®
Module'1')'Lecture'2' 54'
Directory structure of an OpenFOAM® case
$WM_PROJECT_USER_DIR/run
case_directory (case name) case_directory: path to the
case, often located in
system $WM_PROJECT_USER_DIR/run
controlDict
system: contains run-time control
fvSchemes and solver numerics.
fvSolution constant: contains physical
constant properties and turbulence
modeling properties and so on.
physical properties
constant/polyMesh: contains
polyMesh the polyhedral mesh information.
mesh information
0: contains boundary conditions
0 and initial conditions.
boundary/initial conditions time_directories: contains the
solution and derived fields.
time_directories
solution files
Module'1')'Lecture'2' 55'
Directory structure of an OpenFOAM® case
REMEMBER
You always run the solvers and utilities in the the top
level of the case directory (the directory with the case
name).
Not in the directory system, not in the directory
constant, not in the directory 0.
Module'1')'Lecture'2' 56'
Directory structure of an OpenFOAM® case
REMEMBER
You can put your OpenFOAM® cases, solvers, utilities
and libraries in any directory, but it is highly advisable to
save everything in your OpenFOAM® user directory or
$WM_PROJECT_USER_DIR.
Module'1')'Lecture'2' 57'
Directory structure of an OpenFOAM® case
• In the USB key you will find many tutorials (which are different
from those that come with the OpenFOAM® installation), let us
work with these tutorials to understand and get functional using
OpenFOAM®.
• $PTOFC
(abbreviation of path to OpenFOAM® course).
Module'1')'Lecture'2' 59'
Directory structure of an OpenFOAM® case
Module'1')'Lecture'2' 60'
Module 1
Module'1')'Lecture'3' 1'
Today’s lecture
Module'1')'Lecture'3' 2'
Today’s lecture
Module'1')'Lecture'3' 3'
Before we start
Module'1')'Lecture'3' 4'
Before we start
Simulation workflow – Generic global view.
GEOMETRY
MESH
SOLVER CO-PROCESSING
VISUALIZATION
Module'1')'Lecture'3' 5'
Before we start
Simulation workflow – Parametric or optimization approach.
GEOMETRY
MESH
SOLVER CO-PROCESSING
PARAMETRIZATION
OPTIMIZATION
VISUALIZATION
Module'1')'Lecture'3' 6'
Before we start
Simulation workflow – Concurrent approach.
PARALLEL ASYNCHRONOUS OR CONCURRENT DRIVER
MULTIDIMENSIONAL OR PARAMETRIC STUDY
DESIGN OF EXPERIMENTS
SENSITIVITY ANALYSIS
OPTIMIZATION STUDY
UNCERTAINTY QUANTIFICATION
ROBUST DESIGN AND OPTIMIZATION UNDER UNCERTAINTY
MULTIOBJECTIVE OPTIMIZATION
SURROGATE BASED OPTIMIZATION
AUTOMATIC POST-PROCESSING
Module'1')'Lecture'3' 7'
Before we start
Module'1')'Lecture'3' 8'
Today’s lecture
Module'1')'Lecture'3' 9'
My first OpenFOAM® case setup
Ux = 1 m/s
h = 0.1 m
(0,0,0)
l = 0.1 m
Module'1')'Lecture'3' 10'
My first OpenFOAM® case setup
Running the case
blockMesh
icoFoam functionObjects
paraFoam
Module'1')'Lecture'3' 11'
My first OpenFOAM® case setup
At the end of the day you should get something like this
Mesh
Module'1')'Lecture'3' 12'
My first OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 13'
My first OpenFOAM® case setup
$PTOFC/first_tutorial/cavity
Module'1')'Lecture'3' 14'
My first OpenFOAM® case setup
What are we going to do?
• We will use the lid-driven square cavity tutorial as a general example to show you
how to set up and run solvers and utilities in OpenFOAM®.
• In this tutorial we are going generate the mesh (domain discretization), using
blockMesh. However, we can use any application that can generate a valid mesh for
OpenFOAM®.
• After generating the mesh, we look for topological errors and assess the mesh quality.
For this we use the utility checkMesh. Later on, we are going to talk about what is a
good mesh.
• Then we proceed to find the numerical solution using icoFoam, which is a transient
solver for incompressible, laminar flow of Newtonian fluids. By the way, I hope you did
not forget where to look for this information.
• And we finish by doing some cool visualization and post-processing using paraFoam
(a paraview fork).
Module'1')'Lecture'3' 15'
My first OpenFOAM® case setup
Running the case
• While we run this case, we are going to see a lot of information on the screen
(standard output stream or stdout), but it will not be saved. This information is
mainly related to convergence of the simulation.
• In the directory $PTOFC/first_tutorial/cavity you will find the cavity tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'1')'Lecture'3' 16'
My first OpenFOAM® case setup
Running the case
• In the directory $PTOFC/first_tutorial you will find the cavity tutorial.
• In the terminal window type:
• cd $PTOFC/first_tutorial/cavity
• ls –l
(Just to list all the directories and files. Does the directory structure look familiar to you?)
• blockMesh
(Geometry definition and mesh generation utility)
• checkMesh
(Check topology and mesh quality)
• icoFoam
(This will run the solver and will show the standard output on the fly. The standard output stream will not be saved)
• paraFoam
(Visualization utility)
Module'1')'Lecture'3' 17'
My first OpenFOAM® case setup
Running the case
• In the previous case, we run the simulation but we did not save the standard output
stream (stdout) in a log file. We saw the information on the fly.
• My advice is to always save the standard output stream (stdout) in a log file.
• It is of interest to always save the log as if something goes wrong, and you will like to
do some troubleshooting you will need this information.
• Also, if you are interested in plotting the residuals, you will need this log file.
• By the way, if at any point you ask me what went wrong with your simulation, I will ask
you for this file. I might also ask for the standard error stream (stderr).
Module'1')'Lecture'3' 18'
My first OpenFOAM® case setup
Running with log files
• To save a log file of the simulation, we proceed as follows:
• cd $PTOFC/first_tutorial/cavity
(if you are not already in this directory)
• foamCleanTutorials
(To erase the saved solution. It will erase the mesh and all the folders, except for 0, constant and system)
• blockMesh
• checkMesh
• icoFoam > log.icoFoam
(This will redirect your standard output to an ascii file with the name log.icoFoam, you will not see the information on
the fly. If you do not add the > log.icoFoam modifier you will see your standard output on the fly and it will not be
saved)
• gedit log.icoFoam
(Here I use gedit to open the log.icoFoam file, but you can use any editor.)
• foamLog log.icoFoam
(This utility will extract the information inside log.icoFoam and it will save it in an editable format.
• cd logs
• gnuplot
(We now use gnuplot to plot the information extracted from the log file)
Module'1')'Lecture'3' 19'
These steps are optional
My first OpenFOAM® case setup
Running with log files
• But what if I want to save the standard output stream (stdout), and monitor the
information on the fly?
This will redirect your standard output to an ascii file with the name log.icoFoam.
Then using the pipeline operator ( | ) it will use tail to show you the information on
the fly.
Module'1')'Lecture'3' 20'
My first OpenFOAM® case setup
Running with log files
• You can also save the standard output stream (stdout) and the standard error
stream (stderr) , as followsm
This will redirect the standard output and standard error streams to an ascii file with
the name log.icoFoam. Then using the pipeline operator ( | ) it will use tail to
show you the information on the fly.
Module'1')'Lecture'3' 21'
My first OpenFOAM® case setup
Running with log files
• You can also save the standard output in a log.icoFoam, send the job to
background and then use tail to output the information on the fly. To do this you
can proceed as follows,
This will redirect your standard output to an ascii file with the name log.icoFoam.
The bash operator & will send the job to background.
• tail –f log.icoFoam
This will use tail to show you the information on the fly.
Module'1')'Lecture'3' 22'
My first OpenFOAM® case setup
Running with log files
• You can also save the standard output in log.icoFoam, open a new terminal
window and then use tail to output the information on the fly. To do this you can
proceed as follow:
This will redirect your standard output to an ascii file with the name log.icoFoam.
• tail –f log.icoFoam
This will use tail to show you the information on the fly. Notice that you will need
to open a new terminal window and you need to be in the case directory.
Module'1')'Lecture'3' 23'
My first OpenFOAM® case setup
Running with log files
• You can also use the Linux command tee,
This will redirect your standard output to an ascii file with the name log.icoFoam,
and it will show you at the same time the information that is saved in the
log.icoFoam.
• If for any reason you do not want to see the standard output stream and you are not
interested in saving the log file, you can proceed as follows,
Module'1')'Lecture'3' 24'
My first OpenFOAM® case setup
Running with log files
• Finally, when you run in a cluster, you are always interested in saving the logs files
in order to monitor the solution. Remember to always redirect the solver standard
output and error streams to a log file. We are going to briefly address this issue
later.
• To monitor your solution, just login to the cluster, go to the working directory (the
directory where you launched the solver) and type
• tail –f name_of_the_log_file
• You can login and logout with no problem, everything is being managed by the job
scheduler.
• Besides the log file you are saving, the job scheduler will save all the standard
output stream (stdout) and standard error stream (stderr) in a default file. You
can also access these files to monitor the solution.
Module'1')'Lecture'3' 25'
My first OpenFOAM® case setup
Running with log files
• It is also possible to plot the log information on the fly. The easiest way to do this is
by using PyFoam (you will need to install it):
• pyFoamPlotRunner.py icoFoam
• pyFoamPlotRunner.py --help
Module'1')'Lecture'3' 26'
My first OpenFOAM® case setup
Running with log files
• If you do not feel confortable using pyFoamPlotRunner.py to run the solver, it is
also possible to plot the information saved in the log file using PyFoam. To do this
you will need to use the utility pyFoamPlotWatcher.py. For example, in the
terminal type:
• pyFoamPlotWatcher.py log.icoFoam
Module'1')'Lecture'3' 27'
My first OpenFOAM® case setup
Running with log files
• This is a screenshot on my computer. In this case, pyFoamPlotRunner is plotting
the initial residuals and continuity errors on the fly.
Module'1')'Lecture'3' 28'
My first OpenFOAM® case setup
Running with log files
• You can save log files for every single solver or utility
implemented in OpenFOAM®.
Module'1')'Lecture'3' 29'
My first OpenFOAM® case setup
Stopping the simulation
• Your simulation will automatically stop at the time value you set using the keyword
endTime in the controlDict dictionary.
endTime 0.5;
• If for any reason you want to stop your simulation before reaching the value set by the
keyword endTime, you can change this value to a number lower than the current
simulation time (you can use 0 for instance). This will stop your simulation, but it will
not save your last time-step or iteration, so be careful.
stopAt writeNow;
• This modification can be done on the fly (you will need to set the keyword
runTimeModifiable to yes in the controlDict dictionary). This will stop your
simulation and will save the current time-step or iteration.
• If you launched the solver in background, just identify the process id and terminate it.
Again, this will not save your last time-step or iteration.
Module'1')'Lecture'3' 32'
My first OpenFOAM® case setup
Stopping the simulation
• When working on my workstation, I usually proceed in this way:
This will run the solver icoFoam (by the way, this works for any solver or utility), it
will save the standard output stream in the file log.icofoam and will show the
solver output on the fly. If at any moment I want to stop the simulation, and I am not
interested in saving the last time-step, I press ctrl-c.
• If I am interested in saving the last time step, I modify the controlDict dictionary
and add the following keyword
stopAt writeNow;
• Remember, this modification can be done on the fly. However, you will need to set the
keyword runTimeModifiable to Module'1')'Lecture'3'
yes in the controlDict dictionary. 33'
My first OpenFOAM® case setup
Cleaning the case folder
• If you want to erase the mesh and the solution in the current case folder, you can type
in the terminal,
foamCleanTutorials
• If you are looking to only erase the mesh, you can type in the terminal,
foamClearPolyMesh
• If you are only interested in erasing the saved solutions, in the terminal type,
Module'1')'Lecture'3' 34'
My first OpenFOAM® case setup
Cleaning the case folder
• Another fancy way to clean the case folder is as follows. In the terminal type,
• shopt -s extglob
(You just need to type this once in the terminal. If you do not know what we are doing, just google this)
• rm -rf !(0_org|constant|system|script)
(This will erase everything in the case directory except for the folders and files 0_org, constant, system
and script)
• To make your life easier, you can write a small shell script with the following
information,
#!/bin/sh
shopt -s extglob
rm -rf !(0_org|constant|system|script)
Module'1')'Lecture'3' 35'
Today’s lecture
Module'1')'Lecture'3' 36'
A deeper view to my first OpenFOAM® case setup
• We will take a look at what we did when running the cavity tutorial by looking at the
case files.
• First at all it should be noted that icoFoam is a transient solver for incompressible,
laminar flow of Newtonian fluids.
• The case directory originally contains the following sub-directories: 0, constant, and
system. After running icoFoam it also contains the time step directories 0.1, 0.2,
0.3, 0.4, 0.5 and the log.icoFoam file (if you chose to redirect the standard
output stream).
• The time step directories contain the values of all the variables at those time
steps (the solution). The 0 directory is thus the initial condition and boundary
conditions.
• The constant directory contains the mesh and dictionaries for thermophysical
and turbulence models.
• The system directory contains settings for the run, discretization schemes and
solution procedures.
• The icoFoam solver reads the files in the case directory and runs the case
according to those settings.
Module'1')'Lecture'3' 37'
A deeper view to my first OpenFOAM® case setup
The constant directory
(and by the way, open each file and go thru its content)
• The transportProperties file is a dictionary for the dimensioned scalar nu, or the
kinematic viscosity.
• In this case, where we are working with an incompressible flow, we only need to
define the kinematic viscosity.
µ
⌫=
⇢
• Later on, I will ask you to change the Reynolds number, to do so you can change the
value of nu. Remember,
⇢⇥U ⇥L U ⇥L
Re = =
µ ⌫
• You can also change the free stream velocity U or the reference length L.
Module'1')'Lecture'3' 38'
A deeper view to my first OpenFOAM® case setup
The constant directory
(and by the way, open each file and go thru its content)
• Depending on the physics involved and models used, you will need to define more
variables in the dictionary transportProperties.
• For instance, for a multiphase case you will need to define the density rho and
kinematic viscosity nu for each single phase. You also will need to define the surface
tension .
• Depending of your physical model, you will find more dictionaries in the constant
directory.
• For example, if you need to set gravity, you will need to create the dictionary g.
Module'1')'Lecture'3' 39'
A deeper view to my first OpenFOAM® case setup
The constant directory
(and by the way, open each file and go thru its content)
• For the sake of completeness, if you work with compressible flows you will need to
define the dynamic viscosity mu, and many other physical properties in the dictionary
thermophysicalProperties, yes it is a different dictionary.
• As we are not working with compressible flows, I am not going into details. If you are
interested in learning more, you can take a look at the tutorials that deal with
compressible flows.
Module'1')'Lecture'3' 40'
A deeper view to my first OpenFOAM® case setup
The constant directory
(and by the way, open each file and go thru its content)
• The polyMesh directory originally contains the blockMeshDict dictionary for the
blockMesh mesh generator. After generating the mesh, it will contain the mesh in
OpenFOAM® format.
• We will now take a quick look at the blockMeshDict dictionary in order to
understand what we have done (and yes, this is part of the meshing session as well).
• Go to the directory constant/polyMesh and open blockMeshDict dictionary
with your favorite text editor, I will use gedit.
Module'1')'Lecture'3' 41'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/blockMeshDict dictionary
The blockMeshDict dictionary first of all contains a list with a number of vertices:
convertToMeters 0.1;
vertices
(
(0 0 0) //Vertex 0
(1 0 0) //Vertex 1
(1 1 0) //Vertex 2
(0 1 0) //Vertex 3
(0 0 0.1) //Vertex 4
(1 0 0.1) //Vertex 5
(1 1 0.1) //Vertex 6
(0 1 0.1) //Vertex 7
);
• There are eight vertices defining a 3D block. OpenFOAM® always uses 3D meshes,
even if the simulation is 2D.
• convertToMeters 0.1; multiplies the coordinates by 0.1. It is a scaling factor.
Module'1')'Lecture'3' 42'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/blockMeshDict dictionary
The blockMeshDict dictionary then defines a block and the mesh from the vertices:
blocks
(
hex (0 1 2 3 4 5 6 7) (20 20 1) simpleGrading (1 1 1)
);
Module'1')'Lecture'3' 43'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/blockMeshDict dictionary
fixedWalls //NAME
{
type wall; //TYPE
faces
(
(0 4 7 3) //FACE
(2 6 5 1) //FACE
(1 5 4 0) //FACE
);
}
Module'1')'Lecture'3' 44'
1 2
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/blockMeshDict dictionary
Each boundary patch in the blockMeshDict dictionary defines a type, a name, and a
list of boundary faces:
fixedWalls
{
type wall;
faces
(
(0 4 7 3)
(2 6 5 1)
(1 5 4 0)
);
}
• wall is the type of the boundary and fixedWalls is the name of the patch.
• The patch is defined by three faces of the block according to the list, which refers to
the vertex numbers.
Module'1')'Lecture'3' 45'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/blockMeshDict dictionary
• When defining the block and boundaries, the vertices in the lists must be neighbors.
• The order of the vertices in the block must be such that if you sit down in the origin of
coordinates (vertex 0 for this case), and you look towards the axis z (where the axis z
is coming out of the screen), the vertices are marched in a counter clockwise sense.
• The type empty tells OpenFOAM® that this is a 2D case.
Module'1')'Lecture'3' 46'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/blockMeshDict dictionary
• If you are interested in visualizing the actual blocking, you can use paraFoam with
the following option,
• paraFoam –block'
• First at all, this file is automatically generated after you create the mesh
using blockMesh or snappyHexMesh, or you convert the mesh from any
of the compatible formats.
• In this file, the geometrical information related to the base patch type of each
boundary of the domain is specified.
• The base type is different from the numerical type (or primitive type).
• The base type is described purely in terms of geometrical information, while
the numerical type assign a field value to the boundary type.
• You define the numerical patch type (or the value of the boundary condition),
in the directory 0 or time directories.
Module'1')'Lecture'3' 49'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/boundary file
• The base patch type of each boundary of the domain is specified in the file
boundary, which is located in the directory constant/polyMesh/.
• The patch type is specified under the type keyword for each patch defined
in the file boundary.
movingWall
{
type wall;
nFaces 20;
startFace 760;
}
fixedWalls
{
type wall;
nFaces 60;
startFace 780;
}
frontAndBack
{
type empty;
inGroups 1(empty);
nFaces 800;
startFace 840;
} Module'1')'Lecture'3' 50'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/boundary file
• The base patch type of each boundary must be consistent with the
numerical patch type, or the boundary condition used in the field files located
in the directory 0 or time directories.
• In this example, the base patch type of the patch frontAndBack (defined
in the file boundary), is consistent with the numerical patch type defined in
the field files 0/U and 0/p. They are of the type empty. Same for the
other patches.
• This is extremely important, specially if you are converting meshes as not
always the patches are set automatically.
• Hence, I highly advise you to do a sanity check and verify that the base
patch type (the patch type defined in the file boundary), is consistent with
the numerical patch type (the patch type defined in the field files contained in
the time directories or directory 0).
Module'1')'Lecture'3' 51'
A deeper view to my first OpenFOAM® case setup
The system directory
(and by the way, open each file and go thru its content)
• The 0 directory contains the initial and boundary conditions for all primitive variables,
in this case p and U. For this case, the U file contains the following:
dimensions [0 1 -1 0 0 0 0];
internalField uniform (0 0 0);
boundaryField
{
movingWall
{
type fixedValue;
value uniform (1 0 0);
}
fixedWalls
{
type fixedValue;
value uniform (0 0 0);
}
frontAndBack
{
type empty;
}
Module'1')'Lecture'3' 53'
}
A deeper view to my first OpenFOAM® case setup
The 0 directory
(and by the way, open each file and go thru its content)
Module'1')'Lecture'3' 54'
A deeper view to my first OpenFOAM® case setup
The 0 directory
(and by the way, open each file and go thru its content)
• And by the way if you take some time and read the files 0/U and 0/p, you will see
that each numerical patch type (the patch type defined in U and p), is consistent with
the base patch type (the patch type defined in the file constant/polyMesh/
boundary).
Module'1')'Lecture'3' 55'
A deeper view to my first OpenFOAM® case setup
The log.icoFoam file
• If you followed the previous instructions you should now have a log.icoFoam file.
This file contains all the residuals and convergence information.
• foamLog log.icoFoam
• A directory logs has now been generated, with extracted values in ascii format in two
columns. The first column is the time or iteration number, and the second column is
the value at that time.
• Add this point, you can plot the residuals using gnuplot, qtiplot or xmgrace (or your
favorite plotting application).
Module'1')'Lecture'3' 57'
A deeper view to my first OpenFOAM® case setup
Dimensions in OpenFOAM®
1 Mass Kilogram kg
2 Length meters m
3 Time second s
4 Temperature Kelvin K
6 Current ampere A
Luminuous
7 candela cd
intensity
Module'1')'Lecture'3' 59'
A deeper view to my first OpenFOAM® case setup
At this point you should have realized a few things:
• In the header of your field variables, the class type should be consistent with
the type of field variable you are using. That is to say, if the field variable is
a vector, the class should be volVectorField
Module'1')'Lecture'3' 60'
A deeper view to my first OpenFOAM® case setup
At this point you should have realized a few things:
• And if the field variable is a scalar, the class should be volScalarField.
Module'1')'Lecture'3' 61'
A deeper view to my first OpenFOAM® case setup
At this point you should have realized a few things:
Module'1')'Lecture'3' 62'
A deeper view to my first OpenFOAM® case setup
Error output
Module'1')'Lecture'3' 63'
A deeper view to my first OpenFOAM® case setup
• Sometimes OpenFOAM® will give you the error FOAM FATAL IO ERROR.
• This error only means that there is a problem with a dictionary and it is likely
that you misspelled something or you are forgetting a keyword.
• This error does not mean that the actual OpenFOAM® installation is
corrupted.
• Maybe the guys of OpenFOAM® went a little bit extreme here.
/*---------------------------------------------------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
Build : 2.3.x-5d8318b22cbe
Exec : icoFoam
Date : Nov 02 2014
Time : 00:33:41
Host : "linux-cfd"
PID : 3675
Case : /home/cfd/my_cases_course/cavity
nProcs : 1
sigFpe : Enabling floating point exception trapping (FOAM_SIGFPE).
fileModificationChecking : Monitoring run-time modified files using timeStampMaster
allowSystemOperations : Allowing user-supplied system call operations
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Create time
Module'1')'Lecture'3' 64'
A deeper view to my first OpenFOAM® case setup
• Also, before entering into panic, read carefully the output because
OpenFOAM® is telling you what is the error and how to correct it.
/*---------------------------------------------------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
Build : 2.3.x-5d8318b22cbe
Exec : icoFoam
Date : Nov 02 2014
Time : 00:33:41
Host : "linux-cfd"
PID : 3675
Case : /home/cfd/my_cases_course/cavity
nProcs : 1
sigFpe : Enabling floating point exception trapping (FOAM_SIGFPE).
fileModificationChecking : Monitoring run-time modified files using timeStampMaster
allowSystemOperations : Allowing user-supplied system call operations
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Create time
/*---------------------------------------------------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
Build : 2.3.x-5d8318b22cbe
Exec : interDyMFoam
Date : Nov 02 2014
Time : 01:16:57
Host : "linux-cfd"
PID : 4876
Case : /home/cfd/my_cases_course/cavity
nProcs : 1
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Module'1')'Lecture'3' 67'
A deeper view to my first OpenFOAM® case setup
Module'1')'Lecture'3' 68'
A deeper view to my first OpenFOAM® case setup
Dictionary files hints
• If you do not know which entries are available for a specific keyword in a dictionary,
just use a dummy word (a word that does not exist in OpenFOAM®) and the solver
will list the alternatives. For instance if we add,
stopAt banana;
in the controlDict dictionary file; the solver will give you the following message:
• C++ commenting:
// This is my comment
/*
My comments, line 1
My comments, line 2
*/
• #include directive:
#include “initialConditions”
Module'1')'Lecture'3' 70'
A deeper view to my first OpenFOAM® case setup
Dictionary files advanced features
• Macro expansion:
/*
some code lines here
*/
/*
some code lines here
*/
Module'1')'Lecture'3' 71'
A deeper view to my first OpenFOAM® case setup
Dictionary files advanced features
leftWall
{
type fixedValue;
value uniform (0 0 0);
}
rightWall
{
type fixedValue;
value uniform (0 0 0);
}
topWall
{
type fixedValue;
value uniform (0 0 0);
}
Module'1')'Lecture'3' 72'
A deeper view to my first OpenFOAM® case setup
Dictionary files advanced features
“(left|right|top)Wall”
{
type fixedValue;
value uniform (0 0 0);
}
“.*Wall”
{
type fixedValue;
value uniform (0 0 0);
}
• Switches: they are used to enable or disable a function or a feature in the dictionaries.
• Switches are logical values, hence they are paired. You can use the following values:
false true
off on
no yes
n y
f t
none true
• You can find all the valid switches in the following file:
OpenFOAM-2.3.x/src/OpenFOAM/primitives/bools/Switch/Switch.C
Module'1')'Lecture'3' 74'
A deeper view to my first OpenFOAM® case setup
Dictionary files advanced features
• Switches: they are used to enable or disable a function or a feature in the dictionaries.
• For example, the following entries in the dictionary controlDict are valid:
runTimeModifiable yes;
runTimeModifiable true;
runTimeModifiable on;
Module'1')'Lecture'3' 75'
A deeper view to my first OpenFOAM® case setup
Module'1')'Lecture'3' 76'
A deeper view to my first OpenFOAM® case setup
Solvers and utilities help
• If you need help about a solver or utility, you can use the flag –help. For
instance:
• icoFoam –help
will print some basic help and usage information about icoFoam.
• Remember, you have the source code there so you can always
check the original source.
Module'1')'Lecture'3' 77'
A deeper view to my first OpenFOAM® case setup
Solvers and utilities help
• The doc directory contains the documentation of OpenFOAM®, namely;
user guide, programmer’s guide and Doxygen generated documentation in
html format.
Module'1')'Lecture'3' 78'
A deeper view to my first OpenFOAM® case setup
Solvers and utilities help
• Documentation usage. In the terminal type:
acroread $WM_PROJECT_DIR/doc/Guides-a4/UserGuide.pdf
acroread $WM_PROJECT_DIR/doc/Guides-a4/ProgrammersGuide.pdf
firefox file://$WM_PROJECT_DIR/doc/Doxygen/html/index.html
• Notice that I am using acroread for opening the *.pdf files and firefox
for the *.html files.
Module'1')'Lecture'3' 79'
A deeper view to my first OpenFOAM® case setup
Solvers and utilities help
• The helper utility, foamHelp, allows the user to bring up documentation from
a terminal prompt. The foamHelp utility will give you more information on
boundary conditions and function objects.
Module'1')'Lecture'3' 80'
A deeper view to my first OpenFOAM® case setup
Solvers and utilities help
• To open the Doxygen documentation of a functionObject, e.g.
• To use the option –browse, you will need to compile the Doxygen
documentation.
Module'1')'Lecture'3' 81'
A deeper view to my first OpenFOAM® case setup
Solvers and utilities help
• A high-level view of the boundary conditions and function objects help can
also be accessed from the main Doxygen page, just look for the
Using the code section.
Module'1')'Lecture'3' 82'
A deeper view to my first OpenFOAM® case setup
Module'1')'Lecture'3' 83'
A deeper view to my first OpenFOAM® case setup
• Break time!!!
Module'1')'Lecture'3' 84'
Today’s lecture
Module'1')'Lecture'3' 85'
My second OpenFOAM® case setup
Damp break free surface flow
l = 0.584 m
Gravity
0.146 m
Water column
h = 0.584 m
0.292 m
Y
X 0.048 m
(0,0,0)
0.024 m
Module'1')'Lecture'3' 86'
My second OpenFOAM® case setup
Running the case
blockMesh
setFields
interFoam functionObjects
paraFoam
Module'1')'Lecture'3' 87'
My second OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 88'
My second OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 89'
My second OpenFOAM® case setup
$PTOFC/first_tutorial/dampBreak
Module'1')'Lecture'3' 90'
My second OpenFOAM® case setup
• We will use the damp break tutorial for our second OpenFOAM® case setup.
• In the directory $PTOFC/first_tutorial/dampBreak you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'1')'Lecture'3' 91'
My second OpenFOAM® case setup
• In the terminal window type:
• cd $PTOFC/first_tutorial/dampBreak
• ls –l
(Just to list all the directories and files. Does the directory structure look familiar to you?)
• blockMesh
• checkMesh
• cp 0/alpha.water.org 0/alpha.water
(This is done in order to keep a copy of the original alpha.water boundary and initials conditions. Why?, in the next
step we are going to use the utility setFields, which overwrites the file alpha.water)
• setFields
(This utility will initialize fields according to an user criterion. It uses a dictionary, which is located in the directory system.
It will overwrite the initial conditions, so it is advisable to keep a backup of the files located in the directory 0)
Module'1')'Lecture'3' 92'
My second OpenFOAM® case setup
• Let us study all the dictionaries.
• In the terminal window type:
• gedit constant/transportProperties
(Take a look at the dictionary and notice the differences with the previous case)
• gedit constant/g
(Take a look at the new dictionary)
• gedit 0/alpha.water.org
(Take a look at the original dictionary)
• gedit 0/alpha.water
(Take a look at the modified dictionary, it might take a while to open)
• gedit 0/U
(Take a look at the dictionary)
• gedit 0/p_rgh
(Take a look at the dictionary)
Module'1')'Lecture'3' 93'
My second OpenFOAM® case setup
• Let us study all the dictionaries.
• In the terminal window type:
• gedit constant/polyMesh/blockMeshDict
(Take a look at the dictionary)
• gedit constant/polyMesh/boundary
(Take a look at the dictionary)
• gedit system/fvSchemes
(Take a look at the dictionary and identify the changes)
• gedit system/fvSolution
(Take a look at the dictionary and identify the changes)
• gedit system/controlDict
(Take a look at the dictionary and identify the changes)
• gedit system/setFieldsDict
(Take a look at the new dictionary)
Module'1')'Lecture'3' 94'
My second OpenFOAM® case setup
• Now we are ready the run the simulation.
• In the terminal window type:
• paraFoam –block
(This will use paraFoam blockMesh reader to visualize the blocks)
• paraFoam
Module'1')'Lecture'3' 95'
My second OpenFOAM® case setup
• If you want to take a look at the residuals,
• foamLog log.interFoam
(If you chose to redirect the standard output. This step is optional)
• cd logs
(This step is optional)
• gnuplot
(If you chose to redirect the standard output stream. We now use gnuplot to visualize the files in
the directory, if you do not know how to use gnuplot follow me. This step is optional)
Module'1')'Lecture'3' 96'
Today’s lecture
Module'1')'Lecture'3' 97'
My third OpenFOAM® case setup
Module'1')'Lecture'3' 98'
My third OpenFOAM® case setup
Module'1')'Lecture'3' 99'
My third OpenFOAM® case setup
Flow around a cylinder
20
(0,0,0)
20
Y
20 Module'1')'Lecture'3'
30 100'
All the dimensions are in meters
My third OpenFOAM® case setup
Running the case
External
pre-processor
fluentMeshToFoam
ico/piso/simple/potentia/
Foam functionObjects
postProcessing
paraFoam
utilities
Module'1')'Lecture'3' 101'
My third OpenFOAM® case setup
At the end of the day you should get something like this
Mesh
Module'1')'Lecture'3' 102'
My third OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 103'
My third OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 104'
My third OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 105'
Aerodynamic coefficients for Reynolds 200
My third OpenFOAM® case setup
$PTOFC/first_tutorial/vortex_shedding
Module'1')'Lecture'3' 106'
My third OpenFOAM® case setup
• In this tutorial, we are going to learn how to setup the solvers potentialFoam,
simpleFoam, pisoFoam and pimpleFoam. We are also going to learn how to
setup a turbulent case and how to use a few utilities.
• cd $PTOFC/first_tutorial/vortex_shedding
• In this directory, you will find thirteen folders, each one representing a different case
setup. In the terminal window type:
• ls –l
(Just to list all the directories and files)
Module'1')'Lecture'3' 107'
My third OpenFOAM® case setup
• Let us go first to the folder c2. In the terminal window type:
• cd c2
• ls –l
(Just to list all the directories and files. Does the directory structure look familiar to you?)
Module'1')'Lecture'3' 108'
My third OpenFOAM® case setup
• Let us go first to the folder c2. In this tutorial we convert the mesh from Fluent format
to OpenFOAM® format.
• In the terminal window type:
• fluent3DMeshToFoam ../../../meshes/vortex_shedding/
ascii.msh
(This utility will convert the mesh to OpenFOAM®)
• checkMesh
• gedit constant/polyMesh/boundary
• We change the patches back and front from patch to empty, because it is a 2D
problem. The empty type patch means do not do anything in the third dimension.
Module'1')'Lecture'3' 111'
My third OpenFOAM® case setup
• After finishing the modifications to the file constant/polyMesh/boundary, in the
terminal window type:
• checkMesh
• icoFoam > log.icofoam | tail –f log.icofoam
• pyFoamPlotWatcher.py log.icofoam
(To use this utility you need to install pyFoam. Also, you will need to open a new terminal window and go to the case
directory, if you are not already there)
• paraFoam
Module'1')'Lecture'3' 112'
My third OpenFOAM® case setup
• At this point try to use the following utilities. In the terminal type:
• vorticity –noZero
(This utility will compute and write the vorticity field. The –noZero option means do not compute the vorticity field for the
solution in the directory 0. If you do not add the –noZero option, it will compute and write the vorticity field for all the
saved solutions, including 0)
• wallGradU –latestTime
(This utility will compute and write the velocity gradient at the walls. The –latestTime option means compute the
velocity gradient only for the last saved solution)
• Co –noWrite
(This utility will compute and write the Courant number. The –noWrite option means do not write the Courant number
to the solution directories. It will only show you the minimum and maximum values for all the saved solutions, including
the directory 0)
Module'1')'Lecture'3' 113'
My third OpenFOAM® case setup
• As an exercise, try to use the following utilities:
• stressComponents
• wallShearStress
• wallGradU
• Q
• Pe
• yPlusRAS
• refineWallLayer
• refineHexMesh
• renumberMesh
• Be careful, some of these utilities will not run with this tutorial. Try to figure
out why.
Module'1')'Lecture'3' 115'
My third OpenFOAM® case setup
• I have two words for you, thank you. This is what you will find in each
directory,
Module'1')'Lecture'3' 116'
My third OpenFOAM® case setup
• I have two words for you, thank you. This is what you will find in each
directory,
Module'1')'Lecture'3' 118'
My first 3D OpenFOAM® case setup
Running the case
SALOME
blockMesh
Geometry module
snappyHexMesh
pimpleFoam functionObjects
postProcessing
paraFoam
utilities
Module'1')'Lecture'3' 119'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 120'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 121'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this
Mesh
Module'1')'Lecture'3' 122'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 124'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this
Streamlines
Module'1')'Lecture'3' 125'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 126'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this
Module'1')'Lecture'3' 127'
My first 3D OpenFOAM® case setup
This geometry can be used to conduct an optimization study.
For instance, the goal can be to optimize the slant angle to obtain
the minimum drag.
Module'1')'Lecture'3' 128'
My first 3D OpenFOAM® case setup
$PTOFC/first_tutorial/ahmed_body
Module'1')'Lecture'3' 129'
My first 3D OpenFOAM® case setup
• In this tutorial, we use pimpleFoam to solve a 3D case.
• Running a 3D simulation is not different from the previous 2D simulations. The only
difference is that we need to define the boundary conditions in the third dimension.
• It also requires more computational resources.
• In the directory $PTOFC/first_tutorial/ahmed_body you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'1')'Lecture'3' 130'
My first 3D OpenFOAM® case setup
• In the directory $PTOFC/first_tutorial/ahmed_body you will find this tutorial.
• From this point on, please follow me. In the terminal window type:
• cd $PTOFC/first_tutorial/ahmed_body
• ls –l
(Just to list all the directories and files. Does the directory structure look familiar to you?)
• blockMesh
(To generate the background mesh for snappyHexMesh)
• surfaceFeatureExtract
(Extract geometry features for snappyHexMesh. We are going to talk about this utility later on)
• snappyHexMesh –overwrite
(3D Mesh generation. We are going to talk about snappyHexMesh later on)
• Do not worry, starting from tomorrow we are going to talk about what is happening
when we use the utilities blockMesh, surfaceFeatureExtract, and
snappyHexMesh.
Module'1')'Lecture'3' 131'
My first 3D OpenFOAM® case setup
• Now we are ready to run the simulation.
• In the terminal window type:
• checkMesh
• pimpleFoam > log.pimplefoam | tail –f log.pimplefoam
• pyFoamPlotWatcher.py log.pimplefoam
(You will need to open a new terminal window and go to the case directory, if you are not already there)
• paraFoam
• You do not need to run this case until the end time.
• Just run a few time-steps, monitor the solution and try to do some
post-processing and visualization.
Module'1')'Lecture'3' 132'
My first 3D OpenFOAM® case setup
• At this point, try to use the following utilities:
OpenFOAM® tutorials
• The OpenFOAM® installation comes with many tutorials, try to do all of them (or at
least those that interest you).
Module'1')'Lecture'3' 134'
OpenFOAM® tutorials and additional tutorials
Additional tutorials
• In the course’s directory ($PTOFC) you will find many tutorials (which are different
from those that come with the OpenFOAM® installation), try to go through each one
to understand and get functional using OpenFOAM®.
• In each tutorial directory there is a README.FIRST file. In this file you will find
general comments and the instructions of how to run the case
• Let me know if a tutorial does not work or is outdated. It is a difficult task to maintain
all these tutorials.
• Finally, fell free to bring your own cases.
Module'1')'Lecture'3' 135'
OpenFOAM® tutorials and additional tutorials
Tutorials warning
• Use the tutorials just for recreational, instructional, or
learning purposes and not for validation or
benchmarking.
Module'1')'Lecture'3' 136'
Thank you for your attention
Module'1')'Lecture'3' 137'
Today’s lecture
Module'1')'Lecture'3' 138'
Hands-on session
In the course’s directory ($PTOFC) you will find many tutorials (which are different from
those that come with the OpenFOAM® installation), let us try to go through each one to
understand and get functional using OpenFOAM®.
If you have a case of your own, let me know and I will try to do my best to help you to
setup your case. But remember, the physics is yours.
Module'1')'Lecture'3' 139'
Module 2
Module'2')'Lecture'4' 1'
Today’s lecture
Module'2')'Lecture'4' 2'
CFD simulation workflow
Geometry description
Mesh generation
Visualization
Module'2')'Lecture'4' 3'
CFD simulation workflow
GEOMETRY
MESHING
Module'2')'Lecture'4' 4'
The percentages shown are based on my personal experience.
CFD simulation workflow
GEOMETRY
MESH
SOLVER CO-PROCESSING
PARAMETRIZATION
OPTIMIZATION
VISUALIZATION
Module'2')'Lecture'4' 5'
Parametric or optimization approach – Simulation loop
CFD simulation workflow
PARALLEL ASYNCHRONOUS OR CONCURRENT DRIVER
MULTIDIMENSIONAL OR PARAMETRIC STUDY
DESIGN OF EXPERIMENTS
SENSITIVITY ANALYSIS
OPTIMIZATION STUDY
UNCERTAINTY QUANTIFICATION
ROBUST DESIGN AND OPTIMIZATION UNDER UNCERTAINTY
MULTIOBJECTIVE OPTIMIZATION
SURROGATE BASED OPTIMIZATION
AUTOMATIC POST-PROCESSING
Module'2')'Lecture'4' 6'
Concurrent approach – Simulation nested loop
CFD simulation workflow
CASE SETUP POST
GEOMETRY MESHING
AND SOLVER PROCESSING
This list does not enumerate all the open source applications available. It only shows those applications that7' I like
Module'2')'Lecture'4'
to use or I feel confortable with.
CFD simulation workflow
OpenFOAM built-in meshing technology
blockMesh or
external mesher
Background mesh Any commercial or open source CAD or solid modelling tool
snappyHexMesh
Geometry
foamyHexMesh
Any commercial or open source CAD or solid modelling tool (STL file)
blockMesh foamyQuadMesh
Salome cfMesh
OpenFOAM polyMesh
Module'2')'Lecture'4' 8'
The diagram does not show all the applications available.
Module 2
Module'2')'Lecture'5' 1'
Today’s lecture
Module'2')'Lecture'5' 2'
Geometry generation using open source tools
.. among others.
Sew faces
Align faces
Delete overlapping faces
Connect/disconnect edges
Geometry generation using open source tools
Geometry repair/cleanup
Geometry generation using open source tools
Geometry repair/cleanup
Geometry generation using open source tools
Geometry repair/cleanup
Geometry generation using open source tools
Geometry repair/cleanup
Geometry generation using open source tools
• Many times, it is not necessary to model all the details of the geometry. In these
cases you should consider simplifying the geometry (geometry defeaturing).
• Geometry defeaturing can save you a lot of time when generating the mesh.
So be smart, and use it whenever is possible.
Original Geometry
Defeatured Geometry
Geometry generation using open source tools
• Salome: is a history based CAD tool (parametric design). It has quite
extensive capabilities for creation and manipulation of solid geometries.
http://www.salome-platform.org/
Module'3')'Lecture'6' 1'
Meshing and mesh quality
This lecture is about meshing and mesh quality
assessment for CFD computations
Module'3')'Lecture'6' 2'
Meshing and mesh quality
This lecture is about meshing and mesh quality
assessment for CFD computations
I do not know how much I will stress this, but try to always
use a good quality mesh.
Have always in mind, garbage in - garbage out.
As I am a really positive guy, I prefer to say,
good mesh - good results.
Module'3')'Lecture'6' 3'
Meshing and mesh quality
Module'3')'Lecture'6' 4'
Today’s lecture
Module'3')'Lecture'6' 5'
Meshing preliminaries
• Mesh generation consist in dividing the physical domain into a finite number
of discrete regions, called control volumes or cells in which the solution is
sought (domain discretization).
Module'3')'Lecture'6' 6'
Meshing preliminaries
• Meshes used for the FVM method can consist of tetrahedras, pyramids,
prisms, hexes, dodecahedrons, or any kind of polyhedral element (or a mix
of all of them).
Module'3')'Lecture'6' 7'
Meshing preliminaries
• In the next slides, I will show a few meshes generated by using different
meshing methods.
• Also, I will present a table with a comparison of four commonly used mesh
generation methods.
• The figures of merit used to compare the meshes are related to the method
used to generate the mesh and not to the flow solver.
• All the methods that we are going to talk about, can generate a valid mesh
to be used with the FVM.
Module'3')'Lecture'6' 8'
Meshing preliminaries
Geometric Flexibility/
Adaptation
Grid Adaptation/
Local Refinement
Viscous Computation
Moving/Deforming
Meshes Quality
Interpolation/
Conservation
Grid generation
easiness
Memory
Requirements
CPU Requirements
Module'3')'Lecture'6' 15'
Meshing preliminaries
A structured mesh requires as input
the blocking definition (blue lines in
the figure).
For complicated geometries, it can
be extremely difficult arrive to the
right blocking, it requires a lot user
experience.
After defining the blocking, the mesh
generation time is quite fast, in the
order of seconds or minutes.
Cell count:
approx. 5 000 000
Structured Mesh
(hexahedrals)
Cell count:
approx. 5 000 000
Module'3')'Lecture'6' 17'
Meshing preliminaries
Cell count:
approx. 5 000 000
Structured Mesh
(hexahedrals)
Cell count:
approx. 5 000 000
Module'3')'Lecture'6' 18'
Meshing preliminaries
Cell count:
approx. 5 000 000
Structured Mesh
(hexahedrals)
Cell count:
approx. 5 000 000
Module'3')'Lecture'6' 19'
Meshing preliminaries
Cell count:
approx. 5 000 000
Structured Mesh
(hexahedrals)
Cell count:
approx. 5 000 000
Module'3')'Lecture'6' 20'
Meshing preliminaries
Cell count:
approx. 5 000 000
Structured Mesh
(hexahedrals)
Cell count:
approx. 5 000 000
Module'3')'Lecture'6' 21'
Meshing preliminaries
Cell count:
approx. 5 000 000
Structured Mesh
(hexahedrals)
Cell count:
approx. 5 000 000
Module'3')'Lecture'6' 22'
Meshing preliminaries
Unstructured Vs. Structured meshes,
Who wins?
• Each mesh type has its advantages and disadvantages.
• From a practical point of view, the time invested to setup and generate the
mesh should be reasonable. It must meet your project requirements in
terms of time frame.
• The mesh density should be high enough to capture all relevant flow
features, without degenerating due to clustering or stretching.
• At the end of the day, the mesh you use must has a good overall quality
and must be smooth.
• But wait, what is a good mesh?. Mesh quality and smoothness will be
studied in the next lecture. Module'3')'Lecture'6' 23'
Meshing preliminaries
What cell type do I use?
• It is clear from the previous discussion that the cell type,
depends on the mesh type.
Module'3')'Lecture'6' 24'
Meshing preliminaries
What cell type do I use?
• Each cell type has its very own properties when it comes to
domain discretization, we are going to talk about this later on
when we deal with the FVM.
Module'3')'Lecture'6' 25'
Module 3
Module'3')'Lecture'7' 1'
Today’s lecture
Module'3')'Lecture'7' 2'
Mesh quality assessment
What is a good mesh?
• There is no written theory when it comes to mesh generation. Basically, the
whole process depends on user experience.
• A standard rule of thumb is that the elements shape and distribution should
be pleasing to the eye.
Cells ≈ 3 500 000 ≈ 11 000 000 ≈ 36 000 000 ≈ 105 000 000
Module'3')'Lecture'7' 4'
Mesh quality assessment
What is a good mesh?
• No single standard benchmark or metric exists that can effectively assess
the quality of a mesh, but you can rely on suggested best practices.
• After generating the mesh, we measure these quality metrics and we use
them to assess mesh quality.
• Hereafter, I will present you the most common mesh quality metrics:
• Orthogonality.
• Skewness.
• Aspect Ratio.
• Smoothness.
Module'3')'Lecture'7' 5'
Mesh quality assessment
Mesh quality metrics. Mesh orthogonality
• Mesh orthogonality is the angular deviation of the vector S (located at the
face center f ) from the vector d connecting the two cell centers P and N. In
this case is 20 .
• Affects the gradient of the face center f.
• It adds diffusion to the solution.
• It mainly affects the diffusive terms.
S
d
P f N
Module'3')'Lecture'7' 6'
Mesh quality assessment
Mesh quality metrics. Mesh skewness
• Skewness is the deviation of the vector d that connects the two cells P and
N, from the face center f. The deviation vector is represented with
and fi is the point where the vector d intersects the face f .
• Affects the interpolation of the cell centered quantities to the face center f.
• It adds diffusion to the solution.
• It affects the convective terms.
f S
P
Di
d fi
N
Module'3')'Lecture'7' 7'
Mesh quality assessment
Mesh quality metrics. Mesh aspect ratio AR
• Mesh aspect ratio AR is the ratio between the longest side x and the
shortest side y .
• Large AR are ok if gradients in the largest direction are small.
• High AR smear gradients.
Dy
Dx
Module'3')'Lecture'7' 8'
Mesh quality assessment
Mesh quality metrics. Smoothness
• Smoothness, also known as expansion rate, growth factor or uniformity,
defines the transition in size between contiguous cells.
• Large transition ratios between cells add diffusion to the solution.
• Ideally, the maximum change in mesh spacing should be less than 20%:
y2
1.2
y1
Dy2
Dy1
Module'3')'Lecture'7' 9'
Steep transition Smooth transition
Mesh quality assessment
Element type close to the walls -
Cell/Flow alignment
• Hexahedrals, prisms, and quadrilaterals can be stretched easily to resolve
boundary layers without losing quality.
• Triangular and tetrahedral meshes have inherently larger truncation error.
• Less truncation error when faces aligned with flow direction and gradients.
P f f
Dy
P
⇥ 2 ⇥
f = P + y + O( yModule'3')'Lecture'7'
) f = P + y + O( 10'y 2 )
⇥y ⇥y
Mesh quality assessment
Module'3')'Lecture'7' 11'
Mesh quality assessment
Striving for quality
• For the same cell count, hexahedral meshes will give more accurate
solutions, especially if the grid lines are aligned with the flow.
• But this does not mean that tetra meshes are no good, by carefully choosing
the numerical scheme you can get the same level of accuracy as in hex
meshes. The problem with tetra meshes are mainly related to the way
gradients are computed.
Tetra
QOI
Hexa
Module'3')'Lecture'7' 12'
Year
Mesh quality assessment
Striving for quality
• Hexahedrals, prisms, and quadrilaterals can be easily aligned with the flow.
• They can also be stretched to resolve boundary layers without losing much
quality.
Module'3')'Lecture'7' 13'
Mesh quality assessment
Striving for quality
• Tetra meshes normally need more computing resources during the solution
stage. But his can be easily offset by the time saved during the mesh
generation stage.
• Increasing the cells count will likely improve the solution accuracy, but at the
cost of a higher computational cost.
• But attention, finer mesh does not mean a good or better mesh. After
refining your mesh, always check the quality metrics.
Module'3')'Lecture'7' 14'
Mesh quality assessment
Striving for quality
• And by the way, you can combine all cell types to get a hybrid mesh.
Module'3')'Lecture'7' 15'
Mesh quality assessment
Striving for quality
• The mesh density should be high enough to capture all relevant flow
features. In areas where the solution change slowly, you can use larger
elements. A good mesh does not rely in the fact that the more cells we use
the better the solution.
• In boundary layers, quad, hex, and prism/wedge cells are preferred over
triangles, tetrahedras, or pyramids.
Module'3')'Lecture'7' 17'
Mesh quality assessment
Striving for quality
• If you are not using wall functions (turbulence modeling), the mesh adjacent
to the walls should be fine enough to resolve the boundary layer flow. Have
in mind that this will rocket the cell count and increase the computing time.
• For complex flows without dominant flow direction, quad and hex meshes
loose their advantages.
Module'3')'Lecture'7' 18'
Mesh quality assessment
Striving for quality
• Keep orthogonality, skewness, and aspect ratio to a minimum.
• Always check the mesh quality. Remember, one single cell can cause
divergence or give you inaccurate results.
• When you strive for quality, you avoid the GIGO syndrome.
Module'3')'Lecture'7' 19'
Mesh quality assessment
Striving for quality
Module'3')'Lecture'7' 20'
Mesh quality assessment
Striving for quality
• Just to end for good the mesh talk:
• So, as long as your results are physically realistic, reliable and accurate;
your mesh is good.
• At the end of the day, the final mesh will depend on the physic involve.
• Know your physics and generate a mesh able to resolve that physics,
without over-doing.
Module'3')'Lecture'7' 21'
Mesh quality assessment
Module'3')'Lecture'7' 22'
Mesh quality assessment
Mesh quality metrics in OpenFOAM®
• In $WM_PROJECT_DIR/src/OpenFOAM/meshes/primitiveMesh/
primitiveMeshCheck/primitiveMeshCheck.C you will find the
quality metrics used in OpenFOAM®. Their maximum (or minimum) values
are defined as follows:
Module'3')'Lecture'7' 23'
Mesh quality assessment
Module'3')'Lecture'7' 24'
Mesh quality assessment
Checking mesh quality in OpenFOAM®
• OpenFOAM® comes with the utility checkMesh which checks the validity of
the mesh.
• checkMesh will look for/check for:
• Mesh stats and overall number of cells of each type.
• Check topology (boundary conditions definitions).
• Check geometry and mesh quality (bounding box, cell volumes,
skewness, orthogonality, aspect ratio, and so on).
• If for any reason checkMesh finds errors, it will give you a message and it
will tell you what check failed.
• It will also write a set with the faulty cells, faces, and/or points. These sets
are saved in the directory constant/polyMesh/sets/
Module'3')'Lecture'7' 25'
Mesh quality assessment
Checking mesh quality in OpenFOAM®
• You will be able to run with mesh quality errors such as skewness, aspect
ratio, minimum face area, and non-orthogonality. But remember, they will
severely tamper the solution accuracy, might give you strange results, and
eventually can made the solver blow-up.
• Unfortunately, checkMesh does not repair these errors. You will need to
check the geometry for possible errors and generate a new mesh.
• To visualize the failed sets you can use the utility foamToVTK. This utility
converts the failed sets to VTK format.
Module'3')'Lecture'7' 26'
Mesh quality assessment
Checking mesh quality in OpenFOAM®
• At the end, foamToVTK will create a directory named VTK, where you will find the
failed faces/cells/points in VTK format. At this point you can use paraFoam to
visualize the failed sets.
Module'3')'Lecture'7' 27'
Mesh quality assessment
Checking mesh quality in OpenFOAM®
Module'3')'Lecture'7' 28'
Mesh quality assessment
$PTOFC/mesh_conversion_manipulation/
M2_wingbody
Module'3')'Lecture'7' 29'
Mesh quality assessment
• In the directory
$PTOFC/mesh_conversion_manipulation/M2_wingbody you will
find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'3')'Lecture'7' 30'
Mesh quality assessment
Checking mesh quality in OpenFOAM®
We will now check the mesh quality of a sample case. From now on follow me.
• cd $PTOFC/mesh_conversion_manipulation/M2_wingbody
• fluent3DMeshToFoam ../../meshes/M2_wingbody/ascii.msh
• checkMesh
(It will automatically generate the failed sets, if there are any)
At this point, read the screen output and try to assess the mesh quality.
Is it a good mesh?
Module'3')'Lecture'7' 31'
Mesh quality assessment
Checking mesh quality in OpenFOAM®
• The utility checkMesh will automatically write the failed sets (if there are
any). The information related to the faulty sets is saved in the directory
constant/polyMesh/sets
• ls constant/polyMesh/sets
Module'3')'Lecture'7' 32'
Mesh quality assessment
Checking mesh quality in OpenFOAM®
• To visualize the failed sets you can to convert them to VTK format:
• At this point you can visualize the faulty sets by using paraFoam.
• Alternatively, you can open the faulty sets directly in paraFoam
(as previously explained).
Module'3')'Lecture'7' 33'
Mesh quality assessment
By following the instructions, you should get something like this
Module'3')'Lecture'7' 34'
Mesh quality assessment
By following the instructions, you should get something like this
Module'3')'Lecture'7' 35'
Mesh quality assessment
Module'3')'Lecture'7' 36'
Mesh quality assessment
Removing bad quality sets from the mesh
• It is possible to remove the bad quality sets (cells, faces, points) detected by
checkMesh. This is mesh manipulation.
Module'3')'Lecture'7' 37'
Mesh quality assessment
Removing bad quality sets from the mesh
• These sets are later used by subsetMesh to create a new polyMesh using
the information contained in the cellSet.
• By the way, removing the bad quality sets is not the solution to the meshing
problems.
• I am just showing you how to manipulate the mesh using the faulty sets.
Module'3')'Lecture'7' 38'
Mesh quality assessment
Removing bad quality sets from the mesh
• Let us remove the nonOrthoFaces from the polyMesh. From now on
follow me.
• checkMesh
(It will automatically generate the failed sets)
• topoSet
(It will create the cellSet that we will use with subsetMesh. It reads the dictionary system/topoSetDict)
• subsetMesh newcells
(It uses the set newcells created with topoSet, to create a new polyMesh. The new polyMesh will not contain the
cells connected to the nonOrthoFaces faces)
• checkMesh -time 1
(It will check the new polyMesh. It will give a few errors related to the patch oldInternalFaces. The error is due to
the fact that by default oldInternalFaces is set to empty patch type. To remove the error, change the patch type of
oldInternalFaces to the type patch or wall. You will need to do this modification in the file constant/
polyMesh/boundary. By the way and in case you did not notice it, there are no more non-orthogonality problems)
• paraFoam
Module'3')'Lecture'7' 39'
Mesh quality assessment
Removing bad quality sets from the mesh
• This trick, will remove the bad quality cells, but not necessary the new mesh
is a good one. Just take a look at the surface.
Module'3')'Lecture'7' 40'
Mesh quality assessment
Removing bad quality sets from the mesh
• This trick, will remove the bad quality cells, but not necessary the new mesh
is a good one. Just take a look at the surface.
Module'3')'Lecture'7' 41'
Mesh quality assessment
Removing bad quality sets from the mesh
• This trick, will remove the bad quality cells, but not necessary the new mesh
is a good one. Just take a look at the surface.
Module'3')'Lecture'7' 42'
Mesh quality assessment
Removing bad quality sets from the mesh
• If you often use similar meshes and you know where exactly are the errors,
you can write a small script to modify your mesh, I have mine that works on
very specific meshes.
Module'3')'Lecture'7' 43'
Module 3
Module'3')'Lecture'8' 1'
Today’s lecture
Module'3')'Lecture'8' 2'
Today’s lecture
Module'3')'Lecture'8' 3'
Mesh conversion
• If your format is not supported, you can write your own conversion tool.
• By the way, many of the commercially available meshers can save the mesh
in OpenFOAM® polyMesh format or in a compatible format.
Module'3')'Lecture'8' 4'
Mesh conversion
• Some of the utilities available for mesh conversion are listed below:
• ansysToFoam: converts an ANSYS input mesh file OpenFOAM® format.
• cfx4ToFoam: converts a CFX 4 mesh to OpenFOAM® format.
• fluent3DMeshToFoam: converts a Fluent mesh to OpenFOAM® format.
• gambitToFoam: converts a GAMBIT mesh to OpenFOAM® format.
• gmshToFoam: reads .msh file as written by Gmsh.
• ideasUnvToFoam: I-Deas unv format mesh conversion.
• plot3dToFoam: plot3d mesh (ascii/formatted format) converter.
• star4ToFoam: converts a STAR-CD (v4) PROSTAR mesh into OpenFOAM®
format.
• tetgenToFoam: Converts .ele and .node and .face files, written by tetgen.
Ideas UNV
ideasUnvToFoam
KIVA3D
kivaToFoam
netgen
OpenFOAM polyMesh
netgenNeutralToFoam
plot3d
plot3dToFoam
starCD-samm mesh
sammToFoam
starCD-prostar
star4ToFoam
starCD-smap
smapToFoam
Your own format and Any commercial or open starCCM 2.6 CGNS VTK Legacy format Tetgen
converter source application that ccm26ToFoam cgnsToFoam vtkUnstructuredToFoam tetgenToFoam
produces an output in
any of the previous
formats Requires CD-adapco
Extended version
ccmio library
The diagram is not complete. Refer to the user guide or source code to
get more information about all the conversion utilities available in
Module'3')'Lecture'8' 6'
OpenFOAM®
Mesh conversion
• In $FOAM_UTILITIES (use alias util to go there) you will find the directories
containing the source code for the utilities available in the OpenFOAM® installation
(version 2.3.x):
• mesh
• miscellaneous
• parallelProcessing
• postProcessing
• preProcessing
• surface
• Thermophysical
• In the sub-directory mesh you will find the source code for the mesh utilities included
in the OpenFOAM® installation.
Module'3')'Lecture'8' 7'
Mesh conversion
• Let us visit the mesh directory. In the terminal type:
• util
• cd mesh
• In this directory you will find the directories containing the source code for the
following mesh utilities
• advanced
• conversion
• generation
• manipulation
• In the directory conversion you will find the utilities source code for the mesh
conversion utilities. Let us visit this directory, in the terminal type:
• cd conversion
• ls -l
Module'3')'Lecture'8' 8'
Mesh conversion
• In the directory $FOAM_UTILITIES/mesh/conversion you will find the following
mesh conversion utilities:
• ansysToFoam • kivaToFoam
• cfx4ToFoam • mshToFoam
• datToFoam • netgenNeutralToFoam
• fluent3DMeshToFoam • Optional/ccm26ToFoam
• fluentMeshToFoam • plot3dToFoam
• foamMeshToFluent • sammToFoam
• foamToStarMesh • star3ToFoam
• foamToSurface • star4ToFoam
• gambitToFoam • tetgenToFoam
• gmshToFoam • vtkUnstructuredToFoam
• ideasUnvToFoam • writeMeshObj
$PTOFC/mesh_conversion_manipulation/
M3_mixing_elbow_salome
Module'3')'Lecture'8' 10'
Mesh conversion
• In the directory $PTOFC/
mesh_conversion_manipulation/
M3_mixing_elbow_salome you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'3')'Lecture'8' 11'
Mesh conversion
Case 1. Mixing elbow (internal mesh).
Let us convert to OpenFOAM® a mesh generated using Salome.
From now on, follow me.
Module'3')'Lecture'8'
our mesh in Salome looks like this one. 12'
Mesh conversion
Case 1. Mixing elbow (internal mesh).
Let us convert to OpenFOAM® a mesh generated using Salome.
From now on, follow me.
Remember to export the mesh in UNV format in Salome. Then use the mesh
converter utility ideasUnvToFoam to convert the mesh to OpenFOAM® native format.
In the terminal window type:
• cd $PTOFC/mesh_conversion_manipulation/
M3_mixing_elbow_salome
• ideasUnvToFoam ../../meshes/M3_mixing_elbow_salome/
Mesh_1.unv
(To convert the mesh to polyMesh from ideas format)
• checkMesh
• paraFoam
Module'3')'Lecture'8' 13'
Mesh conversion
$PTOFC/mesh_conversion_manipulation/
M1_square_tube_periodic
Module'3')'Lecture'8' 14'
Mesh conversion
• In the directory $PTOFC/
mesh_conversion_manipulation/
M1_square_tube_periodic you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'3')'Lecture'8' 15'
Mesh conversion
Case 2. Square tube with periodic boundary conditions
(external mesh).
Let us convert the mesh from fluent format to OpenFOAM® format.
From now on, follow me.
• checkMesh –time 0
• paraFoam
Module'3')'Lecture'8' 16'
Mesh conversion
$PTOFC/mesh_conversion_manipulation/
M7_polydualmesh/
Module'3')'Lecture'8' 17'
Mesh conversion
• In the directory $PTOFC/
mesh_conversion_manipulation/M7_polydualmesh/
you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'3')'Lecture'8' 18'
Mesh conversion
Case 3. Polyhedral mesh.
Module'3')'Lecture'8' 21'
Mesh conversion
Case 3. Polyhedral mesh.
• In this tutorial we are going to generate a polyhedral mesh.
• First we need to generate a tetrahedral mesh and then we need to convert it to
polyhedral mesh by using the utility polyDualMesh.
• From now on, you can follow me. In the terminal type:
• cd $PTOFC/mesh_conversion_manipulation/M7_polydualmesh/
• ideasUnvToFoam ../../meshes/M3_mixing_elbow_salome/
Mesh_1.unv
(This mesh already has the patches assigned, you do not need to use the utility autoPatch)
• checkMesh
(To check the mesh before converting it to polyhedral type)
• checkMesh
(To check the mesh after converting it to polyhedral type)
• paraFoam
Module'3')'Lecture'8' 22'
Mesh conversion
$PTOFC/mesh_conversion_manipulation/
M9_static_mixer_gmsh
Module'3')'Lecture'8' 23'
Mesh conversion
• In the directory $PTOFC/
mesh_conversion_manipulation/
M9_static_mixer_gmsh you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'3')'Lecture'8' 24'
Mesh conversion
Static mixer geometry
Module'3')'Lecture'8' 25'
Mesh conversion
Static mixer mesh
Module'3')'Lecture'8' 26'
Mesh conversion
Case 4. Static mixer (internal mesh).
Let us convert the mesh from GMSH format to OpenFOAM® format.
From now on, follow me.
• cd $PTOFC/mesh_conversion_manipulation/M9_static_mixer_gmsh
(The geometry is in the directory ./geometry)
• gmshToFoam ../../meshes/M9_static_mixer_gmsh/
staticmixer.msh
(If you generated a mesh of your own, just add the right file name and path)
• checkMesh
• paraFoam
Module'3')'Lecture'8' 27'
Mesh conversion
Case 4. Static mixer (internal mesh).
Let us convert the mesh from GMSH format to OpenFOAM® format.
From now on, follow me.
Additional tutorials
In the directories $PTOFC/sHM, and $PTOFC/mesh_conversion_manipulation
and $PTOFC/geometries_meshers_tutorials, you will find many tutorials, try to
go through each one to understand and get functional using the meshing tools.
Module'3')'Lecture'8' 29'
Module 3
Module'3')'Lecture'9' 1'
Today’s lecture
Module'3')'Lecture'9' 2'
Today’s lecture
Module'3')'Lecture'9' 3'
Geometry and mesh manipulation utilities
Module'3')'Lecture'9' 4'
Geometry and mesh manipulation utilities
• OpenFOAM® comes with many mesh manipulation utilities. Some of them
are listed below:
• checkMesh: checks validity of a mesh.
• mirrorMesh: mirrors a mesh around a given plane.
• setSet: manipulate a cell/face/point/ set or zone interactively.
• splitMeshRegions: splits mesh into multiple regions.
• refineWallLayer: utility to refine cells next to patches.
• refineMesh: utility to refine cells in multiple directions.
• renumberMesh: renumbers the cell list in order to reduce the bandwidth,
reading and renumbering all fields from all the time directories.
• topoSet: operates on cellSets/faceSets/pointSets through a dictionary.
• transformPoints: transforms the mesh points in the polyMesh directory
according to the translate, rotate and scale options.
• mesh
• miscellaneous
• parallelProcessing
• postProcessing
• preProcessing
• surface
• Thermophysical
• In the sub-directory mesh you will find the source code for the mesh utilities in the
OpenFOAM® installation.
Module'3')'Lecture'9' 6'
Geometry and mesh manipulation utilities
• Let us visit the mesh directory. In the terminal type:
• util
• cd mesh
• In this directory you will find the directories containing the source code for the
following mesh utilities
• advanced
• conversion
• generation
• manipulation
• In the directory manipulation you will find the utilities source code for the mesh
manipulation utilities. Let us visit this directory, in the terminal type:
• cd manipulation
• ls -l
Module'3')'Lecture'9' 7'
Geometry and mesh manipulation utilities
• In the directory $FOAM_UTILITIES/mesh/manipulation you will find the
following mesh manipulation utilities:
• attachMesh • orientFaceZone
• autoPatch • polyDualMesh
• checkMesh • refineMesh
• createBaffles • renumberMesh
• createPatch • rotateMesh
• deformedGeom • setSet
• flattenMesh • setsToZones
• insideCells • singleCellMesh
• mergeMeshes • splitMesh
• mergerOrSplitBaffles • splitMeshRegions
• mirrorMesh • stitchMesh
• moveDynamicMesh • subsetMesh
• moveEngineMesh • topoSet
• moveMesh • transformPoints
• objToVTK • zipUpMesh
Module'3')'Lecture'9' 8'
For more information about the mesh manipulation utilities, refer to the User Guide
Geometry and mesh manipulation utilities
• Inside each utility directory you will find a *.C file with the same name as
the directory. This is the main file, where you will find the top-level source
code and a short description of the utility.
• For instance, in the directory checkMesh, you will find the file
checkMesh.C, which is the source code of the utility checkMesh. In the
source code you will find the following description:
Checks validity of a mesh.
Usage
- checkMesh [OPTION]
\param -allGeometry \n
Checks all (including non finite-volume specific) geometry
\param -allTopology \n
Checks all (including non finite-volume specific) addressing
\param -meshQuality \n
Checks against user defined (in \a system/meshQualityDict) quality settings
Module'3')'Lecture'9' 9'
Take your time and dig into each directory to get a complete description of each utility.
Geometry and mesh manipulation utilities
• In OpenFOAM® it is also possible to manipulate the geometries in STL
format. Some of the utilities available are listed below:
• surfaceAutoPatch: patches surface according to feature angle.
Like autoPatch.
• surfaceCheck: checks geometric and topological quality of a surface.
• surfaceClean: removes baffles and collapses small edges, by removing
triangles. Converts sliver triangles into split edges.
• surfaceFeatureExtract: extracts and writes surface edge features to file.
• surfaceMeshInfo: miscellaneous information about surface.
• surfaceMeshTriangulate: extracts triSurface from a polyMesh.
• surfaceTransformPoints: transform (scale/rotate) a surface. Like
transformPoints but for surfaces.
• mesh
• miscellaneous
• parallelProcessing
• postProcessing
• preProcessing
• surface
• Thermophysical
• In the sub-directory surface you will find the source code for the surface
manipulation utilities in the OpenFOAM® installation.
Module'3')'Lecture'9' 11'
Geometry and mesh manipulation utilities
• Let us visit the surface directory. In the terminal type:
• util
• cd surface
• In this directory you will find the directories containing the source code for the surface
manipulation utilities.
Module'3')'Lecture'9' 12'
Geometry and mesh manipulation utilities
• In the directory $FOAM_UTILITIES/surface you will find the following surface
manipulation utility directories:
• surfaceAdd • surfaceMeshExport
• surfaceAutoPatch • surfaceMeshImport
• surfaceBooleanFeatures • surfaceMeshInfo
• surfaceCheck • surfaceMeshTriangulate
• surfaceClean • surfaceOrient
• surfaceCoarsen • surfacePointMerge
• surfaceConvert • surfaceRedistributePar
• surfaceFeatureConvert • surfaceRefineRedGreen
• surfaceFeatureExtract • surfaceSplitByPatch
• surfaceFind • surfaceSplitByTopology
• surfaceHookUp • surfaceSplitNonManifolds
• surfaceInertia • surfaceSubset
• surfaceLambdaMuSmooth • surfaceToPatch
• surfaceMeshConvert • surfaceTransformPoints
• surfaceMeshConvertTesting
Module'3')'Lecture'9' 13'
For more information about the surface manipulation utilities, refer to the User Guide
Geometry and mesh manipulation utilities
• Inside each utility directory you will find a *.C file with the same name as
the directory. This is the main file, where you will find the top-level source
code and a short description of the utility.
• For instance, in the directory surfaceTransformPoints, you will find the
file surfaceTransformPoints.C, which is the source code of the utility
surfaceTransformPoints. In the source code you will find the following
description:
Module'3')'Lecture'9' 14'
Take your time and dig into each directory to get a complete description of each utility.
Geometry and mesh manipulation utilities
$PTOFC/mesh_conversion_manipulation/
M6_ahmed_body_transform
Module'3')'Lecture'9' 15'
Geometry and mesh manipulation utilities
• In the directory $PTOFC/
mesh_conversion_manipulation/
M6_ahmed_body_transform you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'3')'Lecture'9' 16'
Geometry and mesh manipulation utilities
By following the instructions, you should get something like this
• cd $PTOFC/mesh_conversion_manipulation/
M6_ahmed_body_transform
• surfaceMeshInfo ./constant/triSurface/ahmed_body.stl
• surfaceCheck ./constant/triSurface/ahmed_body.stl
• surfaceTransformPoints -rollPitchYaw '(0 0 15)’./constant/
triSurface/ahmed_body.stl ./constant/triSurface/rotated.stl
Module'3')'Lecture'9' 18'
Note: in this case we only manipulated the STL file.
Geometry and mesh manipulation utilities
Geometry manipulation in OpenFOAM®
• We will now manipulate a STL geometry. From now on follow me.
• Go to the directory $PTOFC/mesh_conversion_manipulation/
M6_ahmed_body_transform. In the terminal type:
Module'3')'Lecture'9' 19'
Note: in this case we only manipulated the STL file.
Geometry and mesh manipulation utilities
$PTOFC/mesh_conversion_manipulation/
M10_cylinder_transform
Module'3')'Lecture'9' 20'
Geometry and mesh manipulation utilities
By following the instructions, you should get something like this
Mesh manipulation
Module'3')'Lecture'9' 21'
Geometry and mesh manipulation utilities
• In the directory $PTOFC/
mesh_conversion_manipulation/
M10_cylinder_transform you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'3')'Lecture'9' 22'
Geometry and mesh manipulation utilities
By following the instructions, you should get something like this
Temperature
Module'3')'Lecture'9' 23'
Geometry and mesh manipulation utilities
Mesh manipulation in OpenFOAM®
• We will now manipulate a mesh. From now on follow me.
• Go to the directory $PTOFC/mesh_conversion_manipulation/
M10_cylinder_transform. In the terminal type:
• cd $PTOFC/mesh_conversion_manipulation/M10_cylinder_transform
• blockMesh
• transformPoints -rollPitchYaw '(0 0 90)'
• transformPoints -scale '(0.01 0.01 0.01)’
• createPatch -noFunctionObjects –overwrite
(It reads the dictionary system/createPatchDict)
• checkMesh
• paraFoam
Module'3')'Lecture'9' 24'
Note: in this case we manipulated the mesh.
Geometry and mesh manipulation utilities
$PTOFC/mesh_conversion_manipulation/
M2_wingbody
Module'3')'Lecture'9' 25'
Geometry and mesh manipulation utilities
• In the directory $PTOFC/
mesh_conversion_manipulation/M2_wingbody you will
find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'3')'Lecture'9' 26'
Geometry and mesh manipulation utilities
By following the instructions, you should get something like this
Module'3')'Lecture'9' 27'
Geometry and mesh manipulation utilities
Geometry and mesh manipulation in OpenFOAM®
• We will now manipulate a mesh. From now on follow me.
• Go to the directory $PTOFC/mesh_conversion_manipulation/M2_wingbody. In the
terminal type:
• cd $PTOFC/mesh_conversion_manipulation/M2_wingbody
• blockMesh
• fluent3DMeshToFoam ../../meshes/M2_wingbody/ascii.msh
• checkMesh
• mirrorMesh –noFunctionObjects
(This utility uses the dictionary mirrorMeshDict, located in the directory system)
• checkMesh
• foamToVTK -faceSet nonOrthoFaces
• foamToVTK -pointSet unusedPoints
• paraFoam
Module'3')'Lecture'9' 28'
Note: in this case we manipulated the mesh.
Geometry and mesh manipulation utilities
Additional tutorials
In the directories $PTOFC/sHM, and $PTOFC/mesh_conversion_manipulation,
you will find many tutorials, try to go through each one to understand and get functional
using the meshing tools.
Module'3')'Lecture'9' 29'
Module 3
Module'3')'Lecture'10' 1'
Today’s lecture
Module'3')'Lecture'10' 2'
Today’s lecture
Module'3')'Lecture'10' 3'
Mesh generation using blockMesh and snappyHexMesh
• If you are not confortable using OpenFOAM® meshing applications, you can
use an external mesher.
Module'3')'Lecture'10' 4'
Mesh generation using blockMesh and snappyHexMesh
• OpenFOAM® comes with the following meshing applications:
• blockMesh
• snappyHexMesh
• foamyHexMesh
• foamyQuadMesh
• You can find the source code of these applications in the directory:
• $WM_PROJECT_DIR/applications/utilities/mesh/generation
• In this directory you can also find the master dictionaries for each meshing
application.
Module'3')'Lecture'10' 5'
Mesh generation using blockMesh and snappyHexMesh
blockMesh
• “blockMesh is a multi-block mesh generator.”
• For simple geometries, the mesh generation utility blockMesh can be used.
• We are going to work with this application, in the training material you will
find many tutorials.
Module'3')'Lecture'10' 6'
Mesh generation using blockMesh and snappyHexMesh
blockMesh
Module'3')'Lecture'10' 7'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh
• “Automatic split hex mesher. Refines and snaps to surface.”
• We are going to address how to use this tool, in the training material you will
find many tutorials.
Module'3')'Lecture'10' 8'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh
Module'3')'Lecture'10' 9'
Mesh generation using blockMesh and snappyHexMesh
blockMesh workflow
Module'3')'Lecture'10' 10'
Mesh generation using blockMesh and snappyHexMesh
blockMesh workflow
• As we are going to use blockMesh to generate the background mesh, I am
going to briefly address how blockMesh works.
blockMeshDict
blockMesh
OpenFOAM polyMesh
Module'3')'Lecture'10' 12'
Mesh generation using blockMesh and snappyHexMesh
blockMesh workflow
Refer to OpenFOAM®Module'3')'Lecture'10'
User Guide for more Information 13'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
Module'3')'Lecture'10' 14'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
Geometry
Background mesh
(STL file)
snappyHexMesh
OpenFOAM polyMesh
Module'3')'Lecture'10' 15'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
• To generate a mesh with snappyHexMesh, we proceed as follows:
• Generation of a background or base mesh.
• Geometry definition.
• Generation of a castellated mesh or cartesian mesh.
• Generation of a snapped mesh or body fitted mesh.
• Addition of layers close to the surfaces or boundary layer
meshing.
• Check/enforce mesh quality.
Geometry
Background mesh
(STL file)
snappyHexMesh
OpenFOAM polyMesh
Module'3')'Lecture'10' 16'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
• All the volume and surface refinement is done in reference to the
background or base mesh.
Base cell RL 1 RL 2 RL 3
* RL = refinement level
blockMesh or external mesher
Geometry
Background mesh
(STL file)
snappyHexMesh
OpenFOAM polyMesh
Module'3')'Lecture'10' 17'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
• The meshing utility snappyHexMesh reads the dictionary
snappyHexMeshDict located in the directory system.
• The utility surfaceFeatureExtract reads the dictionary
surfaceFeatureExtractDict located in the directory system.
• The output of the utility surfaceFeatureExtract (*.eMesh), is located in the
directory constant/triSurface.
• The final mesh must be located in the directory constant/polyMesh
Geometry
Background mesh
(STL file)
snappyHexMesh
OpenFOAM polyMesh
Module'3')'Lecture'10' 18'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
• The STL geometry can be obtained from any geometry modeling tool.
• The STL file can be made up of a single surface describing the geometry.
• Alternatively, the STL file can be made up of multiple surfaces that describe
the geometry.
• In the case of a STL file with multiple surfaces, we can use local refinement
in every individual surface. This gives us more control when generating the
mesh.
• The STL geometry is located in the directory constant/triSurface
Geometry
Background mesh
(STL file)
snappyHexMesh
OpenFOAM polyMesh
Module'3')'Lecture'10' 19'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
• The background or base mesh can be generated using blockMesh or an
external mesher.
• The following criteria must be observed when creating the background
mesh:
• The mesh must consist purely of hexes.
• The cell aspect ratio should be approximately 1, at least near the
STL surface.
• There must be at least one intersection of a cell edge with the
STL surface.
blockMesh or external mesher
Geometry
Background mesh
(STL file)
snappyHexMesh
OpenFOAM polyMesh
Module'3')'Lecture'10' 20'
Mesh generation using blockMesh and snappyHexMesh
Module'3')'Lecture'10' 21'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
• The process of generating a mesh using snappyHexMesh will be described using this figure.
• The objective is to mesh a rectangular shaped region (shaded grey in the figure) surrounding an object
described by a STL surface (shaded green in the figure).
• This is an external mesh (e.g. for external aerodynamics). You can also generate an internal mesh (e.g. flow in
a pipe), in this case you will mesh the interior of the green region.
Module'3')'Lecture'10' 22'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
Module'3')'Lecture'10' 29'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow
Module'3')'Lecture'10' 31'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh in action
Module'3')'Lecture'10' 32'
Mesh generation using blockMesh and snappyHexMesh
$PTOFC/sHM/M9_wolf
Module'3')'Lecture'10' 33'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
• geometry
Definition of geometry entities to be used for meshing
• castellatedMeshControls
Definition of feature, surface and volume mesh refinement
'
• snapControls
Definition of surface mesh snapping and advanced parameters
• addLayersControls
Definition of boundary layer meshing and advanced parameters
• meshQualityControls
Definition of mesh quality metrics
Module'3')'Lecture'10' 34'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
• My best advice is to start with a smooth geometry (no sharp angles) and
study the effect of every parameter.
• Then use a geometry with sharp angles and try to get a good mesh. Sharp
angles are difficult to deal with.
• Finally, try to add the boundary layer mesh. Again, start first with a smooth
geometry and then use a geometry with sharp angles.
Module'3')'Lecture'10' 35'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
geometry
{
...
...
}
castellatedMeshControls
{
...
...
}
snapControls
{
...
...
}
• The snappyHexMesh dictionary is made up of five sections, namely:
addLayersControls geometry, castellatedMeshControls, snapControls,
{ addLayersControls and meshQualityControls. Each section
... controls a step of the meshing process.
...
} • In the first three lines we can turn off and turn on the different
meshing steps. For example, if we want to generate a body fitted
meshQualityControls mesh with no boundary layer we should proceed as follows:
{
... castellatedMesh true;
... snap true;
}
Module'3')'Lecture'10' addLayers false; 36'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
geometry
{
regions Use this option if you have a STL with multiple patches defined
{
wolflocal This is the name of the region or surface patch in the STL file
{
name wolf_wall; User-defined patch name. This is the final name of the patch
}
}
}
• In this section we read in the STL geometry. Remember, the input
box Name of geometrical entity geometry is always located in the directory constant/triSurface
{
type searchableBox; • We can also define geometrical entities that can be used to refine the
min (-100.0 -120.0 -50.0 ); mesh, create regions, or generate baffles.
max (100.0 120.0 150.0 );
} • You can add multiple STL files.
sphere Name of geometrical entity • If you do not give a name to the surface, it will take the name of the
{ STL file.
type searchableSphere; Note 1
centre (120.0 -100.0 50.0 ); • The geometrical entities are created inside snappyHexMesh.
radius 40.0;
} Note 1:
If you want to know what geometrical entities are available, just
} misspelled something in the type keyword.
Module'3')'Lecture'10' 38'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
castellatedMeshControls
{
//Refinement parameters
maxLocalCells 100000;
maxGlobalCells 2000000;
nCellsBetweenLevels 1;
...
...
castellatedMeshControls
{
// Refinement parameters
maxLocalCells 100000;
maxGlobalCells 2000000;
minRefinementCells 0;
maxLoadUnbalance 0.10;
nCellsBetweenLevels 1; Note 1
planarAngle 30;
allowFreeStandingZoneFaces true;
castellatedMeshControls
{
...
...
...
regions Note 2
{
wolflocal Note 3
Note 1:
{
The surface wolf was defined in the geometry section.
level (2 4); Local refinement
Note 2:
patchInfo
The region wolflocal was defined in the geometry section.
{
type wall; Note 4
Note 3:
}
Named region in the STL file. This refinement is local.
}
To use the surface refinement in the regions, the local
}
regions must exist in STL file. We created a pointer to this
}
region in the geometry section.
...
...
}
Module'3')'Lecture'10' Note 4: 41'
You can only define patches of type wall or patch.
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
castellatedMeshControls
{
...
...
...
//This surface or geometrical entity
//was defined in geometry section
sphere Note 1
{
level (1 1);
faceZone face_inner;
cellZone cell_inner;
cellZoneInside inside;
//faceType internal;
Note 1:
} Optional specification of what to do with faceZone faces:
Module'3')'Lecture'10' 42'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
castellatedMeshControls
{
...
...
...
//Region-wise refinement
refinementRegions Dictionary block'
{
box Note 1
{
mode inside;
levels (( 1 1 ));
}
//Mesh selection
locationInMesh (-100.0 0.0 50.0 );
} Note 1:
This region or geometrical entity was created in the geometry section.
Module'3')'Lecture'10' 43'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
castellatedMeshControls
{
...
...
...
//Region-wise refinement
refinementRegions Dictionary block'
{
//Mesh selection This point defines where do you want the mesh
locationInMesh (-100.0 0.0 50.0 ); Can be internal mesh or external mesh
Module'3')'Lecture'10' 44'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
snapControls
{
tolerance 2.0;
// Feature snapping
addLayersControls
{
//Global parameters
relativeSizes true;
expansionRatio 1.2;
finalLayerThickness 0.5;
minThickness 0.1;
layers Note 1
{
wolf_wall Note 2
{
nSurfaceLayers 3;
//Local parameters
//expansionRatio 1.3;
//finalLayerThickness 0.3;
//minThickness 0.1;
}
}
// Advanced settings
nGrow 0;
featureAngle 130; Note 3 Note 1:
maxFaceThicknessRatio 0.5; In this section we select the patches where we want to add the
nSmoothSurfaceNormals 1; layes. We can add multiple patches (if they exist).
nSmoothThickness 10;
minMedianAxisAngle 90; Note 2:
maxThicknessToMedialRatio 0.3; This patch was created in the geometry section.
nSmoothNormals 3;
slipFeatureAngle 30; Note 3:
nRelaxIter 5; Specification of feature angle above which layers are collapsed
nBufferCellsNoExtrude 0; automatically.
nLayerIter 50;
nRelaxedIter 20; • In this step, we are generating the boundary layer mesh.
}
Module'3')'Lecture'10' 46'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
meshQualityControls
{
maxNonOrtho 75; Note 1
maxBoundarySkewness 20;
maxInternalSkewness 4; Note 2
maxConcave 80;
minVol 1.00E-13;
minTetQuality 1e15;
//minTetQuality -1e30;
minArea -1;
minTwist 0.02;
minDeterminant 0.001;
Note 1:
Maximum non-orthogonality angle.
minFaceWeight 0.05;
Note 2:
minVolRatio 0.01;
Maximum skewness angle.
minTriangleTwist -1;
• During the mesh generation process, the mesh quality is continuously
monitored.
minFlatness 0.5;
• The utility snappyHexMesh will try to generate a mesh using the mesh
nSmoothScale 4;
quality parameters defined by the user.
errorReduction 0.75;
• If a mesh motion or topology change introduces a poor quality cell or
}
Module'3')'Lecture'10'
face the motion or topology change is undone to revert the mesh 47'
back
to a previously valid error free state.
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.
debugFlags
(
// write intermediate meshes
mesh
writeFlags
(
// write volScalarField with cellLevel for • At the end of the dictionary you will find the sections:
// postprocessing debugFlags and writeFlags
scalarLevels
• By default they are commented. If you uncomment them you will
// write cellSets, faceSets of faces in layer enable debug information.
layerSets
• debugFlags and writeFlags will produce a lot of outputs that you
// write volScalarField for layer coverage can use to post process and troubleshoot the different steps of
layerFields the meshing process.
);
Module'3')'Lecture'10' 48'
Mesh generation using blockMesh and snappyHexMesh
Module'3')'Lecture'10' 49'
Mesh generation using blockMesh and snappyHexMesh
Module'3')'Lecture'10' 50'
Today’s lecture
Module'3')'Lecture'10' 51'
Mesh generation using blockMesh and snappyHexMesh
$PTOFC/sHM/M1_cyl
Module'3')'Lecture'10' 52'
Mesh generation using blockMesh and snappyHexMesh
Case 1. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh.
From now on, follow me.
• checkMesh -latestTime
• paraFoam
Module'3')'Lecture'10' 55'
Mesh generation using blockMesh and snappyHexMesh
Case 1. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh.
• At this point, you should have in your case directory two time directories 1 and 2 (if
you chose a time step of 1 in your controlDict).
• In the time directory 1, you should have the mesh with the castellated mesh.
• In the time directory 2 you should have the mesh with the conforming mesh (the
mesh after snapping).
• Additionally, if you chose to generate the boundary layer mesh, you should have a
time directory 3, where you should have the mesh with the inflation layer.
• In the directory $PTOFC/sHM/M1_cyl_er_bl you will find the case setup for
generating the boundary layer mesh.
• We are going to deal with boundary layer meshing later on.
Module'3')'Lecture'10' 56'
Mesh generation using blockMesh and snappyHexMesh
Case 1. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh.
• cp -r 2/polyMesh constant/polyMesh
(To copy the new mesh to your constant/polyMesh directory, this is compulsory)
• rm -rf 1
(If you do not want to keep this time folder)
• rm -rf 2
(If you do not want to keep this time folder)
• Now you are ready to run. Remember, you will need to set the boundary condition
patches and they must be compatible with the patch type defined in the file
constant/polyMesh/boundary
Module'3')'Lecture'10' 57'
Mesh generation using blockMesh and snappyHexMesh
Case 1. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh.
• snappyHexMesh -overwrite
• If you use this option, you will not save intermediate steps.
• Hence, you will not be able to visualize the intermediate steps.
• You might be wondering, why should we save the intermediate steps? Besides is
cool to look at what snappyHexMesh is doing, there is another reason.
• If you save the intermediate steps, you will be able to restart the meshing process
from a saved state (castellated or snapped mesh).
• Therefore, in case something goes wrong or you do not like the final mesh you do not
need to start from zero.
Module'3')'Lecture'10' 58'
Mesh generation using blockMesh and snappyHexMesh
$PTOFC/sHM/M1_cyl_er
Module'3')'Lecture'10' 59'
Mesh generation using blockMesh and snappyHexMesh
Case 2. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement.
• paraview
(Take a look at the .obj files created by surfaceFeatureExtract, we use paraview instead of paraFoam
because by default paraFoam reads the mesh generated by blockMesh. The .obj files are located in the directory
constant/extendedFeatureEdgeMesh)
• snappyHexMesh
• checkMesh -latestTime
• paraFoam
Module'3')'Lecture'10' 64'
Mesh generation using blockMesh and snappyHexMesh
Case 2. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement.
• The utility surfaceFeatureExtract will create a file named *.eMesh (e.g.
banana.eMesh), this file will be saved in the directory constant/triSurface This file
contains the information of the feature edges.
• By the way, try to read the file, it is easy to understand.
• If you need to capture features that were not captured by surfaceFeatureExtract, you can
manually create this file.
• Next, you should tell to snappyHexMesh that you want to use refinement in the feature edges,
and this is done by pointing to the *.eMesh file in the snappyHexMeshDict dictionary
// Explicit feature edge refinement
features
(
{
file “banana.eMesh”;
level 4;
}
);
• snappyHexMesh knows that the *.eMesh file is in constant/triSurface
Module'3')'Lecture'10' 65'
Mesh generation using blockMesh and snappyHexMesh
Case 2. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement.
• At this point, you should have in your case directory two time directories 1 and 2 (if
you chose a time step of 1 in your controlDict).
• In the time directory 1, you should have the mesh with the castellated mesh.
• In the time directory 2 you should have the mesh with the conforming mesh (the
mesh after snapping).
• Additionally, if you chose to generate the boundary layer mesh, you should have a
time directory 3, where you should have the mesh with the inflation layer.
• In the directory $PTOFC/sHM/M1_cyl_er_bl you will find the case setup for
generating the boundary layer mesh.
• We are going to deal with boundary layer meshing later on.
Module'3')'Lecture'10' 66'
Mesh generation using blockMesh and snappyHexMesh
Case 2. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement.
• cp -r 2/polyMesh constant/polyMesh
(To copy the new mesh to your constant/polyMesh directory, this is compulsory)
• rm -rf 1
(If you do not want to keep this time folder)
• rm -rf 2
(If you do not want to keep this time folder)
• Now you are ready to run. Remember, you will need to set the boundary condition
patches and they must be compatible with the patch type defined in the file
constant/polyMesh/boundaryModule'3')'Lecture'10' 67'
Mesh generation using blockMesh and snappyHexMesh
Case 2. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement.
• snappyHexMesh -overwrite
• If you use this option, you will not save intermediate steps.
• Hence, you will not be able to visualize the intermediate steps.
• You might be wondering, why should we save the intermediate steps? Besides is
cool to look at what snappyHexMesh is doing, there is another reason.
• If you save the intermediate steps, you will be able to restart the meshing process
from a saved state (castellated or snapped mesh).
• Therefore, in case something goes wrong or you do not like the final mesh you do not
need to start from zero. Module'3')'Lecture'10' 68'
Mesh generation using blockMesh and snappyHexMesh
$PTOFC/sHM/M1_cyl_er_bl
Module'3')'Lecture'10' 69'
Mesh generation using blockMesh and snappyHexMesh
Case 3. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement and boundary layer.
...
...
...
Module'3')'Lecture'10' 73'
Mesh generation using blockMesh and snappyHexMesh
Case 3. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement and boundary layer.
From now on, follow me.
• paraview
(Take a look at the .obj files created by surfaceFeatureExtract, we use paraview instead of paraFoam
because by default paraFoam reads the mesh generated by blockMesh. The .obj files are located in the directory
constant/extendedFeatureEdgeMesh)
• snappyHexMesh
• checkMesh -latestTime
• paraFoam
Module'3')'Lecture'10' 74'
Mesh generation using blockMesh and snappyHexMesh
Case 3. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement and boundary layer.
• At this point, you should have in your case directory three time directories 1, 2, and 3
(if you chose a time step of 1 in your controlDict).
• In the time directory 1, you should have the mesh with the castellated mesh.
• In the time directory 2 you should have the mesh with the conforming mesh (the
mesh after snapping).
• In the time directory 3 you should have the mesh with the conforming mesh and the
boundary layer.
Module'3')'Lecture'10' 75'
Mesh generation using blockMesh and snappyHexMesh
Case 3. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement and boundary layer.
• cp -r 3/polyMesh constant/polyMesh
(To copy the new mesh to your constant/polyMesh directory, this is compulsory)
• rm -rf 1
(If you do not want to keep this time folder)
• rm -rf 2
(If you do not want to keep this time folder)
• rm –rf 3
(If you do not want to keep this time folder)
• Now you are ready to run. Remember, you will need to set the boundary condition
patches and they must be compatible with the patch type defined in the file
Module'3')'Lecture'10' 76'
constant/polyMesh/boundary
Mesh generation using blockMesh and snappyHexMesh
Case 3. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement and boundary layer.
• snappyHexMesh -overwrite
• If you use this option, you will not save intermediate steps.
• Hence, you will not be able to visualize the intermediate steps.
• You might be wondering, why should we save the intermediate steps? Besides is
cool to look at what snappyHexMesh is doing, there is another reason.
• If you save the intermediate steps, you will be able to restart the meshing process
from a saved state (castellated or snapped mesh).
• Therefore, in case something goes wrong or you do not like the final mesh you do not
need to start from zero. Module'3')'Lecture'10' 77'
Mesh generation using blockMesh and snappyHexMesh
$PTOFC/sHM/M2_mixing_elbow1
Module'3')'Lecture'10' 78'
Mesh generation using blockMesh and snappyHexMesh
Case 4. Mixing elbow (internal mesh).
Let us generate the mesh by using SnappyHexMesh.
• paraview
(Take a look at the .obj files created by surfaceFeatureExtract, we use paraview instead of paraFoam
because by default paraFoam reads the mesh generated by blockMesh. The .obj files are located in the directory
constant/extendedFeatureEdgeMesh)
• snappyHexMesh
• checkMesh -latestTime
• paraFoam
Module'3')'Lecture'10' 81'
Mesh generation using blockMesh and snappyHexMesh
Case 4. Mixing elbow (internal mesh).
Let us generate the mesh by using SnappyHexMesh.
• snappyHexMesh -overwrite
• If you use this option, you will not save intermediate steps.
• Hence, you will not be able to visualize the intermediate steps.
• Also, you will not be able to restart the meshing process from a saved state
(castellated or snapped mesh).
Module'3')'Lecture'10' 82'
Mesh generation using blockMesh and snappyHexMesh
Case 4. Mixing elbow (internal mesh).
• The mesh used in the previous case was a STL with multiple surfaces.
• Try to use this STL file to generate the mesh. You will notice that the
final mesh has only one patch, namely mixing_elbow.
• Also, is not possible to have local control on the mesh refinement and
boundary layer meshing.
• You will also face the conundrum that as there is only one surface patch,
it is not possible to assign boundary conditions.
Module'3')'Lecture'10' 83'
Mesh generation using blockMesh and snappyHexMesh
Case 4. Mixing elbow (internal mesh).
• To solve the problem of the single surface patch, you can use the utility
autoPatch. To do so, you can proceed as follows:
• autoPatch 60
• The utility autoPatch will use an angle criterion to find the patches, and
will assign the name auto0, auto1, auto2 and auto3 to the new patches.
$PTOFC/sHM/M3_sphere_sHM
Module'3')'Lecture'10' 85'
Mesh generation using blockMesh and snappyHexMesh
Case 5. Sphere (external mesh).
Let us generate first the geometry using blender (or whatever you want to
use) and then the mesh by using SnappyHexMesh.
Module'3')'Lecture'10' 88'
Mesh generation using blockMesh and snappyHexMesh
Case 5. Sphere (external mesh).
Inflation layers with different control parameters
Module'3')'Lecture'10' 89'
Mesh generation using blockMesh and snappyHexMesh
Case 5. Sphere (external mesh).
Let us generate first the geometry using blender (or whatever you want to
use) and then the mesh by using SnappyHexMesh.
From now on, follow me.
For this tutorial you will first need to generate the geometry using blender or whatever
you want to use, I will use blender. In the terminal type:
• cd $PTOFC/sHM/M3_sphere_sHM
(The geometry was generated with blender. You will find the blender file and the STL file are in the directory geometry)
• blender
(This step is optional. For geometry modeling. Do not forget to export the geometry in ascii STL format.)
• blockMesh
• snappyHexMesh –noFunctionObjects
• checkMesh -latestTime
• paraFoam
• cp -r 3/polyMesh constant/polyMesh
(To copy the new mesh to your constant/polyMesh directory, this is compulsory
• rm -r 1, rm -r 2, rm -r 3
(If you do not want to keep these time folders)
Module'3')'Lecture'10' 90'
Mesh generation using blockMesh and snappyHexMesh
Case 5. Sphere (external mesh).
Let us generate first the geometry using blender (or whatever you want to
use) and then the mesh by using SnappyHexMesh.
• snappyHexMesh -overwrite
• If you use this option, you will not save intermediate steps.
• Hence, you will not be able to visualize the intermediate steps.
• Also, you will not be able to restart the meshing process from a saved state
(castellated or snapped mesh).
Module'3')'Lecture'10' 91'
Mesh generation using blockMesh and snappyHexMesh
Case 5. Sphere (external mesh).
Let us generate first the geometry using blender (or whatever you want to
use) and then the mesh by using SnappyHexMesh.
• If you do not like the inflation layer or you want to try different layer parameters,
you do not need to start the meshing form scratch.
• To restart the meshing process from a saved state you need to run
snappyHexMesh, save the intermediate steps (castellation and snapping), and
then create the inflation layers starting from the snapped mesh.
• Before creating the mesh with the inflation layers, you will need to transfer the
snapped mesh to the directory constant/polyMesh, and erase the intermediate
steps.
Module'3')'Lecture'10' 92'
Mesh generation using blockMesh and snappyHexMesh
Case 5. Sphere (external mesh).
Let us generate first the geometry using blender (or whatever you want to
use) and then the mesh by using SnappyHexMesh.
• Do not forget to turn off the castellation and snapping options in the
snappyHexMeshDict dictionary.
• castellatedMesh false;
• snap false;
• addLayers true;
Module'3')'Lecture'10' 93'
Mesh generation using blockMesh and snappyHexMesh
Case 5. Sphere (external mesh).
Let us restart the meshing from a saved state.
From now on, follow me.
Module'3')'Lecture'10' 94'
Mesh generation using blockMesh and snappyHexMesh
$PTOFC/sHM/M4_2d_cylinder
Module'3')'Lecture'10' 95'
Mesh generation using blockMesh and snappyHexMesh
Case 6. 2D Cylinder (external mesh).
• checkMesh –time 0
• paraFoam
Module'3')'Lecture'10' 99'
Mesh generation using blockMesh and snappyHexMesh
Case 6. 2D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh.
• snappyHexMesh -overwrite
• If you use this option, you will not save intermediate steps.
• Hence, you will not be able to visualize the intermediate steps.
• Also, you will not be able to restart the meshing process from a saved state
(castellated or snapped mesh).
Module'3')'Lecture'10' 100'
Mesh generation using blockMesh and snappyHexMesh
$PTOFC/sHM_1/M7_bwb_parallel
Module'3')'Lecture'10' 101'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
Module'3')'Lecture'10' 102'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
Module'3')'Lecture'10' 103'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
Module'3')'Lecture'10' 104'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
From now on, follow me.
• surfaceFeatureExtract -noFunctionObjects
• blockMesh
Module'3')'Lecture'10' 105'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
From now on, follow me.
• paraFoam –builtin
(To visualize the decomposed mesh)
Module'3')'Lecture'10' 107'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
From now on, follow me.
• But first you will need to transfer the boundary and initial conditions information to the
decomposed mesh, to do this
• decomposePar -fields
Module'3')'Lecture'10' 108'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
From now on, follow me.
• blockMesh
• snappyHexMesh –overwrite
• checkMesh
• paraFoam
Module'3')'Lecture'10' 109'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
From now on, follow me.
• By the way, if you want to use symmetry, just modify the blockMeshDict dictionary
so the background mesh cut the geometry in the middle.
• You can also modify the geometry and get half the airplane.
• Do not forget to change the boundary conditions and the boundary file.
Module'3')'Lecture'10' 110'
Mesh generation using blockMesh and snappyHexMesh
Additional tutorials
In the directories $PTOFC/sHM, and $PTOFC/mesh_conversion_manipulation,
you will find many tutorials, try to go through each one to understand and get functional
using the meshing tools.
Module'3')'Lecture'10' 111'
Module 4
Module'4')'Lecture'11' 1'
Before we begin
Module'4')'Lecture'11' 2'
Before we begin
Module'4')'Lecture'11' 3'
Before we begin
Module'4')'Lecture'11' 4'
Today’s lecture
Module'4')'Lecture'11' 5'
Data visualization with paraFoam
• paraFoam is the main post-processor distributed with OpenFOAM®.
However, you can use other alternatives (commercial or open source).
• paraFoam comes with many built-in filters. By using these filters you can
manipulate your data in order to create vectors, streamlines, iso-surfaces,
cut-planes, plot over a lines, and so on.
Module'4')'Lecture'11' 6'
Data visualization with paraFoam
$PTOFC/postprocessing/cavity3d/
Module'4')'Lecture'11' 7'
Data visualization with paraFoam
• In the directory $PTOFC/postprocessing/cavity3d/ you
will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'11' 8'
Data visualization with paraFoam
By following the instructions, you should get something like this
Module'4')'Lecture'11' 9'
Data visualization with paraFoam
By following the instructions, you should get something like this
Module'4')'Lecture'11' 10'
Data visualization with paraFoam
By following the instructions, you should get something like this
Iso-surfaces of passive scalar colored by velocity Volume rendering of passive scalar colored by T
magnitude concentration
Module'4')'Lecture'11' 11'
Data visualization with paraFoam
• By the way, to run this case you will need to compile the solver
my_icoFoam.
• cd $PTOFC/programming/applications/solvers/my_icoFoam
• wmake
• which my_icoFoam
Module'4')'Lecture'11' 12'
Data visualization with paraFoam
• We will now do some post-processing using paraFoam. From now on
follow me.
• cd $PTOFC/postprocessing/cavity3d/
• cp 0/T.org 0/T
• setFields
• blockMesh
• my_icoFoam
• paraFoam
Module'4')'Lecture'11' 13'
Data visualization with paraFoam
• A few words about paraFoam. You should have in mind that paraFoam is
not a visualization tool per-se (binary) , it is a script that calls paraview.
• If you want to read multiple cases, you will need to generate the
case_name.OpenFOAM file manually. In the terminal,
• touch new_case_name.OpenFOAM
Module'4')'Lecture'11' 14'
Data visualization with paraFoam
$PTOFC/postprocessing/yf17/
Module'4')'Lecture'11' 15'
Data visualization with paraFoam
• In the directory $PTOFC/postprocessing/yf17/ you will
find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'11' 16'
Data visualization with paraFoam
Try to capture the vortex
Module'4')'Lecture'11' 17'
Data visualization with paraFoam
Try to capture the vortex
Module'4')'Lecture'11' 18'
Data visualization with paraFoam
Try to capture the vortex
Module'4')'Lecture'11' 19'
Data visualization with paraFoam
• We will now do some post-processing using paraFoam. From now on follow
me.
• Go to the postprocessing/yf17/ directory. In the terminal type:
• cd $PTOFC/postprocessing/yf17/c1
• cd c1
• fluent3DMeshToFoam ../../../meshes/yf17/yf17.cas
• cp –r fs_0.20 0.20
• paraFoam
• We do not need to run this case, the solution is in the directory fs_0.20.
but if you want you can run the simulation, the case is ready to go. Have in
mind that is time consuming.
• The mesh is in the directory $PTOFC/meshes/yf17/
• At this point, try to get familiar with the user interface and most important, try
to use all the features available in paraFoam.
Module'4')'Lecture'11' 20'
Data visualization with paraFoam
• Sometimes it can happen that you have a mesh, but you do not have the
*.stl file of the geometry.
• You can extract the geometry from a valid polyMesh. From within the case
directory, type in the terminal:
• surfaceMeshTriangulate –patches ‘(fuselage strake
wing vertical-tail horizontal-tail intake intake-ramp
exhaust)’ –noFunctionOnjects yf17.stl
• At this point you should have the aircraft mesh in the file yf17.stl. Now
you can use this file as an input for snappyHexMesh.
Module'4')'Lecture'11' 21'
Data visualization
Additional tutorials
In the directory $PTOFC/postprocessing you will find many tutorials, try to go
through each one to understand and get functional using the post processing tools.
Module'4')'Lecture'11' 22'
Module 4
Module'4')'Lecture'12' 1'
Today’s lecture
Module'4')'Lecture'12' 2'
Data visualization with VISIT
• VISIT is an open source interactive parallel visualization and graphical
analysis tool.
• VISIT was developed by the U.S. Department of Energy (DOE) Advanced
Simulation and Computing Initiative (ASCI) to visualize and analyze the
results of terascale simulations
• VISIT contains a rich set of visualization filters for data manipulation.
• VISIT can read OpenFOAM® native format.
• VISIT can also read other formats, such as VTK format. To convert the
OpenFOAM® results to VTK format you need to use the foamToVTK utility.
• VISIT can be downloaded from the following site:
https://wci.llnl.gov/codes/visit/home.html
• Personally speaking, for large datasets, I do prefer to use VISIT rather than
paraFoam.
Module'4')'Lecture'12' 3'
Data visualization with VISIT
$PTOFC/postprocessing/
multiphase_dambreak/
Module'4')'Lecture'12' 4'
Data visualization with VISIT
• In the directory $PTOFC/postprocessing/
multiphase_dambreak you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'12' 5'
Data visualization with VISIT
By following the instructions, you should get something like this
Module'4')'Lecture'12' 6'
Data visualization with VISIT
By following the instructions, you should get something like this
Module'4')'Lecture'12' 7'
Data visualization with VISIT
• Let us do some post-processing using VISIT. From now on follow me.
Module'4')'Lecture'12' 8'
Data visualization with VISIT
• To do post-processing with VISIT, let us first convert the case to VTK format.
In the terminal type:
• foamToVTK
• cd VTK
• visit
(I added this alias to my .bashrc file. In visit you will need to open the VTK files)
Module'4')'Lecture'12' 9'
Data visualization with paraFoam
$PTOFC/postprocessing/vespacoarse/
Module'4')'Lecture'12' 10'
Data visualization with VISIT
• In the directory $PTOFC/postprocessing/vespacoarse
you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'12' 11'
Data visualization with VISIT
By following the instructions, you should get something like this
Module'4')'Lecture'12' 12'
Data visualization with VISIT
By following the instructions, you should get something like this
Pressure contours on driver and motorcycle and cut plane with velocity
magnitude contours
Module'4')'Lecture'12' 13'
Data visualization with VISIT
By following the instructions, you should get something like this
Pressure contours on driver and motorcycle and velocity magnitude volume rendering
Module'4')'Lecture'12' 14'
Data visualization with VISIT
By following the instructions, you should get something like this
Module'4')'Lecture'12' 15'
Data visualization with VISIT
• Let us do some post-processing using VISIT. From now on follow me.
Module'4')'Lecture'12' 16'
Data visualization with VISIT
• However, we need a valid mesh in order to do the post processing.
Module'4')'Lecture'12' 17'
Data visualization with VISIT
• Now that we have a valid mesh, we can convert the saved solution to VTK
format.
• cp -r fs_500 500
• foamToVTK -latestTime
• cd VTK
• visit
(I added this alias to my .bashrc file)
Module'4')'Lecture'12' 18'
Data visualization with VISIT
If you are into immerse visualization, you can do stereo rendering
Module'4')'Lecture'12' 19'
Data visualization with VISIT
If you are into immerse visualization, you can do stereo rendering
Red/Green Stereo rendering (eye angle 4), suitable for immerse visualization.
Module'4')'Lecture'12'
Pressure contours on driver and motorcycle 20'
Data visualization with VISIT
If you are into immerse visualization, you can do stereo rendering
Red/Green Stereo rendering (eye angle 0.8), suitable for immerse visualization.
Module'4')'Lecture'12'
Pressure contours on driver and motorcycle 21'
Data visualization with VISIT
• By the way, you can also do stereo rendering with paraview/paraFoam. To
do so, type in the terminal:
• paraFoam –stereo
or
• paraview --stereo
Module'4')'Lecture'12' 22'
Data visualization with VISIT
• The previous mesh was generated using snappyHexMesh, so feel free to
take a look at the snappyHexMesh dictionary and the .stl file containing
the geometry.
• At this point, try to get familiar with the user interface and most important, try
to use all the features available in VISIT.
Module'4')'Lecture'12' 23'
Data visualization
Additional tutorials
In the directory $PTOFC/postprocessing you will find many tutorials, try to go
through each one to understand and get functional using the post processing tools.
Module'4')'Lecture'12' 24'
Module 4
Module'4')'Lecture'13' 1'
Today’s lecture
Module'4')'Lecture'13' 2'
Today’s lecture
Module'4')'Lecture'13' 3'
Data conversion
• You can convert the solution obtained with OpenFOAM® to many third party
formats. To do this, you can use OpenFOAM® data conversion utilities.
• If you are looking for a specific format and it is not supported, you can write
your own conversion tool.
Module'4')'Lecture'13' 4'
Data conversion
Fluent solution Ensight GMV Tecplot tetDualMesh
foamDataTofluent foamToEnsight foamToGMV foamToTecplot360 foamToTetDualMesh
VTK
foamToVTK
solution
Mesh boundaries
foamToSurface
The diagram is not complete. Refer to the user guide or source code to
get more information about all the conversion utilities available in
Module'4')'Lecture'13' 5'
OpenFOAM®
Data conversion
• In $FOAM_UTILITIES (use alias util to go there) you will find the directories
containing the source code for the utilities available in the OpenFOAM® installation
(version 2.3.x):
• mesh
• miscellaneous
• parallelProcessing
• postProcessing
• preProcessing
• surface
• Thermophysical
• In the sub-directory postProcessing you will find the source code for the post
processing utilities included in the OpenFOAM® installation.
Module'4')'Lecture'13' 6'
Data conversion
• Let us visit the postProcessing directory. In the terminal type:
• util
• cd postProcessing
• In this directory you will find the directories containing the source code for the
following post processing utilities
• dataConversion • sampling
• foamCalc • scalarField
• graphics • stressField
• lagrangian • turbulence
• miscellaneous • velocityField
• noise • wall
• patch
Module'4')'Lecture'13' 7'
Data conversion
• Let us go to the directory dataConversion, in the terminal type:
• cd dataConversion
• ls –l
• foamDataToFluent • foamToTecplot360
• foamToEnsight • foamToTetDualMesh
• foamToEnsightParts • foamToVTK
• foamToGMV • smapToFoam
Module'4')'Lecture'13' 9'
Data manipulation
Module'4')'Lecture'13' 10'
Data manipulation
• In $FOAM_UTILITIES (use alias util to go there) you will find the directories
containing the source code for the utilities available in the OpenFOAM® installation
(version 2.3.x):
• mesh
• miscellaneous
• parallelProcessing
• postProcessing
• preProcessing
• surface
• Thermophysical
• In the sub-directory postProcessing you will find the source code for the post
processing utilities included in the OpenFOAM® installation.
Module'4')'Lecture'13' 11'
Data manipulation
• Let us visit the postProcessing directory. In the terminal type:
• util
• cd postProcessing
• In this directory you will find the directories containing the source code for many post
processing and data manipulation utilities,
• dataConversion • sampling
• foamCalc • scalarField
• graphics • stressField
• lagrangian • turbulence
• miscellaneous • velocityField
• noise • wall
• patch
• A friendly advice, always remember to develop your own utilities in your user
directory (WM_PROJECT_USR_DIR), and to keep the same directory
structure as in the original OpenFOAM® installation.
• Take your time and dig into each directory to get a complete
description of each utility.
Module'4')'Lecture'13' 14'
Data manipulation
$PTOFC/postprocessing/supersonic_cyl/
Module'4')'Lecture'13' 15'
Data manipulation
• In the directory $PTOFC/postprocessing/
supersonic_cyl/ you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'13' 16'
Data manipulation
By following the instructions, you should get something like this
Courant number
Module'4')'Lecture'13' 17'
Data manipulation
By following the instructions, you should get something like this
Mach number
Module'4')'Lecture'13' 18'
Data manipulation
By following the instructions, you should get something like this
Z vorticity
Module'4')'Lecture'13' 19'
Data manipulation
By following the instructions, you should get something like this
Density contours
Module'4')'Lecture'13' 20'
Data manipulation
By following the instructions, you should get something like this
Module'4')'Lecture'13' 22'
Data manipulation
• Go to the postprocessing/supersonic_cyl/ directory. In the terminal
type:
• cd $PTOFC/postprocessing/supersonic_cyl/
• ls –al 0
(Take a look at the files in the diectory 0. By the default the solver will compute only the primitive variables p, T, and U)
• blockMesh
• checkMesh
• renumberMesh -overwrite
• sonicFoam > log.sonicfoam | tail -f log.sonicfoam
(This is a supersonic solver - compressible flows -. Take a look at the dictionaries, as they are different from the
dictionaries from the incompressible solvers. The theory is also slightly different)
• paraFoam
Module'4')'Lecture'13' 23'
Data manipulation
• After finding the solution, we can compute the new field variables using the
primitive variables computed during the solution stage.
• Mach
• vorticity
• Co
• wallGradU
• enstropy
• Pe
Module'4')'Lecture'13' 24'
Data manipulation
• After finding the solution, we can compute the new field variables using the
primitive variables computed during the solution stage.
• foamToVTK –surfaceFields
• paraFoam
Module'4')'Lecture'13' 25'
Data manipulation
• By the way, if you take a look at the dictionary controlDict, you will see
that we are using a functionObject named writeRegisteredObject.
• This functionObject will compute field variables that are not computed
by default by the solver.
• For instance, in this case the solver will only compute p, T and U, by using
this functionObject we can compute rho as well.
Module'4')'Lecture'13' 26'
Data manipulation
• For instance, in this case the solver will only compute p, T and U, by using
this functionObject we can compute rho as well.
additional_fields
{
type writeRegisteredObject;
functionObjectLibs ( "libIOFunctionObjects.so" );
objectNames ("rho”);
enabled true;
outputControl outputTime;
}
Module'4')'Lecture'13' 27'
Data manipulation
Additional tutorials
In the directory $PTOFC/postprocessing you will find many tutorials, try to go
through each one to understand and get functional using the post processing tools.
Module'4')'Lecture'13' 28'
Module 4
Module'4')'Lecture'14' 1'
Today’s lecture
Module'4')'Lecture'14' 2'
Today’s lecture
Module'4')'Lecture'14' 3'
The sample utility
• OpenFOAM® provides the sample utility to sample field data for plotting.
• During the job execution, inside the case directory a new folder named
postProcessing/, will be created. In this folder, the sampled values are
stored.
• The sampling can be executed by running the utility sample in the case
folder and according to the application syntax.
• A final word, this utility does not do the sampling while the solver is running.
It does the sampling after you finish the simulation.
Module'4')'Lecture'14' 4'
For more information about the sample utility, refer to the user guide.
The sample utility
$PTOFC/postprocessing/turb_backstep/
Module'4')'Lecture'14' 5'
The sample utility
• In the directory $PTOFC/postprocessing/
turb_backstep/ you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'14' 6'
The sample utility
By following the instructions, you should get something like this
Mesh
Module'4')'Lecture'14' 7'
The sample utility
By following the instructions, you should get something like this
Module'4')'Lecture'14' 8'
The sample utility
By following the instructions, you should get something like this
Turbulence kinetic energy (k) contours Turbulence dissipation rate (epsilon) contours
Module'4')'Lecture'14' 9'
The sample utility
By following the instructions, you should get something like this
[U/Uc] 0 0.02
Exp
CFD
0 1 2 3 4 5 6 7 8 9 10 [x/H]
0 1 2 3 4 5 6 7 8 9 10 [x/H]
Module'4')'Lecture'14' 10'
The sample utility
We will now do some post-processing using the sample utility. From now on
follow me.
• Go to the postprocessing/turb_backstep directory. In the terminal
type:
• cd $PTOFC/postprocessing/turb_backstep/
• blockmesh
• cp 0_org/* 0
• setDiscreteFields
(If you do not have this tool, copy the files located in the directory 0init to the directory 0)
• simpleFoam
• sample –latestTime
(The utility sample reads the dictionary ./system/sampleDict)
• At this point take a look at the case folder. You will notice that the sample
utility creates a new folder named postProcessing, which contains the
folder sets where you will find n time directories (one for each time step
sampled). Module'4')'Lecture'14' 11'
My third OpenFOAM® case setup
• You can use the following options with the sample utility (and most of the
utilities):
• sample –latestTime
(The –latestTime option will do the sampling only for the last saved solution)
• sample –noZero
(The –noZero option will do the sampling for all the saved solutions except the time directory 0)
• sample
(If you do not add any option, the utility will do the sampling for all the saved solutions, including time directory 0)
• To know what options you can use with the sample utility (and most of the
utilities), type in the terminal:
• sample –help
Module'4')'Lecture'14' 12'
The sample utility
• You will find in the case directory a small shell script named script. From
the terminal type:
• ./script
(Take some time and read the script to understand what is going on)
• This script will generate two output files in .eps format using the gnuplot
scripts located in the case folder (profilek.gp and profileU.gp). Take
a look at these files, this is a part of the post-processing tutorials.
Module'4')'Lecture'14' 14'
For more information about the sample utility, refer to the user guide.
The sample utility
The sampleDict file
Module'4')'Lecture'14' 15'
For more information about the sample utility, refer to the user guide.
Today’s lecture
Module'4')'Lecture'14' 16'
Probes
• OpenFOAM® provides the probeLocations utility to sample field data in
some discrete points.
• During the job execution, inside the case directory a new folder named
postProcessing/, will be created. In this folder, the probed values are
stored.
• The probed values are saved in a ascii file, with the name of the probed
field.
• A final word, this utility does not probe while the solver is running. It does the
probing after you finish the simulation.
Module'4')'Lecture'14' 17'
Probes
$PTOFC/postprocessing/2d_cylinder_60
Module'4')'Lecture'14' 18'
Probes
• In the directory
$PTOFC/postprocessing/2d_cylinder_60 you will find
this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'14' 19'
Probes
By following the instructions, you should get something like this
Mesh
Module'4')'Lecture'14' 20'
Probes
By following the instructions, you should get something like this
Module'4')'Lecture'14' 21'
Probes
By following the instructions, you should get something like this
Module'4')'Lecture'14' 22'
Pressure probes time history
My third OpenFOAM® case setup
By following the instructions, you should get something like this
Module'4')'Lecture'14' 23'
Aerodynamic coefficients for Reynolds 60
Probes
We will now run a simulation using some probes. From now on follow me.
Note: do not erase the log file, we are going to use it in the next tutorial.
• Let us explore the case directory. You will see that we have a new folder
named postProcessing/probes, which contains the ./0 time directory,
this is the directory from which we started to do the sampling.
• If you start to sampling from time 20, in the directory postProcessing/
probes you will find the time directory 20 with the probes information. 24'
Module'4')'Lecture'14'
Probes
• Let us now study the probesDict dictionary. Go to the system directory
and open the file probesDict. The probesDict dictionary contains at
least the following entries (the header is not shown):
Module'4')'Lecture'14' 25'
Today’s lecture
Module'4')'Lecture'14' 26'
foamLog
• During execution, OpenFOAM® writes values of residuals, number of
iterations and so on, on the standard output (terminal).
• It is possible to extract this information with the foamLog utility, provided the
standard output has been written to a file (logfile).
• All the information extracted from the logfile file is saved in the directory
logs
• To plot this info we can use gnuplot, grace, xmgr, octave, qtiPlot
and/or jPlot (just to name a few).
Module'4')'Lecture'14' 27'
foamLog
• By default, the files are presented in two-column format of time and the
extracted values. You can plot each file by using gnuplot or your favorite
plotting tool. Depending of your case setup, you will find the following files:
• courant_0
• contCumulative_0
• contGlobal_0
• contLocal_0
• executionTime_0
• Separator_0
• Time_0
• p_0
• pFinalRes_0
• pIters_0
• Ux_0
• UxFinalRes_0
• UxIters_0
• Uy_0
• UyFinalRes_0
• UyIters_0 Module'4')'Lecture'14' 28'
foamLog
• Let us analyze the log file of the previous tutorial. In the terminal type:
• cd $PTOFC/postprocessing/2d_cylinder_60/
(If you are not already in there)
• foamLog log
• cd logs
• gnuplot
• plot ‘CourantMean_0’ using 1:2 with lines
• plot ‘p_0’ u 1:2 w l, ‘pFinalRes_0’ u 1:2 w l
• If you do not have the log file from the previous tutorial, you can use the log
file icofoam_run, which is located in the case directory top level.
Module'4')'Lecture'14' 29'
foamLog
• This is a screenshot on my computer. This is a plot of the pressure initial and
final residual using gnuplot. You can plot any of the output files generated
by foamLog.
Module'4')'Lecture'14' 30'
foamLog
• It is also possible to plot this information on the fly.
• To do this you will need to install PyFoam and use the following utility:
• pyFoamPlotWatcher.py name_of_log_file
Module'4')'Lecture'14' 31'
foamLog
• Let us run again the case postprocessing/2d_cylinder_60 but this
time using pyFoamPlotWatcher.py. In the terminal type:
• cd $PTOFC/postprocessing/2d_cylinder_60
• blockMesh
• icoFoam > log | tail –f log
• pyFoamPlotWatcher.py log
• You do not need to run until the end time, just run for a few seconds to see
the output of pyFoamPlotWatcher.py.
Module'4')'Lecture'14' 32'
foamLog
• This is a screenshot on my computer. In this case, pyFoamPlotWatcher is
showing the initial residuals and continuity errors on the fly.
Module'4')'Lecture'14' 33'
Post-processing
Additional tutorials
In the directory $PTOFC/postprocessing you will find many tutorials, try to go
through each one to understand and get functional using the post processing tools.
Module'4')'Lecture'14' 34'
Module 4
Module'4')'Lecture'15' 1'
Today’s lecture
1. functionObjects
2. Co-processing
3. Hands-on session
Module'4')'Lecture'15' 2'
Today’s lecture
1. functionObjects
2. Co-processing
3. Hands-on session
Module'4')'Lecture'15' 3'
functionObjects
• It is possible to perform data extraction/manipulation operations while the
simulation is running by using the functionObject feature.
Module'4')'Lecture'15' 4'
functionObjects
• Below is a list of some of the available functionObject that can be called
at run-time:'
'
• fieldAverage - temporal averaging of fields.
• fieldMinMax - writes min/max values of fields.
• fieldValue - averaging/integration across sets of faces/cells, e.g. for flux across a plane.
• readFields - loads fields to the database for post-processing.
• surfaceInterpolateFields - generates surfaceFields from volFields for further postprocessing.
• forces - calculates pressure/viscous forces and moments.
• forceCoeffs - calculates lift, drag and moment coefficients.
• sampledSet - data sampling along lines, e.g. for graph plotting.
• probes - data probing at point locations.
• isoSurface - generation of an isosurface of given fields in one of the standard sample formats.
• cuttingPlane - generation of a cuttingPlane with field data in one of the sample formats.
• sampledPatch - generation of a surface of a patch with field data in one of the sample formats.
• systemCall - execute any system call, e.g. email you to tell you your job is finished.
• abortCalculation - aborts the calculation if a given file is present in the case directory.
• partialWrite - allows registered objects, e.g. fields, to be written at different times (frequencies).
• nearWallFields - generates a volField with boundary values from interpolated internal field.
• streamLine - generates streamlines in one of the sample formats.
• timeActivatedFileUpdate - modifies case settings at specified times in a simulation.
• writeRegisteredObject - writes registered objects, e.g. fields that are not scheduled to be written in
the application, i.e. created with NO_WRITE.
• systemCall
• timeActivatedFileUpdate
• writeRegisteredObject
• Try to figure out what they do and when they can be used.
$PTOFC/postprocessing/2d_cylinder_100
Module'4')'Lecture'15' 7'
functionObjects
• In the directory
$PTOFC/postprocessing/2d_cylinder_100 you will find
this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'15' 8'
functionObjects
By following the instructions, you should get something like this
Mesh
Module'4')'Lecture'15' 9'
functionObjects
By following the instructions, you should get something like this
Module'4')'Lecture'15' 10'
functionObjects
By following the instructions, you should get something like this
Module'4')'Lecture'15' 11'
functionObjects
By following the instructions, you should get something like this
Module'4')'Lecture'15' 12'
Aerodynamic coefficients time history – Reynolds number = 100
functionObjects
By following the instructions, you should get something like this
Module'4')'Lecture'15' 13'
PSD – Reynolds number = 100
functionObjects
By following the instructions, you should get something like this
Module'4')'Lecture'15' 14'
Pressure probes time history – Reynolds number = 100
functionObjects
By following the instructions, you should get something like this
Module'4')'Lecture'15' 15'
Velocity probes time history – Reynolds number = 100
functionObjects
By following the instructions, you should get something like this
Module'4')'Lecture'15' 16'
Pressure minimum and maximum values – Reynolds number = 100
functionObjects
By following the instructions, you should get something like this
Module'4')'Lecture'15' 17'
Velocity components minimum and maximum values – Reynolds number = 100
functionObjects
• We will now run a simulation using functionObject. From
now on follow me.
• cd $PTOFC/postprocessing/2d_cylinder_100/
• blockMesh
• icoFoam > log &
• tail -f log
Module'4')'Lecture'15' 18'
functionObjects
• Let us explore the case directory. You will see that we now
have a new directory named postProcessing. Inside this
directory, you will find many subdirectories pointing to the
functionObject used.
• forceCoeffs_object
• forces_object
• inMassFlow
• minmaxdomain
• outMassFlow
• patchMassFlows_massFlow
• probes1
• probes2
• sampleset
• surfaceSampling
Module'4')'Lecture'15' 20'
functionObjects
• Inside the directory postProcessing, you will many sub-
directories with the information of each of the
functionObject used during the simulation.
• Inside each sub-directory you will find the time directory 0, this
is the time directory from which we started to sample using
functionObject.
• If you start to sample from time 50, you will find the time
directory 50.
Module'4')'Lecture'15' 21'
functionObjects
Some shell and awk scripting
• Let us go to the postProcessing/minmaxdomain/0 directory. Now type in the
terminal:
• To extract the velocity from out.txt, and save the output in vel_minmax.txt
type in the terminal:
• awk '0 == NR % 2' out.txt > vel_minmax.txt
• To extract the pressure from out.txt, and save the output in pre_minmax.txt
type in the terminal:
• awk '1 == NR % 2' out.txt > pre_minmax.txt
Module'4')'Lecture'15' 23'
functionObjects
Some shell and awk scripting
• Let us go to the postProcessing/forceCoeffs_object/0 directory. Now type
in the terminal:
• To compute the mean value of the aerodynamic coefficients (drag coefficient in this case)
using the data in forceCoeffs.dat, type in the terminal:
• To compute the mean value of the aerodynamic coefficients (lift coefficient in this case)
using the data in forceCoeffs.dat, type in the terminal:
Module'4')'Lecture'15' 24'
functionObjects
Some shell and awk scripting
• Let us go to the postProcessing/forceCoeffs_object/0 directory. Now type
in the terminal:
• To compute the standard deviation of the aerodynamic coefficients (drag coefficient in this
case) using the data in forceCoeffs.dat, type in the terminal:
• To compute the standard deviation of the aerodynamic coefficients (lift coefficient in this
case) using the data in forceCoeffs.dat, type in the terminal:
• To run the scripts you need to be inside the scripts directory. In the terminal type,
• cd scripts
• sh script_name
• To know what the scripts are doing, what information is saved and where the output
file of the script is saved, just take a look at the scripts.
Module'4')'Lecture'15' 26'
functionObjects
Some shell and awk scripting
• The script script_force_coe will compute the mean value and standard
deviation of the lift and drag coefficients.
• The script script_probes will extract the information of the probes.
• The script script_minmax will extract the minimum and maximum values of
the field variables.
Feel free to adapt these scripts to your needs. I just showed how to compute the
average and standard deviation and do some manipulation of the information saved
in the output files, but you can do many things in an automatic way.
• Let us do some plotting using gnuplot. Type in the terminal (you must be inside the
scripts directory):
• gnuplot
Module'4')'Lecture'15' 28'
functionObjects
Plotting in gnuplot
• Let us do some plotting using gnuplot. Type in the terminal (you must be inside the
scripts directory):
• gnuplot
Module'4')'Lecture'15' 29'
functionObjects
• Let us now study the controlDict dictionary. Go to the case system
directory and open the file controlDict using your favorite text editor
• At the end of the controlDict dictionary, you will find a new sub-
dictionary entry,
functions
(
//some functionObjects here//
);
Module'4')'Lecture'15' 30'
functionObjects
• The functionObject entry in the controlDict dictionary, contains at
least the following information:
function_object_name Name,of,func%onObject,
{
enabled true;
outputControl outputTime;
}
Module'4')'Lecture'15' 31'
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, additional_fields
{
func%onObject,to,use, type writeRegisteredObject;
objectNames ("U_0")
enabled true;
Keywords,and,sub8dic%onaries,
specific,to,the,func%onObject,
timeStart 100;
timeEnd 200;
outputControl outputTime;
}
Module'4')'Lecture'15' 32'
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, fieldAverage
{
func%onObject,to,use, type fieldAverage;
Library,to,use, functionObjectLibs ("libfieldFunctionObjects.so");
enabled true;
outputControl outputTime;
cleanRestart false;
timeStart 20;
timeEnd 200;
fields
(
U
{
mean on;
Keywords,and,sub8dic%onaries,
specific,to,the,func%onObject, prime2Mean on;
base time;
}
p
{
mean on;
prime2Mean on;
base time;
}
); Module'4')'Lecture'15' 33'
}
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, forces_object
{
func%onObject,to,use, type forces;
outputControl timeStep;
outputInterval 1;
patches ("cylinder");
pName p;
Uname U;
rhoName rhoInf;
rhoInf 1.0;
CofR (0 0 0);
} Module'4')'Lecture'15' 34'
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, forceCoeffs_object
{
func%onObject,to,use, type forceCoeffs;
patches ("cylinder");
pName p;
Uname U;
rhoName rhoInf;
Keywords,and,sub8dic%onaries, rhoInf 1.0;
specific,to,the,func%onObject, log true;
CofR (0.0 0 0);
liftDir (0 1 0);
dragDir (1 0 0);
pitchAxis (0 0 1);
magUInf 1.0;
lRef 1.0;
Aref 2.0;
outputControl timeStep;
outputInterval 1;
} Module'4')'Lecture'15' 35'
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, minmaxdomain
{
func%onObject,to,use, type fieldMinMax;
enabled true;
mode component;
log true;
fields (p U);
}
Module'4')'Lecture'15' 36'
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, probes1
{
func%onObject,to,use, type probes;
probeLocations
(
(2 1 0)
);
Keywords,and,sub8dic%onaries, fields
specific,to,the,func%onObject, (p U);
outputControl timeStep;
outputInterval 1;
}
Module'4')'Lecture'15' 37'
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, probes2
{
func%onObject,to,use, type probes;
probeLocations
(
(5 0.5 0)
(5 0 0)
Keywords,and,sub8dic%onaries, (5 -0.5 0)
specific,to,the,func%onObject, (10 0.5 0)
(10 0 0)
(10 -0.5 0)
);
fields
(p U);
outputControl timeStep;
outputInterval 1;
}
Module'4')'Lecture'15' 38'
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, surfaceSampling
{
func%onObject,to,use, type surfaces;
Library,to,use, functionObjectLibs ("libsampling.so");
enabled true;
outputControl outputTime;
interpolationScheme cellPoint;
surfaceFormat raw;
fields
(
Keywords,and,sub8dic%onaries,
specific,to,the,func%onObject, p
);
surfaces
(
nearWall
{
type patch;
patches ( "cylinder" )
//distance 0;
interpolate true;
triangulate false;
}
); Module'4')'Lecture'15' 39'
}
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, sampleset
{
func%onObject,to,use, type sets;
Library,to,use, functionObjectLibs ("libsampling.so");
enabled true;
outputControl timeStep;
outputInterval 1;
setFormat raw;
surfaceFormat vtk;
interpolationScheme cellPoint;
fields
( p U );
sets
(
Keywords,and,sub8dic%onaries, lineX1
specific,to,the,func%onObject,
{
type midPoint;
axis y;
start (5 -4 0);
end (5 4 0);
}
//...
//More lines here//
//...
); Module'4')'Lecture'15' 40'
}
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, inMassFlow
{
func%onObject,to,use, type faceSource;
enabled true;
//outputControl outputTime;
outputControl timeStep;
Keywords,and,sub8dic%onaries, outputInterval 1;
specific,to,the,func%onObject,
log true;
valueOutput false;
source patch;
sourceName in;
operation sum;
fields
( phi );
Module'4')'Lecture'15' 41'
}
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, outMassFlow
{
func%onObject,to,use, type faceSource;
enabled true;
outputControl timeStep;
outputInterval 1;
source patch;
sourceName out;
operation sum;
fields
( phi );
Module'4')'Lecture'15' 42'
}
functionObjects
• This is the functionObject entry in the controlDict dictionary,
Name,of,func%onObject, massFlow
{
func%onObject,to,use, type patchMassFlow;
verbose true;
patches
(
in
Keywords,and,sub8dic%onaries, out
specific,to,the,func%onObject, );
factor 1
outputControlMode timeStep;
outputInterval 1;
}
Module'4')'Lecture'15' 43'
• To use this functionObject you will need to install swak4foam.
functionObjects
• In the previous example we only used a few of the functionObject
available in OpenFOAM®, namely:
writeRegisteredObject
fieldAverage
forces
forceCoeffs
fieldMinMax
probes
surfaces
sets
faseSource
patchMassFlow
• For instance, let us say that you forgot to save the additional field U_0_0,
you do not need rerun the simulation. Open the dictionary controlDict
and uncomment the section corresponding to the functionObject
additional_fields_forgot (at the end of the file). Then type in the
terminal,
• execFlowFunctionObjects -latestTime
Module'4')'Lecture'15' 45'
Today’s lecture
1. functionObjects
2. Co-processing
3. Hands-on session
Module'4')'Lecture'15' 46'
Co-processing
• Multi-physics and CFD simulations have the potential to overwhelm any computer
(including the largest super computers) with the output obtained from simulations.
• The traditional approach is to run a simulation and save the solution at given time-
steps or intervals for post processing at a later time.
• An alternative way to do post processing, is to extract results or pretty pictures while
the simulation is running (on the fly), this is co-processing.
GEOMETRY
MESH
SOLVER CO-PROCESSING
VISUALIZATION
Module'4')'Lecture'15' 47'
Co-processing
• For unsteady and big simulations, co-processing is an
alternative if we do not want to overflow the system with tons of
data.
Module'4')'Lecture'15' 48'
Co-processing
• An added benefit of co-processing is that results can be
immediately reviewed and problems can be immediately
addressed.
Module'4')'Lecture'15' 49'
Co-processing
• By the way, we define the co-processing as a
functionObject, and you can change it on-the-fly.
Module'4')'Lecture'15' 50'
Co-processing
$PTOFC/postprocessing/vespacoarse/
Module'4')'Lecture'15' 51'
Co-processing
• In the directory $PTOFC/postprocessing/vespacoarse
you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'4')'Lecture'15' 52'
Co-processing
• Go to the postprocessing/vespacoarse directory. In the
terminal type:
• cd $PTOFC/postprocessing/vespacoarse/
• We do not need to run this case for a long time. In the directory
$PTOFC/postprocessing/vespacoarse/c1/fs_500 you
will find a converged solution.
• In the directory sol_mesh you will find the mesh, you do not
need to generate it. To run the case, type in the terminal,
• rm –rf 0
• cp –rf 0org 0
• cp -r sol_mesh/polyMesh constant
• checkMesh
• potentialFoam –noFunctionObjects
Module'4')'Lecture'15' 54'
Co-processing
• If you are in the mood and you feel like you want to generate
the mesh, in the terminal type:
• rm –rf 0
• cp –rf 0org 0
• blockmesh
• snappyHexMesh –overwrite –noFunctionObjects
• checkMesh
• potentialFoam –noFunctionObjects
Module'4')'Lecture'15' 57'
Co-processing
• In each of these sub-directories you will find the pretty pictures
saved in VTK format.
• At this point, let us take a look at few of the files located in the
system directory.
Module'4')'Lecture'15' 58'
Co-processing
• This is a functionObject for co-processing,
Name,of,func%onObject, cuttingPlane
{
func%onObject,to,use, type surfaces;
Library,to,use, functionObjectLibs ("libsampling.so");
//outputControl outputTime;
outputInterval 5;
surfaceFormat vtk;
fields (p U);
interpolationScheme cellPoint;
surfaces
(
Keywords,and,sub8dic%onaries, xNormal
specific,to,the,func%onObject, {
type cuttingPlane;
planeType pointAndNormal;
pointAndNormalDict
{
basePoint (0 0 0);
noramlVector (0 1 0);
}
interpolate true;
}
);
Module'4')'Lecture'15' 59'
}
Co-processing
• This is a functionObject for co-processing,
Name,of,func%onObject, isoSurface
{
func%onObject,to,use, type surfaces;
//outputControl outputTime;
outputInterval 10;
surfaceFormat vtk;
fields (p U);
interpolationScheme cellPoint;
Keywords,and,sub8dic%onaries, surfaces
specific,to,the,func%onObject, (
constantIso
{
type isoSurfaceCell;
isoField p;
isoValue 30;
interpolate false;
regularise false;
}
);
}
Module'4')'Lecture'15' 60'
Co-processing
• At this point, take a look at all the functionObject used for
co-processing. In this case we used,
• readFields
• forceCoeffs
• isoSurface
• cuttingPlane
• nearWallFields
• streamLine
• wallBoundedStreamLine
• By the way, you can add the functionObject for co-processing directly
in the dictionary controlDict or you can use the #include statement
and have the dictionary entry for the specific functionObject in a
separate file (cuttingPlane, forceCoeffs, readFields,
streamLines, wallBoundedStreamLines, ./files/isoSurface, in
this case).
Module'4')'Lecture'15' 61'
Post-processing
Additional tutorials
In the directory $PTOFC/postprocessing you will find many tutorials, try to go
through each one to understand and get functional using the post processing tools.
Module'4')'Lecture'15' 62'
Module 5
Module'5')'Lecture'16' 1'
Today’s lecture
Module'5')'Lecture'16' 2'
Today’s lecture
Module'5')'Lecture'16' 3'
Running in parallel
The method of parallel computing used by OpenFOAM® is known as
domain decomposition, in which the geometry and associated fields are
broken into pieces and distributed among different processors.
• You can find this case and the parallel and serial timing in the directory
$PTOFC/mycases1/elbow3d/sHM_mesh.
• The parallel case with 1 processor runs slower than the serial case due to the extra overhead
when calling the MPI library. Module'5')'Lecture'16' 6'
Running in parallel
Some facts about running OpenFOAM® in parallel:
• Applications generally do not require parallel-specific coding. The parallel
programming implementation is hidden from the user.
• Most of the applications and utilities run in parallel.
• If you write a new solver, it will be in parallel (most of the times).
• I have been able to run in parallel up to 14000 processors.
• I have been able to run OpenFOAM® using single GPU and multiple GPUs.
• Do not ask me about scalability, that is problem/hardware specific.
• If you want to learn more about MPI and GPU programming, do not look in
my direction.
• Did I forget to mention that OpenFOAM® is free.
Module'5')'Lecture'16' 7'
Running in parallel
To run OpenFOAM® in parallel you will need to:
Module'5')'Lecture'16' 8'
Running in parallel
Domain Decomposition
• The mesh and fields are decomposed using the decomposePar utility.
• The main goal is to break up the domain with minimal effort but in such a
way to guarantee a fairly economic solution.
Module'5')'Lecture'16' 9'
Running in parallel
Domain Decomposition
• In the decomposeParDict file the user must set the number of domains in
which the case should be decomposed. Usually it corresponds to the
number of cores available for the calculation.
• numberOfSubdomains NP;
where NP is the number of cores/processors.
Module'5')'Lecture'16' 10'
Running in parallel
Domain Decomposition Methods
• scotch: requires no geometric input from the user and attempts to minimize
the number of processor boundaries. Similar to metis but with a more
flexible open-source license.
• metis: requires no geometric input from the user and attempts to minimize
the number of processor boundaries. You will need to install metis as it is
not distributed with OpenFOAM®. Also, you will need to compile the
metisDecomp library.
Module'5')'Lecture'16' 12'
Running in parallel
Module'5')'Lecture'16' 13'
Running in parallel
polyMesh/ and 0/'
decomposePar'
• Inside each processorN folder you will have the mesh information, boundary and
Module'5')'Lecture'16' 14'
initial conditions and the solution for that processor.
Running in parallel
reconstructPar'
• decomposePar
• mpirun –np <NPROCS> <application/utility> –parallel
• reconstructPar
• paraFoam
Module'5')'Lecture'16' 17'
Running in parallel
Module'5')'Lecture'16' 18'
Running in parallel
$PTOFC/parallel_tut/rayleigh_taylor
Module'5')'Lecture'16' 19'
Running in parallel
• In the directory $PTOFC/parallel_tut/rayleigh_taylor
you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'5')'Lecture'16' 20'
Running in parallel
By following the instructions, you should get something like this
Module'5')'Lecture'16' 21'
Running in parallel
• Go to the $PTOFC/parallel_tut/rayleigh_taylor directory. In the
terminal type:
• cd $PTOFC/parallel_tut/rayleigh_taylor/c1
• blockMesh
• checkMesh
• cp 0/alpha.phase1.org 0/alpha.phase1
• funkySetFields -time 0
(If you do not have this tool, copy the file alpha.phae1.init to alpha.phase1. The file is located in the directory 0.
The funkySetFields utility is part of pyFoam.)
• decomposePar
(This will decompose the case. It reads the decomposeParDict dictionary that is located in the directory system)
• ls –al
(Just to list all the directories and files. Do you see something different now?)
Module'5')'Lecture'16' 22'
Running in parallel
• Go to the $PTOFC/parallel_tut/rayleigh_taylor directory. In the
terminal type:
Module'5')'Lecture'16' 23'
Running in parallel
$PTOFC/parallel_tut/cylinder_par
Module'5')'Lecture'16' 24'
Running in parallel
• In the directory $PTOFC/parallel_tut/cylinder_par
you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'5')'Lecture'16' 25'
Running in parallel
• In the directory $PTOFC/parallel_tut/cylinder_par you will find this
tutorial. In the terminal window type:
• cd $PTOFC/parallel_tut/cylinder_par
• ls –l
(Just to list all the directories and files. Does the directory structure look familiar to you?)
• blockMesh
• decomposePar
(This will decompose the case. It reads the decomposeParDict dictionary that is located in the directory system)
• ls –l
(Just to list all the directories and files. Do you see something different now?)
Module'5')'Lecture'16' 26'
Running in parallel
• In the directory $PTOFC/parallel_tut/cylinder_par you will find this
tutorial. In the terminal window type:
Module'5')'Lecture'16' 27'
Running in parallel
• By the way, as a part of the never ending task of verification and validation, it is a
good idea to check from time to time that the serial solution and parallel solution are
equal.
• It might happen that you get different results. If this happens, there is a problem in
the parallel implementation or processors inter-communication.
• In this case, the serial and parallel solutions are equal.
Module'5')'Lecture'16' 28'
Running in parallel
Module'5')'Lecture'16' 29'
Running in parallel
• The traditional way is to first reconstruct the case and then do the post-
process and visualization on the reconstruct case.
• reconstructPar
• paraFoam
Module'5')'Lecture'16' 30'
Running in parallel
• What is the meaning of the option –builtin we used with paraFoam?
• By the way, you will need to select on the object inspector the Decomposed
Case option.
Module'5')'Lecture'16' 31'
Running in parallel
• Both of the previous methods are valid.
• That is to say, we do not need to reconstruct the case, we save one step
Module'5')'Lecture'16' 32'
Running in parallel
• But wait, there is a third option.
• To load all processor directories, you will need to manually create the file
processorN.OpenFOAM (where N is the processor number) in each
processor folder.
Module'5')'Lecture'16' 33'
Running in parallel
$PTOFC/parallel_tut/yf17
Module'5')'Lecture'16' 34'
Running in parallel
• In the directory $PTOFC/parallel_tut/yf17 you will find
this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'5')'Lecture'16' 35'
Running in parallel
• Let us post-process each decomposed domain individually. From now on
follow me.
• cd $PTOFC/parallel_tut/yf17
Module'5')'Lecture'16' 36'
Running in parallel
• In this directory you will find three directories, namely hierarchical,
scotch and scotch_celldist. Let us decompose these cases and
visualize the partitioning. First we start with the scotch partitioning method.
In the terminal type:
• cd $PTOFC/parallel_tut/yf17/scotch
• decomposePar
• By the way, you do not need to run this case. We just need to decompose it
to visualize the partitions.
Module'5')'Lecture'16' 37'
Running in parallel
• Let us post-process each decomposed domain individually. From now on
follow me.
• cd $PTOFC/parallel_tut/yf17/scotch
• decomposePar
• touch processor0.OpenFOAM
• touch processor1.OpenFOAM
• touch processor2.OpenFOAM
• touch processor3.OpenFOAM
• If you want to change the number of partitions, feel free to modify the
decomposeParDict dictionary.
Module'5')'Lecture'16' 38'
Running in parallel
• Let us post-process each decomposed domain individually. From now on
follow me.
• cp processor0.OpenFOAM processor0
• cp processor1.OpenFOAM processor1
• cp processor2.OpenFOAM processor2
• cp processor3.OpenFOAM processor3
• paraFoam
(Do not forget to open each of the processorN.OpenFOAM files)
Module'5')'Lecture'16' 39'
Running in parallel
• In paraFoam open each *.OpenFOAM file within the processorN
directory.
• By doing this, we are opening the mesh partition for each processor.
• Now, choose a different color for each set you just opened, and visualize the
partition for each processor. You will need to play with transparency and
volume rendering to see the cell distribution among the processors.
• If you partitioned the mesh with many processors, creating the files
*.OpenFOAM manually can be extremely time consuming, for doing this in
an automatic way you can create a small shell or Python script.
• Also, changing the color for each set in paraFoam can be extremely time
consuming, for automate this you can write a Python script.
Module'5')'Lecture'16' 40'
Running in parallel
By following the instructions, you should get something like this
• Now do the same with the directory hierarchical, which contains the
hierarchical partitioning and compare both partitioning methods.
Module'5')'Lecture'16' 42'
Running in parallel
By following the instructions, you should get something like this
Module'5')'Lecture'16' 44'
Running in parallel
• By the way, if you do not want to post-process each decomposed domain
individually, you can use the option –cellDist. This option applies for all
decomposition methods. In the terminal type:
• cd $PTOFC/parallel_tut/yf17/scotch_celldist
• decomposePar -cellDist
• Then launch paraFoam and post process the case as you usually do. You
will need to play with transparency and volume rendering to see the cell
distribution among the processors.
Module'5')'Lecture'16' 45'
Running in parallel
Module'5')'Lecture'16' 46'
Running in parallel
Decomposing big meshes
• One final word, the utility decomposePar does not run in parallel. So, it is
not possible to distribute the mesh among different computing nodes to do
the partitioning in parallel.
• If you need to partition big meshes, you will need a computing node with
enough memory to handle the mesh. I have been able to decompose
meshes with up to 500.000.000 elements, but I used a computing node with
512 gigs of memory.
Module'5')'Lecture'16' 48'
Running in parallel
Do all utilities run in parallel?
• At this point you should have realized that not all solvers/utilities run in
parallel. To know what solvers/utilities do not run in parallel, in the terminal
type:
• By the way, paraFoam by default does not run in parallel. To run paraFoam in
parallel you will need to compile it with MPI support.
withMPI = true
Module'5')'Lecture'16' 50'
Running in parallel
• The syntax used to run OpenFOAM® solvers in parallel:
where mpirun is a shell script to use the mpi library, <NPROCS> is the
number of processors you want to use (same as the number of partitions),
<application/utility> is the OpenFOAM® solver or utility you want
to use, and -parallel is a flag you shall always use if you want to run in
parallel.
Module'5')'Lecture'16' 51'
Running in parallel
• For example, to run the solver icoFoam in parallel you will need to proceed
as follows:
Module'5')'Lecture'16' 52'
Running in parallel
• For example, to run the utility foamToEnsight in parallel you will need to
proceed as follows:
'
Module'5')'Lecture'16' 53'
Today’s lecture
Module'5')'Lecture'16' 54'
Running in a cluster using a job scheduler
• Running OpenFOAM® in a cluster is similar to running in a normal
workstation with shared memory.
• The only difference is that you will need to launch your job using a job
scheduler.
• Common job schedulers are:
• Terascale Open-Source Resource and Queue Manager (TORQUE).
• Simple Linux Utility for Resource Management (SLURM).
• Portable Batch System (PBS).
• Sun Grid Engine (SGE).
• Maui Cluster Scheduler.
• BlueGene LoadLeveler (LL).
• Ask your system administrator the job scheduler installed in your system.
Hereafter I will assume that you are using PBS.
Module'5')'Lecture'16' 55'
Running in a cluster using a job scheduler
• To launch a job in a cluster with PBS, you will need to write a small shell
script where you tell to the job scheduler the resources you want to use and
what you want to do.
#!/bin/bash
#
# Simple PBS batch script that reserves 16 nodes and runs a
# MPI program on 128 processors (8 processor on each node)
# The walltime is 24 hours !
#
#PBS -N openfoam_simulation //name of the job
#PBS -l nodes=16,walltime=24:00:00 //max execution time
#PBS -m abe -M joel.guerrero@unige.it //send an email as soon as the job
//is launch or terminated
mpirun –np 128 pimpleFoam -parallel > log //run parallel openfoam
The green lines are not PBS comments, they are comments inserted in this slide. PBS comments use the number
sign (#).
Module'5')'Lecture'16' 56'
Running in a cluster using a job scheduler
• To launch your job you need to use the qsub command (part of the PBS job
scheduler). The command qsub will send your job to queue.
• qsub script_name
Module'5')'Lecture'16' 57'
Running in a cluster using a job scheduler
• Finally, remember to plan how you will use the resources available.
• For example, if each computing node has 8 gigs of memory available and 8
cores. You will need to distribute the work load in order not to exceed the
maximum resources available per computing node.
Module'5')'Lecture'16' 58'
Running in a cluster using a job scheduler
• So if you are running a simulation that requires 32 gigs of memory, the
following options are valid:
• Use 4 computing nodes and ask for 32 cores. Each node will use 8 gigs
of memory and 8 cores.
• Use 8 computing nodes and ask for 32 cores. Each node will use 4 gigs
of memory and 4 cores.
• Use 8 computing nodes and ask for 64 cores. Each node will use 4 gigs
of memory and 8 cores.
NOTE: In this example each computing node has 8 gigs of memory available and 8 cores. !
Module'5')'Lecture'16' 59'
Running in parallel
Additional tutorials
In the directory $PTOFC/parallel_tut you will find many tutorials, try to go through
each one to understand how to setup a parallel case in OpenFOAM®.
Module'5')'Lecture'16' 60'
Module 6
Module'6')'Lecture'17' 1'
Today’s lecture
Module'6')'Lecture'17' 2'
Finite Volume Method: A Crash introduction
Before continuing,
I want to remind you that this
is not a FVM/CFD course'
Module'6')'Lecture'17' 3'
Finite Volume Method: A Crash introduction
Theoretical background
Module'6')'Lecture'17' 4'
Finite Volume Method: A Crash introduction
• Let us use the general transport equation as the starting point to explain the FVM,
Z Z Z Z
⇤ ⇥
dV + ⇥ · ( u⇥) dV ⇥·( ⇥⇥) dV = S (⇥) dV
VP ⇤t
| {z } VP | {z } VP | {z } VP | {z }
convective term diffusion term source term
temporal derivative
• We want to solve the general transport equation for the transported quantity in a
given domain, with given boundary conditions and initial conditions.
• This is a second order equation. For good accuracy, it is necessary that the order of
the discretization is equal or higher that the order of the equation that is being
discretized.
• Hereafter we are going to assume that the discretization practice is at least second
order accurate in space and time.
Module'6')'Lecture'17' 5'
Finite Volume Method: A Crash introduction
• Let us use the general transport equation as the starting point to explain the FVM,
Z Z Z Z
⇤ ⇥
dV + ⇥ · ( u⇥) dV ⇥·( ⇥⇥) dV = S (⇥) dV
VP ⇤t
| {z } VP | {z } VP | {z } VP | {z }
convective term diffusion term source term
temporal derivative
• Hereafter we are going to assume that the discretization practice is at least second
order accurate in space and time.
PROFILE ASSUMPTIONS
Module'6')'Lecture'17' 6'
Finite Volume Method: A Crash introduction
• Let us divide the solution domain into arbitrary control volumes such as the one
illustrated below.
• The control volumes can be of any shape
(e.g., tetras, hexes, prisms, pyramids,
dodecahedrons, and so on).
• The only requirement is that the elements
need to be convex and the faces that
made up the control volume, need to be
planar.
• We know all the connectivity information
(P location, neighbors N’s of P, faces
Y
connectivity, vertices location and so on).
X
Z
N
X
Module'6')'Lecture'17' 7'
Z
Finite Volume Method: A Crash introduction
• Let us divide the solution domain into arbitrary control volumes such as the one
illustrated below.
X
Module'6')'Lecture'17' VP 8'
Z
Finite Volume Method: A Crash introduction
• Let us divide the solution domain into arbitrary control volumes such as the one
illustrated below.
• The control volume faces are labeled f,
which also denotes the face center.
• The face area vector Sf point outwards
from the control volume, is located at the
face centroid, is normal to the face and
has a magnitude equal to the area of the
face.
• The vector from the centroid P to the face
center f is named Pf.
Module'6')'Lecture'17' 9'
Finite Volume Method: A Crash introduction
• Let us divide the solution domain into arbitrary control volumes such as the one
illustrated below.
Module'6')'Lecture'17' 10'
Finite Volume Method: A Crash introduction
• Let us divide the solution domain into arbitrary control volumes such as the one
illustrated below.
Module'6')'Lecture'17' 11'
Finite Volume Method: A Crash introduction
Summarizing:
• The control volume has a volume V and is constructed around point P, which is
the centroid of the control volume. Therefore the notation .
• The vector from the centroid P of to the centroid N of VN is named d.
• The control volume faces are labeled f, which also denotes the face center.
• The location where the vector d intersects a face is fi .
• The face area vector Sf point outwards from the control volume, is located at the
face centroid, is normal to the face and has a magnitude equal to the area of the face.
• The vector from the centroid P to the face center f is named Pf.
Module'6')'Lecture'17' 12'
Finite Volume Method: A Crash introduction
• In the control volume illustrated, the centroid P is given by
Z
(x xP ) dV = 0
VP
Module'6')'Lecture'17' 13'
Finite Volume Method: A Crash introduction
• Finally, we assume that the values of all variables are computed and stored in
the centroid of the control volume and that they are represented by a
piecewise constant profile (the mean value),
Z
1
P = = (x)dV
VP VP
Module'6')'Lecture'17' 14'
Finite Volume Method: A Crash introduction
• Let us integrate the general transport equation in space over arbitrary control
volumes, this yields to
Z Z Z Z
⇤ ⇥
dV + ⇥ · ( u⇥) dV ⇥·( ⇥⇥) dV = S (⇥) dV
VP ⇤t
| {z } VP | {z } VP | {z } VP | {z }
convective term diffusion term source term
temporal derivative
• Notice that
ndS = dS
Module'6')'Lecture'17' 15'
Finite Volume Method: A Crash introduction
• Let us integrate the general transport equation in space over arbitrary control
volumes, this yields to
Z Z Z Z
⇤ ⇥
dV + ⇥ · ( u⇥) dV ⇥·( ⇥⇥) dV = S (⇥) dV
VP ⇤t
| {z } VP | {z } VP | {z } VP | {z }
convective term diffusion term source term
temporal derivative
• Hereafter, we use the Gauss's theorem to convert the volume integrals into surface
integrals,
Z I I Z
⇤
( ⇥) dV + dS · ( u⇥) dS · ( ⇥⇥) = S (⇥) dV
⇤t VP ⇥VP | {z } ⇥VP | {z } VP
convective flux diffusive flux
Z I
• Recall the Gauss’s theorem · adV = dS · a
V Module'6')'Lecture'17'
V 16'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 17'
Finite Volume Method: A Crash introduction
• Integrating in space each term of the general transport equation and by using
Gauss’s theorem, yields to the following discrete equations for each term
Convective term:
(
where we have approximated the integrant
By using Gauss’s theorem we convert by means of the mid point rule, which is
volume integrals into surface integrals second order accurate
Gauss’s theorem:
Z I
· adV = dS · a
V V
Module'6')'Lecture'17' 18'
Finite Volume Method: A Crash introduction
• Integrating in space each term of the general transport equation and by using
Gauss’s theorem, yields to the following discrete equations for each term
Diffusive term:
(
where we have approximated the integrant
By using Gauss’s theorem we convert by means of the mid point rule, which is
volume integrals into surface integrals second order accurate
Gauss’s theorem:
Z I
· adV = dS · a
V V
Module'6')'Lecture'17' 19'
Finite Volume Method: A Crash introduction
• Integrating in space each term of the general transport equation and by using
Gauss’s theorem, yields to the following discrete equations for each term
Source term: Z
S ( ) dV = Sc VP + Sp VP P
VP
Module'6')'Lecture'17' 20'
Finite Volume Method: A Crash introduction
• Integrating in space each term of the general transport equation and by using
Gauss’s theorem, yields to the following discrete equations for each term
Gradient term:
1 X
(r )P = (Sf f)
VP
f
Module'6')'Lecture'17' 21'
Finite Volume Method: A Crash introduction
• Integrating in space each term of the general transport equation and by using
Gauss’s theorem, yields to the following discrete equations for each term
Convective term:
Diffusive term:
Source term: Z
S ( ) dV = Sc VP + Sp VP P
VP
Gradient term:
1 X
(r )P = (Sf f)
VP
f
Module'6')'Lecture'17' 22'
Finite Volume Method: A Crash introduction
• Using the previous equations to evaluate the general transport equation over all the
control volumes, we obtain the following semi-discrete equation
Z X X
⇤ ⇥
dV + Sf · ( u⇥)f Sf · ( ⇥⇥)f = (Sc VP + Sp VP ⇥P )
VP ⇤t
| {z } f | {z } f | {z } | {z }
convective flux difussive flux source term
temporal derivative
C
where S · (⇢u ) = F is the convective flux and S · (⇢ r ) = F D is the
diffusive flux.
• Recalling that all variables are computed and stored at the centroid of the control
volumes.
• The face values appearing in the convective and diffusive fluxes have to be computed
by some form of interpolation from the centroid values of the control volumes at both
sides of face f.
Module'6')'Lecture'17' 23'
Finite Volume Method: A Crash introduction
Convective fluxes
Module'6')'Lecture'17' 24'
Finite Volume Method: A Crash introduction
• By looking the figure below, the face values appearing in the convective flux can be
computed as follows,
fN
ff
fP
d
P f N
A B
fN ff fN
F F
fP ff fP
d d
P f N P f N
(
f = P for F̊ 0,
f =
f = N for F̊ < 0.
• This type of interpolation scheme is known as upwind differencing and it is first order
accurate.
• This scheme is bounded and diffusive.
Module'6')'Lecture'17' 26'
Finite Volume Method: A Crash introduction
• By looking the figure below, the face values appearing in the convective flux can be
computed as follows,
A F B F
fN fP
ff ff
fP fN
fPP fNN
duu du dd dd du duu
PP ff P f N P f N ff NN
8 1 2 1
>
> + ( PP ) = for F 0,
< P
2
P
3
P
2
PP
f =
>
> 1 2 1
: + (
N N NN ) = N NN for F < 0.
2 3 2
• This type of interpolation scheme is known as second order upwind differencing
(SOU), linear upwind differencing (LUD) or Beam-Warming (BW), and it is second
order accurate.
• For highly convective flows or in the presence of strong gradients, this scheme is
Module'6')'Lecture'17' 27'
oscillatory (unbounded).
Finite Volume Method: A Crash introduction
• To prevent oscillations in the SOU, we add a gradient or slope limiter function (r).
8 1
> +
>
< P P( P PP ) for F 0,
2
f =
>
> 1
: +
N P ( NN N) for F < 0.
2
• When the limiter detects strong gradients or changes in slope, it switches to low
resolution (upwind).
• The concept of the limiter function (r) is based on monitoring the ratio of
successive gradients, e.g.,
N P P N
rP = and rP+ =
P PP N NN
• By adding a well designed limiter function (r) , we get a high resolution (second
order accurate), and bounded scheme. This is a TVD scheme.
• More on TVD schemes on the nextModule'6')'Lecture'17'
slides. 28'
Finite Volume Method: A Crash introduction
TVD Schemes
Module'6')'Lecture'17' 29'
Finite Volume Method: A Crash introduction
• A TVD scheme, is a scheme that does not create new local undershoots and/or
overshoots in the solution or amplify existing extremes.
• In CFD we want stable, non-oscillatory, bounded, high order schemes. We want high
resolution schemes, in other words, TVD and second order accurate schemes.
• The Sweby diagram (Sweby, 1984), gives the necessary and sufficient conditions for
a scheme to be TVD. In the figure, the grey area represents the admissible TVD
region. However, not all limiter functions are second order.
8 1
> +
>
< P P( P PP ) for F 0,
2
(r) = 2r (D) (r) = r (CD) f =
>
>
: 1 +
N P ( NN N) for F < 0.
2
3
2 (r) = 2
1 (r) = 1 (SOU )
(r) = 0 (U D)
0 1 2 3
Module'6')'Lecture'17' TVD REGION 30'
r
Finite Volume Method: A Crash introduction
• Not all TVD schemes are high resolution.
• The choice of the limiter function (r) dictates the order of the scheme and its
boundedness.
• High resolution schemes falls in the blue area. Conversely, low resolution schemes
falls in the grey area.
• The development of high resolution schemes is one of the most remarkable
achievements of the history of CFD.
(r) = 2r (D) (r) = r (CD)
2 (r) = 2
1 (r) = 1 (SOU )
(r) = 0 (U D)
0 1 2 3
Module'6')'Lecture'17'
TVD - HIGH RESOLUTION REGION 31'
r TVD - LOW RESOLUTION REGION
Finite Volume Method: A Crash introduction
• The drawback of the limiters is that they reduce the accuracy of the scheme locally to
first order (low resolution scheme), when r 0 (sharp gradient, opposite slopes or
zero gradient). However, this is justify when it serves to suppress oscillations.
• The various limiters have different switching characteristics and are selected
according to the particular problem and solution scheme.
• No particular limiter has been found to work well for all problems, and a particular
choice is usually made on a trial and error basis.
2 SUPERBEE (r) = 2
VANLEER
(r) = 0 (U D)
0 1 2 3
Module'6')'Lecture'17'
TVD - HIGH RESOLUTION REGION 32'
r
Finite Volume Method: A Crash introduction
• Let us see how the superbee, minmod and vanleer TVD schemes behave in a
numerical schemes killer test case.
• The oblique double step profile in a uniform vector field (pure convection).
• By the way, this problem has an exact solution.
Module'6')'Lecture'17' 33'
Finite Volume Method: A Crash introduction
• Let us see how the superbee, minmod and vanleer TVD schemes behave in a
numerical schemes killer test case.
• The oblique double step profile in a uniform vector field (pure convection).
Module'6')'Lecture'17' 34'
Finite Volume Method: A Crash introduction
• Comparison of the TVD-minmod method (2nd order) and upwind method (1st order).
• The upwind method is extremely stable and non-oscillatory.
• On the other hand, the upwind method is highly diffusive.
Module'6')'Lecture'17' 35'
Finite Volume Method: A Crash introduction
• Let us see how the non-linear limiter functions compare.
Module'6')'Lecture'17' 36'
Finite Volume Method: A Crash introduction
• Let us see how the linear limiter functions compare.
Module'6')'Lecture'17' 37'
Finite Volume Method: A Crash introduction
• Let us see how the linear and non-linear limiter functions compare.
Module'6')'Lecture'17' 38'
Finite Volume Method: A Crash introduction
$PTOFC/my_cases0/oblique_step/c2/d2
Module'6')'Lecture'17' 39'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 40'
Finite Volume Method: A Crash introduction
• In the case of a skew mesh (as the one in the figure), we should introduce a
correction in order to maintain second order accuracy and avoid unboundedness,
1. f = fi + i ·( ) fi
f S 2. fi = fx P + (1 fx ) N
P
Di
d fi r fi = fx r P + (1 fx ) r N
N
fi N | xfi xN |
fx = = .
PN |d|
1 X 1 X h i
3. ( )P = Sf f = Sf fi + i ·( ) fi
VP VP
f f
( N P)
⇥ fi = Initial approximation of the face gradient
|d|
Module'6')'Lecture'17' 41'
Finite Volume Method: A Crash introduction
• In the case of a skew mesh (as the one in the figure), we should introduce a
correction in order to maintain second order accuracy and avoid unboundedness,
1 X
1. (r )P = (Sf f)
VP
f
D Pf
f
S ( P + Pf · P) +( N + Nf · N)
P D Nf
2. f =
2
d
N
3. (r )f = fx (r )P + (1 fx ) (r )N
( P + N) (r P +r N)
f = and r f = are the initial approximations
2 2
Module'6')'Lecture'17' 42'
Finite Volume Method: A Crash introduction
Diffusive fluxes
Module'6')'Lecture'17' 43'
Finite Volume Method: A Crash introduction
• By looking the figures below, the face values appearing in the diffusive flux in an
orthogonal mesh can be computed as follows,
S
d S d
P f N P f N
Orthogonal mesh
N P
S · (⇥ )f = |S| .
|d|
• This is a central difference approximation of the first order derivative. This type of
approximation is second order accurate.
Module'6')'Lecture'17' 44'
Finite Volume Method: A Crash introduction
• By looking the figures below, the face values appearing in the diffusive flux in a non-
orthogonal mesh ( 20 ) can be computed as follows,
S
d S d
P f N P f N
Non-orthogonal mesh
N P
S · (⇥ )f = | ?| + k · (⇥ )f .
|d| | {z }
| {z } non-orthogonal contribution
orthogonal contribution
• This type of approximation is second order accurate but involves a larger truncation
error. It also uses a larger numerical stencil, which make it less stable.
Module'6')'Lecture'17' 45'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 46'
Finite Volume Method: A Crash introduction
• By looking the figures below, the face values appearing in the diffusive flux in a non-
orthogonal mesh ( 40 ) can be computed as follows,
S S k
k
d d
P f D N P f D N
d·S d
? = d. ? = |S|2 .
d·d d·S
S= ? + k.
N P
S · (⇥ )f = | ?| + k · (⇥ )f .
|d| | {z }
| {z } non-orthogonal contribution
orthogonal contribution
Module'6')'Lecture'17' 47'
Finite Volume Method: A Crash introduction
• The face gradient of the non-orthogonal contribution is computed by using linear
interpolation from the gradient of the control volumes centroid, computed using Gauss
theorem.
N P
S · (⇥ )f = | ?| + k · (⇥ )f .
|d| | {z }
| {z } non-orthogonal contribution
orthogonal contribution
S
d
P f N
(r )f = fx (r )P + (1 fx ) (r )N where
Module'6')'Lecture'17' 48'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 49'
Finite Volume Method: A Crash introduction
• Mesh induced errors. In order to maintain second order accuracy, and to avoid
unboundedness, we need to correct non-orthogonality and skewness errors.
S
d S d
P f N P f N
Orthogonal and non skew mesh Non-orthogonal and non skew mesh
f S f S
P Di Di
P d N
d fi fi
N
Orthogonal and skew mesh Module'6')'Lecture'17' Non-orthogonal and skew mesh 50'
Finite Volume Method: A Crash introduction
Temporal discretization
Module'6')'Lecture'17' 51'
Finite Volume Method: A Crash introduction
• Using the previous equations to evaluate the general transport equation over all the
control volumes, we obtain the following semi-discrete equation
Z X X
⇤ ⇥
dV + Sf · ( u⇥)f Sf · ( ⇥⇥)f = (Sc VP + Sp VP ⇥P )
VP ⇤t
| {z } f | {z } f | {z } | {z }
convective flux difussive flux source term
temporal derivative
C
where S · (⇢u ) = F is the convective flux and S · (⇢ r ) = F D is the
diffusive flux.
• The main advantage of the MOL method, is that it allows us to select numerical
approximations of different accuracy for the spatial and temporal terms. Each term
can be treated differently to yield to different accuracies.
Module'6')'Lecture'17' 52'
Finite Volume Method: A Crash introduction
• Now, we evaluate in time the semi-discrete general transport equation
2 3
Z t+ t ✓ ◆ X X
4 ⇤ ⇥ VP + Sf · ( u⇥)f Sf · ( ⇥⇥)f 5 dt
t ⇤t P f f
Z t+ t
= (Sc VP + Sp VP ⇥P ) dt.
t
• At this stage, we can use any time discretization scheme, e.g., Crank-Nicolson, euler
implicit, forward euler, backward differencing, adams-bashforth, adams-moulton.
• It should be noted that the order of the temporal discretization of the transient term
does not need to be the same as the order of the discretization of the spatial terms.
Each term can be treated differently to yield different accuracies. As long as the
individual terms are at least second order accurate, the overall accuracy will also be
second order.
Module'6')'Lecture'17' 53'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 54'
Finite Volume Method: A Crash introduction
• After spatial and temporal discretization and by using equation
2 3
Z t+ t ✓ ◆ X X
4 ⇤ ⇥ VP + Sf · ( u⇥)f Sf · ( ⇥⇥)f 5 dt
t ⇤t P f f
Z t+ t
= (Sc VP + Sp VP ⇥P ) dt.
t
in every control volume of the domain, a system of linear algebraic equations for
the transported quantity is assembled
0 1 0 1 0 1
..
a11 a12 .
B C B C B C
B .. C B C B C
B a21 a22 a23 . C B C B C
B C B C B C
B .. .. .. .. C B C B C
B . . . . C B S C B bS C
B C B C B C
B .. .. .. .. .. C B C B C
B . . . . . C B C=B C
B C⇥B W C B bW C
B aS aW aP aE aN C
B C B C B bP C
C B C B C
P
B .. .. .. ..
B . . . . C B C B bE C
C B C B C
E
B B C B C
B .. .. .. .. C B C B C
B . . . . C
@ A @ N A @ bN A
.. ..
. . aP P
Module'6')'Lecture'17' 55'
and which can be solved by using any iterative or direct method.
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 56'
Finite Volume Method: A Crash introduction
So, what does OpenFOAM® do?
Module'6')'Lecture'17' 57'
Finite Volume Method: A Crash introduction
So, what does OpenFOAM® do?
Therefore, we need to give to OpenFOAM® the following information:
Module'6')'Lecture'17' 59'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 60'
Finite Volume Method: A Crash introduction
$PTOFC/my_cases0/pureconvection/c1
Module'6')'Lecture'17' 61'
Finite Volume Method: A Crash introduction
• Pure convection of a scalar in a vector field in a one dimensional tube.
Module'6')'Lecture'17' 62'
Finite Volume Method: A Crash introduction
• This problem has an exact solution in the form of a traveling wave.
• In the figure, we show the solution for time = 0.5 s
Module'6')'Lecture'17' 63'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 64'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 65'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 66'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 67'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 68'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 69'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 70'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 71'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 72'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 73'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 74'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 75'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 76'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 77'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 78'
Finite Volume Method: A Crash introduction
u t
CF L =
x
Module'6')'Lecture'17' 79'
Finite Volume Method: A Crash introduction
u t
CF L =
x
Module'6')'Lecture'17' 80'
Finite Volume Method: A Crash introduction
• Accuracy
• Stability
• Boundedness
Module'6')'Lecture'17' 82'
Finite Volume Method: A Crash introduction
Module'6')'Lecture'17' 83'
Finite Volume Method: A Crash introduction
• Numerical Heat Transfer and Fluid Flow.
S. Patankar. 1980, Taylor & Francis
• An Introduction to Computational Fluid Dynamics.
H. K. Versteeg, W. Malalasekera. 2007, Prentice Hall.
• Computational Methods for Fluid Dynamics.
J. H. Ferziger, M. Peric. 2001, Springer.
• Computational Fluid Dynamics: Principles and Applications.
J. Blazek. 2006, Elsevier Science.
• Computational Techniques for Multiphase Flows
G. H. Yeoh, J. Tu. 2009, Butterworth-Heinemann
• Turbulence Modeling for CFD
D. Wilcox. 2006, DCW Industries.
• A Finite Volume Method for the Prediction of Three-Dimensional Fluid Flow in Complex
Ducts.
M. Peric. PhD Thesis. 1985. Imperial College, London.
• Error analysis and estimation in the Finite Volume method with applications to fluid
flows.
H. Jasak. PhD Thesis. 1996. Imperial College, London.
• Computational fluid dynamics of dispersed two-phase flows at high phase fractions
H. Rusche. PhD Thesis. 2002. ImperialModule'6')'Lecture'17'
College, London. 84'
Module 6
Module'6')'Lecture'18' 1'
Today’s lecture
Module'6')'Lecture'18' 2'
Boundary conditions and initial conditions
• First at all, when we use OpenFOAM® to find the approximate solution of
the governing equations, we are solving an Initial Boundary Value Problem
(IBVP).
• No need to say that the boundary conditions and initial conditions need to be
physically realistic.
Module'6')'Lecture'18' 3'
Boundary conditions and initial conditions
Module'6')'Lecture'18' 4'
Boundary conditions and initial conditions
• Boundary conditions can be divided into three fundamental or
mathematical types:
• By the way, during this discussion the semantics is not important, that
depends of how you want to call the boundary conditions or how they are
named in the solver, i.e.,
Module'6')'Lecture'18' 6'
Boundary conditions and initial conditions
• Defining boundary conditions involves:
• Geometrical considerations.
• Physics involved.
• Numerical considerations.
Module'6')'Lecture'18' 7'
Boundary conditions and initial conditions
• To define boundary conditions you need to know the location of the
boundaries (where they are in your mesh), and supply the information at the
boundaries.
• You must know what information is required at the boundaries, you must
know the physics involved.
BC
BC BC
Y BC
X Module'6')'Lecture'18' 8'
Boundary conditions and initial conditions
Module'6')'Lecture'18' 9'
Boundary conditions and initial conditions
• Initial conditions can be divided into two groups:
• For non-uniform initial conditions, the value used can be obtained from:
• A potential solver.
• Experimental results.
• A mathematical function
• Geometrical considerations.
• Physics involved.
• Information available.
• Numerical considerations.
Module'6')'Lecture'18' 11'
Boundary conditions and initial conditions
• For initial conditions, you need to supply the initial information or initial state
of your problem.
• This information can be a uniform value or a non-uniform value.
• You can apply the initial conditions to the whole domain or zones of the
domain (patches).
BC
BC BC
Y BC
X Module'6')'Lecture'18' 12'
Boundary conditions and initial conditions
Module'6')'Lecture'18' 13'
Boundary conditions and initial conditions
• Remember:
• For incompressible, and laminar flows you will need to set only the
velocity and pressure.
• If you are solving a turbulent compressible flow you will need to set
velocity, pressure, temperature and the turbulent variables.
• For multiphase flows you will need to set the primitives variables for
each phase. You might also need to initialize the phases patches.
Module'6')'Lecture'18' 16'
Boundary conditions and initial conditions
• General guidelines when choosing the boundary conditions and initial
conditions:
• Do not force the flow at the outlet, use a zero normal gradient for all
flow variables except pressure. The solver extrapolates the required
information from the interior.
• Be careful with backward flow at the outlets (flow coming back to the
domain) and backward flow at inlets (reflection waves), they
required special treatment.
Module'6')'Lecture'18' 17'
Boundary conditions and initial conditions
• General guidelines when choosing the boundary conditions and initial
conditions:
• Inlets that take flow into the domain from the atmosphere can use a
total pressure boundary condition (e.g. open window).
Module'6')'Lecture'18' 18'
Boundary conditions and initial conditions
• General guidelines when choosing the boundary conditions and initial
conditions:
Module'6')'Lecture'18' 19'
Boundary conditions and initial conditions
• Inlets and outlets boundary conditions:
• Inlets are for regions where inflow is expected; however, inlets might support outflow
when a velocity profile is specified.
• Pressure boundary conditions do not allow outflow at the inlets.
• Velocity specified inlets are intended for incompressible flows.
• Pressure and mass flow inlets are suitable for compressible and incompressible
flows.
• Same concepts apply to outlets, which are regions where outflow is expected.
Outlet Outlet
No-slip wall No-slip wall
Module'6')'Lecture'18' 20'
Boundary conditions and initial conditions
• Zero gradient and backflow boundary conditions:
• Zero gradient boundary conditions extrapolates the values from the domain. They
require no information.
Slip wall or symmetry
• Zero gradient boundary conditions canPressure
be
Mass used at inlets and outlets.
or
flow Inlet
Inlet Inlet
Module'6')'Lecture'18' 21'
Boundary conditions and initial conditions
• Symmetry boundary conditions:
• I do not like to use symmetry boundary conditions. They are a big simplification of
the problem, specially if you are dealing with turbulence.
• However, they help to reduce mesh dimension and they speed-up the computations.
• Have in mind that symmetry boundary conditions only apply to planar faces.
• To use symmetry boundary conditions, both the geometry and the flow field must be
symmetric.
• Mathematically speaking, setting a symmetry boundary condition is equivalent to:
• Zero normal velocity at the symmetry plane.
• Zero normal gradients of all variables at symmetry plane.
NO-SLIP WALLS
SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW
Y Y
X Z
5L
5L 15L 5L
Y 5L Y
X Z
Z
Module'6')'Lecture'18' 23'
Boundary conditions and initial conditions
• Location of the outlet boundary condition:
• Place outlet boundary conditions as far as possible from recirculation zones or
backflow conditions, by doing this you increase the stability.
• Remember, backflow conditions requires special treatment.
Y Y
X
X Z
Module'6')'Lecture'18' 24'
Boundary conditions and initial conditions
Module'6')'Lecture'18' 25'
Boundary conditions and initial conditions
• OpenFOAM® distinguish between base type boundary conditions and
numerical type boundary conditions.
• Base type. This boundary condition is based on geometry information
or an inter-processor communication link (halo boundaries).
• Numerical type. This boundary condition assigns the value to the field
variables in the given patch. It can be of primitive type or derived type.
• Some base type and numerical type boundary conditions are paired. That
is, you define the same type for the base type and the numerical type.
Module'6')'Lecture'18' 26'
Boundary conditions and initial conditions
• OpenFOAM® distinguish between base type boundary conditions and
numerical type boundary conditions.
Unpaired Paired
symmetry
empty
patch
Base type wedge
wall
cyclic
processor
fixedValue
fixedGradient
zeroGradient
symmetry
fixedFluxPressure empty
Numerical type inletOutlet wedge
totalPressure cyclic
processor
uniformFixedValue
Module'6')'Lecture'18' 27'
and so on …
Boundary conditions and initial conditions
• Base type boundary conditions are defined in the file boundary located in
the directory constant/polyMesh
• The file boundary is automatically created when you generate or convert
the mesh.
• When you convert a mesh to OpenFOAM® format, you might need to
manually modify the file boundary. This is because the conversion utilities
do not recognize the boundary type of the original mesh.
• Remember, if a base type boundary condition is missing, OpenFOAM® will
complain and will tell you where and what is the error.
• Also, if you misspelled something OpenFOAM® will complain and will tell
you where and what is the error.
Module'6')'Lecture'18' 28'
Boundary conditions and initial conditions
• Numerical type boundary conditions are defined in the field variables
dictionaries located in the directory 0 (e.g. U, p).
• When we talk about numerical type boundary conditions we are referring to
Dirichlet, Neumann or Robin boundary conditions.
• In OpenFOAM®, numerical type boundary conditions can be of primitive or
derived type.
• You need to manually create the field variables dictionaries (e.g. 0/U, 0/p).
I hope you know how to do it, because we have done it.
• Remember, if you forget to define a boundary condition, OpenFOAM® will
complain and will tell you where and what is the error.
• Also, if you misspelled something OpenFOAM® will complain and will tell
you where and what is the error.
Module'6')'Lecture'18' 29'
Boundary conditions and initial conditions
• The name of the base type boundary condition and the name of the
numerical type boundary condition needs to be the same, if not,
OpenFOAM® will complain.
• Pay attention to this, specially if you are converting the mesh from another
format.
symmetry symmetry
symmetryPlane symmetryPlane
empty empty
wedge wedge
cyclic cyclic
processor processor
Module'6')'Lecture'18' 31'
Boundary conditions and initial conditions
• The following numerical type boundary conditions can be any of the
primitive or derived type available in OpenFOAM®. Mathematically
speaking; they can be Dirichlet, Neumann or Robin boundary conditions.
fixedValue
fixedGradient
zeroGradient
fixedFluxPressure
inletOutlet
patch freeStream
slip
totalPressure
uniformFixedValue
Module'6')'Lecture'18'
and so on … 32'
Boundary conditions and initial conditions
• The wall base type boundary condition is defined as follows:
type fixedValue;
wall zeroGradient
value uniform (0 0 0);
• This boundary condition is not contained in the patch base type boundary
condition group, because specialize modeling options can be used on this
boundary condition.
• An example is turbulence modeling, where turbulence can be generated or
dissipated at the walls.
Module'6')'Lecture'18' 33'
Boundary conditions and initial conditions
• There are numerous primitive and derived type boundary conditions
implemented in OpenFOAM®.
• You can find the source code of the numerical boundary conditions in the
following directory:
• $FOAM_SRC/finiteVolume/fields
• The wall boundary conditions for the turbulence models (wall functions), are
located in the following directory:
• $FOAM_SRC/turbulenceModels/
Module'6')'Lecture'18' 34'
Boundary conditions and initial conditions
• To get more information about all the boundary conditions available in
OpenFOAM® you can read the Doxygen documentation, just look for the
Using the code section at the bottom of the page.
• If you did not compile the Doxygen documentation, you can access the
information online, http://www.openfoam.org/docs/cpp/
Module'6')'Lecture'18' 35'
Boundary conditions and initial conditions
Module'6')'Lecture'18' 36'
Boundary conditions and initial conditions
• Boundary conditions setup:
At inflow: At outflow: At no-slip wall: At symmetry plane: At slip walls:
U = fixed value U = back flow U =0 U = symmetry U = slip
p = zero gradient p = fixed value p = zero gradient p = symmetry p = slip
T = fixed value T = back flow T = zero gradient T = symmetry T = slip
= fixed value = back flow = zero gradient or fixed value = symmetry = slip
! = fixed value ! = back flow ! = zero gradient or fixed value ! = symmetry ! = slip
NO-SLIP WALLS
SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW
Y Y
X Z
SYMMETRY SYMMETRY
NO-SLIP WALLS
SYMMETRY
OUTFLOW
SYMMETRY
INFLOW
Y Y
X Z
NO-SLIP WALLS
SYMMETRY
OUTFLOW
SYMMETRY
INFLOW
Y Y
X Z
OUTFLOW OUTFLOW
NO-SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW
OUTFLOW
Y Y
X Z
SYMMETRY SYMMETRY
NO-SLIP WALLS
SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW
Y Y
X Z
NO-SLIP WALLS
SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW
Y Y
X Z
PERIODIC
INFLOW
PERIODIC
Y Y
X Z
• Do not worry we are going to address the boundary conditions needed for
turbulence modeling later on.
Module'6')'Lecture'18' 44'
Boundary conditions and initial conditions
• All the previous boundary conditions setup will generate a well posed
problem.
Module'6')'Lecture'18' 45'
Boundary conditions and initial conditions
• And some configurations are unreliable.
• Inlet velocity, mass flow or total pressure at inlet and zero gradient at
outlet. These combinations should be avoided because the static
pressure level is not fixed.
• Velocity at outlet. Unless the flow is fully developed, you will be
forcing the flow to an unrealistic condition.
• Zero gradients at inlet and outlet, this will result in an ill-posed
problem.
• Velocity at inlet and outlet. The configuration is unstable.
Module'6')'Lecture'18' 46'
Boundary conditions and initial conditions
• And some configurations are unreliable.
Module'6')'Lecture'18' 47'
Boundary conditions and initial conditions
• And some configurations are unreliable.
Residual plot for pressure Quantity of interest – Force coefficient on the body
Module'6')'Lecture'18' 48'
Boundary conditions and initial conditions
A mental exercise
Module'6')'Lecture'18' 49'
Boundary conditions and initial conditions
• Let us do a mental exercise.
• What boundary conditions will you use for this case?
• By the way, there is no wrong or right answer (maybe there are a few bad
choices), everything depends of what do you want to do.
BC
BC BC
Y BC
Module'6')'Lecture'18' 50'
Boundary conditions and initial conditions
• One of the possible scenarios, external aerodynamics.
Uniform flow
No-slip wall
Module'6')'Lecture'18' 51'
Boundary conditions and initial conditions
• Another possible scenarios, buoyant flow and a heated body.
Outlet value
Uniform flow
X Module'6')'Lecture'18'
Wall temperature 52'
Boundary conditions and initial conditions
• For those interested in marine applications, a virtual towing tank and 1DOF
simulation.
Outlet value
Phase 1
Phase 2
Y Slip wall
Module'6')'Lecture'18' 53'
Boundary conditions and initial conditions
• And if you go to the real world (3D), nothing change. You just need to
impose the boundary conditions in the third dimension.
Symmetry Symmetry
No-slip walls
Outlet value
Inlet value
Periodic
Periodic
Uniform flow Y Uniform flow Y
X Z
Symmetry Symmetry
Periodic
Outlet value
Inlet value
Y
Periodic
Module'6')'Lecture'18' 54'
X
Z
Module 6
Module'6')'Lecture'19' 1'
Today’s lecture
Module'6')'Lecture'19' 2'
Today’s lecture
Module'6')'Lecture'19' 3'
Unsteady and steady simulations
• Nearly all flows in nature and industrial applications are unsteady (or
transient).
• If you are dealing with turbulence (almost every scenario), you need to take
into account the unsteadiness inherent of turbulent flows.
• Unsteadiness is due to:
• Instabilities.
• Non-equilibrium initial conditions.
• Time-dependent boundary conditions.
• Source terms.
• Moving or deforming bodies.
• Turbulence.
• Buoyancy.
• Convection, and so on.
Module'6')'Lecture'19' 4'
Unsteady and steady simulations
• A few examples of unsteady applications:
• Internal and external aerodynamics.
• Shock wake interaction.
• Hydrodynamics, sea keeping, free surface, waves.
• Multiphase flows.
• Turbomachinery.
• Moving and deforming bodies.
• Fluid-structure interaction.
• Vortex-induced vibrations.
• Unsteady heat transfer.
• HVAC.
Module'6')'Lecture'19' 5'
Unsteady and steady simulations
• A few examples of unsteady applications:
Vortex shedding
Module'6')'Lecture'19' 6'
Unsteady and steady simulations
• A few examples of unsteady applications:
Buoyant flow
Module'6')'Lecture'19' 7'
Unsteady and steady simulations
• A few examples of unsteady applications:
Multiphase flow
Module'6')'Lecture'19' 8'
Unsteady and steady simulations
• A few examples of unsteady applications:
Turbulent flow
Module'6')'Lecture'19' 9'
Unsteady and steady simulations
• A few examples of unsteady applications:
Flapping UAV
Module'6')'Lecture'19' 10'
Unsteady and steady simulations
• A few examples of unsteady applications:
• Select the time step. The time-step must be chosen in such a way that it
resolves the time-dependent features and maintains solver stability.
• Select the temporal discretization scheme.
• Set the tolerance (absolute and/or relative) of the linear solvers.
• If it applies, monitor the CFL condition.
• Monitor the stability and boundedness of the solution.
• Monitor a quantity of interest.
• And of course, you need to save the solution with a given frequency.
• Have in mind that unsteady simulations generate a lot of data.
• End time of the simulation?, it is up to you.
Module'6')'Lecture'19' 13'
Unsteady and steady simulations
How to run unsteady simulations in OpenFOAM®?
Module'6')'Lecture'19' 14'
Unsteady and steady simulations
What about steady simulations?
Module'6')'Lecture'19' 15'
Unsteady and steady simulations
What about steady simulations?
Module'6')'Lecture'19' 16'
Unsteady and steady simulations
What about steady simulations?
n n 1 n⇤ n 1
P = P + ↵( P P )
• If < 1 means that we are using under-relaxation.
Module'6')'Lecture'19' 17'
Unsteady and steady simulations
What about steady simulations?
• If you do not set the under-relaxation factors, OpenFOAM® will use the
default hard-wired values (1.0 for all field variables).
• These are the under-relaxation factors I often use (which are the commonly
used).
relaxationFactors
{
p 0.3;
U 0.7;
k 0.7;
omega 0.7;
}
• According to the physics involved you will need to add more under-relaxation
Module'6')'Lecture'19' 18'
factors.
Unsteady and steady simulations
What about steady simulations?
relaxationFactors
0 1
Velocity
Stability
Module'6')'Lecture'19' 21'
Unsteady and steady simulations
• Remember, when running unsteady simulations the time-step must be
chosen in such a way that it resolves the time-dependent features and
maintains solver stability.
Module'6')'Lecture'19' 22'
Unsteady and steady simulations
• When running unsteady simulations, it is highly advisable to monitor a
quantity of interest.
• The quantity of interest can fluctuate in time, this is an indication of
unsteadiness.
Module'6')'Lecture'19' 23'
Unsteady and steady simulations
• Remember to choose wisely where to do the sampling.
sampling
Module'6')'Lecture'19' 24'
Unsteady and steady simulations
• Remember to choose wisely where to do the sampling.
Module'6')'Lecture'19' 25'
Unsteady and steady simulations
• When you run unsteady simulations, flow variables can stop changing with
time. When this happens, we say we have arrived to a steady state.
• Remember this is the exception rather than the rule.
• If you use a steady solver, you will arrive to the same solution (maybe not),
in less iterations.
Module'6')'Lecture'19' 26'
Unsteady and steady simulations
• Steady simulations require less computational power than unsteady
simulations.
• They are much faster than unsteady simulations.
• They are easier to post-process and analyze.
Module'6')'Lecture'19' 27'
Unsteady and steady simulations
• Steady simulations require less computational power than unsteady
simulations.
• But sometimes they do not converge to the right solution.
• You can use the solution of an unconverged steady simulation as initial
conditions for an unsteady simulation.
Module'6')'Lecture'19' 28'
Unsteady and steady simulations
• Before talking about residuals, let me clarify something.
• When I talk about iterations in unsteady simulations, I am talking about the
time-step or outer-iterations.
Module'6')'Lecture'19' 29'
Unsteady and steady simulations
• Before talking about residuals, let me clarify something.
• When I talk about iterations in unsteady simulations, I am talking about the
time-step or outer-iterations.
• And we loop inside each time-step (outer-iteration), until reaching the linear
solver tolerance or maximum number of iterations.
Module'6')'Lecture'19' 30'
Today’s lecture
Module'6')'Lecture'19' 31'
Understanding residuals
• This is the typical residual plot for an unsteady simulation.
Module'6')'Lecture'19' 32'
Understanding residuals
• This is the typical residual plot for an unsteady simulation.
• The solution must converge at every time-step.
• The first time-steps the solution might not converge, this is acceptable.
• Also, you might need to use a smaller time-step during the first iterations to
maintain solver stability.
• If the solution is not converging, try to reduce the time-step size.
• You can also increase the number of maximum inner iterations.
• If the initials residuals fall bellow the convergence criterion, you might say
that you have arrived to a steady solution.
Module'6')'Lecture'19' 33'
Understanding residuals
• This is the typical residual plot for an unsteady simulation.
• Remember, residuals are not a direct indication that you are converging to
the right solution.
• It is better to monitor a quantity of interest.
• And by the way, you should get physically realistic values.
• To monitor the stability, you can check the minimum and maximum values of
the field variables.
• If you have bounded quantities, check that you do not have over-shoots or
under-shoots.
Module'6')'Lecture'19' 34'
Understanding residuals
• Let us study in details the residual plot of an unsteady solution.
• Pay attention that we are plotting the residuals against iterations or
time-steps or outer-iterations.
Module'6')'Lecture'19' 35'
Understanding residuals
• Let us do the distinction between inner-iterations and outer-iterations.
• This the plot of the number on inner-iterations against the number of
outer-iterations (time-steps).
• Each time-step is converging to the given criterion (linear solvers) in n
inner-iterations.
Module'6')'Lecture'19' 36'
Understanding residuals
• This is the residual plot of an unsteady solution that reached a steady-state
behavior.
• Pay attention that we are plotting the residuals against iterations or
time-steps or outer-iterations.
Module'6')'Lecture'19' 37'
Understanding residuals
• And this the plot of the number of inner-iterations against the number of
outer-iterations (time-steps).
• Notice that after 2000 time-steps, the solution arrives to the convergence
criterion (in the linear solvers) in just 1 iteration.
Module'6')'Lecture'19' 38'
Understanding residuals
• Let us study the residual plot of a steady solver.
• Notice that I am making the distinction between steady solver and unsteady
solution.
• Here the initial residuals are not falling. This is an indication of an unsteady
solution.
Module'6')'Lecture'19' 39'
Understanding residuals
• Let us study the residual plot of a steady solver.
• In this case initial residuals are falling below the convergence criterion,
hence we have reached a steady-state.
• In comparison to unsteady solvers, steady solvers require less iterations to
arrive to a converge solution, if they arrived.
Module'6')'Lecture'19' 40'
Understanding residuals
• Let us compare the solution of a steady solver and the solution of a
unsteady solver.
• In comparison to unsteady solvers, steady solvers require less iterations to
arrive to a converge solution, if they arrived.
Module'6')'Lecture'19' 41'
Understanding residuals
• Finally, let us compare the residuals of a first order and a second order
numerical scheme.
• This is the residual plot of an unsteady simulation and the final residuals of
both methods are converging to the desired tolerance.
Module'6')'Lecture'19' 42'
Understanding residuals
• This is the plot of the number of inner-iterations against the number of outer-
iterations (time-steps).
• As you can see, the first order method is less computationally expensive.
Module'6')'Lecture'19' 43'
Understanding residuals
• However, the fact that the first order method converge faster and is less
computationally expensive, it does not mean it is better.
• As you can see, it converge to the wrong solution.
Module'6')'Lecture'19' 44'
Understanding residuals
• All the previous examples correspond to the cylinder case at Reynolds
number equal to 200 and 20.
• If you are interested in reproducing the previous results, the case is located
in the directory:
$PTOFC/first_tutorial/vortex_shedding/c1
Module'6')'Lecture'19' 45'
Understanding residuals
• This is the output of all residuals for a Reynolds number equal to 200.
Module'6')'Lecture'19' 46'
Understanding residuals
• This is the output of the inner-residual against the outer-residuals for a
Reynolds number equal to 200.
Module'6')'Lecture'19' 47'
Understanding residuals
• This is the output of the aerodynamic coefficients for a Reynolds number
equal to 200.
Module'6')'Lecture'19' 48'
Understanding residuals
• This is the output of all residuals for a Reynolds number equal to 20.
Module'6')'Lecture'19' 49'
Understanding residuals
• This is the output of the inner-residual against the outer-residuals for a
Reynolds number equal to 20.
Module'6')'Lecture'19' 50'
Understanding residuals
• This is the output of the aerodynamic coefficients for a Reynolds number
equal to 20.
Module'6')'Lecture'19' 51'
Module 6
Module'6')'Lecture'20' 1'
Today’s lecture
Module'6')'Lecture'20' 2'
On the CFL number
• First at all, what is the CFL or Courant number?
u t
CF L =
x
• The CFL number is a measure of how much information ( u )
traverses a computational grid cell ( x ) in a given
time-step ( t ).
Module'6')'Lecture'20' 3'
On the CFL number
• The CFL number is a necessary condition to guarantee the
stability of the numerical scheme.
Module'6')'Lecture'20' 4'
On the CFL number
Module'6')'Lecture'20' 5'
On the CFL number
• Let us talk about the CFL number condition.
Xn
ui
CF L = t CF Lmax
i=1
x i
Module'6')'Lecture'20' 6'
On the CFL number
Module'6')'Lecture'20' 7'
On the CFL number
Explicit methods
• However, the fact that you are using a numerical scheme that is
unconditionally stable, does not mean that you can choose a
time step of any size.
• This means that they are approximately ten times slower than
implicit methods.
• However, the memory requirements are really low and they are
extremely easy to parallelize.
Module'6')'Lecture'20' 10'
On the CFL number
Some facts of explicit and implicit methods
• If you use large time steps with implicit methods, it is likely that
you will need to increase the cell count in order to maintain the
accuracy of the solution, and this translates in an increased
computational cost.
Module'6')'Lecture'20' 11'
On the CFL number
Some facts of explicit and implicit methods
Module'6')'Lecture'20' 12'
On the CFL number
Module'6')'Lecture'20' 13'
On the CFL number
• I like to view the CFL number as follows,
Module'6')'Lecture'20' 14'
On the CFL number
• The CFL number is an indication of the amount of information
that propagates through one cell (or many cells), in one time-
step. f P
fE
CV CENTER FACE CENTER CV FACE
f(x)
f
CV W
CV P
CV P
W P E x
CV E
CV W
CV E
fW
i+2
CFL = 1 i+1
BOUNDARY NODE i
i-1
i-2
CFL = 2
CFL = 3
Module'6')'Lecture'20' 16'
Finite Volume Method: A Crash introduction
u t
CF L =
x
Module'6')'Lecture'20' 17'
Finite Volume Method: A Crash introduction
u t
CF L =
x
Module'6')'Lecture'20' 18'
Module 7
Module'7')'Lecture'21' 1'
Today’s lecture
Module'7')'Lecture'21' 2'
Programming in OpenFOAM®
During this session we will:
• Then, we will take a look at how to generate tensor fields from tensors.
• Finally we will see how to discretize a model equation and solve the
linear system of equations using OpenFOAM® classes and templates.
Module'7')'Lecture'21' 3'
Programming in OpenFOAM®
During this session we will:
Module'7')'Lecture'21' 5'
Programming in OpenFOAM®
Some preliminaries,
• The PDEs must be discretized in time and space before we solve them.
Module'7')'Lecture'21' 6'
Programming in OpenFOAM®
Basic tensor classes in OpenFOAM®
• OpenFOAM® contains a C++ class library named primitive
($FOAM_SRC/OpenFOAM/primitives/). In this library, you will find the
classes for the tensor mathematics.
• In the following table, we show the basic tensor classes available in
OpenFOAM®, with their respective access functions.
0 Scalar scalar
Module'7')'Lecture'21' 7'
Programming in OpenFOAM®
Basic tensor classes in OpenFOAM®
We can access the component T13 or Txz using the xz ( ) access function.
Module'7')'Lecture'21' 8'
Programming in OpenFOAM®
Basic tensor classes in OpenFOAM®
Txz = 3
Notice that in OpenFOAM® we use the function Info instead of the function cout.
Module'7')'Lecture'21' 9'
Programming in OpenFOAM®
Algebraic tensor operations in OpenFOAM®
• Tensor operations operate on the entire tensor entity instead of a series of
operations on its components.
• The OpenFOAM® syntax closely mimics the syntax used in written
mathematics, using descriptive functions or symbolic operators.
• Some of the algebraic tensor operations are listed in the following table.
Mathematical OpenFOAM®
Operation Remarks
description description
Addition a+b a + b
Scalar
sa s * a
multiplication
Double inner
rank a, b >=2 a:b a && b
product
Module'7')'Lecture'21' 10'
The list is not complete
Programming in OpenFOAM®
Examples of the use of some tensor classes
Module'7')'Lecture'21' 11'
Programming in OpenFOAM®
Examples of the use of some tensor classes
• cd $PTOFC/test/tensor
• wmake
(This will compile the source code and put the binary in the directory $FOAM_USER_APPBIN)
• Test-tensor
At this point look at the output and study the file Test-tensor.C, and try to
understand what we have done.
Module'7')'Lecture'21' 12'
Programming in OpenFOAM®
Dimensional units in OpenFOAM®
Module'7')'Lecture'21' 13'
Programming in OpenFOAM®
Dimensional units in OpenFOAM®
• Units are defined using the dimensionSet class tensor, with its units
defined using the dimensioned<Type> template class, the <Type>
being scalar, vector, tensor, etc. The dimensioned<Type> stores the
variable name, the dimensions and the tensor values.
• For example, a tensor with dimensions is declare in the following way:
dimensionedTensor sigma
(
0 6
1
10 0 0
“sigma”,
dimensionSet(1, -1, -2, 0, 0, 0, 0), ⌘ =@ 0 106 0 A
tensor(10e6,0,0,0,10e6,0,0,0,10e6) 0 0 106
);
Module'7')'Lecture'21' 14'
Programming in OpenFOAM®
Units correspondence in dimensionSet
1 Mass kilogram kg
2 Length meters m
3 Time second s
4 Temperature Kelvin K
6 Current ampere A
Luminuous
7 candela cd
intensity
dimensionedTensor sigma
(
0 6
1
“sigma”,
10 0 0
dimensionSet(1, -1, -2, 0, 0, 0, 0), ⌘ =@ 0 106 0 A
tensor(1e6,0,0,0,1e6,0,0,0,1e6)
);
0 0 106
#include “dimensionedTensor.H”
• Before return(0):
dimensionedTensor sigma
(
"sigma",
dimensionSet(1, -1, -2, 0, 0, 0, 0),
tensor(1e6,0,0,0,1e6,0,0,0,1e6)
);
Info<< "Sigma: " << sigma << endl;
By the end of this exercise, your output should looks like this:
Notice that the object sigma, which belongs to the dimensionedTensor class,
contains the name, the dimensions and values.
Module'7')'Lecture'21' 18'
Programming in OpenFOAM®
Dimensional units examples
Try to add the following member functions of the dimensionedTensor class in Test-
tensor.C (in the directory $PTOFC/test/my_tensor you will find the modified
files):
Also, extract some of the values of the tensor by adding the following line:
Note that the value() member function first converts the expression to a tensor, which
has a yy() member function. The dimensionedTensor class does not have a yy()
member function, so it is not possible to directly get its value by using sigma.yy().
Module'7')'Lecture'21' 19'
Programming in OpenFOAM®
OpenFOAM® lists and fields
• Lists of the tensor classes are defined in OpenFOAM® by the template class
Field<Type>. For better code legibility, all instances of Field<Type>, e.g.
Field<vector>, are renamed using typedef declarations as scalarField,
vectorField, tensorField, symmTensorField, tensorThirdField and
symmTensorThirdField.
Module'7')'Lecture'21' 20'
Programming in OpenFOAM®
OpenFOAM® lists and fields
• OpenFOAM® also supports operations between a field and a zero rank tensor, e.g.
all values of a Field U can be multiplied by the scalar 2 by simple coding the
following line, U = 2.0 * U.
Module'7')'Lecture'21' 21'
Programming in OpenFOAM®
Construction of a tensor field in OpenFOAM®
Add the following to Test-tensor.C (in the directory
$PTOFC/test/my_tensor you will find the modified files):
• Before main():
#include "tensorField.H"
• Before return(0):
Module'7')'Lecture'21' 23'
Programming in OpenFOAM®
• The cells are contiguous, i.e., they do not overlap and completely fill the domain.
• Dependent variables and other properties are stored at the cell centroid.
Module'7')'Lecture'21' 25'
Programming in OpenFOAM®
Discretization of a tensor field in OpenFOAM®
• The mesh class polyMesh is used to construct the polyhedral mesh using the
minimum information required.
• The fvMesh class extends the polyMesh class to include additional data needed for
the FVM discretization.
Module'7')'Lecture'21' 26'
Programming in OpenFOAM®
Discretization of a tensor field in OpenFOAM®
• The template class geometricField stores internal fields, boundary fields, mesh
information, dimensions, old values and previous iteration values.
• A geometricField inherits all the tensor algebra of its corresponding field, has
dimension checking, and can be subjected to specific discretization procedures.
Module'7')'Lecture'21' 27'
Programming in OpenFOAM®
Data stored in the fvMesh class
Access
Class Description Symbol
function
volScalarField Cell volumes V V()
Module'7')'Lecture'21' 28'
Programming in OpenFOAM®
Examine a fvMesh
• Let us study a fvMesh example. First let us compile the Test-mesh application.
From the terminal
• cd $PTOFC/test/mesh
• wmake
• cd $PTOFC/test/my_mesh/cavity
• blockMesh
Module'7')'Lecture'21' 29'
Programming in OpenFOAM®
Examine a fvMesh
Module'7')'Lecture'21' 30'
Programming in OpenFOAM®
Examine a fvMesh
Now, try to add in Test-mesh.C the following lines (in the directory
$PTOFC/test/my_mesh you will find the modified files):
• before return(0):
Module'7')'Lecture'21' 31'
Programming in OpenFOAM®
Examine a volScalarField
Let us now read a volScalarField that corresponds to the mesh in
$PTOFC/test/my_mesh/cavity. Add the following to Test-mesh.C
• Before return(0):
volScalarField p
(
IOobject
(
"p",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
);
Info<< p << endl;
Info<< p.boundaryField()[0] << endl;
• In this phase, OpenFOAM® converts the PDEs into a set of linear algebraic
equations, A x = b, where x and b are volFields (geometricField). A is a
fvMatrix, which is created by a discretization of a geometricField and inherits
the algebra of its corresponding field, and it supports many of the standard algebraic
matrix operations.
Mathematical fvm::
Term description
expression fvc::
laplacian(phi)
Laplacian r2 , · laplacian(Gamma, phi)
⇥ , ⇤ ⇥ ddt(phi)
Time derivative
ddt(rho,phi)
⇥t ⇤t
div(psi,scheme)
Convection ·( ), ·( ) div(psi,phi)
Sp(rho,phi)
Source ⇢ SuSp(rho,phi)
$PTOFC/test/my_convection_diffusion
Module'7')'Lecture'21' 35'
Programming in OpenFOAM®
• In the directory $PTOFC/test/my_convection_diffusion
you will find this tutorial.
• From this point on, please follow me.
• We are all going to work at the same pace.
Module'7')'Lecture'21' 36'
Programming in OpenFOAM®
Solution of the convection-diffusion equation
Let us now solve the convection-diffusion equation
⇥T
+ ⇥ · ( T) ⇥ · ( ⇥T ) = 0
⇥t
solve
(
fvm::ddt(T)
+ fvm::div(phi,T)
- fvm::laplacian(DT,T)
);
Module'7')'Lecture'21' 37'
Programming in OpenFOAM®
Solution of the convection-diffusion equation
• In $PTOFC/test/my_convection_diffusion, you will find the source code for
the solver of the convection-diffusion equation. In the terminal:
• cd $PTOFC/test/my_convection_diffusion
• wmake
• cd $PTOFC/test/my_convection_diffusion/case
• blockMesh
• my_test_convection_difusion
• paraFoam
Module'7')'Lecture'21' 38'
Programming in OpenFOAM®
Solution of the convection-diffusion equation
By the end of this exercise, your output should looks like this:
Module'7')'Lecture'21' 39'
Programming in OpenFOAM®
Solution of the convection-diffusion equation
By the end of this exercise, your output should looks like this:
Module'7')'Lecture'21' 40'
Solution plot with different mesh resolution
Programming in OpenFOAM®
Module'7')'Lecture'21' 41'
Programming in OpenFOAM®
I just presented the basic building blocks to program in
OpenFOAM®.
As usual,
remember that you have
the source code.
Module'7')'Lecture'21' 43'
Programming in OpenFOAM®
Additional tutorials
In the directories $PTOFC/c++_tuts, $PTOFC/test and $PTOFC/programming
you will find many tutorials, try to go through each one to understand the basic concepts
of C++ and how to program in OpenFOAM®.
Module'7')'Lecture'21' 44'
Module 7
Module'7')'Lecture'22' 1'
Today’s lecture
Module'7')'Lecture'22' 2'
Today’s lecture
Module'7')'Lecture'22' 3'
How to implement a new boundary condition in OpenFOAM®
Module'7')'Lecture'22' 4'
How to implement a new boundary condition in OpenFOAM®
• Rename all the copied .C and .H files, for instance you can change
their names to myFvPatchField.*. In the new files, search for all
text occurrences with originalFvPatchField (the original name of
the .C and .H files) and replace them with myFvPatchField.
• Modify the boundary condition to suit your needs. After you finish
modifying it, compile it and use it as a dynamic library.
Module'7')'Lecture'22' 5'
How to implement a new boundary condition in OpenFOAM®
Module'7')'Lecture'22' 6'
How to implement a new boundary condition in OpenFOAM®
• cd $PTOFC/programming/src/finiteVolume/fields/
fvPatchFields/derived/parabolicVelocity
• wmake libso
If you did not get any error, the new boundary condition is ready to use. wmake
will compile the new boundary condition and will place the new library in the
directory $WM_PROJECT_USER_DIR /platforms/linux64GccDPOpt/lib
(environment variable $FOAM_USER_LIBBIN).
Module'7')'Lecture'22' 8'
How to implement a new boundary condition in OpenFOAM®
libs (“parabolicvelocityBC.so”)
Module'7')'Lecture'22' 10'
How to implement a new boundary condition in OpenFOAM®
Remember to always add the newly created boundary condition to your control
dictionary controlDict. If you do not do this OpenFOAM® will complain.
Now we are ready to run the case. From the terminal type:
• cd $PTOFC/mycases1/elbow2d_1/elbow_parabolic_inlet_0
• fluentMeshToFoam ../../../meshes/elbow2d_1/ascii.msh
• checkMesh
• icoFoam
• paraFoam
Module'7')'Lecture'22' 11'
How to implement a new boundary condition in OpenFOAM®
Mesh
Module'7')'Lecture'22' 12'
How to implement a new boundary condition in OpenFOAM®
Module'7')'Lecture'22' 13'
How to implement a new boundary condition in OpenFOAM®
Module'7')'Lecture'22' 14'
Inlet profiles
How to implement a new boundary condition in OpenFOAM®
parabolicVelocityFvPatchVectorField.C
parabolicVelocityFvPatchVectorField.H
• The .H file is the header file, and it is included in the header of the .C file.
Module'7')'Lecture'22' 15'
How to implement a new boundary condition in OpenFOAM®
• There are some public constructors and member functions that are defined
in detail in the .C file.
• We used the third constructor when we tested the boundary condition, i.e.
we read the member data from a dictionary.
Module'7')'Lecture'22' 16'
How to implement a new boundary condition in OpenFOAM®
• The member function write defines how to write out the boundary values in
the time directory. The final line, writeEntry("value", os); writes out
all the values, which is only needed for post-processing.
Module'7')'Lecture'22' 17'
How to implement a new boundary condition in OpenFOAM®
Module'7')'Lecture'22' 18'
How to implement a new boundary condition in OpenFOAM®
• Do not worry, I will show how to use swak4foam and how to run this case.
Module'7')'Lecture'22' 19'
How to implement a new boundary condition in OpenFOAM®
• For more information about swak4foam you can visit the following site
http://openfoamwiki.net/index.php/Contrib/swak4Foam.
Module'7')'Lecture'22' 20'
How to implement a new boundary condition in OpenFOAM®
Module'7')'Lecture'22' 21'
How to implement a new boundary condition in OpenFOAM®
• Notice that we also kept the same naming convention for the files and
classes as for the parabolic inlet profile boundary condition, that is, we simply
cloned the directory. This is to show you how the code can be reused.
• Starting from this point, we can modify the files to fit our needs.
Module'7')'Lecture'22' 22'
How to implement a new boundary condition in OpenFOAM®
• By the way, take a look at the files and identify all the modifications.
Module'7')'Lecture'22' 23'
How to implement a new boundary condition in OpenFOAM®
• While this approach will work, I highly recommend you to change the names
of the files and classes. For instance, if you use the library
parabolicvelocityBC.so and p3d.so in the same case, you will have
a conflict between the libraries as both of them use the same symbols.
Module'7')'Lecture'22' 24'
How to implement a new boundary condition in OpenFOAM®
To compile:
• cd $PTOFC/programming/src/finiteVolume/fields/
fvPatchFields/derived/paraboloid
• wmake libso
If you did not get any error, the new boundary condition is ready to use. wmake
will compile the new boundary condition and will place the new library in the
directory $WM_PROJECT_USER_DIR /platforms/linux64GccDPOpt/lib
(environment variable $FOAM_USER_LIBBIN).
Module'7')'Lecture'22' 26'
How to implement a new boundary condition in OpenFOAM®
libs (“paraboloid.so”)
Module'7')'Lecture'22' 28'
How to implement a new boundary condition in OpenFOAM®
Remember to always add the newly created boundary condition to your control
dictionary controlDict. If you do not do this OpenFOAM® will complain.
Now we are ready to run the case. From the terminal type:
• cd $PTOFC/mycases1/elbow3d/elbow_paraboloid
• blockMesh
• surfaceFeatureExtract
• snappyHexMesh -overwrite
• checkMesh
• icoFoam
• paraFoam
Note: you will need to modify the boundary file in the directory constant/polyMesh. If you do not know how
to modify the file boundary, take a look at the README.FIRST file for instructions.
Module'7')'Lecture'22' 29'
How to implement a new boundary condition in OpenFOAM®
Geometry
Module'7')'Lecture'22' 30'
How to implement a new boundary condition in OpenFOAM®
Mesh
Module'7')'Lecture'22' 31'
How to implement a new boundary condition in OpenFOAM®
Paraboloid profile
Module'7')'Lecture'22' 32'
How to implement a new boundary condition in OpenFOAM®
Module'7')'Lecture'22' 34'
How to implement a new boundary condition in OpenFOAM®
Starting from the parabolic inlet profile boundary condition, let us now created a new
boundary condition to model the atmospheric boundary layer.
• cd $PTOFC/programming/src/finiteVolume/fields/
fvPatchFields/derived/ablVelocity
• wmake libso
If you did not get any error, the new boundary condition is ready to use. wmake
will compile the new boundary condition and will place the new library in the
directory $WM_PROJECT_USER_DIR /platforms/linux64GccDPOpt/lib
(environment variable $FOAM_USER_LIBBIN).
Module'7')'Lecture'22' 36'
How to implement a new boundary condition in OpenFOAM®
Module'7')'Lecture'22' 37'
How to implement a new boundary condition in OpenFOAM®
libs (“ablvelocityBC”)
Module'7')'Lecture'22' 38'
How to implement a new boundary condition in OpenFOAM®
Remember to always add the newly created boundary condition to your control
dictionary controlDict. If you do not do this OpenFOAM® will complain.
Now we are ready to run the case. From the terminal type:
• cd $PTOFC/mycases4/building/c0
• fluent3DMeshToFoam ../../../meshes/building/
ascii1.msh
• checkMesh
• simpleFoam
• paraFoam
To run this case, you can use as initial conditions the solution obtained using
potentialFoam. From the terminal type:
• cd $PTOFC/mycases4/building/potential
• rm ./0/*
• cp 0org/U 0/U
• cp 0org/p 0/p
• fluent3DMeshToFoam ../../../meshes/building/
ascii1.msh
• checkMesh
• potentialFoam –writep -noFunctionObjects
Module'7')'Lecture'22' 40'
How to implement a new boundary condition in OpenFOAM®
To run this case, you can use as initial conditions the solution obtained using
potentialFoam. From the terminal type:
• cd $PTOFC/mycases4/building/c0
• rm ./0/*
• cp ./0rg/* ./0
• cp ../potential/0/U 0/
• cp ../potential/0/p 0/
• fluent3DMeshToFoam ../../../meshes/building/
ascii1.msh
• checkMesh
• simpleFoam
Module'7')'Lecture'22' 41'
How to implement a new boundary condition in OpenFOAM®
Mesh
Module'7')'Lecture'22' 42'
How to implement a new boundary condition in OpenFOAM®
Inlet profile
Module'7')'Lecture'22' 46'
Today’s lecture
Module'7')'Lecture'22' 47'
How to implement my own application in OpenFOAM®
• To add a new application, start by finding one that does almost what
you want to do. Then, copy that application implementation to
$WM_PROJECT_USER_DIR and modify it according to your needs.
• You can also write a solver from scratch. Remember to keep the
prototype body of a solver or utility.
Module'7')'Lecture'22' 48'
How to implement my own application in OpenFOAM®
Module'7')'Lecture'22' 49'
How to implement my own application in OpenFOAM®
• cd $PTOFC/programming/applications/solvers/
my_laplace_st/
• wmake
Module'7')'Lecture'22' 50'
How to implement my own application in OpenFOAM®
If you did not get any error, the new boundary condition is ready to use. wmake
will compile the new boundary condition and will place the new library in the
directory $WM_PROJECT_USER_DIR /platforms/linux64GccDPOpt/bin
(environment variable $FOAM_USER_APPBIN).
Module'7')'Lecture'22' 51'
How to implement my own application in OpenFOAM®
#include "write.H”
This line of code will look for the header file write.H and will write out
volScalarField gradTx, volScalarField gradTx and
volScalarField gradTx (the T gradient)
Module'7')'Lecture'22' 53'
How to implement my own application in OpenFOAM®
Let us now setup a new case using my_laplace_st. From the terminal:
• cd $PTOFC/mycases0/laplace_1/c1
Remember to always add the new entries to the case dictionaries in the
directory system. Also, you will need to initialize all the fields you use in your
solver. If you do not do this OpenFOAM® will complain.
Let us now setup a new case using my_laplace_st. From the terminal:
• blockMesh
• my_laplace_st
• sample –latestTime
• paraFoam
• gnuplot gnuplot_script
• evince T_sampling.ps
Module'7')'Lecture'22' 55'
How to implement my own application in OpenFOAM®
Mesh (5 cells)
Module'7')'Lecture'22' 56'
How to implement my own application in OpenFOAM®
Module'7')'Lecture'22' 57'
Comparison analytical solution versus numerical solution
Today’s lecture
Module'7')'Lecture'22' 58'
How to add temperature to icoFoam
• After creating the new application’s directory, various small changes are
necessary to introduce in the solver files.
• Finally, the new field (temperature), needs to be added to the initial and
boundary conditions. Also, we need to tell to OpenFOAM® how to discretize
the new terms, this is done in the fvSchemes dictionary. In the
fvSolution dictionary, we need to set the solver that we want to use to
solve the field temperature.
Module'7')'Lecture'22' 59'
How to add temperature to icoFoam
• In the folder $PTOFC/programming/applications/solvers/
icoFoam/, you will find a copy of the original icoFoam solver. Let us copy
the content of this folder to the folder my_icoFoam. From the terminal:
• cp -r $PTOFC/programming/applications/solvers/
icoFoam/ $PTOFC/programming/applications/solvers/
my_icoFoam/
Module'7')'Lecture'22' 60'
How to add temperature to icoFoam
• Now go to the Make sub-directory, and open the file files with your favorite
editor and add the following changes:
my_icoFoam.C
EXE = $(FOAM_USER_APPBIN)/my_icoFoam
Module'7')'Lecture'22' 61'
How to add temperature to icoFoam
• Before compiling the new application, make sure that you do not have old
binaries, old object files or old dependencies files in your application
directory. In the terminal:
• wclean
This will clean the directory.
Module'7')'Lecture'22' 63'
How to add temperature to icoFoam
• First, we need to create the new temperature field. Open the
createFields.H file using your favorite editor.
• The first thing we can notice in createFields.H is that OpenFOAM® loads
the kinematic viscosity from the transportProperties dictionary file. Let
us add a new transport property related to the thermal diffusion which we will
denote as DT. Make the following changes:
dimensionedScalar nu
(
//Look for these lines
transportProperties.lookup("nu"));
fvScalarMatrix TEqn
(
fvm::ddt(T)
+ fvm::div(phi,T)
- fvm::laplacian(nu,T)
);
TEqn.solve( );
Module'7')'Lecture'22' 66'
How to add temperature to icoFoam
• Now, we need to add the new equation to the file my_icoFoam.C. Using
your favorite editor add the following modifications.
• Because the temperature transport depends on the velocity field, we will add
the equation after the momentum equation is solved (after the PISO loop),
but before the time step is written. Edit your file so it looks like this:
U -= rAU*fvc::grad(p);
U.correctBoundaryConditions( );
}
//Starting from here add these lines
fvScalarMatrix TEqn
(
fvm::ddt(T)
+ fvm::div(phi,T)
- fvm::laplacian(nu,T)
);
TEqn.solve( );
//End adding lines
runTime.write();
Module'7')'Lecture'22' 67'
How to add temperature to icoFoam
• Save the modifications and compile the new solver. From the terminal
• wclean
• wmake
• ls $FOAM_USER_APPBIN
Module'7')'Lecture'22' 68'
How to add temperature to icoFoam
• The next step is to test the new solver.
• cd $PTOFC/mycases1/elbow2d_1/elbow_plus_temperature
• In this directory you will find the case setup files for a case using
my_icoFoam solver.
Module'7')'Lecture'22' 69'
How to add temperature to icoFoam
• Notice that we need to create the field file for T in the 0 directory (initial and
boundary conditions).
• Finally, you will need to tell to OpenFOAM® how to solve the field T. This is
done in the fvSolution dictionary in the system directory.
Module'7')'Lecture'22' 70'
How to add temperature to icoFoam
• We will now use the new solver. From now on follow me.
• cd $PTOFC/mycases1/elbow2d_1/
elbow_plus_temperature
(This is one line)
• fluentMeshToFoam ../../../meshes/elbow2d_1/
ascii.msh
(This is one line)
• checkMesh
• my_icoFoam
• paraFoam
Module'7')'Lecture'22' 71'
How to implement my own application in OpenFOAM®
By following the instructions, you should get something like this
Mesh
Module'7')'Lecture'22' 72'
How to implement my own application in OpenFOAM®
By following the instructions, you should get something like this
Contours of pressure
Module'7')'Lecture'22' 74'
How to add temperature to icoFoam
• Try to run all cases and identify the changes in the dictionaries.
Module'7')'Lecture'22' 75'
How to add temperature to icoFoam
Remember, all components in OpenFOAM® are implemented in library form for
easy re-use. So, in order to implement a new application, we should follow
these basic steps:
• To create a new application, start by finding one that does almost what you
want to do. Then, copy that application implementation to your user directory
$WM_PROJECT_USER_DIR and modify it according to your needs.
• You can also write a solver from scratch. Remember to keep the prototype
body of a solver.
• After you finish modifying or writing your application, compile it and use it as
you normally do.
Module'7')'Lecture'22' 76'
How to add temperature to icoFoam
Module'7')'Lecture'22' 77'
Mesh generation using open source tools
Additional tutorials
In the folders $PTOFC/programming/applications and
$PTOFC/programming/src you will find many tutorials, try to go through each one to
understand how to program in OpenFOAM®.
Module'7')'Lecture'22' 78'
Module 8
Module'8')'Lecture'23' 1'
Today’s lecture
Module'8')'Lecture'23' 2'
Today’s lecture
Module'8')'Lecture'23' 3'
A crash introduction to turbulence modeling in OpenFOAM®
Module'8')'Lecture'23' 4'
A crash introduction to turbulence modeling in OpenFOAM®
Module'8')'Lecture'23' 5'
A crash introduction to turbulence modeling in OpenFOAM®
Turbulent waters
Photo credit: https://www.flickr.com/photos/thepaegan Module'8')'Lecture'23' 9'
This work is licensed under a Creative Commons License (CC BY-NC-ND 2.0)
A crash introduction to turbulence modeling in OpenFOAM®
Von Karman vortices created when prevailing winds sweeping east across the northern Pacific Ocean
ecountered Alaska's Aleutian Islands
Photo credit: USGS EROS Data Center Satellite Systems Branch.
Module'8')'Lecture'23' 12'
Copyright on the images is held by the contributors. Apart from Fair Use, permission must be sought for any other purpose.
A crash introduction to turbulence modeling in OpenFOAM®
Von Karman Vortex Streets in the northern Pacific Photographed from the International Space Station''
Photo credit: NASA Module'8')'Lecture'23' 13'
Copyright on the images is held by the contributors. Apart from Fair Use, permission must be sought for any other purpose.
A crash introduction to turbulence modeling in OpenFOAM®
Trailing vortices
Photo credit: Steve Morris. AirTeamImages. Module'8')'Lecture'23' 14'
Copyright on the images is held by the contributors. Apart from Fair Use, permission must be sought for any other purpose.
A crash introduction to turbulence modeling in OpenFOAM®
G.E.P Box
18
16
14
12
+
U 10
8 u+ = y +
6
4
0
-1 0 1 2 3
10 10 10 10 10
+
Y
Module'8')'Lecture'23'
Inner region Outer region 22'
A crash introduction to turbulence modeling in OpenFOAM®
Modeled in RANS
E()
Computed in DNS
1 1
l ⌘
Inner region
Energy Inertial Viscous
Viscous sublayer
Containing Sub-range range
Buffer Eddies Module'8')'Lecture'23' 23'
Log-law layer
Layer
A crash introduction to turbulence modeling in OpenFOAM®
Outer region
Boundary layer
Log-law layer
30 < y+ < 300
Buffer layer
10 < y+ < 30
Viscous sublayer
y+ < 10
Wall
Module'8')'Lecture'23' 24'
A crash introduction to turbulence modeling in OpenFOAM®
Outer region
Boundary layer
Log-law layer
30 < y+ < 300
Buffer layer
10 < y+ < 30
Viscous sublayer
Wall Function
y+ < 10
Wall
Module'8')'Lecture'23' 25'
A crash introduction to turbulence modeling in OpenFOAM®
Outer region
Boundary layer
Log-law layer
30 < y+ < 300
Buffer layer
10 < y+ < 30
Viscous sublayer
Scalable Wall Function
y+ < 10
Wall
Module'8')'Lecture'23' 26'
A crash introduction to turbulence modeling in OpenFOAM®
RANS
Increasing complexity
SAS
DES
LES
DNS
Module'8')'Lecture'23' 27'
A crash introduction to turbulence modeling in OpenFOAM®
RANS LES
• DeardorffDiffStress
• LRRDiffStress
• Smagorinsky
• SpalartAllmaras
• SpalartAllmarasDDES
• SpalartAllmarasIDDES
• dynLagrangian
• dynOneEqEddy
• homogeneousDynOneEqEddy
• homogeneousDynSmagorinsky
• kOmegaSSTSAS
• laminar
• mixedSmagorinsky
• oneEqEddy
• spectEddyVisc
Module'8')'Lecture'23' 30'
A crash introduction to turbulence modeling in OpenFOAM®
Suitable for external aerodynamics, tubomachinery and high speed flows. Good for mildly
Spalart-Allmaras complex external/internal flows and boundary layer flows under pressure gradient. Performs
poorly for free shear flows and flows with strong separation.
Robust. Widely used despite the known limitations of the model. Performs poorly for complex
Standard k–epsilon flows involving severe pressure gradient, separation, strong streamline curvature. Suitable for
initial iterations, initial screening of alternative designs, and parametric studies.
Suitable for complex shear flows involving rapid strain, moderate swirl, vortices, and locally
transitional flows (e.g. boundary layer separation, massive separation, and vortex shedding
Realizable k–epsilon behind bluff bodies, stall in wide-angle diffusers, room ventilation). It overcome the limitations of
the standard k-epsilon model.
Superior performance for wall-bounded boundary layer, free shear, and low Reynolds number
Standard k–omega flows compared to models from the k-epsilon family. Suitable for complex boundary layer flows
under adverse pressure gradient and separation (external aerodynamics and turbomachinery).
Offers similar benefits as standard k–omega. Not overly sensitive to inlet boundary conditions
SST k–omega like the standard k–omega. Provides more accurate prediction of flow separation than other
RANS models.
Module'8')'Lecture'23' 31'
A crash introduction to turbulence modeling in OpenFOAM®
• $FOAM_SRC/turbulenceModels/compressible/RAS/backwardsCompatibility/
wallFunctions
• $FOAM_SRC/turbulenceModels/incompressible/RAS/derivedFvPatchFields/
wallFunctions
• $FOAM_SRC/turbulenceModels/incompressible/RAS/backwardsCompatibility/
wallFunctions Module'8')'Lecture'23' 32'
A crash introduction to turbulence modeling in OpenFOAM®
• If you have absolutely no idea of what model to use, I highly recommend you
the ! family models or the realizable ✏
• Remember, when a turbulent flow enters a domain, turbulent boundary conditions
and initial conditions must be specified.
• Also, if you are dealing with wall bounded turbulence you will need to choose the
near-wall treatment. You can choose to solve the viscous sub-layer or use wall
functions.
• You will need to give the appropriate boundary conditions to the near-wall treatment.
Module'8')'Lecture'23' 33'
A crash introduction to turbulence modeling in OpenFOAM®
• The initial conditions and boundary conditions change from model to model and
depends on the physics involve, so get familiar with the theory.
• Remember, there is no universal turbulence model.
• To set the initial conditions and boundary conditions, my best advise is to find and
read the original reference used to implement the turbulence model.
• For instance, if you are interested in the incompressible version of the !
turbulence model, you can go to the directory:
$FOAM_SRC/turbulenceModels/incompressible/RAS/kOmegaSST
Module'8')'Lecture'23' 34'
A crash introduction to turbulence modeling in OpenFOAM®
• You have the source code, so take your time and try to read it.
Module'8')'Lecture'23' 35'
A crash introduction to turbulence modeling in OpenFOAM®
Module'8')'Lecture'23' 36'
A crash introduction to turbulence modeling in OpenFOAM®
Boundary layer
Log-law layer Log-law layer
30 < y+ < 300 30 < y+ < 300
Wall Wall
No wall-functions Wall-functions
• Generally speaking, wall functions is the approach to use if you are more interested in
the mixing in the outer region, rather than the forces on the wall.
+ +
• By the way, wall functions should never be used if y < 30 . What is y ?, we are
going to talk about this later on.
• If accurate prediction of forces or heat transfer on the wall are key to your simulation
(aerodynamic drag, turbomachinery blade performance, heat transfer) you might not
want to use wall functions. Module'8')'Lecture'23' 37'
A crash introduction to turbulence modeling in OpenFOAM®
• To deal with wall bounded turbulence, several wall functions are available in
OpenFOAM®, e.g., alphatJayatillekeWallFunction,
epsilonWallFunction, nutUSpaldingWallFunction,
omegaWallFunction, v2WallFunction.
• If the first node normal to the wall is in the viscous sub-layer region, you do not use
wall functions. This approach is computationally expensive.
• Instead, if the first node normal to the wall is in the log-law layer, you need to use wall
functions.
• When positioning the first node normal to the wall, try to avoid as much as possible
the buffer layer, this is the transition region and things are not very clear there.
• If you want to find where are the directories containing the wall functions, type in the
terminal:
• find $FOAM_SRC/turbulenceModels –iname wallFunctions
Module'8')'Lecture'23' 38'
A crash introduction to turbulence modeling in OpenFOAM®
• I am going to be really loud on this. To enable wall functions, you need to define the
base type boundary condition of the patch as a wall.
• The base type boundary conditions are defined in the file constant/polyMesh/
boundary.
• The specific wall function or numerical type boundary condition to use, is defined in
the field dictionaries located in the directory 0, or the directory where you set the
initial and boundary conditions.
Module'8')'Lecture'23' 39'
A crash introduction to turbulence modeling in OpenFOAM®
Module'8')'Lecture'23' 40'
A crash introduction to turbulence modeling in OpenFOAM®
@ ⇤ ⇤
⇢ + ⇢r · (ū) = ⌧ R :rū ⇢! + r · [(µ + µT ) r]
@t
@! ! R
⇢ + ⇢r · (ū!) = ↵ ⌧ :rū ⇢! 2 + r · [(µ + µT ) r!]
@t
Module'8')'Lecture'23' 41'
A crash introduction to turbulence modeling in OpenFOAM®
• At the end of the day, we want to determine the turbulent eddy viscosity
⇢
µT =
!
• The turbulent eddy viscosity is used to compute the Reynolds stress tensor,
2 h i 2
R R T
⌧ = ⇢ u0 u0 = 2µT D̄ ⇢I = µT ru + (ru) ⇢I,
3 3
Module'8')'Lecture'23' 42'
A crash introduction to turbulence modeling in OpenFOAM®
r · (ū) = 0,
@ ū rp̄ 1
+ r · (ūū) = + ⌫r2 ū r · ⌧ R.
@t ⇢ ⇢
2 h i 2
R R T
⌧ = ⇢ u0 u0 = 2µT D̄ ⇢I = µT ru + (ru) ⇢I,
3 3
Module'8')'Lecture'23' 44'
A crash introduction to turbulence modeling in OpenFOAM®
• The initial value for the turbulent kinetic energy can be found as follows
3
= (U I)2
2
• The initial value for the specific kinetic energy ! can be found as follows
⇢ µt 1
!=
µ µ
µt u0
• Where is the viscosity ratio and I= is the turbulence intensity. '
µ ū
Module'8')'Lecture'23' 45'
A crash introduction to turbulence modeling in OpenFOAM®
• If you are totally lost, you can use these reference values. They work most of the
times, but it is a good idea to have some experimental data or initial estimate.
µt /µ 1 10 100
Module'8')'Lecture'23' 47'
A crash introduction to turbulence modeling in OpenFOAM®
• Follow these guidelines if you are struggling to find the boundary conditions for the
near-wall treatment.
• I highly recommend you to read the source code and find the references used to
implement the model.
• As for the free-stream boundary conditions, you need to give the boundary conditions
for the near-wall treatment.
• When it comes to near-wall treatment, you have three options:
• Use wall functions:
30 y + 300
• Use scalable wall functions, this only applies with the ! family models:
1 y + 300
• Resolve the boundary layer (no wall functions):
y+ 6 Module'8')'Lecture'23' 48'
A crash introduction to turbulence modeling in OpenFOAM®
wall =
• For ! you should use the wall function omegaWallFunction with the following
value:
6⌫
!wall = 10 2
y
where = 0.075 and y is the distance to the first cell center normal to the
wall.
Module'8')'Lecture'23' 49'
A crash introduction to turbulence modeling in OpenFOAM®
wall = 0
• For ! you should use the wall function omegaWallFunction with the following
value:
6⌫
!wall = 10 2
y
where = 0.075 and y is the distance to the first cell center normal to the
wall.
Module'8')'Lecture'23' 50'
A crash introduction to turbulence modeling in OpenFOAM®
wall = 1e 10
• For ! you should use fixedValue with the following value:
!wall = 1e 10
Module'8')'Lecture'23' 51'
A crash introduction to turbulence modeling in OpenFOAM®
Module'8')'Lecture'23' 52'
A crash introduction to turbulence modeling in OpenFOAM®
• Remember, all this fancy treatment for the closure equations is done to compute
nut.
• Therefore we need to define boundary conditions for nut as well.
• nut is the turbulent viscosity and is not a physical property.
• We only define nut boundary conditions at the walls.
• If you do not create the nut dictionary, OpenFOAM® will create it automatically
for you.
• But be careful, what OpenFOAM® does might not be the best option.
• The source code of the nut wall functions is located in the directory:
$FOAM_SRC/turbulenceModels/incompressible/RAS/
derivedFvPatchFields/wallFunctions/nutWallFunctions
Module'8')'Lecture'23' 53'
A crash introduction to turbulence modeling in OpenFOAM®
Module'8')'Lecture'23' 55'
A crash introduction to turbulence modeling in OpenFOAM®
y + wall distance units
+
• To compute the wall distance units y ,
use the following equation Outer region
+ ⇢ ⇥ U⌧ ⇥ y
y =
Boundary layer
Log-law layer
30 < y+ < 300
µ
Buffer layer
10 < y+ < 30
r
⌧w
U⌧ =
⇢
where ⌧w is the wall shear stresses.
Module'8')'Lecture'23' 56'
A crash introduction to turbulence modeling in OpenFOAM®
y + wall distance units
+
• We never know a priori the y value.
• What we usually do is to run the simulation for a few time-steps or iterations, and then
+
we get an estimate of the y value.
• After determining where we are in the boundary layer (viscous sub-layer, buffer layer
or log-law layer), we take the mesh as a good one or we modify it if is deemed
necessary.
• It is an iterative process and it can be very time consuming.
+
• Have in mind that it is quite difficult to get uniform y values at the walls. This does
not mean that what you have done is wrong, use common sense.
• To get an initial estimate of the distance from the wall to the first cell center y , you
can proceed as follows,
Module'8')'Lecture'23' 57'
A crash introduction to turbulence modeling in OpenFOAM®
⇢⇥U ⇥L 0.2
1. Re = 2. Cf = 0.058 ⇥ Re
µ Skin friction coefficient of a flat plate
r
1 2 ⌧w
3. ⌧w = ⇥ Cf ⇥ ⇢ ⇥ U1 4. U⌧ =
2 ⇢
+ ⇢ ⇥ U⌧ ⇥ y µ ⇥ y+
5. y = y=
µ ⇢ ⇥ U⌧
Module'8')'Lecture'23' 58'
A crash introduction to turbulence modeling in OpenFOAM®
Module'8')'Lecture'23' 59'
A crash introduction to turbulence modeling in OpenFOAM®
• Run the simulation for a few time steps and get a better prediction of y + and
correct your initial prediction of y .
• If you are interesting in modeling the smallest eddies, DES or LES is the right choice.
• If you do not have any restriction in the near wall treatment method, use wall
functions.
• Choose your near-wall modeling strategy ahead of time and check y + and y
values to make sure the near-wall mesh is suitable.
Module'8')'Lecture'23' 60'
A crash introduction to turbulence modeling in OpenFOAM®
• Be aware of the limitations of the turbulence model chosen, find and read the original
references used to implement the model in OpenFOAM®.
• Set reasonable boundary and initial conditions for the turbulence model variables.
Module'8')'Lecture'23' 61'
A crash introduction to turbulence modeling in OpenFOAM®
A few applications
Module'8')'Lecture'23' 62'
A crash introduction to turbulence modeling in OpenFOAM®
LES simulation
Module'8')'Lecture'23' 63'
Iso-surfaces of Q criterion. Walls colored by instantaneous pressure.
A crash introduction to turbulence modeling in OpenFOAM®
LES simulation
LES simulation
Module'8')'Lecture'23' 65'
A crash introduction to turbulence modeling in OpenFOAM®
LES simulation
Module'8')'Lecture'23' 66'
Mesh and instantaneous velocity magnitude.
A crash introduction to turbulence modeling in OpenFOAM®
LES simulation
Module'8')'Lecture'23' 69'
LES (instantaneous velocity) RANS
A crash introduction to turbulence modeling in OpenFOAM®
DES simulation
Module'8')'Lecture'23' 72'
Iso-surfaces of Q criterion.
A crash introduction to turbulence modeling in OpenFOAM®
SAS simulation
Module'8')'Lecture'23' 73'
Iso-surfaces of vorticity magnitude.
A crash introduction to turbulence modeling in OpenFOAM®
URANS simulation
Module'8')'Lecture'23' 74'
Iso-surfaces of Q criterion.
A crash introduction to turbulence modeling in OpenFOAM®
References
• Turbulent Flows
Stephen B. Pope
Module'8')'Lecture'23' 75'
Module 8
Module'8')'Lecture'24' 1'
Today’s lecture
Module'8')'Lecture'24' 2'
Introduction to multiphase flows
Module'8')'Lecture'24' 3'
Introduction to multiphase flows
• Gas–particle flows:
• Natural: sand storms, volcanoes, avalanches, rain droplets, mist
formation.
• Biological: aerosols, dust particles, smoke (finely soot particles),
• Industrial: pneumatic conveyers, dust collectors, fluidized beds, solid
propellant rockets, pulverized solid particles, spray drying, spray casting.
• Liquid–solid flows:
• Natural: sediment transport of sand in rivers and sea, soil erosion, mud
slides, debris flows, iceberg formation.
• Biological: blood flow, eyes, lungs.
• Industrial: slurry transportation, flotation, fluidized beds, water jet cutting,
sewage treatment plants, bio-reactors.
Module'8')'Lecture'24' 5'
Introduction to multiphase flows
• Liquid–liquid flows:
• Industrial: emulsifiers, fuel-cell systems, micro-channel applications,
extraction systems.
• Gas–liquid–solid flows:
• Industrial: air lift pumps, fluidized beds, oil transportation.
Module'8')'Lecture'24' 6'
Introduction to multiphase flows
Module'8')'Lecture'24' 7'
Introduction to multiphase flows
Module'8')'Lecture'24' 9'
Introduction to multiphase flows
Computational power!
• Eulerian-Lagragian: solves idealized
isolated particles that are transported
with the flow. One- or two-way coupling
is possible. Can account for turbulence,
momentum transfer, and mass transfer.
• Eulerian-eulerian: solves two or more
co-existing fluids. The system can be
dispersed or separated, and can account
for turbulence, momentum transfer, and Increase!
mass transfer. Module'8')'Lecture'24' 11'
Introduction to multiphase flows
Eulerian-Eulerian approach
Eulerian-Eulerian approach Eulerian-Lagragian approach
(Multi-fluid and mixture
(VOF) (Particle tracking)
models)
Module'8')'Lecture'24' 12'
Introduction to multiphase flows
Free surface flows and surface tracking at scales larger than grid size
Applicability of VOF method to separated systems (non-interpenetrating continua)
Module'8')'Lecture'24' 13'
Introduction to multiphase flows
Average phase
properties
VOF ≈ 0.5
Module'8')'Lecture'24' 16'
Bubble coalescence, bubble break-up and wake entrainment in dispersed systems
Introduction to multiphase flows
• Eulerian-Lagragian approach:
l
>1 l
x <1 l
V OF = 1 x << 1
V OF < 1 x
V OF << 1 x = grid resolution
V OF = liquid volume fraction
l = liquid characteristic length scale
Separated flow system, dispersed flow system and particles can be present in the 18'
Module'8')'Lecture'24'
same
problem.
Introduction to multiphase flows
Module'8')'Lecture'24' 19'
Introduction to multiphase flows
Volume-of-Fluid (VOF) governing equations for separated systems
r·U=0
@⇢U
+ r · (⇢UU) = rp + r · ⌧ + ⇢g + f + ⇢S
@t
Surface tension
Source terms:
• Porous media
• Coriolis forces
• Centrifugal forces
• Mass transfer
Module'8')'Lecture'24' • and so on … 20'
Introduction to multiphase flows
Volume-of-Fluid (VOF) governing equations for separated systems
@
+ r · U + r · (Ur (1 )) = 0
@t
0< <1
Interface compression velocity
• The fluid properties can be written on either side of the interface as follows,
⇢= 1 ⇢1 + (1 1 )⇢2
µ= 1 µ1 + (1 1 )µ2
Module'8')'Lecture'24' 21'
Introduction to multiphase flows
Volume-of-Fluid (VOF) governing equations for separated systems
@
+ r · U + r · (Ur (1 )) = 0
@t
Module'8')'Lecture'24' 22'
Introduction to multiphase flows
Volume-of-Fluid (VOF) governing equations for separated systems
• Continuum surface force (CSF) model for the calculation of the surface
tension,
@⇢U
+ r · (⇢UU) = rp + r · ⌧ + ⇢g + f + ⇢S
@t
f = kr
✓ ◆
r
k =r·
|r |
Module'8')'Lecture'24' 24'
Introduction to multiphase flows
Eulerian-Eulerian governing equations for dispersed systems
@(↵k ⇢k Uk )
+ r · (↵k ⇢k Uk Uk ) = r · (↵k ⌧k ) ↵k rp + ↵k ⇢k g + Mk + f + Sk
@t
X X P Source terms:
↵k = 1.0 ⇢m = ↵k ⇢k k ↵ k ⇢k U k • Porous media
Um = • Coriolis forces
k k ⇢m •
•
Centrifugal forces
Mass transfer
Module'8')'Lecture'24' • and so25'
on …
Introduction to multiphase flows
Eulerian-Eulerian governing equations for dispersed systems
@(↵k ⇢k Uk )
+ r · (↵k ⇢k Uk Uk ) = r · (↵k ⌧k ) ↵k rp + ↵k ⇢k g + Mk + f + Sk
@t
@↵k ⇢k
+ r · Uk ↵k ⇢k + r · (Ur ↵k ⇢k (1 ↵k )) = 0 Source terms:
@t • Porous media
• Coriolis forces
• Centrifugal forces
• Mass transfer
X X P • and so on …
↵k = 1.0 ⇢m = ↵k ⇢k k ↵ k ⇢k U k
Um =
k k ⇢m
Module'8')'Lecture'24' 26'
Introduction to multiphase flows
Interfacial momentum transfer models
Ml = Mg = MD + ML + MV M + MT D
Drag
3 Cd
MD = ↵g ⇢l |Ul Ug |(Ul Ug )
4 db
Lift
ML = ↵g ⇢l Cl (Ul Ug ) ⇥ r ⇥ Ul
Virtual Mass ✓ ◆
Dl Ul Dg Ug
MV M = ↵g ⇢l CV M (Ul
Dt Dt
Turbulence Dispersion
MT D = ⇢l CT D r↵g
Module'8')'Lecture'24' 27'
Introduction to multiphase flows
Interfacial momentum transfer models
Module'8')'Lecture'24' 28'
Introduction to multiphase flows
Interfacial momentum transfer models in OpenFOAM®
Module'8')'Lecture'24' 29'
Introduction to multiphase flows
Module'8')'Lecture'24' 30'
Introduction to multiphase flows
Eulerian-Eulerian governing equations for dispersed systems of
gas-solid or liquid-solid (Eulerian-Granular KTGF)
@↵k ⇢k
+ r · (↵k ⇢k Uk ) = 0 =P
↵s,k Momentum transfer
@t k
k ↵s,k
@(↵k ⇢k Uk )
+ r · (↵k ⇢k Uk Uk ) = r · (↵k ⌧k ) ↵k rp k rpk + ↵ k ⇢k g + M k
@t
Stress tensor for solid
and fluid Disperse phase
Module'8')'Lecture'24'Shared pressure pressure 31'
Introduction to multiphase flows
Eulerian-Eulerian governing equations for dispersed systems of
gas-solid or liquid-solid (Eulerian-Granular KTGF)
• Granular temperature
1 Particle fluctuating velocity
⇥s = U2f s
3
• Plus the following additional terms that require closure relations (models),
s Solid bulk viscosity
µs Solid bulk viscosity
⌧f Frictional stresses
g0 Radial distribution function
Module'8')'Lecture'24' 34'
Introduction to multiphase flows
Module'8')'Lecture'24' 35'
Introduction to multiphase flows
Eulerian-Lagrangian governing equations
dU
m = Fdrag + Fpressure + Fvirtual mass + Fother
dt
+
Any of the Eulerian formulations (single or multi-phase)
Module'8')'Lecture'24' 36'
Introduction to multiphase flows
Eulerian-Lagrangian governing equations
• The DPM or Dense Particle Flows* approach, which includes the effect of
the particulate volume fraction on the continuous phase, suitable for dense
particle flow simulation.
*D.M. Snider, An Incompressible Three-Dimensional Multiphase Particle-in-Cell Model for Dense Particle Flows, Journal of
Computational Physics, Volume 170, Issue 2, 1 July 2001, Pages 523–549
**P. J. O’Rourke et al., A model for collisional exchange inModule'8')'Lecture'24' 38' 64,
gas/liquid/solid fluidized beds, Chemical Engineering Science, Volume
2009, pages 1784-1797
Introduction to multiphase flows
Eulerian-Lagrangian models in OpenFOAM®
Module'8')'Lecture'24' 39'
Introduction to multiphase flows
A few applications
Module'8')'Lecture'24' 40'
Introduction to multiphase flows
Simulation of gravity current – Onset of Kelvin-Helmholtz instability
Liquid-liquid interaction (VOF) !
Module'8')'Lecture'24' 41'
Introduction to multiphase flows
Rayleigh-Taylor instability – Liquid-liquid interaction
(VOF with AMR)
Module'8')'Lecture'24' 42'
Introduction to multiphase flows
Rayleigh-Taylor instability – Liquid-liquid-liquid interaction
(VOF with 3 phases)
Module'8')'Lecture'24' 43'
Introduction to multiphase flows
Particle interaction (no hydrodynamic coupling)!
Module'8')'Lecture'24' 44'
Introduction to multiphase flows
Fluidized bed hydrodynamics – Gas-solid interaction with hydrodynamic
coupling!
Module'8')'Lecture'24' 45'
Introduction to multiphase flows
MRF vs. Sliding grids – VOF
Module'8')'Lecture'24' 46'
Introduction to multiphase flows
Dynamics of gas-liquid flow in a reactor tank (Euler-Euler)!
Module'8')'Lecture'24' 47'
Introduction to multiphase flows
Bubble column – Eulerian-Eulerian approach
Module'8')'Lecture'24' 48'
Introduction to multiphase flows
Free surface – Sea keeping (VOF)!
Module'8')'Lecture'24' 49'
Introduction to multiphase flows
Free surface – Water splash (VOF)!
Module'8')'Lecture'24' 50'
Introduction to multiphase flows
Three rising bubbles – VOF with AMR
Module'8')'Lecture'24' 51'
Introduction to multiphase flows
The objective of reactor design is to create the right conditions for reactions. The
temperature and reactant species distribution, appropriate residence time and
removal of products must be considered. Including the effect of a catalyst may
be necessary. A comprehensive understanding of all the competing and
interacting mechanisms is required to arrive at better designs and improved
processes. In particular, gas-solids reacting flows involve, not only complex
interactions of granular materials with gas flow, but also phase-change,
heterogeneous and homogeneous reactions, heat and mass transfer.
Moreover, the spatial and temporal scales may vary over many orders of
magnitude. Thus modeling gas-solid reacting flows requires the integration of
the best physics and chemistry models from various science and engineering
fields with the most advanced computational algorithms. These algorithms must
be scalable to large high-performance computers in order to bear on this
important topic.
Module'8')'Lecture'24'
Excerpt from the preface of “Computational Gas-Solids 52'
Flows and Reacting Systems: Theory, Methods and Practice”
May, 2010, Eds. S. Pannala, M. Syamlal and T. O’Brien,
Introduction to multiphase flows
Module'8')'Lecture'24' 53'
Introduction to multiphase flows
Module'8')'Lecture'24' 54'
Module 9
Module'9')'Lecture'25' 1'
Today’s lecture
Module'9')'Lecture'25' 2'
Tips and tricks in OpenFOAM®
Module'9')'Lecture'25' 3'
Tips and tricks in OpenFOAM®
Module'9')'Lecture'25' 4'
Tips and tricks in OpenFOAM®
• What I am about to show you is based on my personal experience.
• Most important of all, before starting this long road, I got familiar with the
theory behind the FVM and CFD, the physics behind what I was doing, and
OpenFOAM® source code.
• Please, use these slides as a reference only. I am not responsible for your
failures and mistakes.
Module'9')'Lecture'25' 5'
Tips and tricks in OpenFOAM®
Our vertical workflow
• Do you remember this vertical workflow? I hope so.
• Everything starts with the geometry. So in order to
get a good mesh, you need a good geometry. GEOMETRY GENERATION
# source $HOME/OpenFOAM/OpenFOAM-1.6-ext/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-1.6-ext.GPU/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-1.7.1/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-2.0.x/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-2.1.1/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-2.2.0/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-2.2.x/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-2.3.0-debug/etc/bashrc
source $HOME/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc
Module'9')'Lecture'25' 7'
Tips and tricks in OpenFOAM®
OpenFOAM® shell environment
• If at any time I want to use a different version of OpenFOAM®, I just source the right
OpenFOAM® environment variables. For instance if I want to switch from version
2.2.0 to version 2.3.x, I modify my .bashrc as follows,
• Then open a new terminal, and you can start using the new version. You can also
have two different versions of OpenFOAM® running together at the same time in
different terminals.
• You can also use aliases to sourceModule'9')'Lecture'25'
the OpenFOAM® version. 8'
Tips and tricks in OpenFOAM®
OpenFOAM® shell environment
• When switching from one OpenFOAM® version to another one, it is highly advisable
to clear as many OpenFOAM environment settings as possible, to do so you can use
the script unset.sh. In the terminal type:
• unset
• Be careful, there may be more than one unset.sh script. The OpenFOAM® specific
script is located in the directory $WM_PROJECT_DIR/etc/config.
• You can also use the alias wmUNSET, which is set in the OpenFOAM® environment
variables. Remember, you can type alias in the terminal window to see all the
aliases available.
• If you want to find a string inside a file, you can use the command grep
• For instance, if you are interested in finding all dictionary files that end with the
“Dict” word in the tutorials directory, in the terminal type:
Module'9')'Lecture'25' 11'
Tips and tricks in OpenFOAM®
Looking for information in OpenFOAM® source code
• A few more advanced commands to find information in your OpenFOAM® installation.
• To find where the source code for the boundary condition "slip" is located:
• Before using the Doxygen documentation, you will need to compile it. To compile the
Doxygen documentation, from the terminal:
• cd $WM_PROJECT_DIR
• ./Allwmake doc
Note: You will need to install doxygen and graphviz/dot
Module'9')'Lecture'25' 13'
• The compilation is time consuming.
Tips and tricks in OpenFOAM®
Intensive IO
• If you are doing intensive IO or running big cases, I highly advise you to save the
solution in binary format. When using binary format, the IO is a way much faster and
the output files use less space.
• Remember, you can get a performance gain when you save in binary format as you
minimize any requirement for parsing.
'
• If OpenFOAM® binary format is not good enough for you, you can try another format.
For instance you can use HDF5 format with OpenFOAM®.
http://openfoamwiki.net/index.php/Contrib/IOH5Write
'
Module'9')'Lecture'25' 14'
Tips and tricks in OpenFOAM®
Intensive IO
• Know your hardware, intensive IO can slow-down your computations or crash your
system, even the most powerful supercomputers.
• For big simulations, most of the times the bottleneck is the IO.
• No need to say that eventually you will run out of space if you are working with big
files.
• One naïve solution to the IO bottleneck and big datasets space, do not save your
solution very often. But be careful, at least save your solution before stopping your
solution or reaching the job maximum time.'
Module'9')'Lecture'25' 15'
Tips and tricks in OpenFOAM®
Running in a cluster
• Best advice, familiarize with your hardware.
• Depending on the system current demand of resources, the resources you request
and your job priority, sometimes you can be in queue for hours, even days, so be
patient and wait for your turn.
• For those running on fancy clusters, such as blue gene supercomputers, I have found
a processor limit of 512, after that is quite difficult to get any improvement.
Module'9')'Lecture'25' 17'
Tips and tricks in OpenFOAM®
OpenFOAM® mesh quality and checkMesh utility
• Before running a simulation remember to always check the mesh quality using the
checkMesh utility.
• Remember, good quality meshes are of paramount importance to obtain accurate
results.
• checkMesh will also check for topological errors.
• Have in mind that topological errors must be repaired.
• You will be able to run with mesh quality errors (such as skewness, aspect ratio,
minimum face area, and non-orthogonality), but they will severely tamper the solution
accuracy and can made the solver run super slow or even blow-up.
• In my personal experience, I have found that OpenFOAM® is very picky when it
comes to mesh quality. So if checkMesh is telling you that the mesh is bad, you
better correct those errors.
• Unfortunately, to correct mesh quality errors you will have to remesh the geometry.
Module'9')'Lecture'25' 18'2
Tips and tricks in OpenFOAM®
OpenFOAM® mesh quality and checkMesh utility
• If for any reason checkMesh finds errors, it will give you a message and it will tell you
what check failed.
• It will also write a set with the faulty cells, faces, and/or points. These sets are saved
in the directory constant/polyMesh/sets/
• If at any point you want to visualize the failed faces/cells/points you will need to
convert them to VTK format using the utility foamToVTK.
• At the end, foamToVTK will create a directory named VTK, where you will find the
failed faces/cells/points in VTK format. At this point you can use paraFoam/
paraview to visualize the failed sets.
Module'9')'Lecture'25' 19'
Tips and tricks in OpenFOAM®
OpenFOAM® mesh quality and checkMesh utility
• I want to emphasize the fact that you will be able to run with mesh quality errors such
as skewness, aspect ratio, minimum face area, and non-orthogonality.
• However, they will severely tamper the solution accuracy and can made the solver
explode.
Module'9')'Lecture'25' 20'
Tips and tricks in OpenFOAM®
OpenFOAM® mesh quality and checkMesh utility
• If you want to know the quality metrics hard-wired in OpenFOAM®, just read the file
$WM_PROJECT_DIR/src/OpenFOAM/meshes/primitiveMesh/
primitiveMeshCheck/primitiveMeshCheck.C. Their maximum (or minimum)
values are defined as follows:
• By the way, if you are not happy with these values, you can just change them and
voila, your quality problems are solved (I am kidding of course).
Module'9')'Lecture'25' 21'
Tips and tricks in OpenFOAM®
OpenFOAM® mesh quality and renumberMesh utility
• Before running a simulation, I highly recommend you to use the renumberMesh
utility. This utility will renumber the mesh to minimize its bandwidth, in other words, it
will make the linear solver run faster (at least for the first time-steps)
• Before running a simulation, try to always get a good quality mesh. Remember,
garbage in – garbage out. Or in a positive way, good mesh – good results.
Module'9')'Lecture'25' 22'3
Tips and tricks in OpenFOAM®
Boundary conditions
• Boundary conditions should be physically realistic. They must represent the physics
involved.
• Minimize grid skewness, non-orthogonality, growth rate, and aspect ratio near the
boundaries. You do not want to introduce diffusion errors early in the simulation,
specially close to the inlets.
• Remember, for each single variable you are solving you need to specify a boundary
condition.
Module'9')'Lecture'25' 23'4
Tips and tricks in OpenFOAM®
Boundary conditions
• Try to avoid large gradients in the direction normal to the boundaries near inlets and
outlets. That is to say, put your boundaries far away from where things are
happening.
• Do not force the flow at the outflow, use a zero normal gradient for all flow variables
except pressure. The solver extrapolates the required information from the interior.
• Be careful with backward flow at the outlets (flow coming back to the domain) and
backward flow at inlet (reflection waves), they require special treatment.
Module'9')'Lecture'25' 24'4
Tips and tricks in OpenFOAM®
Initial conditions
• First at all, a good initial condition can improve the stability and convergence rate. On
the other hand, unphysical boundary conditions can slow down the convergence rate
or can cause divergence.
• As for boundary conditions, for each single variable you are solving you need to
specify initial conditions.
• potentialFoam can also give you an idea of the sensitivity of the mesh quality.
Module'9')'Lecture'25' 25'5
Tips and tricks in OpenFOAM®
Initial conditions
• You can also get a computational inexpensive solution on a coarse mesh and then
interpolate it to a fine mesh. This will be a very good initial solution only if the solution
in the coarse mesh is acceptable.
• Use mapFields to map the solution from a coarse mesh to a finer mesh. It also
works the other way around, but I do not see any reason to proceed in this way.
Module'9')'Lecture'25' 26'5
Tips and tricks in OpenFOAM®
Initial conditions
• If you are using a turbulence model, you can initialize the velocity and pressure fields
from the solution obtained from a laminar case.
• If you are running an unsteady simulation and if the initial transient is of no interest,
you can initialize your flow using the solution obtained from a steady simulation.
• Always try to get initial conditions that are close to the solution (I know this is difficult
to achieve as we do not know the solution, if we knew the solution we would not have
a job).
Module'9')'Lecture'25' 27'
Tips and tricks in OpenFOAM®
Starting and running a simulation
• Remember, you can change the parameters in the dictionaries controlDict,
fvSchemes and fvSolution on the fly. But you will need to set the keyword
runTimeModifiable to yes in the controlDict dictionary.
• When starting a simulation and if the initial transient is of no interest, you can start the
simulation by using a high value of viscosity (low Reynolds number), and as the
simulation runs you can change the value until you reach the desired value.
• If you are working with high Reynolds numbers and you do not like the trick of
increasing the viscosity, you can get a very good initial solution using an Euler solver
with upwind.
• You can also start the simulation by using a first order scheme and then switch to a
high order scheme.
Module'9')'Lecture'25' 28'
Tips and tricks in OpenFOAM®
Starting and running a simulation
• You can also change the convergence criterion of the linear solvers on the fly.
• For instance, you can start using a not so tight convergence criterion with a robust
numerical scheme, and as the simulation runs you can tighten the convergence
criterion to increase the accuracy.
• When the simulation starts I usually use more correctors steps (for
• and PIMPLE methods), and as the solution advance or stabilizes I decrease the
number of corrector steps, but I always use at least one corrector step.
• Remember to always check the time step continuity errors. This number should be
small (negative or positive), if it increases in time for sure something is wrong.
• If you want to know how the continuity errors are computed just type in the terminal
find $FOAM_SRC –iname *continuity*, and open any of the files.
Module'9')'Lecture'25' 29'
Tips and tricks in OpenFOAM®
Discretization schemes
• Never get a final solution using first order schemes. They are too diffusive, which
means they will under predict the forces and smear the gradients. In the other side,
first order schemes are extremely robust, so you might be tented to use them as they
will always give you a solution.
• You can start using a first order scheme, and then switch to a high order scheme.
Remember, you can change the parameters on the fly.
• Bad quality meshes will add numerical oscillations and reduce the accuracy of the
numerical solution.
Module'9')'Lecture'25' 30'6
Tips and tricks in OpenFOAM®
Discretization schemes
• If you have a good mesh and a good initial solution, you can start immediately with
a high order scheme, but be careful, remember to always check the stability of the
solution.
• If at one point your solution starts to oscillate, you can switch to upwind and let the
simulation stabilize, then you can switch back to high order accuracy.
• Have in mind that this behavior is telling you that something is happening so you
better adjust other parameters, such as, solver tolerances, non-orthogonal
corrections, number of correctors, gradient discretization and so on.
• Try to always use a good quality mesh. Avoid the GIGO syndrome.
• In the next slides I will show you how I usually setup the discretization schemes.
Module'9')'Lecture'25' 31'7
Tips and tricks in OpenFOAM®
Discretization schemes – Convective terms
• A robust numerical scheme but too diffusive,
divSchemes
{
div(phi,U) Gauss upwind;
div(phi,omega) Gauss upwind;
div(phi,k) Gauss upwind;
div((nuEff*dev(T(grad(U))))) Gauss linear;
}
Module'9')'Lecture'25' 32'
Tips and tricks in OpenFOAM®
Discretization schemes – Convective terms
• An accurate and stable numerical scheme,
divSchemes
{
div(phi,U) Gauss linearUpwind grad(U);
div(phi,omega) Gauss linearUpwind default;
div(phi,k) Gauss linearUpwind default;
div((nuEff*dev(T(grad(U))))) Gauss linear;
}
Module'9')'Lecture'25' 33'
Tips and tricks in OpenFOAM®
Discretization schemes – Convective terms
• An even more accurate but oscillatory scheme,
divSchemes
{
div(phi,U) Gauss linear;
div(phi,omega) Gauss linearUpwind default;
div(phi,k) Gauss linearUpwind default;
div((nuEff*dev(T(grad(U))))) Gauss linear;
}
Module'9')'Lecture'25' 34'
Tips and tricks in OpenFOAM®
Discretization schemes – Diffusive terms
• For the discretization of the diffusive terms, you can use a fully orthogonal scheme,
laplacianSchemes
{
default Gauss linear corrected;
}
• You can also use a scheme that uses a blending between a fully orthogonal scheme
and a non-orthogonal scheme,
laplacianSchemes
{
default Gauss linear limited ;
}
Module'9')'Lecture'25' 35'
Tips and tricks in OpenFOAM®
Discretization schemes – Diffusive terms
• The method you use highly depends on the quality of the mesh.
• For meshes with low non-orthogonality you can use the corrected scheme or the
limited 1 scheme.
• For meshes with high non-orthogonality you can use the limited scheme.
The higher the non-orthogonality the lower the value of the blending factor .
0 1
• Bad quality mesh • Good quality mesh
• Non-orthogonal correction • Orthogonal correction
• Bounded on low quality meshes • Unbounded on low quality meshes
Module'9')'Lecture'25' 36'
Tips and tricks in OpenFOAM®
Discretization schemes – Diffusive terms
• An accurate numerical scheme on orthogonal meshes (this is a very good quality
mesh with uniform cell size, this is what we want),
laplacianSchemes
{
default Gauss linear orthogonal;
}
snGradSchemes
{
default orthogonal;
}
Module'9')'Lecture'25' 37'8
Tips and tricks in OpenFOAM®
Discretization schemes – Diffusive terms
• An accurate numerical scheme on orthogonal meshes (with non-orthogonal
corrections),
laplacianSchemes
{
default Gauss linear limited 1;
}
snGradSchemes
{
default limited 1;
}
Module'9')'Lecture'25' 38'
Tips and tricks in OpenFOAM®
Discretization schemes – Diffusive terms
• A less accurate numerical scheme valid on non-orthogonal meshes (with non-
orthogonal corrections),
laplacianSchemes
{
default Gauss linear limited 0.5;
}
snGradSchemes
{
default limited 0.5;
}
Module'9')'Lecture'25' 39'
Tips and tricks in OpenFOAM®
Discretization schemes – Gradient terms
• Let us talk about the gradSchemes, this entry defines the way we compute the
gradients.
• The gradients can be computed using the Gauss method or the least squares
method. The keywords are:
• Gauss linear;
• leastSquares;
• In practice, the leastSquares method is more accurate, however, I have found that
it tends to be more oscillatory on tetrahedral meshes.
Module'9')'Lecture'25' 40'
Tips and tricks in OpenFOAM®
Discretization schemes – Gradient terms
• You can also use gradient limiters.
• Gradient limiters will avoid over and under shoots on the gradient computations.
There are four available,
gradSchemes
{
default cellMDLimited Gauss linear ;
}
0 1
Accuracy Stability
Limiter off Module'9')'Lecture'25'
Limiter on 42'
Tips and tricks in OpenFOAM®
Discretization schemes – How to choose the schemes
• If after checking the mesh quality, the non-orthogonality is higher than 80, I prefer to
redo the mesh and improve the quality.
• By the way, if you are running LES simulations, do not even think about running in
highly non-orthogonal meshes. Better spend more time in getting a good quality
mesh, maybe with non-orthogonality less than 60.
• Do not try to push too much the numerical scheme on highly non-orthogonal meshes.
You already know that the quality is low, so this highly influence the accuracy and
stability of the solution. Specially the gradient computations.
• I do not like to run simulations on highly orthogonal meshes, but if I have to, I often
use the following numerical scheme.
Module'9')'Lecture'25' 43'9
Tips and tricks in OpenFOAM®
Discretization schemes – How to choose the schemes
• Non-orthogonality more than 80. I do not waste my time. I prefer to go back and get a
better mesh. But if you want, you can try something like this,
gradSchemes laplacianSchemes
{ {
default faceLimited leastSquares 1.0; default Gauss linear limited 0.333;
grad(U) faceLimited leastSquares 1.0; }
}
divSchemes snGradSchemes
{ {
div(phi,U) Gauss linearUpwind grad(U); default limited 0.333;
div(phi,omega) Gauss upwind; }
div(phi,k) Gauss upwind;
div((nuEff*dev(T(grad(U))))) Gauss linear;
}
Module'9')'Lecture'25' 44'
Tips and tricks in OpenFOAM®
Discretization schemes – How to choose the schemes
• Non-orthogonality between 70 and 80
gradSchemes laplacianSchemes
{ {
default cellLimited leastSquares 1.0; default Gauss linear limited 0.5;
grad(U) cellLimited leastSquares 1.0; }
}
divSchemes snGradSchemes
{ {
div(phi,U) Gauss linearUpwind grad(U); default limited 0.5;
div(phi,omega) Gauss upwind; }
div(phi,k) Gauss upwind;
div((nuEff*dev(T(grad(U))))) Gauss linear;
}
Module'9')'Lecture'25' 45'
Tips and tricks in OpenFOAM®
Discretization schemes – How to choose the schemes
• Non-orthogonality between 60 and 70
gradSchemes laplacianSchemes
{ {
default cellMDLimited Gauss linear 0.5; default Gauss linear limited 0.777;
grad(U) cellMDLimited Gauss linear 0.5; }
}
divSchemes snGradSchemes
{ {
div(phi,U) Gauss linearUpwind grad(U); default limited 0.777;
div(phi,omega) Gauss linearUpwind default; }
div(phi,k) Gauss linearUpwind default;
div((nuEff*dev(T(grad(U))))) Gauss linear;
}
Module'9')'Lecture'25' 46'
Tips and tricks in OpenFOAM®
Discretization schemes – How to choose the schemes
• Non-orthogonality between 40 and 60
gradSchemes laplacianSchemes
{ {
default cellMDLimited Gauss linear 0.5; default Gauss linear limited 1.0;
grad(U) cellMDLimited Gauss linear 0.5; }
}
divSchemes snGradSchemes
{ {
div(phi,U) Gauss linearUpwind grad(U); default limited 1.0;
div(phi,omega) Gauss linearUpwind default; }
div(phi,k) Gauss linearUpwind default;
div((nuEff*dev(T(grad(U))))) Gauss linear;
}
Module'9')'Lecture'25' 47'
Tips and tricks in OpenFOAM®
Discretization schemes – How to choose the schemes
• I guess at this point you know how to adjust the numerical scheme for meshes with
non-orthogonality less than 40.
Module'9')'Lecture'25' 48'
Tips and tricks in OpenFOAM®
Discretization schemes – How to choose the schemes
• Additionally, I also change the number of non-orthogonal corrections.
• In plain English, this means that the new value of the variable depends upon the
old value, the computed change of , and the under-relaxation factor ↵ .
Module'9')'Lecture'25' 50'
Tips and tricks in OpenFOAM®
Under-relaxation factors
• Under-relaxation factors are typical of steady solvers using the SIMPLE method.
• To find out what are and how to change the under-relaxation factors requires
experience and understanding.
Module'9')'Lecture'25' 51'
Tips and tricks in OpenFOAM®
Under-relaxation factors
• I highly recommend you to use the default under-relaxation factors.
• If you have to change the under-relaxation factors, start by decreasing the values of
the under-relaxation factors in order to improve the stability of the solution.
• Remember, low under-relaxation factors will slow down the solver while high under-
relaxation factors will speed up the computation, but you will give up stability.
• In order to find the optimal under-relaxation factors for your case, it will take some trial
and error.
Module'9')'Lecture'25' 52'
Tips and tricks in OpenFOAM®
Under-relaxation factors
• These are the under-relaxation factors I often use (which by the way are the
commonly used).
relaxationFactors
{
p 0.3;
U 0.7;
k 0.7;
omega 0.7;
}
• According to the physics involved you will need to add more under-relaxation factors.
• If you do not define the new under-relaxation factors, they will be set to 1.0 by default.
Module'9')'Lecture'25' 53'
Tips and tricks in OpenFOAM®
Under-relaxation factors
relaxationFactors
0 1
Velocity
Stability
Module'9')'Lecture'25' 54'
Tips and tricks in OpenFOAM®
Linear solvers
• The linear solvers are defined in the fvSolution dictionary. You will need to define
a solver for each variable you are solving.
• The GAMG solver (generalized geometric-algebraic multigrid solver), can often be the
optimal choice for solving the pressure equation. However, I have found that when
using more than 1024 processors is better to use Newton-Krylov type solvers.
Module'9')'Lecture'25' 55'
Tips and tricks in OpenFOAM®
Linear solvers
• When solving multiphase problems, I have found that the GAMG solver might give
problems when running in parallel, so be careful. The problem is mainly related to
nCoarsestCells keyword, so usually I have to set a high value of cells (in the order
1000).
• The utility renumberMesh can dramatically increase the speed of the linear solvers,
specially during the firsts iterations.
• I usually start by using a not so tight convergence criterion and as the simulation runs,
I tight the convergence criterion.
Module'9')'Lecture'25' 56'
Tips and tricks in OpenFOAM®
Linear solvers
• These are the linear solvers I often use.
• For the pressure equation I usually start with a tolerance equal to 1e-5 and relTol
equal to 0.01. After a while I change these values to 1e-6 and 0.001 respectively.
p
{
solver GAMG;
tolerance 1e-5;
relTol 0.01;
smoother GaussSeidel;
nPreSweeps 0;
nPostSweeps 2;
cacheAgglomeration on;
agglomerator faceAreaPair;
nCellsInCoarsestLevel 1000;
mergeLevels 1;
}
Module'9')'Lecture'25' 57'
Tips and tricks in OpenFOAM®
Linear solvers
• These are the linear solvers I often use.
• For the pressure equation I usually start with a tolerance equal to 1e-5 and relTol
equal to 0.01. After a while I change these values to 1e-6 and 0.001 respectively.
p
{
solver GAMG;
tolerance 1e-6;
relTol 0.001;
smoother GaussSeidel;
nPreSweeps 0;
nPostSweeps 2;
cacheAgglomeration on;
agglomerator faceAreaPair;
nCellsInCoarsestLevel 1000;
mergeLevels 1;
}
Module'9')'Lecture'25' 58'
Tips and tricks in OpenFOAM®
Linear solvers
• These are the linear solvers I often use.
• If I do not use the GAMG solver for the pressure, I often use the PCG solver.
• For the pressure equation I usually start with a tolerance equal to 1e-5 and relTol
equal to 0.01. After a while I change these values to 1e-6 and 0.001 respectively.
• If the speed of the solver is too slow, I change the convergence criteria to 1e-4 and
relTol equal to 0.05. I usually do this during the first iterations.
p
{
solver PCG;
preconditioner DIC;
tolerance 1e-4;
relTol 0.05;
}
Module'9')'Lecture'25' 59'
Tips and tricks in OpenFOAM®
Linear solvers
• These are the linear solvers I often use.
• For the velocity equation I always use a tolerance equal to 1e-8 and
relTol equal to 0.0
U
{
solver PBiCG;
preconditioner DILU;
tolerance 1e-8;
relTol 0.0;
}
Module'9')'Lecture'25' 60'
Tips and tricks in OpenFOAM®
Linear solvers
• I like to set the minimum number of iterations to three, especially for the pressure.
• If your solver is doing too much iterations, you can set the maximum number of
iterations. But be careful, if the solver reach the maximum number of iterations it will
stop, we are talking about unconverged iterations.
• You can set the maximum number of iterations specially during the first time-steps
where the solver takes longer.
• I use minIter and maxIter on symmetric and asymmetric matrix solvers.
p
{
solver PCG;
preconditioner DIC;
tolerance 1e-4;
relTol 0.01;
minIter 3;
maxIter 100;
}
Module'9')'Lecture'25' 61'
Tips and tricks in OpenFOAM®
Linear solvers
• The default option is the conventional segregated solution. That is, you first solve for
velocity component x, then velocity component y and finally velocity component z.
• You can get some improvement in terms of stability and turn around time by using the
coupled matrix solver for vectors and tensors, i.e., if you are solving the velocity field,
you solve all the velocity components at once.
• To select the coupled solver you need to use the keyword coupled in the
fvSolution dictionary.
• In the coupled matrix solver you set tolerance as a vector (absolute and relative)
U
{
type coupled;
solver cPBiCCCG;
preconditioner DILU;
tolerance (1e-08 1e-08 1e-08);
relTol (0 0 0);
minIter 3;
} Module'9')'Lecture'25' 62'
Tips and tricks in OpenFOAM®
Linear solvers
• Remember, you must do at least one corrector step when using PISO solvers.
• When you use the PISO and PIMPLE solvers, you also have the option to set the
tolerance for the final corrector step (.*Final).
• By proceeding in this way, you can put all the computational effort only in last
corrector step (.*Final).
pFinal
{
solver GAMG;
tolerance 1e-06;
relTol 0.0;
smoother GaussSeidel;
nPreSweeps 0;
nPostSweeps 2;
cacheAgglomeration on;
agglomerator faceAreaPair;
nCellsInCoarsestLevel 1000;
mergeLevels 1;
}
Module'9')'Lecture'25' 63'
Tips and tricks in OpenFOAM®
Linear solvers
• By proceeding in this way, you can put all the computational effort only in last
corrector step (.*Final).
• For all the intermediate corrector steps, you can use a more relaxed convergence
criterion.
• For example, you can use the following solver and tolerance criterion for all the
intermediate corrector steps (p), then in the final corrector step (pFinal) you tight the
solver tolerance.
p pFinal
{ {
solver GAMG; solver GAMG;
tolerance 1e-05; tolerance 1e-06;
relTol 0.05; relTol 0.0;
smoother GaussSeidel; smoother GaussSeidel;
nPreSweeps 0; nPreSweeps 0;
nPostSweeps 2; nPostSweeps 2;
cacheAgglomeration on; cacheAgglomeration on;
agglomerator faceAreaPair; agglomerator faceAreaPair;
nCellsInCoarsestLevel 1000; nCellsInCoarsestLevel 1000;
mergeLevels 1; mergeLevels 1;
} }
Module'9')'Lecture'25' 64'
Tips and tricks in OpenFOAM®
Transient simulations and time-step selection
• Remember, the fact that we are using an implicit solver (unconditionally stable), does
not mean that we can choose a time step of any size.
• The time-step must be chosen in such a way that it resolves the time-dependent
features and it maintain the solver stability.
Module'9')'Lecture'25' 65'
Tips and tricks in OpenFOAM®
Transient simulations and time-step selection
• In my personal experience, I have been able to go up to a CFL = 5.0 while
maintaining the accuracy. To achieve this I had to increase the number of corrector
steps in the PIMPLE solver, decrease the under-relaxation factors and tightening the
convergence criteria; and this translates into a higher computational cost.
• I have managed to run with CFL numbers up to 40, but this highly reduces the
accuracy of the solution. Also, is quite difficult to maintain the stability of the solver.
Module'9')'Lecture'25' 66'
Tips and tricks in OpenFOAM®
Transient simulations and time-step selection
• If accuracy is the goal (e.g., predicting forces), definitively use a CFL less than 1.0.
• If you are doing LES simulations, I highly advice you to use a CFL less than 0.6 and if
you can afford it, less than 0.3
• If you are doing LES or you are interested in the accurate prediction of forces,
definitely you need high quality meshes, preferable made of hexahedral elements.
• I usually use the PIMPLE solver. In the PIMPLE solver you have the option to limit
your time-step to a maximum CFL number, so the solver automatically choose the
time-step. This is a very cool feature.
• In the PISO solver you need to give the time-step size. So basically you need to
choose your time-step so it does not exceed a target CFL value.
Module'9')'Lecture'25' 10
67'
Tips and tricks in OpenFOAM®
Transient simulations and time-step selection
• You can easily also modify the PISO solver so it automatically choose the time-step
according to a maximum CFL number, you just need to add one line of code.
• The PIMPLE solver is a solver specially formulated for large time-steps. So in order
to increase the stability you will need to add more corrector steps
(nOuterCorrectors and nCorrectors).
• A smaller time-step may be needed in the first iterations to maintain solver stability.
Have in mind that the first time steps may take longer to converge, do not be alarmed
of this behavior, it is perfectly normal.
Module'9')'Lecture'25' 68'
Tips and tricks in OpenFOAM®
Transient simulations and time-step selection
• If you are interested in the initial transient, you should start using a high order
discretization scheme, with a tight convergence criterion, and the right flow properties.
• If you start from an approximate initial solution obtained from an steady simulation,
the initial transient will not be accurate.
• If the solution is not converging or is taking too long to converge, try to reduce your
time-step.
• If you use the first order Euler scheme, try to use a CFL number less than 1.0 and
preferably in the order of 0.6-0.8, this is in order to keep temporal diffusion to a
minimum. Yes, numerical diffusion also applies in time.
Module'9')'Lecture'25' 69'
Tips and tricks in OpenFOAM®
Transient simulations and time-step selection
• In order to speed up the computation and if you are not interested in the initial
transient, you can start using a large time-step (high CFL).
• When you are ready to sample the quantity of interest, reduce the time-step to get a
CFL less than one and let the simulation run for a while before doing any sampling.
• When using the PIMPLE or PISO solver (with maximum CFL feature enable), the
solver will use as a time-step for the first iteration the value set by the keyword
deltaT in the controlDict dictionary. So if you set a high value, is likely that the
solver will explode.
Module'9')'Lecture'25' 70'
Tips and tricks in OpenFOAM®
Transient simulations and time-step selection
• My advice is to set a low deltaT and then let the solver gradually adjust the time-
step until the desired maximum CFL is reached.
• Some fancy high order numerical schemes (such as the vanLeer, vanAlbada,
superbee, MUSCL, OSPRE – cool names no – ), are hard to start. So it is better to
begin with a small time-step and increase it gradually.
• And by small time-step I mean a time-step that will give a CFL about 0.1.
• Remember, you can change the temporal discretization on the fly. As for the spatial
discretization, first order schemes are robust and second order schemes are
accurate.
Module'9')'Lecture'25' 71'
Tips and tricks in OpenFOAM®
Transient simulations and temporal discretization schemes
• The temporal discretization schemes are set in the fvSchemes dictionary. To select
the schemes you need to use the keyword ddtSchemes.
Module'9')'Lecture'25' 72'
Tips and tricks in OpenFOAM®
Transient simulations and temporal discretization schemes
• It you do not know what temporal discretization scheme to use, go for the Crank-
Nicolson.
• Setting equal to 0 is equivalent to running a pure Euler scheme (robust but first
order accurate). By setting the blending factor equal to 1 you use a pure Crank-
Nicolson (accurate but oscillatory, formally second order accurate). If you set the
blending factor to 0.5, you get something in between first order accuracy and second
order accuracy, or in other words, you get the best of both worlds.
ddtSchemes
{
default CrankNicolson ;
}
Module'9')'Lecture'25' 73'
Tips and tricks in OpenFOAM®
Transient simulations and temporal discretization schemes
• The Crank-Nicolson as it is implemented in OpenFOAM®, uses a blending factor .
ddtSchemes
{
default CrankNicolson ;
}
0 1
Pure Euler Pure Crank-Nicolson
1st order, bounded Module'9')'Lecture'25'
2nd order, bounded 74'
Tips and tricks in OpenFOAM®
Notes on convergence
• Determining when the solution is converged can be really difficult.
• Solutions can be considered converged when the flow field and scalar fields are no
longer changing, but usually this is not the case for unsteady flows. Most flows in
nature and industrial applications are highly unsteady.
• It is a good practice to monitor the residuals. But be careful, residuals are not always
indicative of a converged solution. The final residuals will reach the tolerance
criterion in each iteration, but the flow field may be continuously changing from instant
to instant.
Module'9')'Lecture'25' 75'
Tips and tricks in OpenFOAM®
Notes on convergence
• But be careful, it can be the case that the monitored quantity exhibit a random
oscillatory behavior or a periodic oscillatory behavior, in the former case you are in
the presence of a highly unsteady and turbulent flow with no periodic behavior; in
latter case you may say that you have reached a converged periodic unsteady
solution.
• Remember, for unsteady flows you will need to analyze/sample the solution in a given
time window. Do not take the last saved solution as the final answer.
• If your goal is predicting forces (e.g., drag prediction). You should monitor the forces,
and use them as your convergence criterion.
• The convergence depends on the mesh quality, so a good quality mesh means
faster convergence and accurate solution.
Module'9')'Lecture'25' 11
76'
Tips and tricks in OpenFOAM®
Notes on convergence
• In general, overall mass balance should be satisfied. Remember, the method is
conservative. What goes in, goes out.
• Residuals are not your solution. Low residuals do not automatically mean a correct
solution, and high residuals do not automatically mean a wrong solution.
• Initial residuals are often higher with higher order discretization schemes than with
first order discretization. That does not mean that the first order solution is better.
• Always ensure proper convergence before using a solution. A not converged solution
can be misleading when interpreting the results.
Module'9')'Lecture'25' 77'
Tips and tricks in OpenFOAM®
Notes on convergence
Module'9')'Lecture'25' 78'
Tips and tricks in OpenFOAM®
Notes on convergence
Module'9')'Lecture'25' 79'
Tips and tricks in OpenFOAM®
Monitoring minimum and maximum values of field variables
• I always monitor the minimum and maximum values of the field variables. For me this
is the best indication of stability and accuracy. For this, I use functionObject.
• If at one point of the simulation, velocity is higher that the speed of light (believe me,
that can happen), you know that something is wrong.
• And believe me, using upwind you can get solutions at velocities higher that the
speed of light, you can even do coffee if you want.
• You can also see an oscillatory behavior of the minimum and maximum values of the
monitored quantity. This is also an indication that something is going bananas.
• For some variables (e.g. volume fraction), the method must be bounded. This means
that the values should not exceed some predefined minimum or maximum value
(usually 0 and 1).
Module'9')'Lecture'25' 80'
Tips and tricks in OpenFOAM®
Again, our friend mesh quality
Module'9')'Lecture'25' 81'
Tips and tricks in OpenFOAM®
Mesh quality and cell type
• I do not know how much to stress this, but try to always use a good quality
mesh. Remember, garbage in - garbage out.
• For the same cell count, hexahedral meshes will give more accurate solutions,
especially if the grid lines are aligned with the flow.
• But this does not mean that tetra mesh are no good, by carefully choosing the
numerical scheme, you can get the same level of accuracy. The problem with tetra
meshes are mainly related to the way gradients are computed.
Module'9')'Lecture'25' 12
82'
Tips and tricks in OpenFOAM®
Mesh quality and cell type
• Tetra meshes normally need more computing resources during solving stage. But his
can be easily offset by the time saved during the mesh generation stage.
• Increasing the cells count will likely improve the solution accuracy, but at the cost of a
higher computational cost.
• But attention, finer mesh does not mean a good or better mesh.
• Very often when you refine your mesh (specially when it is done automatically), the
overall quality of the mesh is reduced due to clustering and stretching of the mesh.
Module'9')'Lecture'25' 83'
Tips and tricks in OpenFOAM®
Mesh quality and cell type
• Change in cell size should be smooth.
• In boundary layers, quad, hex, and prism/wedge cells are preferred over triangles,
tetrahedras, or pyramids.
• The mesh density should be high enough to capture all relevant flow features. A
good mesh should be done in such a way that it resolve the physics of interest and it
is adequate for the models used, and not in the fact that the more cells we use the
better the accuracy.
• A good mesh resolve physics, and does not need to follow the CAD model. We are
talking about geometry defeaturing, you do not need to resolve all features of your
CAD model.
Module'9')'Lecture'25' 13
84'
Tips and tricks in OpenFOAM®
Mesh quality and cell type
• There is a new type of meshes in town, polyhedral meshes.
• Many meshing guys and CFDers claim that polyhedral meshes are the panacea of
meshing.
• In polyhedral meshes the cells have more neighbors than in tetrahedral and/or
hexahedral meshes, hence the gradients are approximated better on polyhedral
meshes.
• But attention, this does not mean that this kind of meshes are the solution to all
meshing problems, is just a new religion in the meshing and CFD community, you
need to become a true believer.
Module'9')'Lecture'25' 85'
Tips and tricks in OpenFOAM®
Mesh quality and cell type
• Another interesting property of polyhedral meshes is that they reduce the cell count.
But there is a catch, they increase the number of faces so you need to compute more
fluxes (diffusive and convective).
• Polyhedral meshes are not easy to generate, most of the times you need to start from
tetrahedral meshes.
• Are polyhedral meshes better than hex or tet meshes? You need to conduct your
own numerical experiments.
Module'9')'Lecture'25' 86'
Tips and tricks in OpenFOAM®
Mesh quality and cell type
• Just to end for good the meshing talk:
• So, as long as your results are physically realistic, reliable and accurate; your
mesh is good.
• At the end of the day, the final mesh will depend on the physic involve.
• Know your physics and generate a mesh able to resolve that physics, without
over-doing.
• At this point, I think you got the idea of the relevance of the mesh.
Module'9')'Lecture'25' 14
87'
Tips and tricks in OpenFOAM®
Mesh quality and cell type
Module'9')'Lecture'25' 15
88'
Tips and tricks in OpenFOAM®
My simulation is always exploding
• If after choosing the numerical scheme, linear solvers, and time step, your simulation
always crash, you can try this.
• Set the discretization scheme of the convective terms to upwind.
• Set the discretization scheme of the diffusive terms to Gauss linear
limited 0.5
• Set the discretization scheme of the gradient terms to cellLimited Gauss
linear 1.0
• Set the temporal discretization scheme to euler.
• Use the PISO method, and set nCorrectors 3,'and'
nNonOrthogonalCorrectors 2.'
• Use a high value of viscosity.
• Use Newton-Krylov type linear solvers (do not use multigrid), and set the
minimum number of iterations to 5 (minIter 5) for all variables.
• Use a CFL number of the order of 0.2 and set deltaT to a low value in order to
avoid jumps during the first iteration.
Module'9')'Lecture'25' 89'
Tips and tricks in OpenFOAM®
My simulation is always exploding
• This is one of a hell stable numerical scheme. However is first order accurate.
• If this does not work, you should check your boundary conditions, initial conditions,
physical properties and model properties.
• You should also know the limitations of the solver you are trying to use, maybe the
solver is not compatible or can not solve the physics involve.
Module'9')'Lecture'25' 90'
Tips and tricks in OpenFOAM®
functionObject
• When using utilities (e.g. mirrorMesh), do not use functionObject as they might
cause some problems. Yon can run the utility as follows,
• utility_name –noFunctionObjects
Do this only if you are not interested in computing the actual functionObject
• If you forget to use a functionObject, you do not need to re-run your simulation.
You can use the utility execFlowFunctionObjects, this utility will compute the
functionObject values from the saved solutions. Do not forget to add the new
functionObject to your controlDict before using
execFlowFunctionObjects.
p
P =
So when visualizing your results do not forget to multiply the pressure by the density
in order to get the physical pressure. This will not made much different if you are
working with air, but if you are working with water, you will notice the difference.
Module'9')'Lecture'25' 92'
Tips and tricks in OpenFOAM®
Updating OpenFOAM®
• For those who like to always get the latest version of OpenFOAM®, I will give you a
word of advise.
• Before changing to the newest version, run a series of test cases just to check the
consistency of the results.
• It has come to my attention (and maybe yours as well), that the guys of OpenFOAM®
might change (and will change) something in the new releases and you might not get
the same results.
• No need to say that very often the syntax change from version to version.
• Personally speaking, I have a test matrix of five cases (involving different physics and
models). So before deploying the new version, I always check if I get the same
results. This is part of the continuous and arduous task of verification and validation.
Module'9')'Lecture'25' 16
94'
Module 10
Module'10'*'Lecture'26' 1'
Introductory OpenFOAM® Course
Module'10'*'Lecture'26' 2'
Introductory OpenFOAM® Course
TGIF
&
TGIO
Enjoy OpenFOAM®
el fin!
Module'10'*'Lecture'26' 5'
Thank you for your attention
Module'10'*'Lecture'26' 6'