Anda di halaman 1dari 1334

Disclaimer

“This offering is not approved or


endorsed by OpenCFD Limited, the
producer of the OpenFOAM software
and owner of the OPENFOAM® and
OpenCFD® trade marks.”

Module'0' 1'
These lectures notes are licensed under the Creative Commons
Attribution-ShareAlike 4.0 International License.

To view a copy of this license, visit


http://creativecommons.org/licenses/by-sa/4.0/

Module'0' 2'
Introductory OpenFOAM® Course

University of Genoa, DICCA


Dipartimento di Ingegneria Civile, Chimica e Ambientale

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®?

•  And I hope not to see hands up.

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.

•  I know two or three things.

•  Snug as a bug in a rug.

•  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)

• Running my first OpenFOAM® case. • Before we start - Housekeeping issues.


• Setting cases in OpenFOAM®. Choosing • Introduction - Overview of OpenFOAM®.
boundary conditions, initial conditions, and • Physical models, solvers and utilities.
physical models. • Library organization and code structure.
• Selecting solver parameters. • Running my first OpenFOAM® case.
Day 1

• Controlling solution behavior and solution • Introduction to post-processing and scientific


monitoring. visualization with paraFoam.

• CFD simulation lifecycle.


• Scientific visualization using paraFoam. • Finite Volume Discretization: theoretical
• Sampling, function objects and co-processing in background.
OpenFOAM®. • Meshing preliminaries.
• Assessing mesh quality. • Running in parallel.
• Mesh generation with OpenFOAM®. • How to choose the right numerics.
Day 2

Introduction to blockMesh and snappyHexMesh. • Getting convergence from scratch.


• Hands-on tutorials. • Hans-on tutorials.

• 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

Helyx-os gui. • Hands-on tutorials.

(4:30 pm – 5:00 pm)


• Hands-on tutorials.

• Basics of C++ programming.


• Extending OpenFOAM® capabilities. • Programming in OpenFOAM®: building blocks.
• OpenFOAM® extended project. • OpenFOAM solvers: brief overview and
• Advanced physical modeling capabilities. walkthrough.
• Moving bodies, sliding grids and MRF. • Modifying OpenFOAM® solvers, utilities and
• Turbulence modeling (RANS and LES). boundary conditions.
Day 4

Tips and tricks. • OpenFOAM® documentation.


Before we begin


• Hands-on tutorials. • Implementing boundary and initial conditions
End of the day. Last minute issues and additional questions.

using external libraries.


Provisional timetable

• Numerical optimization and design of


experiments: theoretical background.
• Coupling Dakota with OpenFOAM®.
• Wrap-up session.
• Running parametric studies, optimization
• Open Forum: Questions, doubts and attendees
studies and DACE experiments using Dakota.
own cases.
Day 5

• Surrogate based optimization for engineering


design.
• Hands-on tutorials.
7" made to adjust the course content to suit the needs of the attendees
Before we begin

Linux for open source CFD

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

•  A virtual machine distribution and an ISO distribution are available for


download.

•  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.

•  By the way, in my personal copy I have many multi-physics, CFD, FEA,


CAD, multibody dynamics, visualization, numerical libraries, meshing,
scientific computing, python and developing applications installed.

Module"0" 10"
Before we begin
Linux for open source CFD

•  FYI, I regularly update the distributions.

•  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,

•  alias PTOFC='cd $PATH_TO_TUTORIALS'

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,

•  tar –zxvf file_name.tar.gz

•  On the other side, if you are interested in compressing a directory, you can
proceed as follows,

•  tar –zcvf file_name.tar.gz directory_name

Module"0" 14"
Before we begin

•  By the way, use the tutorials included in the training


material just for recreational, instructional, or learning
purposes and not for validation, benchmarking or
standard practices.

Module"0" 15"
Before we begin

Installing OpenFOAM® - Working on your own

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.

•  FYI, I do not like Ubuntu.

•  To install OpenFOAM®, just follow the instructions given in


http://www.openfoam.org/

•  If for any reason the instructions given in http://www.openfoam.org/ do


not work for you, you can use my instructions. They work fine with Linux
OpenSUSE 12.1 or newer versions.

•  You can find my instructions in the supplement slides.

•  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

As we will be working with the CFD simulation


lifecycle (from geometry generation, to mesh
generation, to governing equations solution, to
post-processing) by using open source tools,
the following additional tools might come in
handy:

Module"0" 18"
Before we begin
For geometry generation, mesh generation, and visualization, the following open source
applications might come in handy:

CAD - 3D modeling - Surface modeling


•  Salome (http://www.salome-platform.org/). *
•  Google SketchUp (http://sketchup.google.com/). **
•  pythonOCC (http://www.pythonocc.org/). *
•  Blender (http://www.blender.org/). *
•  Openscad (http://www.openscad.org/). *
•  OpenVSP (http://www.openvsp.org/). *

* Note: precompiled binaries are available for these applications.


** Note: it is possible to install Google SketchUp in linux by using wine
(http://www.winehq.org/).
Module"0" 19"
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/).

* Note: precompiled binaries are available for these applications.

Module"0" 20"
Before we begin
For geometry generation, mesh generation, and visualization, the following open source
applications might come in handy:

Mesh manipulation tools


•  Mesquite (http://trilinos.sandia.gov/packages/mesquite/index.html).
•  Stellar (http://www.cs.berkeley.edu/~jrs/stellar/).
•  Pyramid (http://www.openchannelsoftware.org/projects/Pyramid).
•  MSTK/Mesh tools (https://software.lanl.gov/MeshTools/trac).
•  Meshkit (http://press3.mcs.anl.gov/sigma/meshkit-library/).

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/) . *

* Note: precompiled binaries are available for these applications.

Module"0" 22"
Before we begin
For geometry generation, mesh generation, and visualization, the following open source
applications might come in handy:

STL files manipulation


•  Meshlab (http://meshlab.sourceforge.net/).
•  Netfabb (Freeware) (http://www.netfabb.com/). *
•  ADMESH (http://www.varlog.com/admesh-htm).

* Note: precompiled binaries are available for these applications.

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).

Note: precompiled binaries are available for these applications.

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.

If you want to keep things to a minimum, install only:


•  Salome
•  Paraview (in addition to the paraview version distributed with OpenFOAM®)
•  Helyx-os
•  OpenFOAM®
•  DAKOTA
•  swak4foam
•  PyFoam

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

•  Introduce OpenFOAM® (this is the workhorse of the course).

•  By the end of the week, help you to become an out-of-the-box


user of OpenFOAM®.

•  But also, introduce you the building blocks to help you to


become an OpenFOAM® user at a developer level.""

•  By friday, you should also be able to make simple modifications


to OpenFOAM® solvers and utilities, and to explore the source
code to learn more about the library.

Module"0" 30"
Course objectives

•  Introduce you to CAD, meshing and post processing using


open source tools, and how to use these tools together with
OpenFOAM®

•  Demystify the FVM in order to teach you how to choose the


right numerics.

•  Give you some guidelines of how to assess mesh quality, and


how to avoid or reduce mesh induce errors.

•  Do some post-processing and data analysis to get quantitative


and qualitative results, and use this information to take
decisions.

Module"0" 31"
Course objectives

•  Address your doubts about the tools used and methods


involved.

•  Not to confuse you at a higher level.

•  Help you to get a degree?.

Module"0" 32"
Prerequisites

•  No prior knowledge of the tools to be used (OpenFOAM®,


Salome, Dakota and so on), C++ or Linux is required, but a
basic knowledge of Linux is beneficial.

•  A basic knowledge of CFD, scientific computing, and numerical


optimization is also desirable.

•  For hands-on examples, you are required to bring your own


laptop with a working installation of Linux and OpenFOAM®
(version 2.3.0 or 2.3.x preferable).

•  By the way, I use OpenSUSE Linux distribution. But you are


free to install any Linux distribution.

Module"0" 33"
What I will try to keep to a minimum

•  This is not a C++ course, so I will try to keep C++ programming


to a minimum.

•  This is not a course on Finite Volume Methods (FVM) -


Computational Fluid Dynamics (CFD), so I will keep the theory
to a minimum.

•  This is not a Linux system administration course, so I will try to


keep Linux system administration issues to a minimum.

•  I am doing this for your own convenience and keeping things


easy. Remember, after all this is an introductory course.

Module"0" 34"
What I need from you

•  Ask as many questions as you like and feel free to interrupt me


at anytime.
•  Helps me understand what you are missing.
•  Helps you clarify misunderstandings.
•  Helps others with the same question.

Module"0" 35"
What I need from you

•  Sometimes I have the tendency to go really fast in some issues,


please stop me if you are not following me.
•  Tell me if you do not understand.
•  Tell me if an example does not work.
•  Let me know if you have any specific requirement.

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,

the physics is yours.

Module"0" 37"
What I need from you

•  Based on this course, I am trying to write some lectures notes


on CFD and related topics, they are far from being complete
but you can take a look at them.

•  A help is needed and much appreciated. To help me, take a


look at the lectures notes and let me know if you find errors.
Suggestions for better wording, figures or new material are also
welcome.

•  The lectures notes are available with the course’s material in


the USB key.

•  Follow-up problems, questions and suggestions at


joel.guerrero@unige.it.
Module"0" 38"
What about OpenFOAM® documentation?

•  OpenFOAM® comes with many very powerful


features but they hard to use and not very well
documented.
•  In general, the learning curve is steep.
•  If you are new to the Linux world, it can be even
more challenging and this in fact makes the learning
curve steeper.

Module"0" 39"
What about OpenFOAM® documentation?

•  OpenFOAM® comes with an user guide and


programmer’s guide.
•  At a first glance, you will have the impression that the
user and programmer’s guide do not provide much
details.
•  But before complaining about the lack of
documentation,

Module"0" 40"
What about OpenFOAM® documentation?

… read carefully and digest all the information


contained in the user guide and programmer’s
guide.

It might not be much, but it is enough to get you


started.

FYI, most of this training is based on the user


guide and programmer’s guide.

Module"0" 41"
What about OpenFOAM® documentation?

Remember,

You have the source code so take


some time and explore it.

Module"0" 42"
How to learn more about OpenFOAM®

•  Read the user and programmer’s guide.


•  Explore the source code and doxygen documentation
(OpenFOAM® C++ documentation)
•  Get familiar with all the applications and utilities
available by doing all the tutorials available in the
OpenFOAM® installation (or at least those that
interest you), and dig into each one to learn more
about all features available.

Module"0" 43"
How to learn more about OpenFOAM®

•  Also, with the course material 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 folder 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.

Module"0" 44"
How to learn more about OpenFOAM®

•  By the way, use the tutorials just for recreational,


instructional, or learning purposes and not for
validation or benchmarking.

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.

•  The Doxygen manual


(http://www.openfoam.org/docs/cpp/).

•  CFD-Online OpenFOAM® user discussion group


(http://www.cfd-online.com/Forums/openfoam/).

•  OpenFOAM® wiki (http://www.openfoamwiki.net).

•  OpenFOAM® website (http://www.openfoam.com/).

•  OpenFOAM® extend project


(http://www.extend-project.de).

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

1.  OpenFOAM® brief overview

Module'1')'Lecture'1' 2'
OpenFOAM® brief overview
General description:
•  OpenFOAM® stands for Open Source Field Operation and
Manipulation.

•  OpenFOAM® is first and foremost a C++ library used to solve


partial differential equations (PDEs), and ordinary differential
equations (ODEs).

•  It comes with several ready-to-use or out-of-the-box solvers,


pre-processing utilities and post-processing utilities.

•  It is licensed under the GNU General Public License (GPL).


That means it is freely available and distributed with the source
code.

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.

•  It is under active development, its capabilities mirror those of


commercial CFD applications.

•  It counts with a wide-spread community around the world


(industry, academia and research labs).

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.

•  Collocated polyhedral unstructured meshes.

•  Second order accuracy in space and time. Many discretization


schemes available (including high order methods).

•  Pressure-velocity coupling via segregated methods (SIMPLE


and PISO).

•  But also coupled solvers are under active development.

Module'1')'Lecture'1' 6'
OpenFOAM® brief overview
Brief overview – Description and implementation:
•  Massive parallelism through domain decomposition.

•  It comes with it own mesh generation tools.

•  It also comes with many mesh manipulation and conversion


utilities.

•  Meshes generated using many of the major mesh generators


can be converted to OpenFOAM® format.

•  All components implemented in library form for easy re-use.

Module'1')'Lecture'1' 7'
OpenFOAM® brief overview
Brief overview – Physical models:
•  Physical modeling library:

•  Thermophysical models and physical properties for liquids


and gases.

•  Transport/rheology models. Newtonian and non-Newtonian


viscosity models.

•  Extensive turbulence modeling capabilities (RANS, SRS,


DES and LES).

Module'1')'Lecture'1' 8'
OpenFOAM® brief overview
Brief overview – Physical models:
•  Physical modeling library:

•  Lagragian particle methods (DSMC, MD).

•  Discrete particle modeling (DPM, MP-PIC).

•  VOF method for multiphase flows .

•  Interphase momentum transfer models for multiphase flows.

•  Combustion, flame speed, chemical reactions, porous


media, etc.

Module'1')'Lecture'1' 9'
OpenFOAM® brief overview
Brief overview – Solvers:
•  OpenFOAM® comes with several ready-to-use or out-of-the-
box solvers:

•  Basic solvers: Laplace, potential flow, passive scalar


transport.

•  Incompressible and compressible flows: segregated


pressure-based algorithms (SIMPLE and PISO).

•  Heat transfer modeling capabilities: buoyancy-driven flows,


conjugate heat transfer.

Module'1')'Lecture'1' 10'
OpenFOAM® brief overview
Brief overview – Solvers:
•  OpenFOAM® comes with several ready-to-use or out-of-the-
box solvers:

•  Multiphase flows: Euler-Euler, VOF for free surfaces,


multiple phases, cavitation, phase change.

•  Combustion and fire dynamic solvers.

•  Stress analysis, electromagnetics, acoustics, MHD, fluid-


structure interaction, etc.

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.

•  OpenFOAM® is designed to be a flexible and programmable


environment for numerical simulations by using a high level
programming language that is a direct representation of the
equations being solved.

•  New solvers can be easily implemented using OpenFOAM®


high level programming or equation mimicking, e.g.:

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)
);

Correspondence between the implementation and the original


Module'1')'Lecture'1' 13'
equation is clear.
OpenFOAM® brief overview
Brief overview – Customizing solvers:
•  Equation mimicking syntax, achieved through the use of object
oriented programming, enables users to create custom solvers
with relative ease.

•  Users have total freedom to modify existing solvers or use them


as the starting point for new solvers.

•  Access to complete source: no secret modeling tricks or black


magic.

Module'1')'Lecture'1' 14'
OpenFOAM® brief overview
Brief overview – Customizing solvers:
•  OpenFOAM® design encourages code and libraries re-use.

•  As solvers can be tailored by a user for a specific need,


OpenFOAM® is ideal for research and development.

•  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.

•  All applications and utilities, are compiled using common


functionality in the collection of libraries distributed with
OpenFOAM®.

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.

•  Transparent solution algorithms which can be viewed by the


user, encouraging better understanding of the underlying
physics.

Module'1')'Lecture'1' 17'
OpenFOAM® brief overview

OpenFOAM® is an excellent piece of C++


and software engineering. Decent piece of
CFD code.
H. Jasak

Module'1')'Lecture'1' 18'
Module 1

Module'1')'Lecture'2' 1'
Today’s lecture

1.  OpenFOAM® directory organization


2.  Directory structure of an application/utility
3.  Applications/utilities in OpenFOAM®
4.  Directory structure of an OpenFOAM® case

Module'1')'Lecture'2' 2'
Today’s lecture

1.  OpenFOAM® directory organization


2.  Directory structure of an application/utility
3.  Applications/utilities in OpenFOAM®
4.  Directory structure of an OpenFOAM® case

Module'1')'Lecture'2' 3'
OpenFOAM® directory organization

$WM_PROJECT_DIR If you installed OpenFOAM® in the default


location, the directory $WM_PROJECT_DIR should
applications be:

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

wmake Typing wcleanAll will search all the directories


below the current one and will delete all the
Allwmake compiled files. So if you type wcleanAll in
Additional
$WM_PROJECT_DIR, it will delete all the compiled
files files in your OpenFOAM® installation.
Module'1')'Lecture'2' 4'
OpenFOAM® directory organization

$WM_PROJECT_DIR

applications By the way, as I use OpenFOAM® version 2.3.x,


the environment variable $WM_PROJECT_DIR
bin points to:
doc
$HOME/OpenFOAM/OpenFOAM-2.3.x
etc

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

bin The entries starting with the symbol $ are


environment variables. You can find out the value
doc of an environment variable by echoing its value,
etc for example:

platforms
echo $WM_PROJECT_DIR
src

tutorials will give you the following output on the terminal


$HOME/OpenFOAM/OpenFOAM-2.3.x
wmake

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

bin By the way, you can go to any of these directories


by using the predefined aliases set by
doc OpenFOAM® (see $WM_PROJECT_DIR/etc/
etc config/alias.sh). For example:

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

Let us now study the applications directory

Module'1')'Lecture'2' 8'
OpenFOAM® directory organization
$WM_PROJECT_DIR

applications

solvers

test

utilities

Let us visit applications directory. Type in the terminal app or


cd $WM_PROJECT_DIR/applications. Here you will find the following
sub-directories:
•  solvers, which contains the source code for the distributed solvers.
•  test, which contains the source code of several test cases that show the usage
of some of the OpenFOAM® classes.
•  utilities, which contains the source code for the distributed utilities.
There is also an Allwmake script, which will compile all the content of solvers
and utilities. To compile the test cases in test go to the desired test case
Module'1')'Lecture'2' 9'
directory and compile it by typing wmake.
OpenFOAM® directory organization

Let us now study the bin directory

Module'1')'Lecture'2' 10'
OpenFOAM® directory organization

$WM_PROJECT_DIR

bin

Let us visit the bin directory:


•  The bin directory contains shell scripts, such as paraFoam, foamNew,
foamLog, foamJob, etc.

Module'1')'Lecture'2' 11'
OpenFOAM® directory organization

Let us now study the doc directory

Module'1')'Lecture'2' 12'
OpenFOAM® directory organization

$WM_PROJECT_DIR

doc

Let us visit the doc directory:


•  The doc directory contains the documentation of OpenFOAM®, namely; user
guide, programmer’s guide and Doxygen generated documentation in html format.

•  The Doxygen documentation needs to be compiled by typing Allwmake doc in


$WM_PROJECT_DIR.

•  You can access the Doxygen documentation online,


http://www.openfoam.org/docs/cpp/

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

Let us now study the etc directory

Module'1')'Lecture'2' 15'
OpenFOAM® directory organization

$WM_PROJECT_DIR

etc

Let us visit the etc directory:


•  The etc directory contains the environment files, global OpenFOAM®
instructions, and the default thermochemical database thermoData/
thermoData.

•  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

Let us now study the platforms directory

Module'1')'Lecture'2' 17'
OpenFOAM® directory organization
$WM_PROJECT_DIR

platforms

linux64GccDPOpt

bin

lib

Let us visit platforms directory. Type in the terminal


cd $WM_PROJECT_DIR/platforms.
This directory contains the binaries generated when compiling the applications
directory (after compilation the binaries will be located in the directory
$WM_PROJECT_DIR/platforms/linux64GccDPOpt/bin) and the libraries
generated by compiling the source code in the src directory (after compilation, the
libraries will be located in the directory $WM_PROJECT_DIR/platforms/
linux64GccDPOpt/lib).
If you installed OpenFOAM® following the default instructions, you compiled the 64
bits version, using the gcc compiler, with double precision, and optimized version.
Module'1')'Lecture'2'
This is reflected in the name of the directory linux64GccDPOpt. 18'
OpenFOAM® directory organization

Let us now study the src directory

Module'1')'Lecture'2' 19'
OpenFOAM® directory organization
$WM_PROJECT_DIR

src/ …

Let us visit src directory. Type in the terminal src or


cd $WM_PROJECT_DIR/src.
This directory contains the source code for all the foundation libraries, this is the
core of OpenFOAM®. It is divided in different subdirectories and each of them
can contain several libraries.
A few interesting directories are:
•  finiteVolume. This library provides all the classes needed for the finite
volume discretization, such as mesh handling, finite volume discretization
operators (divergence, laplacian, gradient, fvc/fvm and so on), and boundary
conditions (fields/fvPatchFields). In lnInclude you also find the very
important file fvCFD.H, which is included in most applications.
•  OpenFOAM. This core library includes the definitions of the containers used for
the operations, the field definitions, the declaration of the mesh and mesh
features such as zones and sets.
Module'1')'Lecture'2' 20'
•  turbulenceModels, which contains many turbulence models.
OpenFOAM® directory organization
$WM_PROJECT_DIR

src/ …

Let us visit src directory. Type in the terminal src or


cd $WM_PROJECT_DIR/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

Let us now study the tutorials directories

Module'1')'Lecture'2' 22'
OpenFOAM® directory organization

$WM_PROJECT_DIR

tutorials

Let us visit the tutorials directory. Type in the terminal tut or


cd $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

Let us now study the wmake directory

Module'1')'Lecture'2' 24'
OpenFOAM® directory organization

$WM_PROJECT_DIR

wmake

Let us visit the wmake directory.

OpenFOAM® uses a special make command: 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

•  We just studied the directory WM_PROJECT_DIR, which


contains the original installation of OpenFOAM®.

•  Any modification you add to the source code in


WM_PROJECT_DIR, will affect the whole library.

•  Tip of day,

Module'1')'Lecture'2' 26'
OpenFOAM® directory organization

Unless you know what are you doing,


do not modify anything in the original
installation ($WM_PROJECT_DIR),
except for updates!
Module'1')'Lecture'2' 27'
OpenFOAM® directory organization

Let us now study the OpenFOAM® user directory

Module'1')'Lecture'2' 28'
OpenFOAM® directory organization
$HOME/OpenFOAM
$WM_PROJECT_DIR
$WM_PROJECT_USER_DIR

User directory $WM_PROJECT_USER_DIR (USER_NAME-2.3.x)


In $WM_PROJECT_USER_DIR directory, all user files are located.
If you are going to develop 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.
It is recommended to create two more directories:
$WM_PROJECT_USER_DIR/run
$WM_PROJECT_USER_DIR/src

This is done so you do not modify anything in the original installation,


except for updates!
Module'1')'Lecture'2' 29'
OpenFOAM® directory organization
$HOME/OpenFOAM
$WM_PROJECT_DIR
$WM_PROJECT_USER_DIR

User directory $WM_PROJECT_USER_DIR (USER_NAME-2.3.x)


Place user developed library source code in $WM_PROJECT_USER_DIR/src
directory, with the same directory structure as in $FOAM_SRC.
In the $WM_PROJECT_USER_DIR/run directory (which has the alias run) you can
place your cases (this is not compulsory).
In $WM_PROJECT_USER_DIR/platforms/linux64GccDPOpt/bin, the binaries
of the user developed applications will be located; whereas, in
$WM_PROJECT_USER_DIR/platforms/linux64GccDPOpt/lib, the binaries of
the user developed libraries will be located.

This is done so you do not modify anything in the original installation,


except for updates!
Module'1')'Lecture'2' 30'
OpenFOAM® directory organization

Remember, you can do all the


modifications you want in your user
directory ($WM_PROJECT_USER_DIR).
By proceeding in this way, you do not
mess around with the original
installation.
Module'1')'Lecture'2' 31'
OpenFOAM® directory organization

Environment variables

•  Remember, OpenFOAM® uses its own environment variables.

•  OpenFOAM® environment settings are contained in the


OpenFOAM-2.3.x/etc directory.

•  If you installed OpenFOAM® in the default location, they should


be in:

•  $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

•  By sourcing the file $WM_PROJECT_DIR/etc/bashrc, we start


to use OpenFOAM® environment variables.

•  By default, OpenFOAM® uses the system compiler and the


system MPI compiler.
Module'1')'Lecture'2' 33'
OpenFOAM® directory organization

WARNING
Remember, when you use OpenFOAM® you are using its
environment settings, that is, path to libraries and
compilers.

So if you are developing your own software or compiling


applications, and you are having compilation problems
due to conflicting libraries or missing compilers, try to
unload OpenFOAM® environment variables
Module'1')'Lecture'2' 34'
Today’s lecture

1.  OpenFOAM® directory organization


2.  Directory structure of an application/utility
3.  Applications/utilities in OpenFOAM®
4.  Directory structure of an OpenFOAM® case

Module'1')'Lecture'2' 35'
Directory structure of an OpenFOAM® solver

Directory structure of an OpenFOAM® solver

Module'1')'Lecture'2' 36'
Directory structure of an OpenFOAM® solver

$WM_PROJECT_DIR/applications/solvers

appName The appName directory contains the source


code.
appName.C
The Make directory contains compilation
createFields.H instructions.
appName/appName.C: is the actual source
code.
Make
appName/createFields.H: declares all
files the field variables and initializes the solution.
options Make/files: names all the source files
(.C). Specifies the appName name and
location of the output file.
Make/options: specifies directories to
search for include files and libraries to link
the solver against.
Module'1')'Lecture'2' 37'
Directory structure of an OpenFOAM® solver
$WM_PROJECT_USER_DIR /applications/solvers
appName
appName.C
createFields.H
Make
files
options

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

Directory structure of an OpenFOAM® utility

Module'1')'Lecture'2' 39'
Directory structure of an OpenFOAM® utility

$WM_PROJECT_DIR/applications/utilities

appName The appName directory contains the source


code.
appName.C
The Make directory contains compilation
header_files(.H) instructions.
appName/appName.C: is the actual source
code.
Make
appName/header_files (.H): header
files files needed to compile the utility.
options Make/files: names all the source files
(.C). Specifies the appName name and
location of the output file.
Make/options: specifies directories to
search for include files and libraries to link
the utility against.
Module'1')'Lecture'2' 40'
Directory structure of an OpenFOAM® utility
$WM_PROJECT_USER_DIR /applications/utilities
appName
appName.C
Header files (.H)
Make
files
options

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

1.  OpenFOAM® directory organization


2.  Directory structure of an application/utility
3.  Applications/utilities in OpenFOAM®
4.  Directory structure of an OpenFOAM® case

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

You have the source code right there.

So take your time and dig into each directory to get a


complete description of each solver.

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:

Automatic split hex mesher. Refines and


snaps to surface.
Module'1')'Lecture'2' 48'
Utilities in OpenFOAM®
•  For example, in the sub-directory postProcessing/velocityField you will find
several sub-directories containing the source code of the following utilities:

•  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:

Calculates and writes the second invariant of the velocity


gradient tensor.
Q = 0.5*(sqr(tr(gradU)) - tr(((gradU)&(gradU)))) [1/s^2]
The -noWrite option just outputs the max/min values without
writing the field.
Module'1')'Lecture'2' 49'
Utilities in OpenFOAM®

REMEMBER

You have the source code right there.

So take your time and dig into each directory to get a


complete description of each utility.

Module'1')'Lecture'2' 50'
Applications and libraries in OpenFOAM®

•  If you are interested in knowing all the solvers, utilities and


libraries that come with OpenFOAM®, you can read the
applications and libraries section in the user guide (chapter 3).

•  In the directory $WM_PROJECT_DIR/doc/ you will find the


OpenFOAM® documentation in pdf format. To open the user
guide type in the terminal,

•  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®

•  The solvers in the OpenFOAM® distribution are in the


$FOAM_SOLVERS directory, reached quickly by typing sol in
the terminal.

•  The utilities in the OpenFOAM® distribution are in the


$FOAM_UTILITIES directory, reached quickly by typing util
in the terminal.

•  The source code of the libraries in the OpenFOAM® distribution


is in the $FOAM_SRC directory, reached quickly by typing src in
the terminal. Module'1')'Lecture'2' 53'
Today’s lecture

1.  OpenFOAM® directory organization


2.  Directory structure of an application/utility
3.  Applications/utilities in OpenFOAM®
4.  Directory structure of an OpenFOAM® case

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®.

•  You can extract the tutorials wherever you want. However, I


highly recommend you to extract them in your OpenFOAM®
user directory or in $WM_PROJECT_USER_DIR/run. From now
on, this directory will become

•  $PTOFC
(abbreviation of path to OpenFOAM® course).

•  You can add this alias to your .bashrc file,

•  alias PTOFC='cd $PATH_TO_TUTORIALS’


Module'1')'Lecture'2' 58'
Directory structure of an OpenFOAM® case
•  By the way, to uncompress the tutorials go to the directory
where you copied the training material and type in the terminal,

•  tar –zxvf file_name.tar.gz

•  On the other side, if you want to compress a directory you can


proceed as follows,

•  tar –zcvf file_name.tar.gz directory_name

Module'1')'Lecture'2' 59'
Directory structure of an OpenFOAM® case

•  At this point we are ready to run our first


case.
•  So buckle up and enjoy the ride.

Module'1')'Lecture'2' 60'
Module 1

Module'1')'Lecture'3' 1'
Today’s lecture

1.  Before we start


2.  My first OpenFOAM® case setup
3.  A deeper view to my first OpenFOAM® case
setup
4.  My second OpenFOAM® case setup
5.  My third OpenFOAM® case setup
6.  My first 3D OpenFOAM® case setup
7.  Hands-on session

Module'1')'Lecture'3' 2'
Today’s lecture

1.  Before we start


2.  My first OpenFOAM® case setup
3.  A deeper view to my first OpenFOAM® case
setup
4.  My second OpenFOAM® case setup
5.  My third OpenFOAM® case setup
6.  My first 3D OpenFOAM® case setup
7.  Hands-on session

Module'1')'Lecture'3' 3'
Before we start

Before we run our first


OpenFOAM® case

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

HUMAN DECISION MAKER


DECISION MATRIX OR
GEOMETRY GEOMETRY GEOMETRY

MESH MESH MESH

SOLVER CO-PROCESSING SOLVER CO-PROCESSING SOLVER CO-PROCESSING

PARAMETRIZATION PARAMETRIZATION PARAMETRIZATION


OPTIMIZATION OPTIMIZATION OPTIMIZATION

VISUALIZATION VISUALIZATION VISUALIZATION

CASE 1 CASE 2 CASE N

AUTOMATIC POST-PROCESSING
Module'1')'Lecture'3' 7'
Before we start

Now we are ready


to run our first
OpenFOAM® case

Module'1')'Lecture'3' 8'
Today’s lecture

1.  Before we start


2.  My first OpenFOAM® case setup
3.  A deeper view to my first OpenFOAM® case
setup
4.  My second OpenFOAM® case setup
5.  My third OpenFOAM® case setup
6.  My first 3D OpenFOAM® case setup
7.  Hands-on session

Module'1')'Lecture'3' 9'
My first OpenFOAM® case setup

Flow in a lid-driven square cavity

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

Pressure field Velocity magnitude field

Module'1')'Lecture'3' 13'
My first OpenFOAM® case setup

•  Let us go to the directory:

$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?

•  To do this, you can proceed as follows:

•  icoFoam > log.icoFoam | tail –f log.icoFoam

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

•  icoFoam > log.icoFoam 2>&1 | tail –f log.icoFoam

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,

•  icoFoam > log.icoFoam &

This will redirect your standard output to an ascii file with the name log.icoFoam.
The bash operator & will send the job to background.

•  Now you cab type in the terminal windows:

•  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:

•  icoFoam > log.icoFoam

This will redirect your standard output to an ascii file with the name log.icoFoam.

•  Now, in a new terminal window type,

•  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,

•  icoFoam | tee log.icoFoam

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,

•  icoFoam > /dev/null

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 [options] <foamApplication>

•  To run this case with pyFoamPlotRunner.py, in the terminal type:

•  pyFoamPlotRunner.py icoFoam

•  If you need help or want to know all the options available,

•  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:

•  icoFoam > log.icoFoam &

•  pyFoamPlotWatcher.py log.icoFoam

This will plot the information saved in log.icoFoam. To use


pyFoamPlotWatcher.py you will need to install gnuplot.

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.

Refer to the UserModule'1')'Lecture'3'


Guide for more Information 30'
My first OpenFOAM® case setup
Stopping the simulation
•  If you want to stop the simulation and save the solution, in the controlDict
dictionary made the following modification,

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.

Refer to the UserModule'1')'Lecture'3'


Guide for more Information 31'
My first OpenFOAM® case setup
Stopping the simulation
•  You can also kill the process. For instance, if you did not launch the solver in
background, go to its terminal window and press ctrl-c. This will stop your
simulation, but it will not save your last time-step or iteration, so be careful.

•  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:

icoFoam > log.icofoam | tail –f log.icofoam

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,

foamListTimes -noZero | xargs rm -rf

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

1.  Before we start


2.  My first OpenFOAM® case setup
3.  A deeper view to my first OpenFOAM® case
setup
4.  My second OpenFOAM® case setup
5.  My third OpenFOAM® case setup
6.  My first 3D OpenFOAM® case setup
7.  Hands-on session

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)
);

•  hex means that it is a structured hexahedral block.


•  (0 1 2 3 4 5 6 7) are the vertices used to define the block (and yes, the order
is important). Each hex block is defined by eight vertices, in sequential order.
Where the first vertex in the list represents the origin of the coordinate system.
•  (20 20 1) is the number of mesh cells in each direction.
•  simpleGrading (1 1 1) is the expansion ratio or mesh stretching, in this case
equidistant.

Module'1')'Lecture'3' 43'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/blockMeshDict dictionary

The blockMeshDict dictionary also defines three boundary patches:

boundary frontAndBack //NAME


( {
movingWall //NAME type empty; //TYPE
{ faces
type wall; //TYPE (
faces (0 3 2 1) //FACE
( (4 5 6 7) //FACE
(3 7 6 2) //FACE );
) ; }
} );

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

•  This is how the block created with blockMeshDict looks like,

Refer to the UserModule'1')'Lecture'3'


Guide for more Information 47'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/blockMeshDict dictionary

•  To sum up, the blockMeshDict dictionary generates a block with:


•  x/y/z dimensions 0.1/0.1/0.01.
•  20 x 20 x 1 cells.
•  wall fixedWalls patch at three sides.
•  wall movingWall patch at one side.
•  empty frontAndBack patch at two sides.

•  If you are interested in visualizing the actual blocking, you can use paraFoam with
the following option,
•  paraFoam –block'

Refer to the UserModule'1')'Lecture'3'


Guide for more Information 48'
A deeper view to my first OpenFOAM® case setup
The constant/polyMesh/boundary file

•  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 system directory consists of three dictionary files:


•  controlDict
•  fvSchemes
•  fvSolution
•  controlDict contains general instructions on how to run the case.
•  fvSchemes contains instructions for the discretization schemes that will be
used for the different terms in the equations.
•  fvSolution contains instructions on how to solve each discretized linear
equation system.
•  Do not worry, we are going to study in details the most important entries of
each dictionary.
Refer to the UserModule'1')'Lecture'3'
Guide for more Information 52'
A deeper view to my first OpenFOAM® case setup
The 0 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)

•  dimensions [0 1 -1 0 0 0 0]; states that the dimension of U is m/s.


•  internalField uniform (0 0 0); sets U to zero internally (initial conditions).
•  The boundary patches movingWall and fixedWalls are given the type
fixedValue; with value uniform (1 0 0), and (0 0 0) respectively (boundary
conditions).
•  The frontAndBack patch is given type empty, indicating that no solution is
required in that direction since the case is 2D.
•  You should now be able to understand the file 0/p.
•  The time step directories are similar but the internalField now contains the
solution. There is also a phi file, containing the resulting face fluxes that are needed
to yield a perfect restart.

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.

•  It is of interest to have a graphical representation of the residual. To do so, the


foamLog utility is used.

•  Let us now execute foamLog utility. In the terminal type:

•  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).

•  Type foamLog -help for more information.


Module'1')'Lecture'3' 56'
A deeper view to my first OpenFOAM® case setup
At this point you should have realized a few things:

•  OpenFOAM® is fully dimensional. You need to define the dimensions for


each field data and physical properties. Your dimensions shall be
consistent.

Module'1')'Lecture'3' 57'
A deeper view to my first OpenFOAM® case setup
Dimensions in OpenFOAM®

No. Property Unit Symbol

1 Mass Kilogram kg

2 Length meters m

3 Time second s

4 Temperature Kelvin K

5 Quantity moles mol

6 Current ampere A
Luminuous
7 candela cd
intensity

dimensions [kg, m, s, K, mol, A, cd]


Module'1')'Lecture'3' 58'
A deeper view to my first OpenFOAM® case setup
At this point you should have realized a few things:
•  Each file in the case directory has a header, you should always keep this
header, if not, OpenFOAM® will complain.

/*--------------------------------*- C++ -*----------------------------------*\


| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object controlDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

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

/*--------------------------------*- C++ -*----------------------------------*\


| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

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.

/*--------------------------------*- C++ -*----------------------------------*\


| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

Module'1')'Lecture'3' 61'
A deeper view to my first OpenFOAM® case setup
At this point you should have realized a few things:

•  If you misspell something or forget a compulsory keyword or file,


OpenFOAM® will complain and will tell you where is and what is the error.

•  It is very important to read the screen and understand the output.

“Experience is simply the name we give our mistakes.”'

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

--> FOAM FATAL IO ERROR:

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

--> FOAM FATAL IO ERROR:

banana_endTime is not in enumeration:


4
(
endTime
nextWrite
noWriteNow
writeNow
)

file: /home/cfd/my_cases_course/cavity/system/controlDict.stopAt at line 24.

From function NamedEnum<Enum, nEnum>::read(Istream&) const


in file lnInclude/NamedEnum.C at line 72.

FOAM exiting Module'1')'Lecture'3' 65'


A deeper view to my first OpenFOAM® case setup
•  Instead, you should worry about the SIGFPE error signal. This error signal indicates
that something went really wrong (erroneous arithmetic operation).
•  This message (that seems a little bit difficult to understand), is giving you a lot
information.
•  For instance, this output is telling us that the error is due to SIGFPE and the class
associated to the error is lduMatrix. It is also telling you that the GAMGSolver
solver is the affected one (likely the pressure is becoming unbounded).
#0 Foam::error::printStack(Foam::Ostream&) at ??:?
#1 Foam::sigFpe::sigHandler(int) at ??:?
#2 in "/lib64/libc.so.6"
#3 Foam::DICPreconditioner::calcReciprocalD(Foam::Field<double>&, Foam::lduMatrix const&) at ??:?
#4 Foam::DICSmoother::DICSmoother(Foam::word const&, Foam::lduMatrix const&, Foam::FieldField<Foam::Field, double>
const&, Foam::FieldField<Foam::Field, double> const&, Foam::UPtrList<Foam::lduInterfaceField const> const&) at ??:?
#5 Foam::lduMatrix::smoother::addsymMatrixConstructorToTable<Foam::DICSmoother>::New(Foam::word const&,
Foam::lduMatrix const&, Foam::FieldField<Foam::Field, double> const&, Foam::FieldField<Foam::Field, double> const&,
Foam::UPtrList<Foam::lduInterfaceField const> const&) at ??:?
#6 Foam::lduMatrix::smoother::New(Foam::word const&, Foam::lduMatrix const&, Foam::FieldField<Foam::Field, double>
const&, Foam::FieldField<Foam::Field, double> const&, Foam::UPtrList<Foam::lduInterfaceField const> const&,
Foam::dictionary const&) at ??:?
#7 Foam::GAMGSolver::initVcycle(Foam::PtrList<Foam::Field<double> >&, Foam::PtrList<Foam::Field<double> >&,
Foam::PtrList<Foam::lduMatrix::smoother>&, Foam::Field<double>&, Foam::Field<double>&) const at ??:?
#8 Foam::GAMGSolver::solve(Foam::Field<double>&, Foam::Field<double> const&, unsigned char) const at ??:?
#9 Foam::fvMatrix<double>::solveSegregated(Foam::dictionary const&) at ??:?
#10 Foam::fvMatrix<double>::solve(Foam::dictionary const&) at ??:?
#11
at ??:?
#12 __libc_start_main in "/lib64/libc.so.6"
#13
at /home/abuild/rpmbuild/BUILD/glibc-2.17/csu/../sysdeps/x86_64/start.S:126
Module'1')'Lecture'3' 66'
Floating point exception
A deeper view to my first OpenFOAM® case setup
•  By default the floating point exception trapping (FOAM_SIGFPE) signal is enable
(signal processing).
•  Signal processing defines how a program handles various signals while it executes.
The SIGFPE signal indicates an erroneous arithmetic operation (such as division by
zero), and the default action is the abnormal termination of the process.
•  FPE, which stands for floating-point exception, also handles integer arithmetic errors.

/*---------------------------------------------------------------------------*\
| ========= | |
| \\ / 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

sigFpe : Enabling floating point exception trapping (FOAM_SIGFPE).

fileModificationChecking : Monitoring run-time modified files using timeStampMaster


allowSystemOperations : Allowing user-supplied system call operations

// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
Module'1')'Lecture'3' 67'
A deeper view to my first OpenFOAM® case setup

Dictionary files hints and advanced


features

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:

banana is not in enumeration


4
(
nextWrite
writeNow
noWriteNow
endTime
)
•  I love to add bananas, from now on let us call this shortcut the banana method (not
related to Rosenbrock's banana function).
Module'1')'Lecture'3' 69'
A deeper view to my first OpenFOAM® case setup
Dictionary files advanced features

•  C++ commenting:

// This is my comment

/*
My comments, line 1
My comments, line 2
*/

•  #include directive:

#include “initialConditions”

Do not forget to create the respective include file initialConditions.

Module'1')'Lecture'3' 70'
A deeper view to my first OpenFOAM® case setup
Dictionary files advanced features

•  Macro expansion:

flowVelocity (20 0 0);

/*
some code lines here
*/

internalField uniform $flowVelocity;

/*
some code lines here
*/

Module'1')'Lecture'3' 71'
A deeper view to my first OpenFOAM® case setup
Dictionary files advanced features

•  Instead of writing (the poor man’s way):

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

•  You can write (the lazy way):

“(left|right|top)Wall”
{
type fixedValue;
value uniform (0 0 0);
}

•  You could also try (even lazier):

“.*Wall”
{
type fixedValue;
value uniform (0 0 0);
}

•  OpenFOAM® understands the syntax of regular expressions (regex or regexp). 73'


Module'1')'Lecture'3'
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.
•  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

Solvers and utilities help

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.

•  To use the Doxygen documentation you will need to compile it first.


•  cd $WM_PROJECT_DIR
•  ./Allwmake doc
Note: You will need to install doxygen and graphviz/dot

•  You can also access the Doxygen documentation online.


http://www.openfoam.org/docs/cpp/

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.

•  To open the Doxygen documentation, e.g.

•  foamHelp boundary -browse fluxCorrectedVelocity

•  To list all boundary conditions for a given field, e.g.

•  foamHelp boundary -field p

•  To list fixed value patches for a given field, e.g.

•  foamHelp boundary -fixedValue -field U

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.

•  foamHelp functionObject -browse forces

•  To use the option –browse, you will need to compile the Doxygen
documentation.

•  To get more information on how to use foamHelp,


•  foamHelp boundary –help
•  foamHelp functionObject –help

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

Now we are ready


to go bananas and
modify the case

Module'1')'Lecture'3' 83'
A deeper view to my first OpenFOAM® case setup

•  Break time!!!

•  But it you want to keep playing with


OpenFOAM®, try to do as many changes as
you like to the case dictionaries and study the
output (specially the errors).

•  I would start by changing the mesh cell


number and the viscosity.

Module'1')'Lecture'3' 84'
Today’s lecture

1.  Before we start


2.  My first OpenFOAM® case setup
3.  A deeper view to my first OpenFOAM® case
setup
4.  My second OpenFOAM® case setup
5.  My third OpenFOAM® case setup
6.  My first 3D OpenFOAM® case setup
7.  Hands-on session

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

Mesh Initial conditions

Module'1')'Lecture'3' 88'
My second OpenFOAM® case setup
At the end of the day you should get something like this

VOF Fraction Pressure field

Module'1')'Lecture'3' 89'
My second OpenFOAM® case setup

•  Let us go to the directory:

$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)

•  interFoam > log.interFoam | tail –f log.interFoam


(This will redirect your standard output to an ascii file with the name log.interFoam. If you do not add the
> log.interFoam modifier you will see your standard output stream on the fly and it will not be saved)

•  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)

These steps are optional

Module'1')'Lecture'3' 96'
Today’s lecture

1.  Before we start


2.  My first OpenFOAM® case setup
3.  A deeper view to my first OpenFOAM® case
setup
4.  My second OpenFOAM® case setup
5.  My third OpenFOAM® case setup
6.  My first 3D OpenFOAM® case setup
7.  Hands-on session

Module'1')'Lecture'3' 97'
My third OpenFOAM® case setup

•  At this point I think we all know


what we are doing.
•  If not, please raise your hand.

Module'1')'Lecture'3' 98'
My third OpenFOAM® case setup

•  Unless it is strictly necessary,


from now on I will not go into
details about the dictionaries and
files we are using.

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

Mean pressure field Mean velocity field

Module'1')'Lecture'3' 103'
My third OpenFOAM® case setup
At the end of the day you should get something like this

Instantaneous velocity magnitude field Instantaneous vorticity magnitude field

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

•  Let us go to the directory:

$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.

•  In the directory $PTOFC/first_tutorial/vortex_shedding you will find this


tutorial. In the terminal window type:

•  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?)

•  From this point on, please follow me.


•  We are all going to work at the same pace.

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

Note: In the folder c1 you will find theModule'1')'Lecture'3'


same setup, but to generate the mesh we use
109'
blockMesh
My third OpenFOAM® case setup
•  At this point, let us use gedit to modify the file constant/polyMesh/boundary,
in the terminal window type:

•  gedit constant/polyMesh/boundary

•  We manually edit the boundary dictionary because the utility


fluent3DMeshToFoam does not recognizes Fluent boundary conditions. There is
no clear, direct correspondence between OpenFOAM® and Fluent boundary
conditions.
•  Most of the times, when you convert a mesh from a third party format, you will need to
manually edit the boundary dictionary.

Note: In the folder c1 you will find theModule'1')'Lecture'3'


same setup, but to generate the mesh we use
110'
blockMesh
My third OpenFOAM® case setup
•  In the file constant/polyMesh/boundary, look for the entries back and front
and change them to:
back
{
type empty;
nFaces 9200;
startFace 18620;
}
front
{
type empty;
nFaces 9200;
startFace 27820;
}

•  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)

•  foamToVTK –time 50:300


(This utility will convert the saved solution from OpenFOAM® format to VTK format. The –time 50:300 option means
convert the solution to VTK format only for the time directories 50 to 300)

•  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.

Refer to the UserModule'1')'Lecture'3'


Guide for more Information 114'
My third OpenFOAM® case setup

•  Now try to do the rest of the cases.

•  Remember, each directory corresponds to a


different solver or setup, so try to figure out
what solver and setup we are using.

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,

•  c1 = blockMesh – icoFoam – Re = 200.


•  c2 = fluentMeshToFoam – icoFoam – Re = 200.
•  c3 = blockMesh – potentialFoam – Re = 200.
•  c4 = blockMesh – mapFields – icoFoam – Re = 200.
•  c5 = blockMesh – mapFields – icoFoam – Re = 200, finer mesh.
•  c6 = blockMesh – pimpleFoam – Re = 200, no turbulence model.
•  c7 = blockMesh – pisoFoam – Re = 200, no turbulence model.

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,

•  c8 = blockMesh – pimpleFoam – Re = 200, SST  !


turbulence model with wall functions.
•  c9 = blockMesh – pimpleFoam – Re = 100000, SST  !
turbulence model with wall functions.
•  c10 = blockMesh – pimpleFoam – Re = 100000, SST  !
turbulence model and no wall functions.
•  c11 = blockMesh – simpleFoam – Re = 100000, SST  !
turbulence model with wall functions.
•  c12 = blockMesh – pisoFoam – Re = 100000, LES Smagorinsky
turbulence model.
•  c13 = blockMesh – pimpleFoam – Re = 1000000, Spalart Allmaras
turbulence model.
Module'1')'Lecture'3' 117'
Today’s lecture

1.  Before we start


2.  My first OpenFOAM® case setup
3.  A deeper view to my first OpenFOAM® case
setup
4.  My second OpenFOAM® case setup
5.  My third OpenFOAM® case setup
6.  My first 3D OpenFOAM® case setup
7.  Hands-on session

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

Cut planes colored by velocity magnitude, pressure and vorticity


Module'1')'Lecture'3' 123'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this

Cut planes and Q criterion iso-surfaces

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

Q criterion iso-surfaces and pressure contours

Module'1')'Lecture'3' 126'
My first 3D OpenFOAM® case setup
At the end of the day you should get something like this

Streamlines, Q criterion iso-surfaces and pressure contours

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

•  Let us go to the directory:

$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:

•  yPlusRAS –time 0.1:0.2


•  Q -latestTime
•  wallShearStress –latestTime
•  Co
•  vorticity –noZero
•  paraFoam -builtin

Refer to the UserModule'1')'Lecture'3'


Guide for more Information 133'
OpenFOAM® tutorials and additional tutorials

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

1.  Before we start


2.  My first OpenFOAM® case setup
3.  A deeper view to my first OpenFOAM® case
setup
4.  My second OpenFOAM® case setup
5.  My third OpenFOAM® case setup
6.  My first 3D OpenFOAM® case setup
7.  Hands-on session

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

1.  CFD simulation workflow

Module'2')'Lecture'4' 2'
CFD simulation workflow

Geometry description

Mesh generation
Visualization

Module'2')'Lecture'4' 3'
CFD simulation workflow

GEOMETRY

UP TO 70% OF USER TIME


THIS IS THE BOTTLENECK

MESHING

CASE SETUP UP TO 10% OF USER TIME

VISUALIZATION UP TO 20% OF USER TIME

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

HUMAN DECISION MAKER


DECISION MATRIX OR
GEOMETRY GEOMETRY GEOMETRY

MESH MESH MESH

SOLVER CO-PROCESSING SOLVER CO-PROCESSING SOLVER CO-PROCESSING

PARAMETRIZATION PARAMETRIZATION PARAMETRIZATION


OPTIMIZATION OPTIMIZATION OPTIMIZATION

VISUALIZATION VISUALIZATION VISUALIZATION

CASE 1 CASE 2 CASE N

AUTOMATIC POST-PROCESSING

Module'2')'Lecture'4' 6'
Concurrent approach – Simulation nested loop
CFD simulation workflow
CASE SETUP POST
GEOMETRY MESHING
AND SOLVER PROCESSING

Salome blockMesh OpenFOAM® (FVM) paraFoam


Blender snappyHexMesh Code Saturne (FVM) paraView
Free-CAD Salome SU2 (FVM) VISIT
Google Sketch-Up Engrid Overture (FDM) Gnuplot
pythonOCC GMSH ELMER (FEM-DG) Scilab
Openscad TETGEN Fenics (FEM) Grace
OpenVSP pythonOCC OpenLB (LBM) Python
Calculix Palabos (LBM) Shell scripting
cfMesh R computational
statistics

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

Any open source


TETGEN GMSH Netgen Engrid Calculix Commercial meshers
mesher

Any commercial or open source CAD or solid modelling tool

Module'2')'Lecture'4' 8'
The diagram does not show all the applications available.
Module 2

Module'2')'Lecture'5' 1'
Today’s lecture

1.  Geometry generation using open source


tools - Preliminaries

Module'2')'Lecture'5' 2'
Geometry generation using open source tools

•  The best way to learn how to use the geometry


generation tools is by doing.
•  Hereafter we are going to show you how to get
started with the geometry generation tools. The
rest is on you.
•  There are many video tutorials available on
internet for each specific tool, so feel free to surf
the web.
Geometry generation using open source tools

•  There are always many ways to accomplish a


task when creating a geometry, this give you the
freedom to work in a way that is confortable to
you. Hereafter I am going to show you my way.

•  There is no wrong or right way to generate a


geometry. The only rule you should keep in mind
is that by the end of the day you should get a
unique clean and watertight geometry.
Geometry generation using open source tools

•  Remember, the quality of the mesh and hence of


the solution, greatly depends on the geometry.
So always do your best when creating the
geometry.
Geometry generation using open source tools
Potential geometry issues

•  Missing faces. •  Cracks.


•  Small faces. •  Gaps.
•  Misaligned faces. •  Free faces, edges, nodes.
•  Overlapping faces. •  Hard edges.
•  Sliver faces (high aspect-ratio). •  Small edges.
•  Repeated faces. •  Sharp angles.
•  Several surfaces connected to a •  Repeated edges.
single surface. •  High curvature NURBS.

.. among others.

These issues must be fixed in order to create a smooth, clean,


watertight body and to prevent meshing issues
Geometry generation using open source tools
Potential geometry issues

•  These issues must be fixed in order to create a smooth, clean,


watertight body and to prevent meshing issues

•  In general, when generating the geometry and by using good


geometry generation practices, we should not experience these
geometry issues.

•  At the end of the day we are interested in getting a smooth,


clean, watertight body.

•  Usually, we find these issues when importing or exporting the


geometry from/to different formats.
Geometry generation using open source tools
Remember, before going to the meshing stage we must fix/
cleanup the geometry.
So, how do we prepare the geometry for mesh generation?

•  Delete hard edges.


•  Delete small edges/faces.
•  Fill holes.
•  Split surfaces with high curvature.
•  Sew faces.
•  Remove sliver faces.
•  Connect/disconnected edges/faces.
•  Delete sharp edges.
•  Remove unnecessary details (defeaturing). This includes points, edges and
faces.
•  Boolean operations among bodies.
•  Decompose geometry into meshable sections.

Let us take a look at a corrupt or incomplete geometry


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

To improve quality, split the single surface


into two surfaces
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

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/

•  Free-CAD: is a history based CAD tool (parametric design). Light CAD


software, good for not very complicated mechanical designs.
http://sourceforge.net/apps/mediawiki/free-cad/

•  Google Sketch-Up: is a direct 3D modeling tool. There are many plugins


available that extend Google Sketch-Up capabilities.
http://sketchup.google.com/

•  Blender: is a direct 3D modeling tool. Extremely powerful for surface


modeling and manipulation.
http://www.blender.org/

Friendliness/Easiness to use: Good Fairly Good Mild Bad Very Bad


Geometry generation using open source tools
•  pythonOCC: is a 3D CAD/CAE/PLM development framework for the Python
programming language. It provides features such as advanced topological
and geometrical operations, data exchange (STEP, IGES, STL import/export),
2D and 3D meshing, rigid body simulation, parametric modeling.
http://www.pythonocc.org/

•  Openscad: is a 3D programming modeling tool. It reads in a script file that


describes the object and renders the 3D model from this script file.
http://www.openscad.org/

•  OpenVSP: is a parametric aircraft geometry tool. It allows users to create a


3D model of an aircraft defined by common engineering parameters.
http://www.openvsp.org/

Friendliness/Easiness to use: Good Fairly Good Mild Bad Very Bad


Thank you for your attention
Module 3

Module'3')'Lecture'6' 1'
Meshing and mesh quality
This lecture is about meshing and mesh quality
assessment for CFD computations

Generating high quality meshes is a critical step for CFD computations.


Depending on the quality of the mesh you can get very different results,
which can made post-processing, validation, assessment and
interpretation of the solution a difficult task, due to contrasting or
misleading results because of meshing issues. This holds independently
of the solver used.

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

Who owns the mesh, owns the solution

Module'3')'Lecture'6' 4'
Today’s lecture

1.  Meshing preliminaries

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).

•  The meshes can be unstructured or structured (grids). In our discussion,


when we talk about unstructured or structured meshes we refer specifically
to the method used to generate them.

•  When we pass the mesh information to an unstructured FVM solver, we


pass the data structure, connectivity information (points, faces, and cells
information), neighbors information, and geometrical information (cell
volume, face area and so on).

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

Single-block C-type structured grid around a NACA 4412 airfoil


Module'3')'Lecture'6' 9'
Meshing preliminaries

Multi-block structured grid around a NLR 7301 airfoil with flap


Module'3')'Lecture'6' 10'
Meshing preliminaries

Unstructured triangular meshModule'3')'Lecture'6'


around a NHLP-2D three element airfoil 11'
Meshing preliminaries

Overlapping structured grid around a NLR 7301 airfoil with flap


Module'3')'Lecture'6' 12'
Meshing preliminaries

Cartesian mesh aroundModule'3')'Lecture'6'


a Drela DAE11 low Reynolds airfoil 13'
Meshing preliminaries
STRUCTURED UNSTRUCTURED CARTESIAN OVERLAPPING

Geometric Flexibility/
Adaptation
Grid Adaptation/
Local Refinement

Viscous Computation

Moving/Deforming
Meshes Quality
Interpolation/
Conservation
Grid generation
easiness
Memory
Requirements

CPU Requirements

Good Fairly Good Mild Bad Very Bad


Module'3')'Lecture'6' 14'
Meshing preliminaries
Unstructured Vs. Structured meshes, Who wins?

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.

Unstructured meshes, only requires


as input the element size on the lines
and surfaces that define the
geometry.
After defining the element size, the
meshing process can be quite time
consuming and memory expensive.
Meshing time is in the order of
minutes or hours, even days.
Module'3')'Lecture'6' 16'
Meshing preliminaries

Unstructured Hybrid Mesh


(tetras, prisms and hexs)

Cell count:
approx. 5 000 000

Structured Mesh
(hexahedrals)

Cell count:
approx. 5 000 000

Module'3')'Lecture'6' 17'
Meshing preliminaries

Unstructured Hybrid Mesh


(tetras, prisms and hexs)

Cell count:
approx. 5 000 000

Structured Mesh
(hexahedrals)

Cell count:
approx. 5 000 000

Module'3')'Lecture'6' 18'
Meshing preliminaries

Unstructured Hybrid Mesh


(tetras, prisms and hexs)

Cell count:
approx. 5 000 000

Structured Mesh
(hexahedrals)

Cell count:
approx. 5 000 000

Module'3')'Lecture'6' 19'
Meshing preliminaries

Unstructured Hybrid Mesh


(tetras, prisms and hexs)

Cell count:
approx. 5 000 000

Structured Mesh
(hexahedrals)

Cell count:
approx. 5 000 000

Module'3')'Lecture'6' 20'
Meshing preliminaries

Unstructured Hybrid Mesh


(tetras, prisms and hexs)

Cell count:
approx. 5 000 000

Structured Mesh
(hexahedrals)

Cell count:
approx. 5 000 000

Module'3')'Lecture'6' 21'
Meshing preliminaries

Unstructured Hybrid Mesh


(tetras, prisms and hexs)

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.

•  Structured meshes are made of hexahedra.

•  Unstructured meshes are mainly made of tetrahedral,


pyramids, hexahedra, and prisms (hybrid meshes).

•  By the way, there is a new guy in town, polyhedral cells.


This type of cells have very interesting properties.

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

1.  Mesh quality assessment in OpenFOAM®

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.

22rd IMR Meshing Maestro Contest Winner


Travis Carrigan, John Chawner and Carolyn Woeber. Pointwise.
Module'3')'Lecture'7' 3'
http://imr.sandia.gov/22imr/MeshingContest.html
Mesh quality assessment
What is a good mesh?
•  The user can rely on grid dependency studies, but they are time consuming
and expensive.

Coarse mesh Medium mesh Fine mesh Extra fine mesh

Cells ≈ 3 500 000 ≈ 11 000 000 ≈ 36 000 000 ≈ 105 000 000

CD 0.0282 0.0270 0.0268 0.0269

CM -0.0488 -0.0451 -0.0391 -0.0391

4th AIAA CFD Drag


Prediction Workshop

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

Striving for quality

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.

•  Triangular and tetrahedral meshes can easily be adapted to any kind of


geometry. The mesh generation process is almost automatic.

•  Triangular and tetrahedral meshes have inherently larger truncation error.

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.

23rd IMR Meshing Maestro Contest Winner


Zhoufang Xiao , Jianjing Zheng, Dawei Zhao, Lijuan Zeng, Jianjun Chen, Yao Zheng
Center for Engineering & Scientific Computation, Zhejiang University, China.
Module'3')'Lecture'7' 16'
http://www.sandia.gov/imr/MeshingContest.html
Mesh quality assessment
Striving for quality
•  To keep cell count low, use non-uniform meshes to cluster cells only where
they are needed. Use local refinements and solution adaption to further
refine only on selected areas.

•  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.

•  Use hexahedral meshes whenever is possible, specially if high accuracy in


predicting forces is your goal (drag prediction) or for turbo machinery
applications.

•  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.

•  Change in cell size should be smooth.

•  Always check the mesh quality. Remember, one single cell can cause
divergence or give you inaccurate results.

•  Plan your meshing approach.

•  When you strive for quality, you avoid the GIGO syndrome.

Module'3')'Lecture'7' 19'
Mesh quality assessment
Striving for quality

•  Remember, a poor quality mesh will generate inaccurate


solutions, questionable results and/or will slow down
solution convergence.

Module'3')'Lecture'7' 20'
Mesh quality assessment
Striving for quality
•  Just to end for good the mesh talk:

•  A good mesh is a mesh that serves your project objectives.

•  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

Mesh quality metrics in OpenFOAM®

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:

•  Foam::scalar Foam::primitiveMesh::closedThreshold_ = 1.0e-6;


•  Foam::scalar Foam::primitiveMesh::aspectThreshold_ = 1000;
•  Foam::scalar Foam::primitiveMesh::nonOrthThreshold_ = 70; // deg
•  Foam::scalar Foam::primitiveMesh::skewThreshold_ = 4;
•  Foam::scalar Foam::primitiveMesh::planarCosAngle_ = 1.0e-6;

Module'3')'Lecture'7' 23'
Mesh quality assessment

Checking mesh quality in OpenFOAM®

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®

•  Mesh topology and patch topology 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 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®

•  To visualize the failed faces/cells/points in paraFoam you will need to


proceed as follows:
•  foamToVTK -set_type name_of_sets

where set_type is the type of sets ( faceSet, cellSet, pointSet,


surfaceFields) and name_of_sets is the name of the set in the directory
constant/polyMesh/sets (highAspectRatioCells,
nonOrthoFaces, wrongOrientedFaces, skewFaces,
unusedPoints, and so on)

•  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®

•  Alternatively, you can load the failed sets


directly within paraFoam.
•  In paraFoam, simply select the option
Include Sets and then select the sets you
want to visualize.
•  Remember, you will need to create the sets.
To do so just run the checkMesh utility, if
there are problems in the mesh checkMesh
will automatically save the sets in the
directory constant/polyMesh/sets

•  Personally speaking, I do prefer to use foamToVTK.

Module'3')'Lecture'7' 28'
Mesh quality assessment

•  Let us check the mesh quality of a tricky geometry.


•  For this we will use the wing body case that you will
find in the directory:

$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.

•  Go to the directory $PTOFC/mesh_conversion_manipulation/


M2_wingbody. In the terminal type:

•  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

•  In the terminal type:

•  ls constant/polyMesh/sets

What faulty sets do you see?

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:

•  foamToVTK -faceSet nonOrthoFaces


•  foamToVTK -pointSet unusedPoints
•  paraFoam

foamToVTK will write the faulty sets in the directory ./VTK

•  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

Non orthogonal faces (green) and unused points (yellow)

Module'3')'Lecture'7' 34'
Mesh quality assessment
By following the instructions, you should get something like this

Non orthogonal faces (green) and unused points (yellow)

Module'3')'Lecture'7' 35'
Mesh quality assessment

Removing bad quality sets from the mesh in


OpenFOAM®

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.

•  You can do this by using the utilities topoSet and subsetMesh.

•  The utility topoSet operates on cellSets/faceSets/pointSets


through the dictionary topoSetDict. You can use this utility to create or
manipulate sets.

•  subsetMesh selects a section of the mesh based on a cellSet. To create


a cellSet we use topoSet.

Module'3')'Lecture'7' 37'
Mesh quality assessment
Removing bad quality sets from the mesh

•  Just to make it clear, the sets created or manipulated by topoSet are


located in the folder constant/polyMesh/sets.

•  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

•  You can also manually modify the polyMesh.

•  It is quite easy to understand the polyMesh format. It works like a linked


list.

•  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

1.  Mesh conversion


2.  Hands-on session

Module'3')'Lecture'8' 2'
Today’s lecture

1.  Mesh conversion


2.  Hands-on session

Module'3')'Lecture'8' 3'
Mesh conversion

•  OpenFOAM® gives users a lot of flexibility when it comes to meshing.

•  You are not constrained to use OpenFOAM® meshing tools.

•  To convert a mesh generated with a third party software to OpenFOAM®


polyMesh format, you can use the OpenFOAM® mesh conversion utilities.

•  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.

In the User Guide you will find the complete listing


Module'3')'Lecture'8' 5'
Mesh conversion
Ansys CFX Fluent 2D mesh Fluent 3D mesh Gambit GMSH
ansysToFoam cfx4ToFoam fluentMeshToFoam fluent3DMeshToFoam gambitToFoam gmshToFoam

Ideas UNV
ideasUnvToFoam

KIVA3D
kivaToFoam

Mesh adventure system


mshToFoam

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

For more information about the mesh conversion


utilities, refer to theModule'3')'Lecture'8'
User Guide 9'
Mesh conversion

•  Let us do some mesh conversion.


•  Our first case will be the mixing elbow, which you will
find in the directory:

$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

•  The next example is a square tube with periodic


boundary conditions. You will find this tutorial in the
directory:

$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.

In the terminal window type:


•  cd $PTOFC/mesh_conversion_manipulation/
M1_square_tube_periodic
•  fluent3DMeshToFoam ../../meshes/M1_square_tube_periodic/
ascii.msh
Attention: The mesh must be in ascii format

•  createPatch –overwrite –noFunctionObjects


(This utility is used to create the periodic patches. By the way, take a look at the dictionary createPatchDict)

•  checkMesh –time 0
•  paraFoam

Module'3')'Lecture'8' 16'
Mesh conversion

•  Let us go back to the mixing elbow mesh, our task


now is to convert the tetrahedral mesh to a general
polyhedral mesh. You will find this tutorial in the
directory:

$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.

And at the end, our Module'3')'Lecture'8'


mesh should looks like this one. 19'
Mesh conversion
Case 3. Polyhedral mesh.

And at the end, our Module'3')'Lecture'8'


mesh should looks like this one. 20'
Mesh conversion
Case 3. Polyhedral mesh.

The utility polyDualMesh only works with tetrahedral meshes

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)

•  polyDualMesh 30 –concaveMultiCells –overwrite


–noFunctionObjects
(This utility will convert a tetra mesh to polyhedral mesh)

•  checkMesh
(To check the mesh after converting it to polyhedral type)

•  paraFoam
Module'3')'Lecture'8' 22'
Mesh conversion

•  Our final example is the static mixer mesh. You will


find this case in the directory:

$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

Tetra mesh Polyhedral 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.

In the terminal type:

•  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)

•  autoPatch 45 –overwrite -noFunctionObjects


(This utility will automatically find the patches according to a given angle criterion)

•  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.

•  Now that we have a polyMesh and we used the utility autoPatch to


automatically find the boundary patches, let us setup this case and in no
more than 20 minutes.

•  Can you convert the tetrahedral mesh to a general polyhedral mesh?

•  Do you take the challenge?

•  If you find it hard, try to use Helyx-os.


Module'3')'Lecture'8' 28'
Mesh conversion

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

1.  Geometry and mesh manipulation utilities


2.  Hands-on session

Module'3')'Lecture'9' 2'
Today’s lecture

1.  Geometry and mesh manipulation utilities


2.  Hands-on session

Module'3')'Lecture'9' 3'
Geometry and mesh manipulation utilities

•  First at all, by mesh manipulation I mean modifying


OpenFOAM® polyMesh format.

•  The modifications can be scaling, rotation, translation, mirroring,


topological changes, mesh refinement and so on.

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.

In the User Guide you will find the complete listing


Module'3')'Lecture'9' 5'
Geometry and mesh manipulation utilities
•  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 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

\param -region \<name\> \n


Specify an alternative mesh region.

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.

In the User Guide you will find the complete listing


Module'3')'Lecture'9' 10'
Geometry and mesh manipulation utilities
•  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 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.

•  Let us see what is inside this directory, in the terminal type:


•  ls -l

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:

Transform (scale/rotate) a surface.


Like transformPoints but for surfaces.
The rollPitchYaw option takes three angles (degrees):
-  roll (rotation about x) followed by
-  pitch (rotation about y) followed by
-  yaw (rotation about z)
The yawPitchRoll does yaw followed by pitch followed by roll.

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

•  We will now do some surface manipulation.


•  For this we will use the ahmed body tutorial located in
the directory:

$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

STL surface manipulation


Module'3')'Lecture'9' 17'
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:

•  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:

•  surfaceTransformPoints -translate '(0 0.12 0)' ./constant/


triSurface/rotated.stl ./constant/triSurface/
translated.stl
•  surfaceTransformPoints -scale '(0.9 1.1 1.3)' ./constant/
triSurface/translated.stl ./constant/triSurface/
scaled.stl
•  surfaceInertia -density 2700 –noFunctionObjects ./constant/
triSurface/ahmed_body.stl
•  surfaceClean ./constant/triSurface/scaled.stl 1 100 ./
constant/triSurface/smooth.stl

Module'3')'Lecture'9' 19'
Note: in this case we only manipulated the STL file.
Geometry and mesh manipulation utilities

•  We will now do some mesh manipulation.


•  Remember when I told you not to forget about the
cylinder geometry?. Guess what?. We are going to
use it again.
•  For this we will use the heated body tutorial located in
the directory:

$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

•  We will now do some mesh manipulation. This time we


are going to mirror a mesh.
•  For this we will use the wing body tutorial located in
the directory:

$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

Original mesh Mirrored mesh

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

1.  Mesh generation using blockMesh and


snappyHexMesh - Workflow.
2.  A few snappyHexMesh meshing cases.
3.  Hands-on session.

Module'3')'Lecture'10' 2'
Today’s lecture

1.  Mesh generation using blockMesh and


snappyHexMesh - Workflow.
2.  A few snappyHexMesh meshing cases.
3.  Hands-on session.

Module'3')'Lecture'10' 3'
Mesh generation using blockMesh and snappyHexMesh

•  OpenFOAM® comes with its own meshing applications.

•  If you are not confortable using OpenFOAM® meshing applications, you can
use an external mesher.

•  OpenFOAM® comes with many mesh conversion utilities. Many popular


meshing formats are supported. To name a few: cfx, fluent, gmsh, ideas,
netgen, plot3d, starccm, VTK.

•  In this training, we are going to address how to mesh using OpenFOAM®


technology.

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.

•  The mesh is generated from a dictionary file named blockMeshDict located in


the constant/polyMesh directory.

•  The blockMeshDict can be parameterize using m4.

•  We are going to address m4 scripting later on.

•  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.”

•  For complex geometries, the mesh generation utility snappyHexMesh can be


used.

•  The snappyHexMesh utility generates 3D meshes containing hexahedra and


split-hexahedra from a triangulated surface geometry in Stereolithography
(STL) format.

•  The mesh is generated from a dictionary file named snappyHexMeshDict


located in the system directory and a triangulated surface geometry file
located in the directory constant/triSurface.

•  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.

•  As the background mesh consist of a single block (most of the times),


blockMesh can be used with no problem.

•  It is highly recommended to create a template of the dictionary


blockMeshDict that you can change according to the dimensions of your
domain.

•  You can also use m4 scripting to automate the whole process.

•  We are going to address m4 scripting and advanced blockMesh meshing


later on.

•  The meshing utility blockMesh, reads the dictionary blockMeshDict located


in the directory constant/polyMesh
Module'3')'Lecture'10' 11'
Mesh generation using blockMesh and snappyHexMesh
blockMesh workflow

blockMeshDict

vertices edges blocks patches

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

blockMesh or external mesher

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.

blockMesh or external mesher

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

blockMesh or external mesher

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

blockMesh or external mesher

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

Let us take a look at


snappyHexMesh in action by
meshing wolf dynamics logo

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

Step 1. Creating the background hexahedral mesh


•  Before snappyHexMesh is executed the user must create a background mesh of hexahedral cells that fills the
entire region as shown in the figure. This can be done by using blockMesh or any other 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.
Module'3')'Lecture'10' 23'
•  There must be at least one intersection of a cell edge with the STL surface.
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow

Step 2. Cell splitting at feature edges


•  Cell splitting is performed according to the specification supplied by the user in the castellatedMeshControls
sub-dictionary in the snappyHexMeshDict dictionary.
•  The splitting process begins with cells being selected according to specified edge features
as illustrated in the figure.
•  The feature edges can be extracted from the Module'3')'Lecture'10'
STL geometry file using the utility surfaceFeatureExtract. 24'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow

Step 3. Cell splitting at surfaces


•  Following feature edges refinement, cells are selected for splitting in the locality of specified surfaces as
illustrated in the figure.
•  The surface refinement (splitting) is performed according to the specification supplied by the user in the
refinementMeshControls in the castellatedMeshControls sub-dictionary in the snappyHexMeshDict dictionary.
Module'3')'Lecture'10' 25'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow

Step 4. Cell removal


•  Once the feature edges and surface splitting is complete, a process of cell removal begins.
•  The region in which cells are retained are simply identified by a location vector within the region, specified by
the locationInMesh keyword in the castellatedMeshControls sub-dictionary in the snappyHexMeshDict
dictionary.
•  Cells are retained if, approximately speaking,Module'3')'Lecture'10'
50% or more of they volume lies within the region. 26'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow

Step 5. Cell splitting in specified regions


•  Those cells that lie within one or more specified volume regions can be further split by a region (in the figure,
the rectangular region within the red rectangle).
•  The information related to the refinement of the volume regions is supplied by the user in the
refinementRegions block in the castellatedMeshControls sub-dictionary in the snappyHexMeshDict dictionary.
•  This is a valid castellated or cartesian mesh that can be used for a simulation.
Module'3')'Lecture'10' 27'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow

Step 6. Snapping to surfaces


•  After deleting the cells in the region specified and refining the volume mesh, the points are snapped on the
surface to create a conforming mesh.
•  The snapping is controlled by the user supplied information in the snapControls sub-dictionary in the
snappyHexMeshDict dictionary.
Module'3')'Lecture'10' 28'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow

Step 6, continuation. Snapping to surfaces


•  Sometimes, the default snapControls options are not enough and you will need to adjust the values to get a
good mesh, so it is advisable to save the intermediate steps with a high writing precision (controlDict).
•  This is a valid snapped or body fitted mesh that can be used for a simulation.

Module'3')'Lecture'10' 29'
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow

Step 7. Mesh layers


•  The mesh output from the snapping stage may be suitable for simulation, although it can produce some
irregular cells along boundary surfaces.
•  There is an optional stage of the meshing process which introduces boundary layer meshing in selected parts
of the mesh.
•  This information is supplied by the user in theModule'3')'Lecture'10'
addLayersControls sub-dictionary in the snappyHexMeshDict
30'
dictionary.
Mesh generation using blockMesh and snappyHexMesh
snappyHexMesh workflow

Step 7, continuation. Mesh layers


•  This is the final step of the mesh generation process using snappyHexMesh.
•  This is a valid body fitted mesh with boundary layer meshing, that can be used for a simulation.

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

•  Let us study the snappyHexMesh dictionary of this


tutorial.
•  You will find this case in the directory:

$PTOFC/sHM/M9_wolf

Module'3')'Lecture'10' 33'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.

The dictionary snappyHexMeshDict consists of five main sections:

•  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.

•  In the snappyHexMeshDict dictionary you will find more than 70


parameters.

•  It is really tricky to get a good mesh at the first time.

•  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.

castellatedMesh true; //or false


snap true; //or false
addLayers true; //or false

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.

castellatedMesh true; //or false


snap true;
addLayers true;
//or false
//or false
•  Before continuing, I want to let you know
that there are more than 80 parameters in
geometry
snappyHexMesh.
{
...
... •  Adding the fact that there is no native GUI,
} it is quite difficult to control the mesh
castellatedMeshControls generation process.
{
...
... •  Nevertheless, snappyHexMesh generates
}
really good hexa dominant meshes.
snapControls
{
... •  Hereafter, I will only comment on the most
...
}
important parameters.
addLayersControls
{ •  The parameters that you will find in the
...
...
snappyHexMeshDict dictionaries
} distributed with the tutorials, in our opinion
meshQualityControls
are really robust and will work most of the
{ times.
...
...
}
Module'3')'Lecture'10' 37'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.

geometry
{

wolfExtruded.stl STL file to read


{
type triSurfaceMesh;
name wolf; Name of the surface inside snappyHexMesh

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;
...
...

//Explicit feature edge refinement


features Dictionary block'
(
...
...
);

//Surface based refinement


refinementSurfaces Dictionary block'
{
...
...
} •  In the castellatedMeshControls section, we define the global
refinement parameters, explicit feature edge refinement,
//Region-wise refinement surface based refinement, region-wise refinement and the
refinementRegions Dictionary block' material point.
{
... •  In this step, we are generating the castellated mesh.
...
}
Note 1:
//Mesh selection The material point indicates where we want to create the mesh,
locationInMesh (-100.0 0.0 50.0 ); Note 1' that is, inside or outside the body to be meshed.
}
Module'3')'Lecture'10' 39'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.

castellatedMeshControls
{

// Refinement parameters
maxLocalCells 100000;
maxGlobalCells 2000000;
minRefinementCells 0;
maxLoadUnbalance 0.10;
nCellsBetweenLevels 1; Note 1

//Local curvature and


//feature angle refinement
resolveFeatureAngle 30; Note 2

planarAngle 30;

allowFreeStandingZoneFaces true;

//Explicit feature edge refinement


Note 1:
features Dictionary block'
This parameter controls the transition between cell
(
refinement levels.
{
file "wolfExtruded.eMesh"; Note 3
Note 2:
level 2;
This parameter controls the local curvature refinement. The
}
higher the value, the less features it captures. For example
);
if you use 100, it will not add refinement in high curvature
areas. It also controls edge feature snapping, high values
...
will not resolve sharp angles in surface intersections.
...
...
Note 3:
This file is automatically created when you use the utility
}
Module'3')'Lecture'10' 40'
surfaceFeatureExtract. The file is located in the directory
constant/triSurface
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.

castellatedMeshControls
{

...
...
...

//Surface based refinement


refinementSurfaces Dictionary block'
{

//wolf was defined in the geometry section


wolf Note 1
{

level (1 1); //Global refinement

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
{

//Surface based refinement


refinementSurfaces Dictionary block'
{

...
...
...
//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:

} internal: keep them as internal faces (default)


baffle: create baffles from them. This gives more freedom in mesh motion
... boundary: create free-standing boundary faces (baffles but without
... the shared points)
}
e.g., faceType internal;

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'
{

//This region or geometrical entity


//was defined in the geometry section
box
{
mode inside;
levels (( 1 1 ));
}

//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
{

//Number of patch smoothing iterations


//before finding correspondence to surface
nSmoothPatch 3;

tolerance 2.0;

//- Number of mesh displacement relaxation


//iterations.
nSolveIter 300; Note 1

//- Maximum number of snapping relaxation


//iterations. Should stop before upon
//reaching a correct mesh.
nRelaxIter 5; Note 2

// Feature snapping

//Number of feature edge snapping iterations.


nFeatureSnapIter 10; Note 3
Note 1:
//Detect (geometric only) features by The higher the value the better the body fitted mesh. 300 is
//sampling the surface (default=false). already a high value, the default value is 30.
implicitFeatureSnap false;
Note 2:
// Use castellatedMeshControls::features Increase this value to improve the body fitted mesh.
// (default = true)
explicitFeatureSnap true; Note 3:
Increase this value to improve the edge features.
multiRegionFeatureSnap false;
•  In this step, we are generating the body fitted mesh.
}
Module'3')'Lecture'10' 45'
Mesh generation using blockMesh and snappyHexMesh
Let us explore the snappyHexMeshDict dictionary.

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

// write current mesh intersections as .obj files


intersections

// write information about explicit feature edge


// refinement
featureSeeds

// write attraction as .obj files


attraction

// write information about layers


layerInfo
);

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

Was that explanation good


enough for you?
Is it clear ?
Questions?

Module'3')'Lecture'10' 49'
Mesh generation using blockMesh and snappyHexMesh

Before proceeding to compute the solution,


remember to always check the quality of
the mesh

Module'3')'Lecture'10' 50'
Today’s lecture

1.  Mesh generation using blockMesh and


snappyHexMesh - Workflow.
2.  A few snappyHexMesh meshing cases.
3.  Hands-on session.

Module'3')'Lecture'10' 51'
Mesh generation using blockMesh and snappyHexMesh

•  Meshing with snappyHexMesh


•  Meshing case 1. 3D Cylinder (external mesh).

$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.

At this point, your Module'3')'Lecture'10'


mesh should looks like this 53'
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.

At this point, your Module'3')'Lecture'10'


mesh should looks like this 54'
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.

In the terminal window type:


•  cd $PTOFC/sHM/M1_cyl
•  blockMesh
•  snappyHexMesh
(And by the way, take a look at the snappyHexMeshDict dictionary)

•  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.

•  So far you do not have a valid mesh in the directory constant/polyMesh.


•  You must copy the mesh from the time directory 2 (or 3) to your constant directory.
In the terminal type:
•  mv constant/polyMesh constant/polyMesh.org
(To have a backup of the background mesh folder, this is optional)

•  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.

•  Alternatively, snappyHexMesh can automatically overwrite the original background


mesh contained in constant/polyMesh. In the terminal type:

•  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

•  Meshing with snappyHexMesh


•  Meshing case 2. 3D Cylinder (external mesh), with
feature edge refinement.

$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.

At this point, your Module'3')'Lecture'10'


mesh should looks like this 60'
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, your Module'3')'Lecture'10'


mesh should looks like this 61'
Mesh generation using blockMesh and snappyHexMesh
Case 2. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement.

No feature edge refinement Feature edge refinement


Module'3')'Lecture'10' 62'
Mesh generation using blockMesh and snappyHexMesh
•  By the way, do not fool yourself, razor type sharp angles are hard to find in
real applications.
•  If you can smooth the edges, do it (chamfer, bevel, fillet, taper, round,
bullnose, etc).
•  By smoothing the edges you are doing geometry defeaturing.
•  It will also made your life easier when generating the boundary layer mesh,
if you need one at all.

Sharp edges Module'3')'Lecture'10' Smooth edges 63'


Mesh generation using blockMesh and snappyHexMesh
Case 2. 3D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh with feature edge
refinement.
From now on, follow me.

In the terminal window type:


•  cd $PTOFC/sHM/M1_cyl_er
•  blockMesh
•  surfaceFeatureExtract
(This utility reads the surfaceFeatureExtractDict dictionary which is located in the system directory)

•  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.

•  So far you do not have a valid mesh in the directory constant/polyMesh.


•  You must copy the mesh from the time directory 2 (or 3) to your constant directory.
In the terminal type:
•  mv constant/polyMesh constant/polyMesh.org
(To have a backup of the background mesh folder, this is optional)

•  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.

•  Alternatively, snappyHexMesh can automatically overwrite the original background


mesh contained in constant/polyMesh. In the terminal type:

•  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

•  Meshing with snappyHexMesh


•  Meshing case 3. 3D Cylinder (external mesh), with
feature edge refinement and boundary layer.

$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.

At this point, your Module'3')'Lecture'10'


mesh should looks like this 70'
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, your Module'3')'Lecture'10'


mesh should looks like this 71'
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.

Effect of featureAngle on boundary layer collapsing

featureAngle 30 featureAngle 130

At this point, your Module'3')'Lecture'10'


mesh should looks like this 72'
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.

•  How do I enable boundary layer?.


•  In the file snappyHexMeshDict, look for the following entry:

castellatedMesh true; //or false


snap true; //or false
addLayers true; //or false

...
...
...

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.

In the terminal window type:


•  cd $PTOFC/sHM/M1_cyl_er_bl
•  blockMesh
•  surfaceFeatureExtract
(This utility reads the surfaceFeatureExtractDict dictionary which is located in the system directory)

•  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.

•  So far you do not have a valid mesh in the directory constant/polyMesh.


•  You must copy the mesh from the time directory 3 to your constant directory. In the
terminal type:
•  mv constant/polyMesh constant/polyMesh.org
(To have a backup of the background mesh folder, this is optional)

•  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.

•  Alternatively, snappyHexMesh can automatically overwrite the original background


mesh contained in constant/polyMesh. In the terminal type:

•  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

•  Meshing with snappyHexMesh


•  Meshing case 4. Mixing elbow (internal mesh), initial
mesh.

$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.

At this point, your Module'3')'Lecture'10'


mesh should looks like this 79'
Mesh generation using blockMesh and snappyHexMesh
Case 4. Mixing elbow (internal mesh).
Let us generate the mesh by using SnappyHexMesh.

At this point, your Module'3')'Lecture'10'


mesh should looks like this 80'
Mesh generation using blockMesh and snappyHexMesh
Case 4. Mixing elbow (internal mesh).
Let us generate the mesh by using SnappyHexMesh.
From now on, follow me.

In the terminal window type:


•  cd $PTOFC/sHM/M2_mixing_elbow1
•  blockMesh
•  surfaceFeatureExtract
(It will use an includedAngle of 130 degrees as defined in the dictionary ./system/surfaceFeatureExtractDict)

•  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.

•  Alternatively, snappyHexMesh can automatically overwrite the original background


mesh contained in constant/polyMesh. In the terminal type:

•  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.

•  In the directory geometry, you fill find the file


mixing_pipe_onesurface.stl, this STL has one single surface.

•  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.

•  The naming convention is autoN, where N is the patch number.

•  Remember, autoPatch will manipulate the mesh located in the directory


constant/polyMesh.
Module'3')'Lecture'10' 84'
Mesh generation using blockMesh and snappyHexMesh

•  Meshing with snappyHexMesh


•  Meshing case 5. Sphere (external mesh), boundary
layer mesh.

$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.

Mesh with no inflation layer.


addLayers false; in snappyHexMeshDict
Module'3')'Lecture'10' 86'
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.

Mesh with inflation layer.


addLayers true; in snappyHexMeshDict
Module'3')'Lecture'10' 87'
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.

Mesh with no inflation layers Mesh with inflation layers

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.

•  Alternatively, snappyHexMesh can automatically overwrite the original background


mesh contained in constant/polyMesh. In the terminal type:

•  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.

In the terminal type:


•  cd $PTOFC/sHM/M3_sphere_sHM
•  foamCleanTutorials
•  foamClearPolyMesh
•  blockMesh
•  snappyHexMesh –noFunctionObjects
•  paraFoam
(To visualize your mesh)

Module'3')'Lecture'10' 94'
Mesh generation using blockMesh and snappyHexMesh

•  Meshing with snappyHexMesh


•  Meshing case 6. 2D cylinder (external mesh)

$PTOFC/sHM/M4_2d_cylinder

Module'3')'Lecture'10' 95'
Mesh generation using blockMesh and snappyHexMesh
Case 6. 2D Cylinder (external mesh).

At this point, your Module'3')'Lecture'10'


mesh should looks like this 96'
Mesh generation using blockMesh and snappyHexMesh
Case 6. 2D Cylinder (external mesh).

At this point, your Module'3')'Lecture'10'


mesh should looks like this 97'
Mesh generation using blockMesh and snappyHexMesh
Case 6. 2D Cylinder (external mesh).

At this point, your Module'3')'Lecture'10'


mesh should looks like this 98'
Mesh generation using blockMesh and snappyHexMesh
Case 6. 2D Cylinder (external mesh).
Let us generate the mesh by using SnappyHexMesh.
From now on, follow me.

In the terminal window type:


•  cd $PTOFC/sHM/M4_2d_cylinder
•  blockMesh
•  snappyHexMesh –noFunctionObjects
•  checkMesh -latestTime
•  extrudeMesh –noFunctionObjects
(Take a look at the dictionary ./system/extrudeMeshDict, this dictionary tells OpenFOAM® to create the 2D 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.

•  Alternatively, snappyHexMesh can automatically overwrite the original background


mesh contained in constant/polyMesh. In the terminal type:

•  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

•  Meshing with snappyHexMesh


•  Meshing case 7. BWB body (external mesh),
meshing in parallel.

$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.

In the terminal window type:


•  cd $PTOFC/sHM_1/M7_bwb_parallel
•  cp constant/triSurface/N2A_Hybrid.stl constant/triSurface/
surfacemesh.stl
(The geometry was generated using openvsp)

•  surfaceTransformPoints –scale ‘(0.3048 0.3048 0.3048)’


constant/triSurface/N2A_Hybrid.stl constant/triSurface/
surfacemesh.stl
(The geometry was generated using openvsp)

•  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.

•  To do the meshing in parallel:


•  decomposePar
(Take a look at the dictionary ./system/decomposeParDict, in this dictionary you need to specify the decomposition
method and the number of partitions. Later on we are going to deal with running in parallel)

•  mpirun –np 8 snappyHexMesh –parallel –overwrite


(This step will generate the mesh in parallel)

Notice the syntax used to run snappyHexMesh in parallel:


mpirun -np 8 snappyHexMesh –parallel –overwrite
where mpirun is a shell script to use the MPI library (you need to install MPI), -np
is the number of processors you want to use, –parallel is a flag that you shall
always use if you want to run in parallel, and –overwrite is an option specific to
snappyHexMesh.
Module'3')'Lecture'10' 106'
Mesh generation using blockMesh and snappyHexMesh
Case 7. Meshing in parallel using snappyHexMesh.
BWB body (external mesh)
From now on, follow me.

•  To do the meshing in parallel:

•  mpirun –np 8 checkMesh –parallel -constant


(To run checkMesh in parallel)

•  reconstructParMesh –mergeTol 1e-06 –constant


(Reconstruct the mesh using geometry information only)

•  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.

•  At this point you are ready to run the simulation.

•  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.

•  If you want to do the meshing in serial, you can proceed as follows:

•  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.

•  This applies to any geometry using serial and parallel meshing

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

Big spoiler alert for those who like cool and


fantastic looking CFD pictures.

Module'4')'Lecture'11' 2'
Before we begin

Cool and fantastic looking pictures do not imply


that the results are correct.

Module'4')'Lecture'11' 3'
Before we begin

As we are going to do some post-processing, I want to


remind you that CFD does not stand for

•  Colorful Fluid Dynamics


•  Careful Fit of Data
•  Colors For Directors

Module'4')'Lecture'11' 4'
Today’s lecture

1.  Data visualization with paraFoam

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 is a wrapper of a third-party open source product named


Paraview (www.paraview.org).

•  Paraview is based on VTK, the visualization toolkit (www.vtk.org).

•  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

•  We will now do some post-processing using


paraFoam. For this we will use the cavity3d tutorial
located in the directory:

$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

Mesh and initial conditions of passive scalar

Module'4')'Lecture'11' 9'
Data visualization with paraFoam
By following the instructions, you should get something like this

Contours of velocity magnitude in two different cutplanes

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.

•  In this solver we simply added a transport equation for a passive scalar. In


the directory programming/applications/solvers/my_icoFoam, you
will find the source code. To compile the solver:

•  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.

•  Go to the postprocessing/cavity3d/ directory. In the terminal type:

•  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.

•  When you use paraFoam, it will generate a file named


case_name.OpenFOAM (where case_name is the name of the case,
cavity3d in this tutorial), which is necessary since Paraview needs a file
to be specified.

•  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

•  Let us do another fantastic tutorial. This time we will


use the yf17 tutorial located in the directory:

$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.

•  The stl file of the geometry is in the directory


$PTOFC/postprocessing/yf17/c1/geo/yf17.stl

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

1.  Data visualization with VISIT

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

•  Let us do some post-processing with VISIT. This time


we will use the multiphase dambreak tutorial located in
the directory:

$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

Mesh Initial conditions

Module'4')'Lecture'12' 6'
Data visualization with VISIT
By following the instructions, you should get something like this

VOF Fraction VOF Fraction volume rendering

Module'4')'Lecture'12' 7'
Data visualization with VISIT
•  Let us do some post-processing using VISIT. From now on follow me.

•  Go to the postprocessing/multiphase_dambreak directory. In the


terminal type:
•  cd $PTOFC/postprocessing/multiphase_dambreak
•  rm –rf 0
•  cp –r 0_org 0
•  blockMesh
•  setFields
•  multiphaseInterFoam

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

•  Now that we warmed-up, let us do a very cool tutorial.


This time we will use the vespa tutorial located in the
directory:

$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

Pressure contours and bounding box

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

Surface mesh and cut plane with velocity vectors

Module'4')'Lecture'12' 15'
Data visualization with VISIT
•  Let us do some post-processing using VISIT. From now on follow me.

•  Go to the postprocessing/vespacoarse directory. In the terminal


type:
•  cd $PTOFC/postprocessing/vespacoarse/

•  We do not need to run this case, the solution is in the directory


$PTOFC/postprocessing/vespacoarse/sol_500

•  However, we need a valid mesh in order to do the post processing.

Module'4')'Lecture'12' 16'
Data visualization with VISIT
•  However, we need a valid mesh in order to do the post processing.

•  If you are in a hurry, the mesh is in the directory sol_mesh,


•  cp -r sol_mesh/polyMesh constant

•  If you want to generate the mesh, in the terminal type:


•  blockmesh
•  snappyHexMesh –overwrite –noFunctionObjects
•  checkMesh

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.

•  In the terminal type:

•  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

Normal rendering Red/Green Stereo rendering (eye angle 4).


Suitable for immerse visualization.

Pressure contours on driver and motorcycle

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.

•  I really like this geometry, it is an actual 3D scan of a Vespa scooter. I


would like to thanks Paul McIntosh for sharing the geometry and the case
setup (http://www.vespalabs.org).

•  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

1.  Data conversion


2.  Data manipulation

Module'4')'Lecture'13' 2'
Today’s lecture

1.  Data conversion


2.  Data manipulation

Module'4')'Lecture'13' 3'
Data conversion

•  OpenFOAM® gives users a lot of flexibility when it comes to scientific


visualization.

•  You are not obliged to use OpenFOAM® visualization tools (paraFoam or


paraview).

•  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

OpenFOAM polyMesh or Fluent mesh


foamMeshToFluent

solution
Mesh boundaries
foamToSurface

Extract surface from


polyMesh patches
surfaceMeshTriangulate

starCD mesh Fieldview 9 CGNS Abaqus mesh


Your own format
foamToStarMesh foamToFieldview9 foamToCGNS foamMeshToAbaqus

Extended version Extended version Extended version Extended version

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

•  In the directory $FOAM_UTILITIES/postProcessing/dataConversion you will


find the following data conversion utilities:

•  foamDataToFluent •  foamToTecplot360
•  foamToEnsight •  foamToTetDualMesh
•  foamToEnsightParts •  foamToVTK
•  foamToGMV •  smapToFoam

For more information about the data conversion


utilities, refer to the User Guide
Module'4')'Lecture'13' 8'
Today’s lecture

1.  Data conversion


2.  Data manipulation

Module'4')'Lecture'13' 9'
Data manipulation

•  First at all, by data manipulation I mean modifying a


field variable or computing a new field variable using
the saved solution (primitive variables).

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

For more information about the post processing


utilities, refer to the User Guide
Module'4')'Lecture'13' 12'
Data manipulation
•  OpenFOAM® utilities can also be cloned and customized to create user
defined utilities.

•  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.

•  In the postProcessing directory, you will find the data manipulation


utilities for post-processing. For example, in the sub-directory
postProcessing/velocityField you will find the following utilities
source code directories:
•  Co, Pe, enstrophy, Q, flowType, streamFunction,
Lambda2, uprime, Mach, vorticity.

In the User Guide you will find the complete listing


Module'4')'Lecture'13' 13'
Data manipulation
•  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 postProcessing/velocityField/Pe, you


will find the file Pe.C, which is the source code of the utility Pe. In the source
code you will find the following description:

Calculates and writes the Pe number as a


surfaceScalarField obtained from field phi.

The -noWrite option just outputs the max/min values


without writing the field.

•  Take your time and dig into each directory to get a complete
description of each utility.
Module'4')'Lecture'13' 14'
Data manipulation

•  Remember the cylinder case?


•  We will now do some data manipulation and post-
processing using the cylinder mesh.
•  For this we will use the supersonic cylinder tutorial
located in the directory:

$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

Courant number animation


Module'4')'Lecture'13' 21'
Data manipulation
•  Let us do some data manipulation.

•  But before starting, I want to remind you that by data


manipulation I mean modifying a field variable or computing a
new field variable using the primitive variables computed during
the solution stage.

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.

•  In the terminal type:

•  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.

•  To visualize peclet number (computed as a surface field), you will need to


converted it to VTK and then plot it as a glyph.

•  foamToVTK –surfaceFields

•  Now you can see the pretty colors in paraview/paraFoam,

•  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.

•  What are functionObject?. Later on we are going to address them.

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;
}

•  What are functionObject?. Later on we are going to address them.

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

1.  The sample utility


2.  Probes
3.  foamLog
4.  Hands-on session

Module'4')'Lecture'14' 2'
Today’s lecture

1.  The sample utility


2.  Probes
3.  foamLog
4.  Hands-on session

Module'4')'Lecture'14' 3'
The sample utility
•  OpenFOAM® provides the sample utility to sample field data for plotting.

•  The sampling locations are specified for a case through a sampleDict


dictionary located in the case system directory.

•  During the job execution, inside the case directory a new folder named
postProcessing/, will be created. In this folder, the sampled values are
stored.

•  Data can be written in a range of formats including well-known plotting


packages such as: grace/xmgr, gnuplot and jPlot.

•  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

•  Let us do some sampling.


•  For this we will use the turbulent backstep case, which
you will find in the directory:

$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

Velocity magnitude contours Pressure contours

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]

Turbulence kinetic energy (k) profiles

[U/Uc] -0.5 0 0.5


Exp
CFD

0 1 2 3 4 5 6 7 8 9 10 [x/H]

Velocity magnitude profiles

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 –time 500:1000


(The –time 500:1000 option will do the sampling for all the solutions saved in the time directories 500 to 1000)

•  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.

•  To visualize the .eps files, from the terminal type:


•  evince profilek.eps
•  evince profileU.eps
or whatever application you use to view .eps files

•  Let us now study the sampleDict dictionary. Go to the system directory


and open the file sampleDict.Module'4')'Lecture'14' 13'
The sample utility
•  The sampleDict dictionary contains at least the following entries (the
header is not shown):
// Set output format
setFormat raw;
// Surface output format.
surfaceFormat foamFile;
// interpolationScheme.
interpolationScheme cellPointFace;
// Fields to sample.
fields
( U k );
// Set sampling definition:
sets
(
x=0H //Name of the sample set
{
type midPoint;
axis z;
start (0 0.5 1);
end (0 0.5 4);
}
//...
//More lines here//
//...
);
// Surface sampling definition:
surfaces
(
);

Module'4')'Lecture'14' 14'
For more information about the sample utility, refer to the user guide.
The sample utility
The sampleDict file

•  The sampleDict file contains several entries to be set according to the


user needs. You can set the following entries,

•  The choice of the interpolationScheme.


•  The format of the line data output.
•  The format of the surface data output.
•  The fields to be sample.
•  The sub-dictionaries that controls each sampling operation.
•  In these sub-dictionaries you can set the name, type and geometrical
information of the sampling operation.

Module'4')'Lecture'14' 15'
For more information about the sample utility, refer to the user guide.
Today’s lecture

1.  The sample utility


2.  Probes
3.  foamLog
4.  Hands-on session

Module'4')'Lecture'14' 16'
Probes
•  OpenFOAM® provides the probeLocations utility to sample field data in
some discrete points.

•  Probes can be created by using the probesDict dictionary, which must be


contained in the system folder.

•  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.

•  The probing can be executed by running the utility probeLocations in the


case folder and according to the application syntax.

•  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

•  Let us do some probing.


•  For this we will use the cylinder vortex shedding case,
which you will find in the directory:

$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

Instantaneous velocity Instantaneous pressure

Reynolds number equal to 60

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.

•  Go to the postprocessing/2d_cylinder_60 directory. In the terminal


type:
•  cd $PTOFC/postprocessing/2d_cylinder_60
•  blockMesh
•  icoFoam > log | tail –f log
•  probeLocations –noFunctionObjects

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):

// Fields to be probed. runTime modifiable!


fields
(
p
U
);

// Locations to be probed. runTime modifiable!


// You can add as many as you like
probeLocations
(
( 5 0.5 0)
( 5 0 0 )
( 5 -0.5 0 )
( 10 0.5 0 )
( 10 0 0 )
( 10 -0.5 0 )
( 2 1 0 )
);

Module'4')'Lecture'14' 25'
Today’s lecture

1.  The sample utility


2.  Probes
3.  foamLog
4.  Hands-on session

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).

•  solver_name > logfile


•  foamLog 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

•  You can also try to write your own script.


•  Remember, in order to use pyFoamPlotWatcher.py you need to save the
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

•  In a new terminal window and inside the directory


postprocessing/2d_cylinder_60, type in the terminal:

•  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.

•  functionObject are small pieces of code executed at a regular interval


without explicitly being linked to the application.

•  When using functionObject, files of sampled data can be written for


plotting and post processing.

•  functionObject are specified in the controlDict dictionary and


executed every timestep or pre-defined intervals.

•  All functionObject are runtime modifiable.

•  All the information related to the functionObject is saved in the directory


postProcessing.

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.

In the User Guide you will find the complete listing


Module'4')'Lecture'15' 5'
functionObjects
•  And by the way, these three functionObject are really powerful:'

•  systemCall
•  timeActivatedFileUpdate
•  writeRegisteredObject

•  Try to figure out what they do and when they can be used.

•  As usual, you can also program your own functionObject.

In the User Guide you will find the complete listing


Module'4')'Lecture'15' 6'
functionObjects

•  Let us do some sampling using functionObject.


•  For this we will use the cylinder vortex shedding case,
which you will find in the directory:

$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

Velocity magnitude Vorticity

Module'4')'Lecture'15' 10'
functionObjects
By following the instructions, you should get something like this

Mean velocity magnitude Mean pressure

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

•  You can compute the vortex shedding


frequency by computing the power
spectral density (PSD) function.
•  The PSD can be computed using the
FFT method.
•  For this you can use matlab, scilab,
octave, scipy.
•  The plotting utility QtiPlot (which is
similar to gnuplot), has a built in FFT
tool.
•  In this case I used scipy.

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.

•  Go to the postprocessing/2d_cylinder_100 directory.


In the terminal type:

•  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.

•  By the way, we are saving an extremely large amount of


information.

•  This is typical of unsteady simulations, and sometimes it can be


too daunting to post-process and analyze the data.

•  To ease the pain of doing data analytics and post-processing,


you can use shell or Python scripting.
Module'4')'Lecture'15' 19'
functionObjects
•  Inside the directory postProcessing, you will find the
following sub-directories:

•  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 erase the parentheses in fieldMinMax.dat and save the output in out.txt,


type in the terminal:
•  cat fieldMinMax.dat | tr -d "()" > out.txt

•  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

•  To erase the temporal file out.txt, type in the terminal:


•  rm out.txt Module'4')'Lecture'15' 22'
functionObjects
Some shell and awk scripting
•  Let us go to the postProcessing/minmaxdomain/0 directory. Now type in the
terminal:

•  To erase the header in pre_minmax.txt, type in the terminal:

•  awk '{if (NR!=1) {print}}’ pre_minmax.txt > temp


•  mv temp pre_minmax.txt

•  To erase the header in vel_minmax.txt, type in the terminal:

•  awk '{if (NR!=1) {print}}’ vel_minmax.txt > temp


•  mv temp vel_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:

•  awk ‘NR>=5009 && NR { total += $3; count++}


END { print “Mean_drag ” total/count}’ forceCoeffs.dat
(This is one line)

•  To compute the mean value of the aerodynamic coefficients (lift coefficient in this case)
using the data in forceCoeffs.dat, type in the terminal:

•  awk ‘NR>=5009 && NR { total += $4; count++}


END { print “Mean_lift ” total/count}’ forceCoeffs.dat
(This is one line)

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:

•  awk ‘NR>=5009 && NR { total += $3; totalsq += $3*$3; count++}


END { print “Std_dev drag ” sqrt(totalsq/count –
(total/count)^2)}’ forceCoeffs.dat
(This is one line)

•  To compute the standard deviation of the aerodynamic coefficients (lift coefficient in this
case) using the data in forceCoeffs.dat, type in the terminal:

•  awk ‘NR>=5009 && NR { total += $4; totalsq += $4*$4; count++}


END { print “Std_dev drag ” sqrt(totalsq/count –
(total/count)^2)}’ forceCoeffs.dat
(This is one line)
Module'4')'Lecture'15' 25'
functionObjects
Some shell and awk scripting
•  In the directory scripts (located in the top level case directory) you will find three
scripts that will do the post processing automatically, namely:
•  script_force_coe
•  script_minmax
•  script_probes

•  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.

The power of scripting!!!


Module'4')'Lecture'15' 27'
functionObjects
Plotting in gnuplot

•  Let us do some plotting using gnuplot. Type in the terminal (you must be inside the
scripts directory):

•  gnuplot

•  plot [][-1:1] 'vel_minmax.txt' u 1:3 w l title "min_ux”

or you can try to plot everything

•  plot [][-1:q] 'vel_minmax.txt' u 1:3 w l title "min_ux",'vel_minmax.txt' u 1:4 w


l title "min_uy",'vel_minmax.txt' u 1:5 w l title "min_uz",'vel_minmax.txt' u 1:9
w l title "max_ux",'vel_minmax.txt' u 1:10 w l title "max_uy",'vel_minmax.txt' u
1:11 every 100 w p pt 7 ps 0.5 lc 8 title "max_uz”

(This is one line)

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

•  plot [][1:2] ’forceCoeffs.dat' u 1:3 title ”Drag coefficient”


with lines
(This is one line)

•  plot [][-1:1] ’forceCoeffs.dat' u 1:4 title ”Lift coefficient”


with lines
(This is one line)

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//
);

here, all the functionObject are defined.

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,
{

type function_object_to_use; func%onObject,to,use,

functionObjectLibs ("function_object_library.so"); Library,to,use,

enabled true;
outputControl outputTime;

timeStart 100; Keywords,and,sub8


timeEnd 200;
dic%onaries,specific,to,
//... the,func%onObject,
//functionObject //
//keywords and sub-dictionaries //
//...

}
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;

Library,to,use, functionObjectLibs ("libIOFunctionObjects.so");

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;

Library,to,use, functionObjectLibs ("libforces.so");

outputControl timeStep;
outputInterval 1;

patches ("cylinder");

Keywords,and,sub8dic%onaries, //If multiple patches are present


specific,to,the,func%onObject, //patches ("body1" "body2" "body3");

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;

Library,to,use, functionObjectLibs ("libforces.so");

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;

Library,to,use, functionObjectLibs ("libfieldFunctionObjects.so");

enabled true;

mode component;

Keywords,and,sub8dic%onaries, outputControl timeStep;


specific,to,the,func%onObject, outputInterval 1;

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;

Library,to,use, functionObjectLibs ("libsampling.so");

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;

Library,to,use, functionObjectLibs ("libsampling.so");

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;

Library,to,use, functionObjectLibs ("libfieldFunctionObjects.so");

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;

Library,to,use, functionObjectLibs ("libfieldFunctionObjects.so");

enabled true;

outputControl timeStep;
outputInterval 1;

Keywords,and,sub8dic%onaries, log true;


specific,to,the,func%onObject,
valueOutput true;
surfaceFormat raw;

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;

Library,to,use, functionObjectLibs ("libsimpleFunctionObjects.so");

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 more information about functionObject, refer to the user guide.


Module'4')'Lecture'15' 44'
functionObjects
•  Sometimes it can happen that you forget to use a functionObject.

•  To solve this conundrum, you can use the utility


execFlowFunctionObjects, this utility will executed the
functionObject using the saved solutions.

•  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.

•  By doing co-processing, we can do visualization on-the-fly.

•  In principle, co-processing is similar to doing sampling using


functionObject, but when we do co-processing we output
pretty pictures (e.g., streamlines, iso-surfaces, cut-planes),
while when we do sampling using functionObject we save
data for plotting (we save a quantity of interest).

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.

•  Co-processing requires that you identify what you want to see


before running the simulation.

•  In OpenFOAM®, you can output on-the-fly streamlines, cutting


planes, iso-surfaces, wall bounded stream lines, forces and
force coefficients written into data bins.

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.

•  Finally, co-processing can save a large amount of information


so check your hardware limitations.

•  Plan everything in advanced.

Module'4')'Lecture'15' 50'
Co-processing

•  Let us do some co-processing using


functionObjects.
•  For this we will use the vespa case, which you will find
in the directory:

$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.

•  Let us run this case for 20 iterations. After finishing the


simulation, go to the directory $PTOFC/postprocessing/
vespacoarse/postProcessing and take a look at the cool
pictures saved concurrently.
Module'4')'Lecture'15' 53'
Co-processing
•  To run the case, you will need a valid mesh.

•  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

•  Attention, the mesh generation is time consuming


•  A friendly reminder, you can run most of the applications and
solvers in parallel. I hopeModule'4')'Lecture'15'
you remember how to do it. 55'
Co-processing
•  To run the simulation in parallel:
•  decomposePar
•  mpirun -np 6 renumberMesh -overwrite
-noFunctionObjects -parallel
•  mpirun -np 6 simpleFoam -parallel >
log.simplefoam | tail –f log.simplefoam
•  mpirun -np 6 yPlusRAS -parallel
•  mpirun -np 6 wallShearStress -parallel
•  paraFoam –builtin

•  I guess you know how to run the simulation in serial or use


more/less processors. Module'4')'Lecture'15' 56'
Co-processing
•  Now you can go to the directory $PTOFC/postprocessing/
vespacoarse/postProcessing and take a look at the cool
pictures saved concurrently.

•  In the directory $PTOFC/postprocessing/vespacoarse/


postProcessing you will find the following sub-directories:
•  cuttingPlane
•  isoSurface
•  sets/streamLines
•  sets/wallBoundedStreamLines

Module'4')'Lecture'15' 57'
Co-processing
•  In each of these sub-directories you will find the pretty pictures
saved in VTK format.

•  To visualize the VTK files you can use paraview/paraFoam.

•  By the way you can choose a different output format.

•  Also, you can have different saving frequencies.

•  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;

Library,to,use, functionObjectLibs ("libsampling.so");

//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

1.  Running in parallel


2.  Running in a cluster using a job scheduler
3.  Hands-on session

Module'5')'Lecture'16' 2'
Today’s lecture

1.  Running in parallel


2.  Running in a cluster using a job scheduler
3.  Hands-on session

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.

Shared memory architectures – Workstations and portable computers

Distributed memory architectures – Cluster and super computers


Module'5')'Lecture'16' 4'
Running in parallel
Why use parallel computing?
•  Save time: run faster (speed-up) and increase your productivity, with the
potential of saving money in the design process.
•  Solve larger and more complex problems: thanks to parallel computing
we can solve bigger problems (scalability). A single computer has limited
physical memory.
•  Provide concurrency: A single computer or processor can only do one
thing at a time. Multiple processors or computing resources can do many
things simultaneously.
•  Save money: in theory, throwing more resources at a task will shorten its
time to completion, with potential cost savings. Parallel computers can be
built from cheap, commodity components.
•  Limits to serial computing: both physical and practical reasons pose
significant constraints to simply building ever faster serial computers (e.g,
transmission speeds, CPU clock rate, limits to miniaturization, hardware
cooling, economic limitations).
Module'5')'Lecture'16' 5'
!
Running in parallel
Speed-up and scalability example

•  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:

•  Decompose the domain. To do so we use the decomposePar utility. You


also will need a dictionary named decomposeParDict which is located in
the system directory of the case.

•  Distribute the jobs among the processors or computing nodes. To do


so, OpenFOAM® uses the public domain OpenMPI implementation of the
standard message passing interface (MPI). By using MPI, each processor
runs a copy of the solver on a separate part of the decomposed domain.

•  Finally, the solution is reconstructed to obtain the final result. This is


done by using the reconstrucPar utility.

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.

•  In other words, we want to minimize the inter-processors communication


and the processor workload.

•  The mesh and fields are broken up according to a set of parameters


specified in a dictionary named decomposeParDict that must be located in
the system directory of the case.

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.

•  The user has a choice of seven methods of decomposition, specified by the


method keyword in the decomposeParDict dictionary.

•  On completion, a set of subdirectories will be created, one for each


processor. The directories are named processorN where N = 0, 1, 2, 3,
and so on. Each directory contains the decomposed fields.

Module'5')'Lecture'16' 10'
Running in parallel
Domain Decomposition Methods

•  simple: simple geometric decomposition in which the domain is split into


pieces by direction.

•  hierarchical: Hierarchical geometric decomposition which is the same as


simple except the user specifies the order in which the directional split is
done.

•  manual: Manual decomposition, where the user directly specifies the


allocation of each cell to a particular processor.

•  multiLevel: similar to hierarchical, but all methods can be used in a nested


form.

•  structured: 2d decomposition of a structured mesh (special case)


Module'5')'Lecture'16' 11'
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.

Please be aware that there are license


restrictions using metis.

Module'5')'Lecture'16' 12'
Running in parallel

Running in parallel – Gathering all together

Module'5')'Lecture'16' 13'
Running in parallel
polyMesh/ and 0/'

decomposePar'

Processor0 processor1' processor2' processor3'

•  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

mpirun –np <NPROCS> <application/utility> –parallel

•  To run in parallel we use the MPI library.


•  The number of processors to use or <NPROCS>, needs to be the same as the
number of partitions.
•  Do not forget to use the flag –parallel
Module'5')'Lecture'16'
. 15'
Running in parallel

•  In the decomposed case, you will find the mesh


information, boundary and initial conditions and
the solution for every processor.
•  The information is inside the directory
processorN.

reconstructPar'

•  When you reconstruct the case, you glue together


all the information contained in the decomposed
case.
•  All the information (mesh, boundary and initial
conditions and the solution), is inside the original
case folder.
Module'5')'Lecture'16' 16'
Running in parallel
•  Summarizing, to run in parallel we proceed in the following way:

•  decomposePar
•  mpirun –np <NPROCS> <application/utility> –parallel
•  reconstructPar
•  paraFoam

•  You can do the post-processing and visualization on the decomposed case


or reconstructed case. We are going to address this later on.

Module'5')'Lecture'16' 17'
Running in parallel

Let us run a case in parallel

Module'5')'Lecture'16' 18'
Running in parallel

•  Let us run the Rayleigh-Taylor instability.


•  Go to the directory:

$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

Mesh VOF Fraction

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:

•  mpirun –np 8 renumberMesh –overwrite -parallel


•  mpirun -np 8 interFoam –parallel | tee log.interfoam
•  reconstructPar
•  paraFoam

Here I am using 8 processors. In your case, use the maximum number of


processor available in your laptop, for this you will need to modify the
decomposeParDict dictionary located in the system folder. Specifically,
you will need to modify the entry numberOfSubdomains, and set its value
to the number of processors you want to use.

Module'5')'Lecture'16' 23'
Running in parallel

•  Remember the cylinder case? I told you not to forget


about it.
•  Let us run this case in parallel.
•  Let us go to the directory:

$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:

•  mpirun –np 4 checkMesh –parallel


•  mpirun –np 4 renumberMesh –overwrite –parallel
(This utility renumber the mesh to minimize the bandwidth)

•  mpirun –np 4 icoFoam –parallel | tee –f log.icofoam


•  paraFoam –builtin
(Wait, what is that –builtin option?, we are going to address that later on)

Here I am using 4 processors. In your case, use the maximum number of


processor available in your laptop, for this you will need to modify the
decomposeParDict dictionary located in the system folder. Specifically,
you will need to modify the entry numberOfSubdomains, and set its value
to the number of processors you want to use.

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

Running in parallel – Post-processing and


visualization

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.

•  To do so, in the terminal type:

•  reconstructPar
•  paraFoam

Module'5')'Lecture'16' 30'
Running in parallel
•  What is the meaning of the option –builtin we used with paraFoam?

•  The option –builtin let us post-process the decomposed case directly.

•  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.

•  When we use the option –builtin we work on the decomposed case


directly.

•  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.

•  The third option consist in post-processing each decomposed domain


individually.

•  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.

•  After creating all processorN.OpenFOAM files, you can launch paraFoam


and load each file.

Module'5')'Lecture'16' 33'
Running in parallel

•  Let us post-process each decomposed domain


individually.
•  For this we are going to use the yf17 tutorial, that you
will find in the directory:

$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.

•  Go to the $PTOFC/parallel_tut/yf17 directory. In the terminal type:

•  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

•  Notice that we are using 4 processors/partitions.

•  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)

•  To visualize the partitions, you will need to open in paraFoam each


processorN.OpenFOAM file.

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

Mesh partitioning – Scotch Method


Module'5')'Lecture'16' 41'
Running in parallel

•  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

Mesh partitioning – Hierarchical Method


Module'5')'Lecture'16' 43'
Running in parallel
By following the instructions, you should get something like this

Mesh partitioning – Scotch Method Mesh partitioning – Hierarchical Method

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

•  The option –cellDist will write the cell distribution as a


volScalarField field that can be used for post-processing. The new field
variable will be saved in the file cellDist located in the time directory 0.

•  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

Decomposing big meshes

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.

•  For example, in a computing node with 16 gigs of memory, it is not possible


to decompose a mesh with 30.000.000; you will need to use a computing
node with at least 32 gigs of memory.

•  Same applies for the utility reconstructPar.


Module'5')'Lecture'16' 47'
Running in parallel

Do all solvers/utilities run in parallel?

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:

•  find $WM_PROJECT_DIR -type f | xargs grep –sl ‘noParallel’

•  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.

•  To compile paraFoam with MPI support in $WM_THIRD_PARTY_DIR/


makeParaView4 set the option withMPI'to'true,'

withMPI = true

•  Another important utility that does not run in parallel is blockMesh.


Module'5')'Lecture'16' 49'
Running in parallel

Right syntax to run in parallel

Module'5')'Lecture'16' 50'
Running in parallel
•  The syntax used to run OpenFOAM® solvers in parallel:

•  mpirun –np <NPROCS> <application/utility> –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:

•  mpirun -np 8 icoFoam -parallel

In this case we are using 8 processors.

Module'5')'Lecture'16' 52'
Running in parallel
•  For example, to run the utility foamToEnsight in parallel you will need to
proceed as follows:

•  mpirun -np 2 foamToEnsight -parallel

In this case we are using 2 processors.

'

Module'5')'Lecture'16' 53'
Today’s lecture

1.  Running in parallel


2.  Running in a cluster using a job scheduler
3.  Hands-on session

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

cd PATH_TO_DIRECTORY //go to this directory

#decomposePar //decompose the case, this line


//is commented

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

•  Remember, running in a cluster is no different from running in your


workstation or portable computer. The only difference is that you need to
schedule your jobs.

•  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.

•  Remember to always double check your scripts.

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.

•  But the following options are not valid:


•  Use 2 computing nodes. Each node will need 16 gigs of memory.
•  Use 16 computing nodes and ask for 256 cores. The maximum number
of cores for this job is 128.

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

1.  Finite Volume Method: A Crash Introduction

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.

•  As consequence of this requirement, all dependent variables are assumed to vary


linearly around a point P in space and instant t in time,

⇥(x) = ⇥P + (x xP ) · (⇥⇥)P where ⇥P = ⇥(xP )


✓ ◆t
⇤⇥
⇥(t + t) = ⇥t + t where ⇥t = ⇥(t)
⇤t

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.

•  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 volume V of all control volumes is
known.
•  We also know the neighbors of the control
Y volume .
X

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.

•  The vector from the centroid P of to


the centroid N of VN is named d.
•  The location where the vector d intersects
a face is fi .
•  We know this information for all control
volumes and all faces.

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.

•  Putting all together, is a lot geometrical


information that we need to track.
•  A lot of overhead goes into the data book-
keeping.

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

•  In the same way, the centroid of face f is given by


Z
(x xP )dS = 0
Sf

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

•  This is known as the collocated arrangement.


•  This is the variable arrangement and mean value assumptions.

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

•  Next, we recall the Gauss’s theorem,


Z I
· adV = dS · a
V V

where is a closed surface bounding the control volume and dS


represents an infinitesimal surface element with associated normal n pointing
outward of the the surface .

•  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

Convective, diffusive, gradients and source


terms approximations

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

This approximation if exact if S is either constant of varies


linearly within the control volume; otherwise is second order
accurate Sc is the constant part of the source term and
Sp is the non-linear part

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

where we have approximated the centroid


gradients by using the Gauss theorem.
This method is second order accurate

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

•  This type of interpolation scheme is known as linear interpolation or central


differencing and it is second order accurate.
•  However, it may generate oscillatory solutions (unbounded solutions).
Module'6')'Lecture'17' 25'
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 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.

(r) = 2r (D) (r) = r (CD)

2 SUPERBEE (r) = 2
VANLEER

1 MINMOD (r) = 1 (SOU )

(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).

SuperBee Minmod vanLeer

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.

Upwind – 1st order TVD-Minmod – 2nd order

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

•  If you are interested, you will find this case in the


directory:

$PTOFC/my_cases0/oblique_step/c2/d2

Module'6')'Lecture'17' 39'
Finite Volume Method: A Crash introduction

Interpolation of convective fluxes in a


skew mesh

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

Correction of diffusive fluxes in a


non-orthogonal mesh

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

Minimum correction approach Over-relaxed approach

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

Mesh induced errors

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.

•  After spatial discretization, we can proceed with the temporal discretization. By


proceeding in this way we are using the Method of Lines (MOL).

•  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

Linear system solution

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

So, what does OpenFOAM® do?

Module'6')'Lecture'17' 56'
Finite Volume Method: A Crash introduction
So, what does OpenFOAM® do?

It simply discretize in space and time the governing


equations in arbitrary polyhedral control volumes over
the whole domain. Assembling in this way a large set of
linear discrete algebraic equations (DAE), and then it
solves this system of DAE to find the solution of the
transported quantities.

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:

•  Discretization of the solution domain or the mesh. This information is


contained in the directory constant/polyMesh/
•  Boundary conditions and initials conditions. This information is contained in
the directory 0/
•  Physical properties such as density, gravity, diffusion coefficient, viscosity,
etc. This information is contained in the directory constant/
•  Physics involve, such as turbulence modeling, mass transfer, etc. This
information is contained in the directories constant/ and/or system/
•  How to discretize in space each term of the governing equations (diffusive,
convective, gradient and source terms). This information is set in the
system/fvSchemes dictionary.
Module'6')'Lecture'17' 58'
Finite Volume Method: A Crash introduction
So, what does OpenFOAM® do?
Therefore, we need to give to OpenFOAM® the following information:

•  How to discretize in time the obtained semi-discrete governing equations.


This information is set in the system/fvSchemes dictionary.
•  How to solve the linear system of discrete algebraic equations. This
information is set in the system/fvSolution dictionary.
•  Set runtime parameters and general instructions on how to run the case
(such as time step and maximum CFL number). This information is set in the
system/controlDict dictionary.
•  Additionally, we may set sampling and functionObjects for post-
processing. This information is contained in the specific dictionaries
contained in the directory system/

Module'6')'Lecture'17' 59'
Finite Volume Method: A Crash introduction

Discretization schemes implemented


in OpenFOAM®

Module'6')'Lecture'17' 60'
Finite Volume Method: A Crash introduction

•  We will now illustrate a few of the discretization


schemes available in OpenFOAM® using a model
case.
•  The case consist in pure convection of a scalar in a
vector field in a one dimensional tube.
•  If you are interested, this case is located in the
directory:

$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

Comparison of different spatial discretization schemes.


Euler in time – 100 cells – CFL = 0.1
Linear limiters on the Sweby diagram.

Module'6')'Lecture'17' 64'
Finite Volume Method: A Crash introduction

Comparison of different spatial discretization schemes.


Euler in time – 100 cells – CFL = 0.1
Linear limiters on the Sweby diagram.

Module'6')'Lecture'17' 65'
Finite Volume Method: A Crash introduction

Comparison of different spatial discretization schemes.


Euler in time – 100 cells – CFL = 0.1
Non-linear limiters on the Sweby diagram.

Module'6')'Lecture'17' 66'
Finite Volume Method: A Crash introduction

Comparison of different spatial discretization schemes.


Euler in time – 100 cells – CFL = 0.1
Non-linear limiters on the Sweby diagram.

Module'6')'Lecture'17' 67'
Finite Volume Method: A Crash introduction

Comparison of different spatial discretization schemes.


Euler in time – 100 cells – CFL = 0.1
All limiters together

Module'6')'Lecture'17' 68'
Finite Volume Method: A Crash introduction

Comparison of different gradient limiters.


Linear upwind in space – Euler in time – 100 cells – CFL 0.1

Module'6')'Lecture'17' 69'
Finite Volume Method: A Crash introduction

Comparison of different gradient limiters.


Linear upwind in space – Euler in time – 100 cells – CFL 0.1

Module'6')'Lecture'17' 70'
Finite Volume Method: A Crash introduction

Comparison of different gradient limiters.


Linear upwind in space – Euler in time – 100 cells – CFL 0.1

Module'6')'Lecture'17' 71'
Finite Volume Method: A Crash introduction

Comparison of different gradient limiters.


Linear upwind in space – Euler in time – 100 cells – CFL 0.1

Module'6')'Lecture'17' 72'
Finite Volume Method: A Crash introduction

Comparison of different temporal discretization schemes


and gradient limiters.
Linear upwind in space – 100 cells – CFL 0.1

Module'6')'Lecture'17' 73'
Finite Volume Method: A Crash introduction

Comparison of different temporal discretization schemes


and gradient limiters.
Linear upwind in space – 100 cells – CFL 0.1

Module'6')'Lecture'17' 74'
Finite Volume Method: A Crash introduction

Comparison of Crank Nicolson blending factor using cellLimited


leastSquares 0.5.
Linear upwind in space – 100 cells – CFL 0.1

Module'6')'Lecture'17' 75'
Finite Volume Method: A Crash introduction

Comparison of Crank Nicolson blending factor using cellLimited


leastSquares 0.5.
Linear upwind in space – 100 cells – CFL 0.1

Module'6')'Lecture'17' 76'
Finite Volume Method: A Crash introduction

Comparison of Crank Nicolson blending factor using cellMDLimited


Gauss linear 1.0 gradient limiter.
Linear upwind in space – 100 cells – CFL 0.1

Module'6')'Lecture'17' 77'
Finite Volume Method: A Crash introduction

Comparison of Crank Nicolson blending factor using cellMDLimited


Gauss linear 1.0 gradient limiter.
Linear upwind in space – 100 cells – CFL 0.1

Module'6')'Lecture'17' 78'
Finite Volume Method: A Crash introduction

Comparison of different time-step size (different CFL number).


Linear upwind in space – Euler in time – 100 cells

u t
CF L =
x

Module'6')'Lecture'17' 79'
Finite Volume Method: A Crash introduction

Comparison of different mesh sizes.


Linear upwind in space – Euler in time

u t
CF L =
x

Module'6')'Lecture'17' 80'
Finite Volume Method: A Crash introduction

•  Accuracy
•  Stability
•  Boundedness

Play by these terms and you will


succeed.
Module'6')'Lecture'17' 81'
Finite Volume Method: A Crash introduction

My favorite FVM/CFD references

Module'6')'Lecture'17' 82'
Finite Volume Method: A Crash introduction

•  As I mentioned earlier this is not a FVM/CFD course, but I


highly advise you to take some time and study the theory in
depth.

•  There is vast amount of literature in the field of FVM/CFD.


I will give you some of my favorite references, which are closed
related to what you will find in OpenFOAM®.

•  Therefore, I am involuntarily omitting other references which


are equally or even more important. Sorry for those guys.

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

1.  Boundary and initial conditions

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).

•  In an IBVP, we need to impose appropriate boundary conditions and initial


conditions.

•  No need to say that the boundary conditions and initial conditions need to be
physically realistic.

•  Boundary conditions are a required component of the numerical method,


they tell what is going on the boundaries of the domain. You can see them
as source terms.

•  Initial conditions are also a required component of the numerical method,


they define the initial state of the problem.

Module'6')'Lecture'18' 3'
Boundary conditions and initial conditions

A few words about boundary conditions

Module'6')'Lecture'18' 4'
Boundary conditions and initial conditions
•  Boundary conditions can be divided into three fundamental or
mathematical types:

•  Dirichlet boundary conditions.

•  Neumann boundary conditions.

•  Robin Boundary conditions.

•  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.,

•  in, inlet, inflow, velocity inlet, incoming flow and so on.

•  out, outlet, outflow, velocity outlet, outgoing flow and so on.

•  solid wall, non-penetrating wall, fixed wall and so on.


Module'6')'Lecture'18' 5'
Boundary conditions and initial conditions
•  When we use a Dirichlet boundary condition, we prescribe the value of a
variable at the boundary.

•  When we use a Neumann boundary condition, we prescribe the gradient


normal to the boundary.

•  Robin boundary conditions, are a mixed of Dirichlet boundary conditions


and Neumann boundary conditions.

•  You can use any of these three boundary conditions in OpenFOAM®.

Module'6')'Lecture'18' 6'
Boundary conditions and initial conditions
•  Defining boundary conditions involves:

•  Determining the boundary condition type.

•  Finding the location of the boundary condition in the domain.

•  Giving the required physical information.

•  The choice of the boundary conditions depend on:

•  Geometrical considerations.

•  Physics involved.

•  Information available at the boundary condition location.

•  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

Types of boundary conditions (B


IC Dirichlet
Neumann
Robin

BC BC

BC Initial contions (IC):


Uniform or non-uniform value in the
whole domain
Patches with uniform or non-uniform
values

Y BC

X Module'6')'Lecture'18' 8'
Boundary conditions and initial conditions

A few words about initial conditions

Module'6')'Lecture'18' 9'
Boundary conditions and initial conditions
•  Initial conditions can be divided into two groups:

•  Uniform initial conditions.

•  Non-uniform initial conditions.

•  For non-uniform initial conditions, the value used can be obtained from:

•  Another simulation, including a solution with different grid resolution.

•  A potential solver.

•  Experimental results.

•  A mathematical function

•  Reduced order model. Module'6')'Lecture'18' 10'


Boundary conditions and initial conditions
•  Defining initial conditions involves:

•  Determining the initial condition type.

•  Finding the location of the initial condition in the domain.

•  Giving the required physical information.

•  The choice of the initial conditions depend on:

•  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

Types of boundary conditions (B


IC1 Dirichlet
Neumann
Robin

BC BC

BC IC2 Initial contions (IC):


Uniform or non-uniform value in the
whole domain
Patches with uniform or non-unifor
values

Y BC

X Module'6')'Lecture'18' 12'
Boundary conditions and initial conditions

A few considerations and guidelines

Module'6')'Lecture'18' 13'
Boundary conditions and initial conditions
•  Remember:

•  Poorly defined boundary conditions can have a significant


impact on your solution.

•  Sometimes, finding the right boundary conditions can be really


tricky.

•  Initial conditions are as important as the boundary conditions.

•  A good initial condition can improve the stability and convergence


rate.

•  On the other hand, unphysical initial conditions can slow


down the convergence rate or can cause divergence.

•  You need to define boundary conditions and initials conditions for


every single variable you are solving.
Module'6')'Lecture'18' 14'
Boundary conditions and initial conditions
•  The required values of the boundary conditions and initial conditions depend
on the equations you are solving and physical models used, e.g.,

•  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.

•  If you are doing turbulent combustion or chemical reactions, you will


need to define the species, reactions and primitive and turbulent
variables.

•  By the way, you also need to define the physical properties.

•  Remember, the physics is yours.


Module'6')'Lecture'18' 15'
Boundary conditions and initial conditions
•  General guidelines when choosing the boundary conditions and initial
conditions:

•  Boundary conditions and initial conditions need to be physically


realistic.

•  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.

•  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.

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.

•  If possible, select inflow and outflow boundary conditions such that


the flow either goes in or out normal to the boundaries.

•  Use zero gradient boundary conditions only with incompressible


flows and when you are sure that the flow is fully developed.

Module'6')'Lecture'18' 17'
Boundary conditions and initial conditions
•  General guidelines when choosing the boundary conditions and initial
conditions:

•  At least one boundary condition should specify pressure


(total or static).

•  Outlets that discharge to the atmosphere can use a static pressure


boundary condition. This is interpreted as the static pressure of the
environment into which the flow exhausts.

•  Inlets that take flow into the domain from the atmosphere can use a
total pressure boundary condition (e.g. open window).

•  Mass flow inlets produce a uniform velocity profile at the inlet.

Module'6')'Lecture'18' 18'
Boundary conditions and initial conditions
•  General guidelines when choosing the boundary conditions and initial
conditions:

•  The mass flow distribution at mass flow outlets is based on the


upstream values.

•  Pressure specified boundary conditions allow a natural velocity


profile to develop.

•  Velocity inlet boundary conditions are intended for incompressible


flow.

•  For compressible flows use mass flow inlets or pressure boundary


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.

Slip wall or symmetry Slip wall or symmetry


Pressure or
Velocity Inlet Mass flow Inlet

Uniform flow Uniform flow

Outlet Outlet
No-slip wall No-slip wall

Outflow Artificial wall


allowed prevents outflow

Y Slip wall or symmetry Slip wall or symmetry

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

•  Backflow boundary conditions provide a generic outflow/inflow Uniform


condition,
flow with
specified inflow/outflow for the case of return flow.
•  In the case of a backflow outlet, when the flux is positiveNo-slip (out
wall of domain) it applies a

Neumann boundary condition (zero gradient), andArtificial


when wall
the flux is negative (into of
domain), it applies a Dirichlet boundary condition prevents
(fixed value).
outflow

•  Same concept applies to backflow inlets. Slip wall or symmetry

Slip wall or symmetry Slip wall or symmetry

Zero gradient outlet Inlet - Outlet


Uniform flow No back flow treatment Uniform flow Back flow treatment

No-slip wall No-slip wall

Inlet Inlet

Back flow Back flow


allowed not allowed

Y Slip wall or symmetry Slip wall or symmetry

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.

SLIP WALLS SLIP WALLS

NO-SLIP WALLS

SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW

Y Y

X Z

SLIP WALLSModule'6')'Lecture'18' SLIP WALLS 22'


Boundary conditions and initial conditions
•  Domain dimensions (when the dimensions are not known):
•  As a general guideline you can use the dimensions illustrated in the figure, where L is
a reference length. In this case, L is the wing chord.
•  Always verify that there are no significant gradients normal to any of the boundaries
patches. If there are, you should consider increasing the domain dimensions.

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

Boundary conditions in OpenFOAM®

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.

0/U 0/p constant/polyMesh/boundary

inlet inlet inlet

oUtlet outlet outlet

top top top

bottom bottom Bottom

cylinder cylinder cylinder

sym sym sym


Module'6')'Lecture'18' 30'
Boundary conditions and initial conditions
•  The following base type boundary conditions are paired. That is, the type
needs to be same in the boundary dictionary and field variables
dictionaries (e.g. U, p).

constant/polyMesh/boundary 0/U - 0/p

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.

constant/polyMesh/boundary 0/U - 0/p

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:

constant/polyMesh/boundary 0/U 0/p

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

A few boundary conditions setup

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

SLIP WALLS SLIP WALLS

NO-SLIP WALLS

SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW

Y Y

X Z

SLIP WALLS Module'6')'Lecture'18' SLIP WALLS 37'


Boundary conditions and initial conditions
•  Boundary conditions setup:
At inflow: At outflow: At no-slip wall: At symmetry plane:
U = fixed value U = back flow U =0 U = symmetry
p = zero gradient p = fixed value p = zero gradient p = symmetry
T = fixed value T = back flow T = zero gradient T = symmetry
 = fixed value  = back flow  = zero gradient or fixed value  = symmetry
! = fixed value ! = back flow ! = zero gradient or fixed value ! = symmetry

SYMMETRY SYMMETRY

NO-SLIP WALLS

SYMMETRY
OUTFLOW

SYMMETRY
INFLOW

Y Y

X Z

SYMMETRY Module'6')'Lecture'18' SYMMETRY 38'


Boundary conditions and initial conditions
•  Boundary conditions setup:
At inflow: At outflow: At no-slip wall: At symmetry plane:
U = fixed value U = back flow U =0 U = symmetry
p = zero gradient p = fixed value p = zero gradient p = symmetry
T = fixed value T = back flow T = zero gradient T = symmetry
 = fixed value  = back flow  = zero gradient or fixed value  = symmetry
! = fixed value ! = back flow ! = zero gradient or fixed value ! = symmetry

NO-SLIP WALLS NO-SLIP WALLS

NO-SLIP WALLS

SYMMETRY
OUTFLOW

SYMMETRY
INFLOW

Y Y

X Z

NO-SLIP WALLSModule'6')'Lecture'18' NO-SLIP WALLS 39'


Boundary conditions and initial conditions
•  Boundary conditions setup:
At inflow: At outflow: At no-slip wall: At symmetry plane:
U = fixed value U = back flow U =0 U = symmetry
p = zero gradient p = fixed value p = zero gradient p = symmetry
T = fixed value T = back flow T = zero gradient T = symmetry
 = fixed value  = back flow  = zero gradient or fixed value  = symmetry
! = fixed value ! = back flow ! = zero gradient or fixed value ! = symmetry

OUTFLOW OUTFLOW

NO-SLIP WALLS

SYMMETRY
OUTFLOW
INFLOW

OUTFLOW
Y Y

X Z

OUTFLOW Module'6')'Lecture'18' OUTFLOW 40'


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

SYMMETRY SYMMETRY

NO-SLIP WALLS

SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW

Y Y

X Z

SYMMETRY Module'6')'Lecture'18' SYMMETRY 41'


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

SLIP WALLS SLIP WALLS

NO-SLIP WALLS

SLIP WALLS
SYMMETRY
OUTFLOW
INFLOW

Y Y

X Z

SLIP WALLS Module'6')'Lecture'18' SLIP WALLS 42'


Boundary conditions and initial conditions
•  Boundary conditions setup:
At inflow: At outflow: At no-slip wall: At periodic patches: At slip walls:
U = fixed value U = back flow U =0 U = periodic U = slip
p = zero gradient p = fixed value p = zero gradient p = periodic p = slip
T = fixed value T = back flow T = zero gradient T = periodic T = slip
 = fixed value  = back flow  = zero gradient or fixed value  = periodic  = slip
! = fixed value ! = back flow ! = zero gradient or fixed value ! = periodic ! = slip

SLIP WALLS SLIP WALLS

NO-SLIP WALLS OUTFLOW

PERIODIC
INFLOW

PERIODIC
Y Y

X Z

SLIP WALLS Module'6')'Lecture'18' SLIP WALLS 43'


Boundary conditions and initial conditions
•  So far we have not study turbulence, however, in all previous configurations
we are missing one boundary condition?

•  Do you know which one?

•  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.

•  However, some of them are more stable.


•  A very robust and stable configuration is to set the inlet velocity and
the static pressure at outlet. The inlet total pressure is an implicit
result of the solution.
•  You can also set mass flow rate at inlet and the static pressure at
outlet. The inlet total pressure will be adjusted to get the given mass
flow.
•  Less robust but still stable, total pressure at inlet with static pressure
at outlet. This configuration is sensitive to initial conditions.

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.

•  Inlet velocity and pressure zero gradient at outlet. This combination


should be avoided because the static pressure level is not fixed.
•  Qualitatively speaking the results are very different.
•  Visualization or co-processing helped us to identify a potential
problem.
BCs 1. BCs 2.
Inlet velocity and fixed outlet pressure Inlet velocity and zero gradient outlet pressure

Module'6')'Lecture'18' 47'
Boundary conditions and initial conditions
•  And some configurations are unreliable.

•  Inlet velocity and pressure zero gradient at outlet. This combination


should be avoided because the static pressure level is not fixed.
•  However, quantitatively speaking the results seem to be fine.
•  Very misleading.

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

Types of boundary conditions (BC):


IC Dirichlet
Neumann
Robin

BC BC

BC Initial contions (IC):


Uniform or non-uniform value in the
whole domain
Patches with uniform or non-uniform
values

Y BC

Module'6')'Lecture'18' 50'
Boundary conditions and initial conditions
•  One of the possible scenarios, external aerodynamics.

Slip wall or symmetry

Uniform flow

Inlet value Outlet value

No-slip wall

Y Slip wall or symmetry

Module'6')'Lecture'18' 51'
Boundary conditions and initial conditions
•  Another possible scenarios, buoyant flow and a heated body.
Outlet value

Uniform flow

Adiabatic wall Adiabatic wall


Wall temperature

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

Moving wall (1DOF)

Inlet value Outlet value

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

1.  Unsteady and steady simulations


2.  Understanding residuals

Module'6')'Lecture'19' 2'
Today’s lecture

1.  Unsteady and steady simulations


2.  Understanding residuals

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:

Multiphase flows – Continuous stirred tank reactor


Module'6')'Lecture'19' 11'
Unsteady and steady simulations
•  A few examples of unsteady applications:

Marine applications - Sea keeping


Module'6')'Lecture'19' 12'
Unsteady and steady simulations
How to run unsteady simulations in OpenFOAM®?

•  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®?

•  In the system/controlDict dictionary you set runtime parameters


and general instructions on how to run the case (such as time step and
maximum CFL number). You also set the saving frequency.
•  In the system/fvSchemes dictionary you set the temporal
discretization scheme.
•  In the system/fvSolution dictionary you set the linear solvers.
•  Also, you will need to set the number of corrections of the
velocity-pressure coupling method used (e.g. PISO or PIMPLE), this is
done in the system/fvSolution dictionary.
•  Additionally, you may set functionObjects in the system/
controlDict dictionary. The functionObjects are used to do
sampling, probing and co-processing.

Module'6')'Lecture'19' 14'
Unsteady and steady simulations
What about steady simulations?

•  First at all, steady simulations are a big simplification of reality.


•  As I told you before, most of the flows you will encounter are unsteady.
•  In steady simulations we made two assumptions:
•  We ignore unsteady fluctuations. That is, we neglect the temporal
derivative in the governing equations.
•  We perform time averaging when dealing with stationary turbulence
(RANS modeling)
•  The advantage of steady simulations is that they require lower
computational cost and are easier to post-process and analyze.

Module'6')'Lecture'19' 15'
Unsteady and steady simulations
What about steady simulations?

•  In OpenFOAM® is possible to run steady simulation.


•  To do so, you need to use the appropriate solver and set the discretization
scheme to deal with a steady simulation.
•  As you are not solving the temporal derivative, you do not need to set the
time step. However, you need to tell to OpenFOAM® how many iterations
you would like to run.
•  You can also set the residual controls. If you do not set the residual
controls, OpenFOAM® will run until reaching the maximum number of
iterations.

Module'6')'Lecture'19' 16'
Unsteady and steady simulations
What about steady simulations?

•  You also need to set the under-relaxation factors. The under-relaxation


factors control the change of the variable .

n n 1 n⇤ n 1
P = P + ↵( P P )
•  If < 1 means that we are using under-relaxation.

•  Under-relaxation is a feature typical of steady solvers using the SIMPLE


method.

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?

•  The under-relaxation factors are bounded between 0 and 1.

relaxationFactors

0 1
Velocity

Stability

•  Selecting the under-relaxation factors it is kind of equivalent to selecting the


Module'6')'Lecture'19' 19'
right time step.
Unsteady and steady simulations
How to run steady simulations in OpenFOAM®?

•  In the system/controlDict dictionary you set runtime parameters


and general instructions on how to run the case (such as the number of
iterations to run). You also set the saving frequency.
•  In the system/fvSchemes dictionary you set the temporal
discretization scheme, for steady simulations it must be steadyState.
•  In the system/fvSolution dictionary you set the linear solvers,
under-relaxation factors and residual controls.
•  Also, you will need to set the number of corrections of the
velocity-pressure coupling method used (e.g. SIMPLE), this is done in
the system/fvSolution dictionary.
•  Additionally, you may set functionObjects in the system/
controlDict dictionary. The functionObjects are used to do
sampling, probing and co-processing.
Module'6')'Lecture'19' 20'
Unsteady and steady simulations

How to choose the time-step in unsteady


simulations and monitor the solution

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.

When you use large time


steps you do not resolve well
the physics

By using a smaller time step


you resolve better the physics

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

1.  Unsteady and steady simulations


2.  Understanding residuals

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

1.  On the CFL number

Module'6')'Lecture'20' 2'
On the CFL number
•  First at all, what is the CFL or Courant number?

•  In one dimension, the CFL number is defined as,

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.

•  But not all numerical schemes have the same stability


constrains.

•  By doing a linear stability study, we can find the stability


requirements of each numerical scheme (but this is out of the
scope of this lecture).

Module'6')'Lecture'20' 4'
On the CFL number

CFL number condition

Module'6')'Lecture'20' 5'
On the CFL number
•  Let us talk about the CFL number condition.

•  The CFL number condition is the maximum allowable CFL


number a numerical scheme can use.

•  For the n - dimensional case, the CFL number condition


becomes,

Xn
ui
CF L = t  CF Lmax
i=1
x i

Module'6')'Lecture'20' 6'
On the CFL number

To get a better idea of the importance of the CFL


number condition, let us talk again about
explicit and implicit methods.

Module'6')'Lecture'20' 7'
On the CFL number
Explicit methods

•  Most of the explicit numerical schemes have a CFL condition


close to 1.0.

•  Some of them have a CFL condition of 0.5, and some of them


can go up to 2.0.

•  If you choose a CFL number larger than the maximum


allowable by the explicit numerical scheme, your numerical
solution will become unstable and it will diverge.

•  Explicit numerical schemes are conditionally stable.

•  In OpenFOAM® you will find explicit numerical schemes, so be


careful when choosing your time-step or CFL number.
Module'6')'Lecture'20' 8'
On the CFL number
Implicit methods

•  On the other hand, implicit numerical schemes are


unconditionally stable.

•  In other words, they are not constrained to the CFL number


condition.

•  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.

•  The time-step must be chosen in such a way that it resolves the


time-dependent features, and it maintains the solver stability.

•  In OpenFOAM® you will find many implicit numerical schemes.


Module'6')'Lecture'20' 9'
On the CFL number
Some facts of explicit and implicit methods

•  For the same CFL number, the time-step of explicit methods is


usually an order of magnitude lower than the time-step required
for implicit methods.

•  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.

•  Explicit methods perform really well in GPUs.

•  Also, explicit methods are really easy to implement.

Module'6')'Lecture'20' 10'
On the CFL number
Some facts of explicit and implicit methods

•  Explicit numerical schemes are extremely accurate.

•  If you are interested in using large time steps (large CFL


number) with implicit methods, it is highly advisable that you
choose a time step in such a way that it resolves the temporal
scales (good accuracy).

•  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

•  In my personal experience, I have been able to go up to a


CFL = 5.0 while maintaining the accuracy and without
increasing too much the computational cost.

•  But as I am often interested in the unsteadiness of the solution,


I usually use a CFL number in the order of 1.0

Module'6')'Lecture'20' 12'
On the CFL number

My personal view of the CFL number

Module'6')'Lecture'20' 13'
On the CFL number
•  I like to view the CFL number as follows,

u t u speed of the PDE


CF L = = =
x x/ t speed of the mesh

•  It is an indication of the amount of information that propagates


through one cell (or many cells), in one time-step.

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

u t u speed of the PDE


CF L = = =
Module'6')'Lecture'20' 15'
x x/ t speed of the mesh
On the CFL number
•  By the way, and this is extremely important, the CFL condition is
a necessary condition for stability (and hence convergence).

•  But it is not always sufficient to guarantee stability.

•  Other properties of the discretization schemes that you should


observe are: conservationess, boundedness, transportiveness,
and accuracy.

•  The CFL number is not a magical number !!!

Module'6')'Lecture'20' 16'
Finite Volume Method: A Crash introduction

Comparison of different time-step size (different CFL number)


for a model problem.
Linear upwind in space – Euler in time – 100 cells

u t
CF L =
x

Module'6')'Lecture'20' 17'
Finite Volume Method: A Crash introduction

Comparison of different mesh sizes for a model problem.


Linear upwind in space – Euler in time

u t
CF L =
x

Module'6')'Lecture'20' 18'
Module 7

Module'7')'Lecture'21' 1'
Today’s lecture

1.  Programming in OpenFOAM®.


Building blocks.

Module'7')'Lecture'21' 2'
Programming in OpenFOAM®
During this session we will:

•  First, we will start by taking a look at the algebra of tensors in


OpenFOAM®.

•  Then, we will take a look at how to generate tensor fields from tensors.

•  Next, we will learn how to access mesh information.

•  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:

•  And of course, we are going to program a little bit in C++.

•  But do not be afraid, after all this is not a C++ course.

•  Remember, all OpenFOAM® components are implemented in library


form for easy re-use.

•  OpenFOAM® encourage code re-use. So basically we are going to take


something that already exist and we are going to modify it to fix our
needs.

•  I like to call this method CPAC (copy-paste-adapt-compile).


Module'7')'Lecture'21' 4'
Programming in OpenFOAM®
By the way and in case you did not know it,

•  In the directory $WM_PROJECT_DIR/applications/test,


you will find the source code of several test cases that show
the usage of most of the OpenFOAM® classes.

•  For your convenience, I already copied the directory


$WM_PROJECT_DIR/applications/test to the
directory $PTOFC/test

Module'7')'Lecture'21' 5'
Programming in OpenFOAM®
Some preliminaries,

•  OpenFOAM® represents scalars, vectors and matrices as tensor fields.


A zero rank tensor is a scalar, a first rank tensor is a vector and a second
rank tensor is a matrix.

•  The PDEs we want to solve involve derivatives of tensor fields with


respect to time and space.

•  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.

Tensor Rank Common name Basic class Access function

0 Scalar scalar

1 Vector vector x(), y(), z()

2 Tensor tensor xx(), xy(), xz() …

Module'7')'Lecture'21' 7'
Programming in OpenFOAM®
Basic tensor classes in OpenFOAM®

In OpenFOAM®, the tensor


0 1
1 2 3
T=@ 4 5 6 A
7 8 9
can be declared in the following way

tensor T(1, 2, 3, 4, 5, 6, 7, 8, 9);

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®

For instance, the following code line

Info << “Txz = “ << T.xz ( ) << endl;

Will generate the following output

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

Outer product rank a, b >=1 ab a * b

Inner product rank a, b >=1 a.b a & b

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

•  In the directory $WM_PROJECT_DIR/applications/test you will find


many examples showing you the use of the classes in OpenFOAM®.

•  For your convenience, I already copied the directory $WM_PROJECT_DIR/


applications/test to the directory $PTOFC/test

Module'7')'Lecture'21' 11'
Programming in OpenFOAM®
Examples of the use of some tensor classes

•  Let us now compile a tensor class example. From the terminal:

•  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.

After all, is not that difficult, right?

Module'7')'Lecture'21' 12'
Programming in OpenFOAM®
Dimensional units in OpenFOAM®

•  As you might already notice, OpenFOAM® is fully dimensional.

•  Dimensional checking is implemented as a safeguard against implementing


a meaningless operation.

•  OpenFOAM® encourages the user to attach dimensional units to any tensor


and it will perform dimension checking of any tensor operation.

•  You can check $FOAM_SRC/OpenFOAM/dimensionedTypes/ for the


dimensional classes.

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

No. Property Unit Symbol

1 Mass kilogram kg

2 Length meters m

3 Time second s

4 Temperature Kelvin K

5 Quantity moles mol

6 Current ampere A
Luminuous
7 candela cd
intensity

dimensionSet (kg, m, s, K, mol, A, cd)


Module'7')'Lecture'21' 15'
Programming in OpenFOAM®
Units correspondence in dimensionSet

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

dimensionSet (kg, m, s, K, mol, A, cd)


Module'7')'Lecture'21' 16'
Programming in OpenFOAM®
Dimensional units examples
Add the following lines to Test-tensor.C (in the directory
$PTOFC/test/my_tensor you will find the modified files):
•  Before the main function main ( ):

#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;

Compile, run, and look at the output.


Module'7')'Lecture'21' 17'
Programming in OpenFOAM®
Dimensional units examples

By the end of this exercise, your output should looks like this:

Sigma sigma [1 -1 -2 0 0 0 0] (1e+06 0 0 0 1e+06 0 0 0 1e+06)

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):

Info << “Sigma name: “ << sigma.name ( ) << endl;


Info << “Sigma dimensions: “ << sigma.dimensions ( ) << endl;
Info << “Sigma value: “ << sigma.value ( ) << endl;

Also, extract some of the values of the tensor by adding the following line:

Info<< "Sigma yy (22) value: " << sigma.value().yy() << endl;

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

•  OpenFOAM® frequently needs to store sets of data and perform mathematical


operations.

•  OpenFOAM® therefore provides an array template class List<Type>, making it


possible to create a list of any object of class Type that inherits the functions of the
Type. For example a List of vector is List<vector>.

•  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

•  You can check $FOAM_SRC/OpenFOAM/fields/Fields for the field classes.

•  Algebraic operations can be performed between Field subject to obvious restrictions


such as the fields having the same number of elements.

•  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):

tensorField tf1(2, tensor::one);


Info<< "tf1: " << tf1 << endl;
tf1[0] = tensor(1, 2, 3, 4, 5, 6, 7, 8, 9);
Info<< "tf1: " << tf1 << endl;
Info<< "2.0*tf1: " << 2.0*tf1 << endl;

Compile, run, and look at the output.


Module'7')'Lecture'21' 22'
Programming in OpenFOAM®

Did something look familiar to you?

Absolutely yes, we already study these concepts in the


previous lecture. That is: typedef declarations,
classes and templates.

Remember, OpenFOAM® uses typedef declarations,


classes and templates a lot!

Module'7')'Lecture'21' 23'
Programming in OpenFOAM®

Let us take a look at the whole solution


process:

•  Creation of the tensors.


•  Mesh assembly.
•  Fields creation.
•  Equation discretization.

All by using OpenFOAM® classes and


template classes
Module'7')'Lecture'21' 24'
Programming in OpenFOAM®
Discretization of a tensor field in OpenFOAM®

•  The dicretization is done using the FVM (Finite Volume Method).

•  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.

•  No limitations on the number of faces bounding each cell.

•  No restriction on the alignment of each face.

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.

•  You can check $FOAM_SRC/OpenFOAM/meshes/ for the polyMesh classes.

•  The fvMesh class extends the polyMesh class to include additional data needed for
the FVM discretization.

•  You can check $FOAM_SRC/src/finiteVolume/fvMesh for the fvMesh classes.

Module'7')'Lecture'21' 26'
Programming in OpenFOAM®
Discretization of a tensor field in OpenFOAM®

•  The template class geometricField relates a tensor field to a fvMesh. Using


typedef declarations geometricField is renamed to volField (cell center),
surfaceField (cell faces), and pointField (cell vertices).

•  You can check $FOAM_SRC/OpenFOAM/fields/GeometricFields for the


geometricField classes.

•  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()

surfaceVectorField Face area vector Sf Sf()

surfaceScalarField Face area magnitude |Sf | magSf()

volVectorField Cell centres C C()

surfaceVectorField Face centres Cf Cf()

surfaceScalarField Face fluxes g Phi()

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

•  In $PTOFC/test/my_mesh/cavity, you will find a modified copy of the cavity


tutorial. From the terminal:

•  cd $PTOFC/test/my_mesh/cavity
•  blockMesh

•  Now run Test-mesh in the $PTOFC/test/my_mesh/cavity directory. Look at


the output.

Module'7')'Lecture'21' 29'
Programming in OpenFOAM®
Examine a fvMesh

•  Let us take a look at the file Test-mesh.C

•  C() gives the center of all cells and boundary faces.


•  V() gives the volume of all the cells.
•  Cf() gives the center of all the faces.

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):

Info<< mesh.C().internalField()[1][1] << endl;


Info<< mesh.boundaryMesh()[0].name() << endl;

•  Compile, run, and look at the output.

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;

•  Compile, run, and look at the output.


Module'7')'Lecture'21' 32'
Programming in OpenFOAM®
Equation discretization in OpenFOAM®

•  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.

•  The fvm (finiteVolumeMethod) and fvc (finiteVolumeCalculus) classes


contain static functions for the differential operators, and discretize any
geometricField.

•  fvm returns a fvMatrix, and fvc returns a geometricField.

•  In the directories $FOAM_SRC/finiteVolume/finiteVolume/fvc and


$FOAM_SRC/finiteVolume/finiteVolume/fvm you will find the respective
classes.
Module'7')'Lecture'21' 33'
Programming in OpenFOAM®
Discretization of the basic PDE terms in OpenFOAM®
The list is not complete

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)

vol<type>Field ⇢ scalar, volScalarField surfaceScalarField


Module'7')'Lecture'21' 34'
Programming in OpenFOAM®

•  Ok, let us apply what we have learnt so far.


•  We will now write a solver to solve the convection-
diffusion equation.
•  For this we will use the convection-diffusion tutorial
located in the directory:

$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

Using OpenFOAM® equation mimicking pragma, we can write this equation as

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

•  Now go to the $PTOFC/test/my_convection_diffusion/case directory and


run the new solver. In the terminal:

•  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:

Mesh (20 cells)

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®

Now you know how to program in


OpenFOAM® using all C++ features.

Not that hard, right?

Module'7')'Lecture'21' 41'
Programming in OpenFOAM®
I just presented the basic building blocks to program in
OpenFOAM®.

For more information you should refer to the


programmer’s guide, doxygen documentation
and the OpenFOAM® coding guide in the
openfoamwiki site.
http://openfoamwiki.net/index.php/OpenFOAM_guide
Module'7')'Lecture'21' 42'
Programming 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

1.  How to implement a new boundary condition


in OpenFOAM®
2.  How to implement my own application in
OpenFOAM®
3.  How to add temperature to icoFoam

Module'7')'Lecture'22' 2'
Today’s lecture

1.  How to implement a new boundary condition


in OpenFOAM®
2.  How to implement my own application in
OpenFOAM®
3.  How to add temperature to icoFoam

Module'7')'Lecture'22' 3'
How to implement a new boundary condition in OpenFOAM®

Remember, all components in OpenFOAM® are implemented in library


form for easy re-use. So, in order to implement a new boundary
condition, we should follow these basic steps:

•  The implementations of the boundary conditions are located in the


directory $FOAM_SRC/finiteVolume/fields/fvPatchFields/

•  To add a new boundary condition, start by finding one that does


almost what you want to do. Then, copy that boundary condition
implementation to $WM_PROJECT_USER_DIR and modify it according
to your needs.

Module'7')'Lecture'22' 4'
How to implement a new boundary condition in OpenFOAM®

Remember, all components in OpenFOAM® are implemented in library


form for easy re-use. So, in order to implement a new boundary
condition, we should follow these basic steps:

•  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®

Parabolic inlet boundary condition

Module'7')'Lecture'22' 6'
How to implement a new boundary condition in OpenFOAM®

Parabolic inlet boundary condition


We will add a new parabolic inlet profile boundary condition.

•  In the directory $PTOFC/programming/src/finiteVolume/


fields/fvPatchFields/derived/parabolicVelocity you will
find the new boundary condition. Notice that we kept the same directory
structure as in $FOAM_SRC.

From the terminal type:

•  cd $PTOFC/programming/src/finiteVolume/fields/
fvPatchFields/derived/parabolicVelocity
•  wmake libso

Starting from OpenFOAM® version 2.2.1, the argument libso is not


required anymore.
Module'7')'Lecture'22' 7'
How to implement a new boundary condition in OpenFOAM®

Parabolic inlet boundary condition

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).

Remember to modify the files located in the Make directory, so they


reflect the location of the new library and its name.

By the way, take a look at the files.

Module'7')'Lecture'22' 8'
How to implement a new boundary condition in OpenFOAM®

Parabolic inlet boundary condition


Let us now setup a new case using the new boundary condition. From the
terminal:
•  cd $PTOFC/mycases1/elbow2d_1/elbow_parabolic_inlet_0

Before running the solver we need to:


•  Add the new boundary condition parabolicVelocity in 0/U.
velocity-inlet-5
{
type parabolicVelocity;
maxValue 2.0;
n (1 0 0);
y (0 1 0);
value (0 0 0); //dummy value
}
Module'7')'Lecture'22' 9'
How to implement a new boundary condition in OpenFOAM®

Parabolic inlet boundary condition


Let us now setup a new case using the new boundary condition.
Before running the solver we need to:

•  Then add the line:

libs (“parabolicvelocityBC.so”)

to the case controlDict dictionary in the system directory.

Module'7')'Lecture'22' 10'
How to implement a new boundary condition in OpenFOAM®

Parabolic inlet boundary condition

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®

Parabolic inlet boundary condition


By following the instructions, you should get something like this

Mesh
Module'7')'Lecture'22' 12'
How to implement a new boundary condition in OpenFOAM®

Parabolic inlet boundary condition


By following the instructions, you should get something like this

Parabolic inlet profile Uniform inlet profile

Module'7')'Lecture'22' 13'
How to implement a new boundary condition in OpenFOAM®

Parabolic inlet boundary condition


By following the instructions, you should get something like this

Module'7')'Lecture'22' 14'
Inlet profiles
How to implement a new boundary condition in OpenFOAM®

A closer look to the parabolic inlet boundary condition


•  The parabolicVelocityFvPatchVectorField boundary condition
consists of two files:

parabolicVelocityFvPatchVectorField.C
parabolicVelocityFvPatchVectorField.H

•  The .H file is the header file, and it is included in the header of the .C file.

•  We can see that in the .H file we create a sub class to the


fixedValueFvPatchVectorField:
class parabolicVelocityFvPatchVectorField: public fixedValueFvPatchVectorField

i.e. this is for Dirichlet boundary conditions for a vector field.

Module'7')'Lecture'22' 15'
How to implement a new boundary condition in OpenFOAM®

A closer look to the parabolic inlet boundary condition


•  The class has private data and takes in the following data

//- Peak velocity magnitude


scalar maxValue_;
//- Flow direction
vector n_;
//- Direction of the y-coordinate
vector y_;

•  The TypeName("parabolicVelocity"), used when specifying the


boundary condition, is defined.

•  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®

A closer look to the parabolic inlet boundary condition


•  The actual implementation of the boundary condition can be found in the
updateCoeffs() member function:

boundBox bb(patch().patch().localPoints(), true);


vector ctr = 0.5*(bb.max() + bb.min());
const vectorField& c = patch().Cf();
scalarField coord = 2*((c - ctr) & y_)/((bb.max() - bb.min()) & y_);
vectorField::operator=(n_*maxValue_*(1.0 - sqr(coord)));

•  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®

A closer look to the parabolic inlet boundary condition


Find out more about all the variables by including the following lines at the end
of the updateCoeffs member function:

Info << “c” << c << endl;


Info << “ctr” << ctr << endl;
Info << “y_” << y_ << endl;
Info << “bb.max()” << bb.max() << endl;
Info << “bb.min()” << bb.min() << endl;
Info << “(c - ctr)” << c - ctr << endl;
Info << “((c - ctr) & y_)” << ((c - ctr) & y_) << endl;
Info << “((bb.max() - bb.min()) & y_)” << ((bb.max() - bb.min()) & y_) << end;
Info << “coord” << coord << endl;

Module'7')'Lecture'22' 18'
How to implement a new boundary condition in OpenFOAM®

Wait, what if I do not want to program my boundary


condition?
•  You can save the pain of programming the boundary conditions in
OpenFOAM® if you use swak4foam.

•  swak4foam offers the possibility of implementing new boundary conditions


without the need of programming.

•  If you go to the directory $PTOFC/mycases1/elbow2d_1/


elbow_parabolic_inlet_1, you will find a case where we use
swak4foam to implement a parabolic profile inlet.

•  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®

Wait, what if I do not want to program my boundary


condition?
•  I highly advise you to spend some time and try to learn how to use
swak4foam as it will save you a lot of time.

•  I have been able to program really complex boundary conditions using


swak4foam. It works most of the times.

•  For more information about swak4foam you can visit the following site
http://openfoamwiki.net/index.php/Contrib/swak4Foam.

•  Let us go to the directory $PTOFC/mycases1/elbow2d_1/


elbow_parabolic_inlet_1, from now on follow me.

Module'7')'Lecture'22' 20'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition

Module'7')'Lecture'22' 21'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition


Starting from the parabolic inlet profile boundary condition, let us now create a
new boundary condition to model a paraboloid inlet profile.

•  In the directory $PTOFC/programming/src/finiteVolume/fields/


fvPatchFields/derived/p3d you will find the new boundary condition.
Notice that we kept the same directory structure as in $FOAM_SRC.

•  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®

Paraboloid inlet boundary condition


Starting from the parabolic inlet profile boundary condition, let us now create a
new boundary condition to model a paraboloid inlet profile.

•  As we simply cloned the directory parabolicVelocity, the name of the


paraboloid inlet boundary condition is the same as the one used in the
parabolicVelocity boundary condition and the implementation consists
of two files:
parabolicVelocityFvPatchVectorField.C
parabolicVelocityFvPatchVectorField.H

•  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®

Paraboloid inlet boundary condition


Starting from the parabolic inlet profile boundary condition, let us now create a
new boundary condition to model a paraboloid inlet profile.

•  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.

•  In the directory $PTOFC/programming/src/finiteVolume/fields/


fvPatchFields/derived/paraboloid you will find the paraboloid
inlet boundary condition. For your convenience, in this implementation I
already replaced all instances of parabolicVelocity by paraboloid
(names of files, classes and functions).

Module'7')'Lecture'22' 24'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition


Starting from the parabolic inlet profile boundary condition, let us now create a
new boundary condition to model a paraboloid inlet profile.

•  By the way, take a look at the files in the directory $PTOFC/programming/


src/finiteVolume/fields/fvPatchFields/derived/paraboloid
and identify all the modifications (in naming convention and implementation).

To compile:
•  cd $PTOFC/programming/src/finiteVolume/fields/
fvPatchFields/derived/paraboloid
•  wmake libso

Starting from OpenFOAM® version 2.2.1, the argument libso is not


required anymore
Module'7')'Lecture'22' 25'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition

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).

Remember to modify the files located in the Make directory, so they


reflect the location of the new library and its name.

By the way, take a look at the files.

Module'7')'Lecture'22' 26'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition


Let us now setup a new case using the new boundary condition. From the
terminal:
•  cd $PTOFC/mycases1/elbow3d/elbow_paraboloid
Before running the solver we need to:
•  Add the new boundary condition parabolicVelocity in 0/U.
inlet1
{
type paraboloid;
maxValue 0.4;
n (1 0 0);
y (0 1 0);
y1 (0 0 1);
radius 1.0;
value uniform (0 0 0); //dummy value
}
Module'7')'Lecture'22' 27'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition


Let us now setup a new case using the new boundary condition.
Before running the solver we need to:

•  Then add the line:

libs (“paraboloid.so”)

to the case controlDict dictionary in the system directory.

Module'7')'Lecture'22' 28'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition

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®

Paraboloid inlet boundary condition


By following the instructions, you should get something like this

Geometry
Module'7')'Lecture'22' 30'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition


By following the instructions, you should get something like this

Mesh
Module'7')'Lecture'22' 31'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition


By following the instructions, you should get something like this

Paraboloid profile
Module'7')'Lecture'22' 32'
How to implement a new boundary condition in OpenFOAM®

Paraboloid inlet boundary condition


By following the instructions, you should get something like this

Velocity magnitude contours in a cut plane


Module'7')'Lecture'22' 33'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer

Module'7')'Lecture'22' 34'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer

Starting from the parabolic inlet profile boundary condition, let us now created a new
boundary condition to model the atmospheric boundary layer.

In the directory $PTOFC/programming/src/finiteVolume/fields/


fvPatchFields/derived/ablVelocity you will find the new boundary condition.
Take a look at the new boundary condition and identify the changes we have done.
Also, try to figure out what kind of law we used to model the atmospheric boundary layer
inlet profile. In the terminal type:

•  cd $PTOFC/programming/src/finiteVolume/fields/
fvPatchFields/derived/ablVelocity
•  wmake libso

Starting from OpenFOAM® version 2.2.1, the argument libso is not


required anymore
Module'7')'Lecture'22' 35'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer

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).

Remember to modify the files located in the Make directory, so they


reflect the location of the new library and its name.

By the way, take a look at the files.

Module'7')'Lecture'22' 36'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer


Let us now setup a new case using the new boundary condition. From the
terminal:
•  cd $PTOFC/mycases4/building/c0

Before running the solver we need to:


•  Add the new boundary condition ablVelocity in 0/U.
inflow
{
type ablVelocity;
n (1 0 0);
y (0 1 0);
maxValue 12.3;
value (0 0 0); //dummy value
}

Module'7')'Lecture'22' 37'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer


Let us now setup a new case using the new boundary condition.
Before running the solver we need to:

•  Then add the line:

libs (“ablvelocityBC”)

to the case controlDict dictionary in the system directory.

Module'7')'Lecture'22' 38'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer

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

By the way, this case is expensiveModule'7')'Lecture'22'


so you better run in parallel. 39'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer

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®

Atmospheric boundary layer

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®

Atmospheric boundary layer


By following the instructions, you should get something like this

Mesh
Module'7')'Lecture'22' 42'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer


By following the instructions, you should get something like this

Pressure and velocity contours


Module'7')'Lecture'22' 43'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer


By following the instructions, you should get something like this

Pressure and velocity contours


Module'7')'Lecture'22' 44'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer


By following the instructions, you should get something like this

Pressure and velocity contours


Module'7')'Lecture'22' 45'
How to implement a new boundary condition in OpenFOAM®

Atmospheric boundary layer


By following the instructions, you should get something like this

Inlet profile
Module'7')'Lecture'22' 46'
Today’s lecture

1.  How to implement a new boundary condition


in OpenFOAM®
2.  How to implement my own application in
OpenFOAM®
3.  How to add temperature to icoFoam

Module'7')'Lecture'22' 47'
How to implement my own application in OpenFOAM®

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:

•  The applications implementations are located in $WM_PROJECT_DIR/


applications

•  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.

•  After you finish modifying or writing your own application, compile it


and use it as you normally do.

Module'7')'Lecture'22' 48'
How to implement my own application in OpenFOAM®

Laplace equation solver

Module'7')'Lecture'22' 49'
How to implement my own application in OpenFOAM®

Laplace equation solver

Let us write a solver for the Laplace equation:

•  In the directory $PTOFC/programming/applications/solvers/


my_laplace_st/ you will find the new application.

From the terminal type:

•  cd $PTOFC/programming/applications/solvers/
my_laplace_st/
•  wmake

Module'7')'Lecture'22' 50'
How to implement my own application in OpenFOAM®

Laplace equation solver

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).

Remember to modify the files located in the Make directory, so they


reflect the location of the new library and its name.

By the way, take a look at the files.

Module'7')'Lecture'22' 51'
How to implement my own application in OpenFOAM®

Laplace equation solver

So, what changes did we introduce in my_laplace_st directory:

•  We created volumeScalarField T in createFields.H


•  We created the dimensionedScalar DT in createFields.H
•  We created the dimensionedScalar sourceterm in
createFields.H
•  We added the Laplace equation in my_lapace_st.C
solve
(
fvm::ddt(T) - fvm::laplacian(DT, T) - sourceterm
);
@T S
r · ( rT )
Module'7')'Lecture'22' 52'
@t
How to implement my own application in OpenFOAM®

Laplace equation solver

So, what changes did we introduce in my_laplace_st directory:

•  Additionally we added in my_laplace_St.C the line:

#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®

Laplace equation solver

Let us now setup a new case using my_laplace_st. From the terminal:

•  cd $PTOFC/mycases0/laplace_1/c1

Before running the solver we need to:

•  Add the new field variable file T to 0 directory.


•  In fvSchemes, add the following lines:
•  grad(T) Gauss linear;
•  laplacian(DT,T) Gauss linear corrected;
•  In fvSolution, add the solutions settings for T.
•  In transportProperties, add the diffusion coefficient DT and the
source term sourceterm.Module'7')'Lecture'22' 54'
How to implement my own application in OpenFOAM®

Laplace equation solver

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®

Laplace equation solver


By following the instructions, you should get something like this

Mesh (5 cells)
Module'7')'Lecture'22' 56'
How to implement my own application in OpenFOAM®

Laplace equation solver


By following the instructions, you should get something like this

Module'7')'Lecture'22' 57'
Comparison analytical solution versus numerical solution
Today’s lecture

1.  How to implement a new boundary condition


in OpenFOAM®
2.  How to implement my own application in
OpenFOAM®
3.  How to add temperature to icoFoam

Module'7')'Lecture'22' 58'
How to add temperature to icoFoam

•  Hereafter we will modify an existing solver (icoFoam).

•  The modification will consist in adding temperature to the solver.

•  We will need to copy the original solver into the directory


$WM_PROJECT_USER_DIR. Remember to use the exact directory structure.

•  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/

•  Now rename the file icoFoam.C to my_icoFoam.C.


•  mv icoFoam.C my_icoFoam.C

Remember, it is highly advisable that the directory and the file


have the same name.

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

•  No changes are necessary for the file options.

•  Now go back to the my_icoFoam directory and compile the application. In


the terminal,
•  cd ..

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.

•  Now we are ready to compile the new application. In the terminal:


•  wmake

•  If everything went fine, your new solver binary should be in the


$FOAM_USER_APPBIN directory. Check this with:
•  ls $FOAM_USER_APPBIN

You should see the new solver my_icoFoam in this directory.


Module'7')'Lecture'22' 62'
How to add temperature to icoFoam

•  So far we only compiled the application with a new name.


•  Let us now add the necessary changes in order to solve the temperature
field.

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"));

//Starting from here add this line


dimensionedScalar DT
(
transportProperties.lookup("DT")
);
//Done adding new lines
Module'7')'Lecture'22' 64'
How to add temperature to icoFoam
•  If you keep reading the file, you will see that the scalar field p
(volScalarField) and the velocity field U (volVectorField) are
created. We need to add the new field for temperature T
(volScalarField).
•  After the creation of the field U and before the line #include
“createPhi.H”, add the following lines:
Info<< "Reading field T\n" <<endl;
volScalarField T
(
IOobject
(
"T",
runTime.timeName(),
mesh,
IOobject::MUST_READ,
IOobject::AUTO_WRITE
),
mesh
); Module'7')'Lecture'22' 65'
How to add temperature to icoFoam
•  Save the modifications in createFields.H. At this point we have created
the new field T and the new transport property DT.
•  Let us now add the new equation to solve. Recalling that we want to add the
transport equation for the scalar T (temperature) to the current solver
⇤T
+ ⇥ · (⇥T ) ⇥ · ( ⇥T ) = 0
⇤t
Using OpenFOAM® equation mimicking syntax, we can write this equation
as

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

•  If everything went fine, your new solver binary should be in the


$FOAM_USER_APPBIN directory. Check this with:

•  ls $FOAM_USER_APPBIN

You should see the new solver my_icoFoam in this directory.

Module'7')'Lecture'22' 68'
How to add temperature to icoFoam
•  The next step is to test the new solver.

•  Go to the directory $PTOFC/mycases1/elbow2d_1/


elbow_plus_temperature. In the terminal:

•  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).

•  We also need to add the new transport property to the


transportProperty dictionary in the constant directory.

•  We need to tell to OpenFOAM® how to discretize the new equations. This


is done in the fvSchemes dictionary in the system directory.

•  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.

•  Take a look at these files (T, transportProperties, fvSchemes and


fvSolution) and identify all the additions and changes made.

•  Always remember, OpenFOAM® is fully dimensional so your


dimensions must be consistent.

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 velocity magnitude and temperature


Module'7')'Lecture'22' 73'
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

•  In the directory $PTOFC/mycases1/elbow2d_1/, you will find various


setup for the same geometry. For instance you could use the solver
my_icoFoam with the parabolic inlet boundary condition we previously
created (elbow_parabolic_inlet_plus_temperature).

•  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:

•  The applications implementations are located in $WM_PROJECT_DIR/


applications

•  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

At this point you should be able


to modify OpenFOAM® solvers
and utilities, and create your own
applications and boundary
conditions.

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

1.  A crash introduction to turbulence modeling


in OpenFOAM®
2.  Hands-on session

Module'8')'Lecture'23' 2'
Today’s lecture

1.  A crash introduction to turbulence modeling


in OpenFOAM®
2.  Hands-on session

Module'8')'Lecture'23' 3'
A crash introduction to turbulence modeling in OpenFOAM®

•  The majority of natural and engineering


flows are turbulent, hence the
necessity of modeling turbulence.

Module'8')'Lecture'23' 4'
A crash introduction to turbulence modeling in OpenFOAM®

Before continuing, I want to share a


few amazing images that show the
beauty and complexity of turbulence
in nature and engineering

Module'8')'Lecture'23' 5'
A crash introduction to turbulence modeling in OpenFOAM®

Buoyant plume of smoke rising from a stick of incense


Photo credit: https://www.flickr.com/photos/jlhopgood/ Module'8')'Lecture'23' 6'
This work is licensed under a Creative Commons License (CC BY-NC-ND 2.0)
A crash introduction to turbulence modeling in OpenFOAM®

Buoyant plume of smoke rising from a stick of incense


Photo credit: M. Rosic Module'8')'Lecture'23' 7'
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®

Tugboat riding on the turbulent wake of a ship


Photo credit: https://www.flickr.com/photos/oneeighteen/ Module'8')'Lecture'23' 8'
This work is licensed under a Creative Commons License (CC BY-NC 2.0)
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®

Spring votex in turbulent waters


Photo credit: https://www.flickr.com/photos/kenii/ Module'8')'Lecture'23' 10'
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®

Wake turbulence behind individual wind turbines


Photo credit: NREL's wind energy research group. Module'8')'Lecture'23' 11'
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 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®

Vortices on a 1/48-scale model of an F/A-18 aircraft inside a Water Tunnel


Photo credit: NASA Dryden Flow Visualization Facility. http://www.nasa.gov/centers/armstrong/multimedia/imagegallery/FVF
Module'8')'Lecture'23' 15'
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®

Wind Tunnel Test of New Tennis Ball


Photo credit: NASA http://tennisclub.gsfc.nasa.gov/tennis.windtunnelballs.html
Module'8')'Lecture'23' 16'
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®

Bullet at Mach 1.5


Photo credit: Andrew Davidhazy. Rochester Institute of Technology.
Module'8')'Lecture'23' 17'
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®

Flow visualization over a spinning spheroid


Photo credit: Y. Kohama. Module'8')'Lecture'23' 18'
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®

Flow around an airfoil with a leading-edge slat


Photo credit: S. Makiya et al. Module'8')'Lecture'23' 19'
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®

•  Modeling turbulence is not an easy task.

•  There is no universal turbulence model, hence you need to


know the capabilities and limitations of the turbulence models.

•  Turbulence can be wall bounded or free shear. Depending of


what you want to simulate, you will need to choose an
appropriate turbulence model and simulation techniques.

•  Simulating turbulent flows in OpenFOAM® (or any general CFD


solver) requires selecting a turbulence model, providing initial
conditions and boundary conditions for the closure equations of
the turbulent model, and selecting a near-wall modeling.

•  You also need to choose the discretization scheme of the


turbulent equations. Module'8')'Lecture'23' 20'
A crash introduction to turbulence modeling in OpenFOAM®

“Essentially, all models are wrong,


but some are useful”

G.E.P Box

•  Equations cannot be derived from fundamental principles.


•  All turbulence models contain some sort of empiricism.
•  Some calibration to observed physical solutions is contained in
the' turbulence models.
'
•  Also, some intelligent guessing is used.
•  A lot of uncertainty is involved
Module'8')'Lecture'23'
! 21'
A crash introduction to turbulence modeling in OpenFOAM®

Turbulence near the wall - Law of the wall


1
u+ = ln y + + C +

20

18
16
14
12
+
U 10
8 u+ = y +
6
4

0
-1 0 1 2 3
10 10 10 10 10

+
Y

Viscous sublayer Buffer Log-law layer


Layer

Module'8')'Lecture'23'
Inner region Outer region 22'
A crash introduction to turbulence modeling in OpenFOAM®

Energy spectrum for a turbulent flow – log-log scales

Modeled in RANS
E()
Computed in DNS

Computed in LES Modeled in LES

GS scales SGS scales

E() ⇠ ✏2/3  5/3

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®

Turbulence near the wall

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®

Turbulence near the wall

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®

Turbulence near the wall

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®

Overview of turbulence modeling approaches

RANS

Increasing computational costs


URANS

Increasing complexity
SAS

DES

LES

DNS
Module'8')'Lecture'23' 27'
A crash introduction to turbulence modeling in OpenFOAM®

Overview of turbulence modeling approaches

RANS LES

RANS/URANS DES/LES DNS


•  Solves the time-averaged NSE. •  Solves the filtered unsteady NSE. •  Solves the unsteady laminar NSE.
•  All turbulent spatial scales are •  SGS scales are modeled, GS are •  Solves all spatial and temporal
modeled. resolved. scales; hence, requires extremely
fine meshes and small time-steps.
•  Many models are available. One •  Resolves the temporal scales, hence
equation models, two equation requires small time-steps. •  No modeling is required.
models, Reynolds stress models,
•  For most industrial applications, it is •  It is extremely computational
transition models, and so on.
computational expensive. However, expensive.
•  This is the most widely approach for thanks to the current advances in
•  Not practical for industrial flows.
industrial flows. parallel and scientific computing it is
becoming affordable. •  It is intrinsically 3D and asymmetric.
•  Unsteady RANS (URANS), use the
same equations as the RANS but •  Many models are available.
with the transient term retained.
•  It is intrinsically 3D and asymmetric.
Module'8')'Lecture'23' 28'
•  It can be used in 2D and 3D cases.
A crash introduction to turbulence modeling in OpenFOAM®

RANS/URANS Turbulence models available in OpenFOAM®


•  LRR
•  LamBremhorstKE
•  LaunderGibsonRSTM
•  LaunderSharmaKE
•  LienCubicKE
•  LienCubicKELowRe
•  LienLeschzinerLowRe
•  NonlinearKEShih
•  RNGkEpsilon
•  SpalartAllmaras
•  kEpsilon
•  kOmega
•  kOmegaSST
•  kkLOmega
•  laminar
•  qZeta
•  realizableKE
•  v2f
Module'8')'Lecture'23' 29'
A crash introduction to turbulence modeling in OpenFOAM®

DES/LES Turbulence models available in OpenFOAM®

•  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®

Short description of some of the turbulence models available in


OpenFOAM®

Model Short description

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®

Turbulence models available in OpenFOAM®

•  As you can see, there is a cornucopia, plethora, fullness, abundance of turbulence


models implemented in OpenFOAM®, from RANS to LES.
•  You can also implement yours!
•  You can find the turbulence models in the following directories:
•  $FOAM_SRC/turbulenceModels
•  $FOAM_SRC/TurbulenceModels
•  The wall functions are in the following directories:
•  $FOAM_SRC/turbulenceModels/compressible/RAS/derivedFvPatchFields/
wallFunctions

•  $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®

Turbulence models available 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®

Turbulence models available 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

and take a look at the source code.

Module'8')'Lecture'23' 34'
A crash introduction to turbulence modeling in OpenFOAM®

Turbulence models available in OpenFOAM®

•  If you open the file $FOAM_SRC/turbulenceModels/incompressible/RAS/


kOmegaSST/kOmegaSST.H, in the header you fill find the references used to
implement the model in OpenFOAM®, namely:

Menter, F., Esch, T., “Elements of Industrial Heat Transfer Prediction”,


16th Brazilian Congress of Mechanical Engineering (COBEM), Nov. 2001.
Hellsten, A. “Some Improvements in Menter’s k-omega-SST turbulence
model”, 29th AIAA Fluid Dynamics Conference, AIAA-98-2554, June 1998.

•  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®

Near-wall treatment and wall functions

Module'8')'Lecture'23' 36'
A crash introduction to turbulence modeling in OpenFOAM®

Near-wall treatment and wall functions


Outer region Outer region
Boundary layer

Boundary layer
Log-law layer Log-law layer
30 < y+ < 300 30 < y+ < 300

Buffer layer Buffer layer


10 < y+ < 30 10 < y+ < 30
Viscous sublayer Viscous sublayer
Wall Function
y+ < 10 y+ < 10

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®

Near-wall treatment and wall functions

•  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®

Near-wall treatment and wall functions

•  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®

 ! Turbulence model overview

Module'8')'Lecture'23' 40'
A crash introduction to turbulence modeling in OpenFOAM®

 ! Turbulence model overview

•  It is called  ! because it solves two additional equations for modeling the


turbulence, namely, the turbulent kinetic energy  and the specific kinetic
energy !.

@ ⇤ ⇤
⇢ + ⇢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®

 ! Turbulence model overview

•  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

•  The Reynolds stress tensor is derived from the Boussinesq Approximation.

Module'8')'Lecture'23' 42'
A crash introduction to turbulence modeling in OpenFOAM®

Incompressible RANS equations

•  The following equations are the incompressible Reynolds-Averaged Navier-Stokes


equations (RANS). These are the equations we want to solve.

r · (ū) = 0,

@ ū rp̄ 1
+ r · (ūū) = + ⌫r2 ū r · ⌧ R.
@t ⇢ ⇢

where ⌧R is the Reynolds stress tensor and is given by,

2 h i 2
R R T
⌧ = ⇢ u0 u0 = 2µT D̄ ⇢I = µT ru + (ru) ⇢I,
3 3

•  To arrive to these equations, we used Reynolds averaging.


Module'8')'Lecture'23' 43'
A crash introduction to turbulence modeling in OpenFOAM®

 ! Turbulence model free-stream boundary conditions

Module'8')'Lecture'23' 44'
A crash introduction to turbulence modeling in OpenFOAM®

 ! Turbulence model free-stream boundary conditions

•  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®

 ! Turbulence model free-stream boundary conditions

•  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.

Low Medium High

I 1.0 % 5.0 % 10.0 %

µt /µ 1 10 100

•  By the way, use these guidelines for external aerodynamics only.


Module'8')'Lecture'23' 46'
A crash introduction to turbulence modeling in OpenFOAM®

 ! Turbulence model wall functions

Module'8')'Lecture'23' 47'
A crash introduction to turbulence modeling in OpenFOAM®

 ! Turbulence model wall functions

•  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®

 ! Turbulence model wall functions


+
•  If you are planning to use wall functions ( 30  y  300 ),
the following values are good choices.
•  For  you should use the wall function kqRWallFunction with the following value:

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®

 ! Turbulence model wall functions


+
•  If you are planning to use scalable wall functions ( 1  y  300 ),
the following values are good choices.
•  For  you should use the wall function kqRWallFunction with the following value:

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®

 ! Turbulence model wall functions


+
•  If you are planning not to use wall functions ( y  6 ),
the following values are good choices.
•  For  you should use fixedValue with the following value:

wall = 1e 10
•  For ! you should use fixedValue with the following value:
!wall = 1e 10

•  To avoid potential erroneous arithmetic operations, I like to use a small value


instead of 0.

Module'8')'Lecture'23' 51'
A crash introduction to turbulence modeling in OpenFOAM®

Setting nut boundary conditions for the


 ! Turbulence model

Module'8')'Lecture'23' 52'
A crash introduction to turbulence modeling in OpenFOAM®

Setting nut boundary conditions for the  ! Turbulence model

•  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®

Setting nut boundary conditions for the  ! Turbulence model

•  As we are using the  ! turbulence model and we are interested in using


continuous wall functions, we use the following wall function:
•  nutUSpaldingWallFunction
•  nutUSpaldingWallFunction is a generic wall function that uses U instead of k. It
can be used with all low-Re and high-Re turbulence models.
•  A low-Re turbulence model solves the boundary layer ( y +  6 ).
•  A high-Re turbulence model uses wall functions ( 30  y +  300 ).
•  Other nut wall function options are:
•  nutkRoughWallFunction (high-Re)
•  nutkWallFunction (high-Re)
•  nutLowReWallFunction (low-Re)
•  nutUWallFunction (high-Re)
Module'8')'Lecture'23' 54'
A crash introduction to turbulence modeling in OpenFOAM®

y + wall distance units

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

•  Where y is the distance to the first cell


Viscous sublayer
y+ < 10

center normal to the wall, and U⌧ is Wall

the friction velocity and is equal to

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®

Estimating normal wall distance


•  To estimate the distance from the wall to the first cell center y you can proceed as
follows,

⇢⇥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®

Turbulence modeling guidelines and tips

Module'8')'Lecture'23' 59'
A crash introduction to turbulence modeling in OpenFOAM®

Turbulence modeling guidelines and tips


•  Compute Reynolds number and determine whether the flow is turbulent.

•  Estimate y before generating the mesh.

•  Run the simulation for a few time steps and get a better prediction of y + and
correct your initial prediction of y .

•  The realizable  ✏ or SST  ! models are good choices for general


applications.

•  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®

Turbulence modeling guidelines and tips


•  The utility refineWallLayer, can be used to refine the cells next to patches. This
can save you a lot time, as you do not have to go back to the meshing stage.

•  Be aware of the limitations of the turbulence model chosen, find and read the original
references used to implement the model in OpenFOAM®.

•  Use the utilities yPlusRAS or yPlusLES to check the y + value.


•  Use the default model constants unless you know what are you doing or you are
confident that you have better values.

•  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

Cut plane with instantaneous velocity magnitude. Walls colored by


Module'8')'Lecture'23' 64'
instantaneous pressure.
A crash introduction to turbulence modeling in OpenFOAM®

LES simulation

Instantaneous velocity magnitude. Instantaneous vorticity magnitude.

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

Energy spectrum and -5/3 slope.


Module'8')'Lecture'23' 67'
A crash introduction to turbulence modeling in OpenFOAM®

LES simulation Vs. RANS simulation

LES RANS LES RANS

•  LES simulations are colored by instantaneous values.


•  RANS simulations are colored by mean values.
Module'8')'Lecture'23' 68'
A crash introduction to turbulence modeling in OpenFOAM®

LES simulation Vs. RANS simulation

Module'8')'Lecture'23' 69'
LES (instantaneous velocity) RANS
A crash introduction to turbulence modeling in OpenFOAM®

LES simulation Vs. RANS simulation

LES (instantaneous velocity)


Module'8')'Lecture'23' RANS 70'
A crash introduction to turbulence modeling in OpenFOAM®

LES simulation Vs. RANS simulation

LES (Mean velocity) Module'8')'Lecture'23' RANS 71'


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

Iso surfaces of Q criteron.

Module'8')'Lecture'23' 74'
Iso-surfaces of Q criterion.
A crash introduction to turbulence modeling in OpenFOAM®

References

•  Turbulent Flows
Stephen B. Pope

•  Turbulence: An Introduction for Scientists and Engineers


P. A. Davidson

•  Large Eddy Simulation for Incompressible Flows


Pierre Sagaut

•  Turbulence Modeling for CFD


David C. Wilcox

Module'8')'Lecture'23' 75'
Module 8

Module'8')'Lecture'24' 1'
Today’s lecture

1.  A crash introduction to multiphase flows


modeling in OpenFOAM®
2.  Hands-on session

Module'8')'Lecture'24' 2'
Introduction to multiphase flows

What is multiphase flow?


•  A multiphase flow is a fluid flow consisting of more than one phase
component and have some level of phase separation above molecular level.
•  Multiphase flows exist in many different forms. Two phase flows can be
classified according to the state of the different phases:
•  Gas-Liquid mixture.
•  Gas-Solid mixture.
•  Liquid-Solid mixture.
•  Immiscible liquid-liquid.

Module'8')'Lecture'24' 3'
Introduction to multiphase flows

Multiphase vs. Multispecies


•  Multiphase flows have some level of phase separation at a scale well above
molecular level.
•  Multispecies flows has a mixing on the molecular level, there is no interphase
that indicates a separation at macroscopic level.

Water + oil = multiphase Water + tea = multispecies


Clear and distinct interface Molecular mixing, no interface
Module'8')'Lecture'24' 4'
Introduction to multiphase flows

Multiphase flows in industry and nature based on


the state of the different phases
•  Multiphase flows are very common in industry and in nature, the following
are a few examples depending on the state of the different phase.

•  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

Multiphase flows in industry and nature based on


the state of the different phases
•  Gas–liquid flows:
•  Natural: ocean waves.
•  Biological: blood flow, eyes, lungs.
•  Industrial: boiling water and pressurized water nuclear reactors,
chemical reactor, desalination systems, sewage treatment plants,
boilers, heat exchangers, internal combustion engines, liquid propellant
rockets, fire sprinkler suppression systems.

•  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

•  As you can see, multiphase flows are


present in many industrial processes and
natural systems.
•  Hence the importance in understanding,
modeling, and simulating multiphase
flows.

Module'8')'Lecture'24' 7'
Introduction to multiphase flows

Classifying multiphase flow: phase morphology


•  Disperse phase: the phase is dispersed as non-contiguous isolated regions
within the other phase (the continuous phase) .
•  Continuous phase: the phase is contiguous throughout the domain and there
is one well defined interphase with the other phase.
•  When we work with a disperse phase we say that the system is dispersed:
disperse-continuous flow.
•  When we work with continuous phases we say that the system is separated:
continuous-continuous flow.

Dispersed system' Separated system'


Module'8')'Lecture'24' 8'
Introduction to multiphase flows

Overview/remarks on modeling approaches


•  Simulating multiphase flows is not an easy task.
•  The complex nature of multiphase flows is due to:
•  The transient nature of the flows.
•  The existence of dynamically changing interfaces.
•  Significant discontinuities (fluid properties and fluid separation).
•  Complicated flow field near the interface.
•  Interaction of small scale structures.
•  Particle-particle interactions.
•  Mass transfer.

Module'8')'Lecture'24' 9'
Introduction to multiphase flows

Overview/remarks on modeling approaches


Free surface
(system scale)

•  Multiphase flows are inherently multi-scale


in nature.
•  It is necessary to account for the cascade
effect of the various flow physics at
different scales: Large bubbles
(system scale)

•  Large flow structures within the fluid Medium bubbles


flow (system-scale). (system-scales)

•  Local structural changes due to


coalescence and breakage processes
(meso-scales). Small bubbles interaction
(meso-scales)
•  Motion and interaction of discrete
constituents or small particles (micro-
scale).
Bubble break-up
And coalescence
(meso-scales) Small sized particles
Module'8')'Lecture'24' 10'
(micro-scales)
Introduction to multiphase flows

How to treat the wide range of behaviors in


multiphase flows
Increase!
•  Fully resolved: solves complete
physics. All spatial and temporal scales

More modeling required!


are resolved.

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

How to treat the wide range of behaviors in


multiphase flows

Separated system Dispersed system

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

How to treat the wide range of behaviors in


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

How to treat the wide range of behaviors in


multiphase flows

•  Bubbles, droplets and/or particles •  Bubbles, droplets and/or particles


bigger than grid scales (GS). smaller than grid scales (sub-grid
•  Can be resolved using VOF. scales or SGS).
•  We need to use models to resolved
Module'8')'Lecture'24' 14'
SGS.
Introduction to multiphase flows

How to treat the wide range of behaviors in


multiphase flows

Average phase
properties

VOF ≈ 0.5

Dispersed phase in a continuous phase


Module'8')'Lecture'24' 15'
VOF is not able to handle bubbles smaller than grid scales
Introduction to multiphase flows

How to treat the wide range of behaviors in


multiphase flows

Module'8')'Lecture'24' 16'
Bubble coalescence, bubble break-up and wake entrainment in dispersed systems
Introduction to multiphase flows

How to treat the wide range of behaviors in


multiphase flows

•  Eulerian-Lagragian approach:

•  The particles can be smaller or larger than the grid size.


•  Can have couple or uncoupled hydrodynamics.
•  The particle position is tracked at all times.
•  Can account for particle interaction and mass transfer.
Module'8')'Lecture'24' 17'
•  The particles can interact with the boundaries: escape, bounce, stick, wall film.
Introduction to multiphase flows

How to treat the wide range of behaviors in


multiphase flows
Dense regime: particles motion is controlled
primarily by particle-particle collisions.

Dilute regime: particle motion is controlled by


the drag and lift forces on the particle
(particles follow the fluid flow).

volume of the phase in a cell/domain


volume fraction of a phase =
volume of the cell/domain

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

Volume-of-Fluid (VOF) governing equations


for separated systems

Module'8')'Lecture'24' 19'
Introduction to multiphase flows
Volume-of-Fluid (VOF) governing equations for separated systems

•  The incompressible, isothermal governing equations can be written as


follows,

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

•  Phase transport equation and interface tracking with surface compression,

@
+ 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

•  Phase transport equation and interface tracking with surface compression,

@
+ r · U + r · (Ur (1 )) = 0
@t

Ur = min(c |U|, max(|U|)) · n

•  Coefficient to control the magnitude of the compression (cAlpha).


•  Usually 0 < cAlpha < 2.
•  Recommended value 1.'

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 |

•  k represents the local curvature, based on local gradients.


Module'8')'Lecture'24' 23'
•  The CSF model neglects the effects of a variable surface tension coefficient.
Introduction to multiphase flows

Eulerian-Eulerian governing equations for


dispersed systems

Module'8')'Lecture'24' 24'
Introduction to multiphase flows
Eulerian-Eulerian governing equations for dispersed systems

•  The Eulerian-Eulerian approach solves the governing equations for each


phase, it treats the phases as interpenetrating continua.
•  The incompressible, isothermal governing equations can be written as
follows,
Interface forces or Surface tension
momentum transfer
@↵k ⇢k
+ r · (↵k ⇢k Uk ) = 0
@t

@(↵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

•  The incompressible, isothermal governing equations with interface tracking


can be written as follows,
Interface forces or Surface tension
momentum transfer
@↵k ⇢k
+ r · (↵k ⇢k Uk ) = 0
@t

@(↵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

•  Closure relations for the interface forces (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®

•  In OpenFOAM®, there are many interfacial momentum


transfer models implemented.
•  I want to remind you that there is no universal model, it is
up to you to choose the model that best fit the problem you
are solving.
•  You need to know the applicability and limitations of each
model, for this refer to the literature.
•  Remember, you have the source code so feel free to
explore it.

Module'8')'Lecture'24' 29'
Introduction to multiphase flows

Eulerian-Eulerian governing equations for


dispersed systems of gas-solid or
liquid-solid (Eulerian-Granular KTGF)

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)

•  The Eulerian-Granular KTGF (kinetic theory of granular flow), is based on the


kinetic theory of granular flow (analogous to kinetic theory of gases).
•  In the E-G KTGF the liquid phase is solved as in the Eulerian-Eulerian
method and the solid phase is solved using appropriate closure relations.
•  The incompressible, isothermal governing equations can be written as
follows,

@↵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)

•  With the following closure relations



3 @↵s ⇢s ⇥s
+ r · (↵s ⇢s ⇥s Us ) = ( rps I + ⌧s ) : rUs + r · (ks r⇥s ) s + Js
2 @t

•  Granular temperature
1 Particle fluctuating velocity
⇥s = U2f s
3

•  Solid stress tensor


1 2
⌧s = ps I + 2↵s µs (rUs + rUTs ) + ↵s ( s µs )r · Us I
2 3

•  Equation of state for the dispersed phase


ps = ⇢s ↵s ⇥s + 2⇢s ↵s2 g0 ⇥s (1 + esModule'8')'Lecture'24'
) 32'
Introduction to multiphase flows
Eulerian-Eulerian governing equations for dispersed systems of
gas-solid or liquid-solid (Eulerian-Granular KTGF)

•  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

 Conductivity of granular energy

es Coefficient of restitution of colliding particles

s Dissipation of granular energy


Js Exchange of fluctuating energy between the phases
Mk Momentum transfer models (usually only drag for gas-solid)
For a complete derivation of the governing equation and closure relations, refer to:
Derivation, Implementation, and Validation of Computer Simulation Module'8')'Lecture'24'
Models for Gas-Solid Fluidized Bed 33'
B. van Wachem. PhD Thesis. 2000, TUDelft.
Introduction to multiphase flows
Closure relations for Eulerian-Granular KTGF in OpenFOAM®

•  In OpenFOAM®, there are many closure relations for


Eulerian-Granular kinetic theory of granular flows.
•  I want to remind you that there is no universal model, it is
up to you to choose the model that best fit the problem you
are solving.
•  You need to know the applicability and limitations of each
model, for this refer to the literature.
•  Remember, you have the source code so feel free to
explore it.

Module'8')'Lecture'24' 34'
Introduction to multiphase flows

Eulerian-Lagrangian governing equations

Module'8')'Lecture'24' 35'
Introduction to multiphase flows
Eulerian-Lagrangian governing equations

•  In the Eulerian-Lagrangian framework, the continuous phase is solved in an


Eulerian reference system and the particles or dispersed phase is solved in a
Lagrangian reference system.
•  The governing equations can be written as follows

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

•  In this formulation the secondary phase is treat as discrete particles


dispersed in the continuous fluid.
•  The particles can be smaller or larger than the grid size.
•  The particles can be transported passively.
•  Or they can be coupled with the fluid governing equations. That is, the
particles can modify the fluid field.
•  This formulation accounts for particle interaction and mass transfer.
•  The particles can interact with the boundaries and have a fate. They can
escape, bounce, stick, or form a wall film.
•  If you want, you can add angular momentum to the formulation.
•  Depending on the number or particles tracked, this type of approach can be
computational expensive.
Module'8')'Lecture'24' 37'
Introduction to multiphase flows
Eulerian-Lagrangian governing equations

•  There are two approaches to model Eulerian-Lagrangian systems with


hydrodynamic coupling in OpenFOAM®

•  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.

•  The MPPIC or Multiphase Particle-in-Cell method** for collisional exchange.


In this approach, particle-particle interactions are represented by models
which utilize mean values calculated on the Eulerian mesh.

•  The MPPIC is suitable for dense to dilute regimes.

*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®

•  In OpenFOAM®, there are many models for Eulerian-


Lagrangian methods.
•  I want to remind you that there is no universal model, it is
up to you to choose the model that best fit the problem you
are solving.
•  You need to know the applicability and limitations of each
model, for this refer to the literature.
•  Remember, you have the source code so feel free to
explore it.

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!

Particles interaction' VOF air and U air'

Module'8')'Lecture'24' 45'
Introduction to multiphase flows
MRF vs. Sliding grids – VOF

interFoam with MRF interFoam with dynamic meshes

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

Why multiphase flow simulations are not easy?


Reactor design

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

Some useful bibliographical references


•  Computational Techniques for Multiphase Flows
G. H. Yeoh, J. Tu. 2009, Butterworth-Heinemann
•  Multiphase Flow Analysis Using Population Balance Modeling:
Bubbles, Drops and Particles
G. H. Yeoh, C. P Cheung, J. Tu. 2013, Butterworth-Heinemann
•  Turbulence Modeling for CFD
D. Wilcox. 2006, DCW Industries.
•  Error analysis and estimation in the Finite Volume method with
applications to fluid flows.
H. Jasak. PhD Thesis. 1996. Imperial College, London.

Module'8')'Lecture'24' 53'
Introduction to multiphase flows

Some useful bibliographical references


•  Computational fluid dynamics of dispersed two-phase flows at high
phase fractions
H. Rusche. PhD Thesis. 2002. Imperial College, London.
•  Towards the numerical simulation of multi-scale two-phase flows
H. Marschall. PhD Thesis. 2011. Technische Universität München.
•  Derivation, Implementation, and Validation of Computer Simulation
Models for Gas-Solid Fluidized Bed
B. van Wachem. PhD Thesis. 2000, TUDelft.
•  Gas-Particle flow in a vertical pipe with particle-particle intractions
J. L. Sinclair, R. Jackson AIChE Journal. Volume 35, Issue 9, 1473-1486,
September 1989

Module'8')'Lecture'24' 54'
Module 9

Module'9')'Lecture'25' 1'
Today’s lecture

1.  Tips and tricks in OpenFOAM®

Module'9')'Lecture'25' 2'
Tips and tricks in OpenFOAM®

Where and how should we


put more salt

Module'9')'Lecture'25' 3'
Tips and tricks in OpenFOAM®

… and as this is kind of a cooking recipe, it comes with a


small warning

Module'9')'Lecture'25' 4'
Tips and tricks in OpenFOAM®
•  What I am about to show you is based on my personal experience.

•  To draw these kind of conclusions or observations, I conducted hundreds of


numerical experiments, under different conditions, with different meshes
(from good quality meshes to bad quality meshes with different element
types), and different physics and models involved.

•  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.

•  At this point, I highly advise you to conduct similar numerical experiments


and draw your own conclusions.

•  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

•  When it comes to geometry generation, the only rule


you should keep in mind is that by the end of the day
MESH GENERATION
you should get a unique clean and watertight
geometry.
•  Geometry defeaturing can made your life easier. Do
CASE SETUP AND SOLUTION
not fool yourself, if you have no constraints avoid
sharp angles.
•  And as for the mesh concerns, try to keep the
POST-PROCESSING
skewness, orthogonality, aspect ratio, and growth rate
low.
•  No need to say that if you have a bad geometry, is
likely probable that your mesh will be bad as well.
Module'9')'Lecture'25' 6'1
•  Always remember: good mesh – good results.
Tips and tricks in OpenFOAM®
OpenFOAM® shell environment
•  You can have as many versions of OpenFOAM® as you like living together. You just
need to source the right environment variables. For instance, on my workstation I
have nine versions living together. This is how my .bashrc file looks like,

### OPENFOAM ###

# 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

### OPENFOAM ###

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,

Old .bashrc New .bashrc


### OPENFOAM ### ### OPENFOAM ###

# source $HOME/OpenFOAM/OpenFOAM-1.6-ext/etc/bashrc # source $HOME/OpenFOAM/OpenFOAM-1.6-ext/etc/bashrc


# source $HOME/OpenFOAM/OpenFOAM-1.6-ext.GPU/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-1.7.1/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-2.0.x/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.1.1/etc/bashrc
source $HOME/OpenFOAM/OpenFOAM-2.2.0/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.2.x/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-2.3.0-debug/etc/bashrc # source $HOME/OpenFOAM/OpenFOAM-2.3.0-debug/etc/bashrc
# source $HOME/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc source $HOME/OpenFOAM/OpenFOAM-2.3.x/etc/bashrc

### OPENFOAM ### ### OPENFOAM ###

•  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.

•  In the directory $WM_PROJECT_DIR/etc/config, you will also find many useful


scripts. For instance, you can take a look at the script aliases.sh, in this script you
will find all the aliases defined in OpenFOAM®
Module'9')'Lecture'25' 9'
Tips and tricks in OpenFOAM®
Looking for information in OpenFOAM® source code
•  To locate files you can use the find command. For instance, if you want to locate a
file that contains the string fvPatch in its name you can proceed as follows,

•  find $FOAM_SOLVERS -name “*fvPatch*”


This command will locate the files containing the string “*fvPatch*” in the
directory $FOAM_SOLVERS

•  If you want to find a string inside a file, you can use the command grep

•  grep -r -n LES $FOAM_SOLVERS


This command will look for the string LES in all files inside the directory
$FOAM_SOLVERS. The option -r means recursive and -n will output the line
number.
Module'9')'Lecture'25' 10'
Tips and tricks in OpenFOAM®
Looking for information in OpenFOAM® source code
•  As you might already know, there are a gazillion dictionaries in OpenFOAM®. The
easiest way to find all of them is to do a local search in the installation directory as
follows,

•  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:

•  find $FOAM_TUTORIALS -name "*Dict”

•  find $FOAM_TUTORIALS -iname ”*dict”

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 which tutorial files use the boundary condition "slip":

•  find $FOAM_TUTORIALS -type f | xargs grep -sl 'slip’

•  To find where the source code for the boundary condition "slip" is located:

•  find $FOAM_SRC -name "*slip*”

•  To find what applications do not run in parallel

•  $WM_PROJECT_DIR -type f | xargs grep -sl ’noParallel’

•  Remember, OpenFOAM® understand REGEX syntax.


Module'9')'Lecture'25' 12'
Tips and tricks in OpenFOAM®
OpenFOAM® Doxygen documentation
•  The best source of information is the source code and the Doxygen documentation.

•  The $WM_PROJECT_DIR/doc directory contains the Doxygen documentation of


OpenFOAM®.

•  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

•  After compiling the Doxygen documentation you can use it by typing:


•  firefox file://$WM_PROJECT_DIR/doc/Doxygen/html/index.html

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.

•  Do not get overwhelm when running in a cluster. Running OpenFOAM® in a cluster


is not different from running in your workstation or portable computer. The only
difference is that you need to schedule your jobs.

•  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.

•  Consequently, remember to always double or triple check your scripts. It will be a


waste of time if after two days in queue, your simulation did not start because there
were errors in your scripts.

•  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.

•  Also, the IO is really time consuming.'


Module'9')'Lecture'25' 16'
Tips and tricks in OpenFOAM®
Running in a cluster
•  By the way, I know it looks super cool, but try to avoid spaces or funny characters
when naming directories and files, specially if you run in clusters. e.g.:

•  my dictionary.dict instead use my_dictionary.dict


•  #my_file;txt instead use my_file.txt
•  my/solution!!! instead use my_solution
•  working@home instead use working_at_home
'
'

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:

•  Foam::scalar Foam::primitiveMesh::closedThreshold_ = 1.0e-6;


•  Foam::scalar Foam::primitiveMesh::aspectThreshold_ = 1000;
•  Foam::scalar Foam::primitiveMesh::nonOrthThreshold_ = 70; // deg
•  Foam::scalar Foam::primitiveMesh::skewThreshold_ = 4;
•  Foam::scalar Foam::primitiveMesh::planarCosAngle_ = 1.0e-6;

•  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)

•  Summarizing, before running a simulation remember to always check the mesh


quality using checkMesh and then reduce the mesh bandwidth by using the
renumberMesh. This is a good standard practice, I always do it (at least for big
meshes).

•  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.

•  Get a good quality mesh at the boundaries.

•  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.

•  When it is possible, use potentialFoam to get an initial solution. It is computational


inexpensive.

•  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.

•  By the way, do not forget to use a good quality coarse mesh.

•  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).

•  I want to remind you again, initial conditions should be physically realistic.

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.

•  This means, start robustly and end with accuracy.

•  By the way, an accurate numerical scheme needs a good quality mesh.

•  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,

cellMDLimited Less diffusive


cellLimited
faceMDLimited
faceLimited More diffusive

•  The following entry corresponds to the leastSquares method using gradient


limiters
cellMDLimited leastSquares 1.0;
Module'9')'Lecture'25' 41'
Tips and tricks in OpenFOAM®
Discretization schemes – Gradient terms
•  Gradient limiters avoid over and under shoots on the gradient computations.
•  The gradient limiter implementation in OpenFOAM®, uses a blending factor .

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.

•  Non-orthogonality between 70 and 80:


nNonOrthogonalCorrectors 3;

•  Non-orthogonality between 50 and 70:


nNonOrthogonalCorrectors 2;

•  Non-orthogonality less than 50:


nNonOrthogonalCorrectors 1;

•  I always like to do at least one correction.


Module'9')'Lecture'25' 49'
Tips and tricks in OpenFOAM®
Under-relaxation factors
•  Because of the non-linearity of the equations being solved, it is necessary to control
the change of . This is achieved by under-relaxation as follows,

n n 1 n n 1
P = P + ↵( P P )
here ↵ is the relaxation factor,
Means under-relaxation. This will slow down the convergence
<1 rate but increases the stability.
↵=1 Means no relaxation at all. We simple use the predicted value of .

Means over-relaxation. It can sometimes be used to accelerate


>1 convergence rate but will decrease the stability.

•  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.

•  In general, under-relaxation factors are there to suppress oscillations.

•  Small under-relaxation factors will significantly slow down convergence. Sometimes


to the extent that the user thinks the solution is converged when it really is not.

•  The recommendation is to always use under-relaxation factors that are as high as


possible, without resulting in oscillations or divergence.

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 solvers can be modified on the fly.

•  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.

•  As I am often interested in the unsteadiness of the solution, I usually use a CFL


number not larger than 1.0.

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.

•  Remember, setting the keyword nOuterCorrectors equal to 1 in the PIMPLE


solver is equivalent to use the PISO solver.

•  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.

•  My recommendation is to always monitor your solution, and preferably use the


PIMPLE solver.

•  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.

•  Euler is a first order implicit scheme (bounded).

•  Backward is a second order implicit scheme (unbounded). Similar to the linear


multistep Adams-Moulton scheme.

•  Crank-Nicolson is a second order implicit scheme (bounded).

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.

•  The Crank-Nicolson as it is implemented in OpenFOAM®, uses a blending factor .


FYI, you can change the blending on the fly.

•  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.

•  In order to properly assess convergence, it is also recommended to monitor a


physical quantity. If this physical quantity does not change in time you may say that
the solution is converge.

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.

•  Or in a positive way, good mesh – good results.

•  Use hexahedral meshes whenever is possible, specially if high accuracy in predicting


forces is your goal (e.g., drag prediction).

•  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.

•  If the geometry is slightly complicated, it is just a waste to spend time on hex


meshing. Your results will not be better, most of time, if not always. With todays
advances in HPC and numerical methods, the computing time saved with hex mesh
is marginal compared with time wasted in mesh generation.

•  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.

•  In my personal experience, polyhedral meshes inhered the same quality problems of


the starting tetrahedral mesh, sometimes they made things worst.

•  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:

•  A good mesh is a mesh that serves your project objectives.

•  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

Who owns the mesh, owns the solution

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.

•  Remember, functionObject can be temporarily disabled by launching the solver


(or utility) with the option –noFunctionObjects.
Module'9')'Lecture'25' 91'
Tips and tricks in OpenFOAM®
On the incompressible solvers
•  I am going to be really loud on this.

•  For those using the incompressible solvers (icoFoam, simpleFoam, pisoFoam,


pimpleFoam), I want to remind you that the pressure used by these solvers is the
modified pressure or

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.

•  A new version of OpenFOAM® not necessary is a guarantee of innovation, and an


old version of OpenFOAM® is no guarantee of efficiency.
Module'9')'Lecture'25' 93'
Tips and tricks in OpenFOAM®
Best tip ever (and totally free)

•  I know I sound like a broken record on this, but try to always


get a good quality mesh.

•  Use accurate and robust numerical schemes (in time and


space).

•  At this point we all know what is a good quality mesh and


what is an accurate numerical scheme, if not, please read the
theory. You do not do CFD without understanding the theory
and the physics involve.

Module'9')'Lecture'25' 16
94'
Module 10

Module'10'*'Lecture'26' 1'
Introductory OpenFOAM® Course

•  Some kind of conclusion,

•  Good mesh – good results.


•  Start robustly and end with accuracy.
•  Stability, accuracy and boundeness, play
by these terms and you will succeed.

Module'10'*'Lecture'26' 2'
Introductory OpenFOAM® Course

That was only the tip of the iceberg

Now the rest is on you


Module'10'*'Lecture'26' 3'
Introductory OpenFOAM® Course
•  Finally, we hope you have found this intensive week useful.
•  In addition, we hope to see you again in some of our advanced training
sessions:
•  Multiphase flows
•  Advanced meshing
•  Optimization
•  Turbulence Modeling
•  Advanced post-processing and scripting
•  And many more available on request
•  Besides consulting services, we also offer ’Mentoring Days' which are days
of one-on-one coaching and mentoring on your specific problem.
•  For more information, ask your trainer, or visit our website
http://www.wolfdynamics.com/
Module'10'*'Lecture'26' 4'
Introductory OpenFOAM® Course

TGIF
&
TGIO
Enjoy OpenFOAM®
el fin!
Module'10'*'Lecture'26' 5'
Thank you for your attention

Module'10'*'Lecture'26' 6'

Anda mungkin juga menyukai