OpenFOAMUserGuide A4
OpenFOAMUserGuide A4
User Guide
version 11
https://openfoam.org
U-2
Typeset in LATEX.
License
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CRE-
ATIVE COMMONS PUBLIC LICENSE (“CCPL” OR “LICENSE”). THE WORK IS PRO-
TECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE
WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW
IS PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND
AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS
LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU
THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF
SUCH TERMS AND CONDITIONS.
1. Definitions
a. “Adaptation” means a work based upon the Work, or upon the Work and other pre-
existing works, such as a translation, adaptation, derivative work, arrangement of music
or other alterations of a literary or artistic work, or phonogram or performance and
includes cinematographic adaptations or any other form in which the Work may be recast,
transformed, or adapted including in any form recognizably derived from the original,
except that a work that constitutes a Collection will not be considered an Adaptation for
the purpose of this License. For the avoidance of doubt, where the Work is a musical
work, performance or phonogram, the synchronization of the Work in timed-relation with
a moving image (“synching”) will be considered an Adaptation for the purpose of this
License.
c. “Distribute” means to make available to the public the original and copies of the Work
through sale or other transfer of ownership.
d. “Licensor” means the individual, individuals, entity or entities that offer(s) the Work
under the terms of this License.
e. “Original Author” means, in the case of a literary or artistic work, the individual, individ-
uals, entity or entities who created the Work or if no individual or entity can be identified,
OpenFOAM-11
U-3
the publisher; and in addition (i) in the case of a performance the actors, singers, mu-
sicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or
otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of
a phonogram the producer being the person or legal entity who first fixes the sounds of
a performance or other sounds; and, (iii) in the case of broadcasts, the organization that
transmits the broadcast.
f. “Work” means the literary and/or artistic work offered under the terms of this License
including without limitation any production in the literary, scientific and artistic domain,
whatever may be the mode or form of its expression including digital form, such as a
book, pamphlet and other writing; a lecture, address, sermon or other work of the same
nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in
dumb show; a musical composition with or without words; a cinematographic work to
which are assimilated works expressed by a process analogous to cinematography; a work
of drawing, painting, architecture, sculpture, engraving or lithography; a photographic
work to which are assimilated works expressed by a process analogous to photography; a
work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to
geography, topography, architecture or science; a performance; a broadcast; a phonogram;
a compilation of data to the extent it is protected as a copyrightable work; or a work
performed by a variety or circus performer to the extent it is not otherwise considered a
literary or artistic work.
g. “You” means an individual or entity exercising rights under this License who has not
previously violated the terms of this License with respect to the Work, or who has re-
ceived express permission from the Licensor to exercise rights under this License despite
a previous violation.
h. “Publicly Perform” means to perform public recitations of the Work and to communicate
to the public those public recitations, by any means or process, including by wire or
wireless means or public digital performances; to make available to the public Works in
such a way that members of the public may access these Works from a place and at a place
individually chosen by them; to perform the Work to the public by any means or process
and the communication to the public of the performances of the Work, including by public
digital performance; to broadcast and rebroadcast the Work by any means including signs,
sounds or images.
i. “Reproduce” means to make copies of the Work by any means including without limitation
by sound or visual recordings and the right of fixation and reproducing fixations of the
Work, including storage of a protected performance or phonogram in digital form or other
electronic medium.
3. License Grant.
Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide,
royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to
exercise the rights in the Work as stated below:
a. to Reproduce the Work, to incorporate the Work into one or more Collections, and to
Reproduce the Work as incorporated in the Collections;
OpenFOAM-11
U-4
b. and, to Distribute and Publicly Perform the Work including as incorporated in Collections.
The above rights may be exercised in all media and formats whether now known or hereafter
devised. The above rights include the right to make such modifications as are technically neces-
sary to exercise the rights in other media and formats, but otherwise you have no rights to make
Adaptations. Subject to 8(f), all rights not expressly granted by Licensor are hereby reserved,
including but not limited to the rights set forth in Section 4(d).
4. Restrictions.
The license granted in Section 3 above is expressly made subject to and limited by the following
restrictions:
a. You may Distribute or Publicly Perform the Work only under the terms of this License.
You must include a copy of, or the Uniform Resource Identifier (URI) for, this License
with every copy of the Work You Distribute or Publicly Perform. You may not offer or
impose any terms on the Work that restrict the terms of this License or the ability of the
recipient of the Work to exercise the rights granted to that recipient under the terms of
the License. You may not sublicense the Work. You must keep intact all notices that
refer to this License and to the disclaimer of warranties with every copy of the Work
You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work,
You may not impose any effective technological measures on the Work that restrict the
ability of a recipient of the Work from You to exercise the rights granted to that recipient
under the terms of the License. This Section 4(a) applies to the Work as incorporated
in a Collection, but this does not require the Collection apart from the Work itself to be
made subject to the terms of this License. If You create a Collection, upon notice from
any Licensor You must, to the extent practicable, remove from the Collection any credit
as required by Section 4(c), as requested.
b. You may not exercise any of the rights granted to You in Section 3 above in any manner
that is primarily intended for or directed toward commercial advantage or private mon-
etary compensation. The exchange of the Work for other copyrighted works by means
of digital file-sharing or otherwise shall not be considered to be intended for or directed
toward commercial advantage or private monetary compensation, provided there is no
payment of any monetary compensation in connection with the exchange of copyrighted
works.
c. If You Distribute, or Publicly Perform the Work or Collections, You must, unless a request
has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and
provide, reasonable to the medium or means You are utilizing: (i) the name of the Original
Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or
Licensor designate another party or parties (e.g., a sponsor institute, publishing entity,
journal) for attribution (“Attribution Parties”) in Licensor’s copyright notice, terms of
service or by other reasonable means, the name of such party or parties; (ii) the title
of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that
Licensor specifies to be associated with the Work, unless such URI does not refer to the
copyright notice or licensing information for the Work. The credit required by this Section
4(c) may be implemented in any reasonable manner; provided, however, that in the case
of a Collection, at a minimum such credit will appear, if a credit for all contributing
authors of Collection appears, then as part of these credits and in a manner at least as
prominent as the credits for the other contributing authors. For the avoidance of doubt,
You may only use the credit required by this Section for the purpose of attribution in
the manner set out above and, by exercising Your rights under this License, You may not
implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by
OpenFOAM-11
U-5
the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your
use of the Work, without the separate, express prior written permission of the Original
Author, Licensor and/or Attribution Parties.
6. Limitation on Liability.
EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL
LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCI-
DENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT
OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN AD-
VISED OF THE POSSIBILITY OF SUCH DAMAGES.
7. Termination
a. This License and the rights granted hereunder will terminate automatically upon any
breach by You of the terms of this License. Individuals or entities who have received
Collections from You under this License, however, will not have their licenses terminated
OpenFOAM-11
U-6
provided such individuals or entities remain in full compliance with those licenses. Sections
1, 2, 5, 6, 7, and 8 will survive any termination of this License.
b. Subject to the above terms and conditions, the license granted here is perpetual (for the
duration of the applicable copyright in the Work). Notwithstanding the above, Licensor
reserves the right to release the Work under different license terms or to stop distributing
the Work at any time; provided, however that any such election will not serve to withdraw
this License (or any other license that has been, or is required to be, granted under
the terms of this License), and this License will continue in full force and effect unless
terminated as stated above.
8. Miscellaneous
a. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor
offers to the recipient a license to the Work on the same terms and conditions as the
license granted to You under this License.
b. If any provision of this License is invalid or unenforceable under applicable law, it shall
not affect the validity or enforceability of the remainder of the terms of this License, and
without further action by the parties to this agreement, such provision shall be reformed
to the minimum extent necessary to make such provision valid and enforceable.
c. No term or provision of this License shall be deemed waived and no breach consented to
unless such waiver or consent shall be in writing and signed by the party to be charged
with such waiver or consent.
d. This License constitutes the entire agreement between the parties with respect to the
Work licensed here. There are no understandings, agreements or representations with
respect to the Work not specified here. Licensor shall not be bound by any additional
provisions that may appear in any communication from You.
e. This License may not be modified without the mutual written agreement of the Licensor
and You. The rights granted under, and the subject matter referenced, in this License were
drafted utilizing the terminology of the Berne Convention for the Protection of Literary
and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961,
the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of
1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights
and subject matter take effect in the relevant jurisdiction in which the License terms are
sought to be enforced according to the corresponding provisions of the implementation
of those treaty provisions in the applicable national law. If the standard suite of rights
granted under applicable copyright law includes additional rights not granted under this
License, such additional rights are deemed to be included in the License; this License is
not intended to restrict the license of any rights under applicable law.
OpenFOAM-11
U-7
Trademarks
OpenFOAM-11
U-8
OpenFOAM-11
Contents
Trademarks U-7
Contents U-9
1 Introduction U-15
2 Tutorials U-17
2.1 Backward-facing step . . . . . . . . . . . . . . . . . . . . . . . . . . . U-18
2.1.1 Pre-processing . . . . . . . . . . . . . . . . . . . . . . . . . . . U-18
2.1.2 Mesh generation . . . . . . . . . . . . . . . . . . . . . . . . . U-18
2.1.3 Viewing the mesh . . . . . . . . . . . . . . . . . . . . . . . . . U-21
2.1.4 Boundary and initial conditions . . . . . . . . . . . . . . . . . U-23
2.1.5 Physical properties . . . . . . . . . . . . . . . . . . . . . . . . U-24
2.1.6 Momentum transport . . . . . . . . . . . . . . . . . . . . . . . U-24
2.1.7 Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-26
2.1.8 Discretisation and linear-solver settings . . . . . . . . . . . . . U-28
2.1.9 Running an application . . . . . . . . . . . . . . . . . . . . . . U-28
2.1.10 Time selection in ParaView . . . . . . . . . . . . . . . . . . . . U-29
2.1.11 Colouring surfaces . . . . . . . . . . . . . . . . . . . . . . . . U-29
2.1.12 Cutting plane (slice) . . . . . . . . . . . . . . . . . . . . . . . U-30
2.1.13 Vector plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-31
2.1.14 Popular filters in ParaView . . . . . . . . . . . . . . . . . . . . U-33
2.1.15 Contours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-34
2.1.16 Streamline plots . . . . . . . . . . . . . . . . . . . . . . . . . . U-34
2.1.17 Inlet boundary condition . . . . . . . . . . . . . . . . . . . . . U-35
2.1.18 Turbulence model . . . . . . . . . . . . . . . . . . . . . . . . . U-38
2.2 Breaking of a dam . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-41
2.2.1 Mesh generation . . . . . . . . . . . . . . . . . . . . . . . . . U-42
2.2.2 Boundary conditions . . . . . . . . . . . . . . . . . . . . . . . U-43
2.2.3 Phases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-44
2.2.4 Setting initial fields . . . . . . . . . . . . . . . . . . . . . . . . U-44
2.2.5 Fluid properties . . . . . . . . . . . . . . . . . . . . . . . . . . U-46
2.2.6 Gravity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-46
2.2.7 Turbulence modelling . . . . . . . . . . . . . . . . . . . . . . . U-46
2.2.8 Time step control . . . . . . . . . . . . . . . . . . . . . . . . . U-46
2.2.9 Discretisation schemes . . . . . . . . . . . . . . . . . . . . . . U-48
2.2.10 Linear-solver control . . . . . . . . . . . . . . . . . . . . . . . U-48
2.2.11 Running the code . . . . . . . . . . . . . . . . . . . . . . . . . U-49
U-10 Contents
OpenFOAM-11
Contents U-11
OpenFOAM-11
U-12 Contents
OpenFOAM-11
Contents U-13
7 Post-processing U-177
7.1 ParaView/paraFoam graphical user interface (GUI) . . . . . . . . . . . U-177
7.1.1 Overview of ParaView/paraFoam . . . . . . . . . . . . . . . . . U-177
7.1.2 The Parameters panel . . . . . . . . . . . . . . . . . . . . . . . U-179
7.1.3 The Display panel . . . . . . . . . . . . . . . . . . . . . . . . . U-180
7.1.4 The button toolbars . . . . . . . . . . . . . . . . . . . . . . . U-181
7.1.5 Manipulating the view . . . . . . . . . . . . . . . . . . . . . . U-181
7.1.6 Contour plots . . . . . . . . . . . . . . . . . . . . . . . . . . . U-182
7.1.7 Vector plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-182
7.1.8 Streamlines . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-182
7.1.9 Image output . . . . . . . . . . . . . . . . . . . . . . . . . . . U-183
7.1.10 Animation output . . . . . . . . . . . . . . . . . . . . . . . . . U-183
7.2 Post-processing command line interface (CLI) . . . . . . . . . . . . . U-183
7.2.1 Run-time data processing . . . . . . . . . . . . . . . . . . . . U-184
7.2.2 The foamPostProcess utility . . . . . . . . . . . . . . . . . . . U-185
7.3 Post-processing functionality . . . . . . . . . . . . . . . . . . . . . . . U-186
7.3.1 Field calculation . . . . . . . . . . . . . . . . . . . . . . . . . U-187
7.3.2 Field operations . . . . . . . . . . . . . . . . . . . . . . . . . . U-188
7.3.3 Forces and force coefficients . . . . . . . . . . . . . . . . . . . U-188
7.3.4 Sampling for graph plotting . . . . . . . . . . . . . . . . . . . U-189
7.3.5 Lagrangian data . . . . . . . . . . . . . . . . . . . . . . . . . . U-189
7.3.6 Volume fields . . . . . . . . . . . . . . . . . . . . . . . . . . . U-189
7.3.7 Numerical data . . . . . . . . . . . . . . . . . . . . . . . . . . U-189
7.3.8 Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-190
7.3.9 Pressure tools . . . . . . . . . . . . . . . . . . . . . . . . . . . U-190
7.3.10 Combustion . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-190
7.3.11 Multiphase . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-190
7.3.12 Probes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-191
7.3.13 Surface fields . . . . . . . . . . . . . . . . . . . . . . . . . . . U-191
7.3.14 Meshing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-192
7.3.15 ‘Pluggable’ solvers . . . . . . . . . . . . . . . . . . . . . . . . U-192
7.3.16 Visualisation tools . . . . . . . . . . . . . . . . . . . . . . . . U-192
7.4 Sampling and monitoring data . . . . . . . . . . . . . . . . . . . . . . U-192
7.4.1 Probing data . . . . . . . . . . . . . . . . . . . . . . . . . . . U-192
7.4.2 Sampling for graphs . . . . . . . . . . . . . . . . . . . . . . . U-193
7.4.3 Sampling for visualisation . . . . . . . . . . . . . . . . . . . . U-195
OpenFOAM-11
U-14 Contents
Index U-221
OpenFOAM-11
Chapter 1
Introduction
This guide accompanies the release of version 11 of the Open Source Field Operation
and Manipulation (OpenFOAM) C++ libraries. It provides a description of the basic
operation of OpenFOAM, first through a set of tutorial exercises in chapter 2 and later
by more detailed descriptions of different components of OpenFOAM.
OpenFOAM is software for computational fluid dynamics (CFD). It includes a collec-
tion of applications which perform a range of tasks in CFD. The applications use packaged
functionality contained within over 150 libraries. As well as performing calculations of
the fluid dynamics, there are applications which configure and initialise simulations, ma-
nipulate case geometry, generate computational meshes, and process and visualise results.
Applications primarily fall into two categories: solvers, which perform the calcula-
tions in fluid (or other continuum) mechanics; and utilities, that perform the other tasks
described above. Prior to version 11 of OpenFOAM, individual solvers were written for
numerous specific types of flow. With so many combinations of flow type and additional
physics, OpenFOAM included almost 100 solvers at one time. Solvers with names like
simpleFoam and pimpleFoam have been the mainstay of OpenFOAM since the early 1990s.
OpenFOAM version 11, however, introduces modular solvers as a major improve-
ment to the original application solvers. The application solvers are replaced by a single
foamRun solver which describes the steps of a general algorithm for fluid dynamics calcula-
tions. foamRun loads a solver module, which defines each step to characterise a particular
type of flow.
Modular solvers are simpler to use and maintain than application solvers. Their source
code is easier to navigate, promoting better understanding. They are more flexible; in
particular, there is also a foamMultiRun solver which can take two or more domain regions
and apply a different solver module to each region. In particular, modules for one or more
fluids and solids can be coupled for conjugate heat transfer (CHT) for different flow types,
e.g. multiphase.
Further details of applications, including modular solvers, are described in chapter 3.
General configuration and running of OpenFOAM cases are described in chapter 4. Chap-
ter 5 covers details of the generation of meshes using the mesh generator supplied with
OpenFOAM and conversion of mesh data generated by third-party products. Post-
processing of results, including visualisation, is in chapter 7. Finally, some aspects of
physical modelling, e.g. transport and thermophysical modelling, are described in chap-
ter 8.
U-16 Introduction
OpenFOAM-11
Chapter 2
Tutorials
This chapter we describes the process of setup, simulation and post-processing for some
OpenFOAM test cases, with the principal aim of introducing a user to the basic proce-
dures of running OpenFOAM. The test cases are taken from the tutorials directory which
contains numerous example cases in OpenFOAM. The directory location is represented
by the $FOAM_TUTORIALS variable in the OpenFOAM “environment”.
The directory contains numerous cases that demonstrate the use of all the solver
modules, other solvers and many utilities supplied with OpenFOAM. Most examples are
stored in sub-directories corresponding to each of the modular solvers. For example, the
cases that use the incompressibleFluid module are stored in $FOAM_TUTORIALS/incom-
pressibleFluid. The user can explore these example cases, starting by listing the top-level
of the $FOAM_TUTORIALS directory, by typing in a terminal
ls $FOAM_TUTORIALS
ls $FOAM_RUN
If a message is returned saying no such directory exists, the user should create the directory
by typing
mkdir -p $FOAM_RUN
Any example case from $FOAM_TUTORIALS can then be copied into the run directory.
For example to try the motorBike example for the incompressibleFluid solver module, the
user can copy it to the run directory by typing:
cd $FOAM_RUN
cp -r $FOAM_TUTORIALS/incompressibleFluid/motorBike .
U-18 Tutorials
25.4 y
x 33.2
25.4
20.6 206 84
lower wall dimensions in mm
Flow enters the inlet in the x-direction with a speed of 10 m/s. The flow will be
assumed isothermal and incompressible and will be solved using the incompressibleFluid
modular solver.
2.1.1 Pre-processing
Cases are configured in OpenFOAM by editing input data files. Users should select a
suitable file editor to do this, e.g. emacs, vi, gedit, nedit, etc. A case involves multiple data
files, corresponding to different parts of the configuration, e.g. mesh, fields, properties,
control parameters, etc. As described in section 4.1, the set of files is stored within a
case directory, which is given a suitably descriptive name. This tutorial uses the case
$FOAM_TUTORIALS/incompressibleFluid/pitzDailySteady, which the user should copy to
their run directory as follows.
cd $FOAM_RUN
cp -r $FOAM_TUTORIALS/modules/incompressibleFluid/pitzDailySteady .
cd pitzDailySteady
OpenFOAM-11
2.1 Backward-facing step U-19
1 4 7
10
12 15 18
0 3 6 9 21
11 14 17 8 20
y 2 5
x 19
z 13 16
Figure 2.2: Block structure of the mesh for the backward step.
OpenFOAM-11
U-20 Tutorials
54 (
55 (1 4 2)
56 (2 3 4)
57 (2 4 0.25)
58 );
59
60 posYR
61 (
62 (2 1 1)
63 (1 1 0.25)
64 );
65
66
67 blocks
68 (
69 hex (0 3 4 1 11 14 15 12)
70 (18 30 1)
71 simpleGrading (0.5 $posY 1)
72
73 hex (2 5 6 3 13 16 17 14)
74 (180 27 1)
75 edgeGrading (4 4 4 4 $negY 1 1 $negY 1 1 1 1)
76
77 hex (3 6 7 4 14 17 18 15)
78 (180 30 1)
79 edgeGrading (4 4 4 4 $posY $posYR $posYR $posY 1 1 1 1)
80
81 hex (5 8 9 6 16 19 20 17)
82 (25 27 1)
83 simpleGrading (2.5 1 1)
84
85 hex (6 9 10 7 17 20 21 18)
86 (25 30 1)
87 simpleGrading (2.5 $posYR 1)
88 );
89
90 boundary
91 (
92 inlet
93 {
94 type patch;
95 faces
96 (
97 (0 1 12 11)
98 );
99 }
100 outlet
101 {
102 type patch;
103 faces
104 (
105 (8 9 20 19)
106 (9 10 21 20)
107 );
108 }
109 upperWall
110 {
111 type wall;
112 faces
113 (
114 (1 4 15 12)
115 (4 7 18 15)
116 (7 10 21 18)
117 );
118 }
119 lowerWall
120 {
121 type wall;
122 faces
123 (
124 (0 3 14 11)
125 (3 2 13 14)
126 (2 5 16 13)
127 (5 8 19 16)
128 );
129 }
130 frontAndBack
131 {
132 type empty;
133 faces
134 (
135 (0 3 4 1)
136 (2 5 6 3)
137 (3 6 7 4)
OpenFOAM-11
2.1 Backward-facing step U-21
138 (5 8 9 6)
139 (6 9 10 7)
140 (11 14 15 12)
141 (13 16 17 14)
142 (14 17 18 15)
143 (16 19 20 17)
144 (17 20 21 18)
145 );
146 }
147 );
148
149 // ************************************************************************* //
The file first contains header information in the form of a banner (lines 1-7), then file
information contained in a FoamFile sub-dictionary, delimited by curly braces ({...}).
blockMesh
The running status of blockMesh is reported in the terminal window. Any mistakes in the
blockMeshDict file are picked up by blockMesh and the resulting error message directs the
user to the source of the error.
OpenFOAM-11
U-22 Tutorials
convenient to keep ParaView open while running other commands from the terminal, we
will launch it in the background using the & operator by typing
paraFoam &
This launches the ParaView window as shown in Figure 7.1. In the Pipeline Browser,
ParaView registers pitzDailySteady.OpenFOAM, representing the pitzDailySteady case.
2. click Edit (in Coloring) and select an appropriate colour e.g. black (for a white
background);
OpenFOAM-11
2.1 Backward-facing step U-23
(Render View) panel. The selection can be saved as a user default by clicking the
Save current view settings button to the right of the View (Render View) heading (the
furthest right of the four buttons). The background colour can be also set in the View
(Render View) panel at the bottom of the Properties window.
Note that, many parameters in the Properties window are only visible by clicking the
Advanced Properties gearwheel button ( ) at the top of the Properties window, next to
the search box.
dimensions specifies the dimensions of the field, here kinematic pressure, i.e. m2 s−2 (see
section 4.2.6 for more information);
internalField the internal field data which can be uniform, described by a single value;
or nonuniform, where the values of the field must be specified for all cells (see
section 4.2.8 for more information);
boundaryField the boundary field data that includes boundary conditions and data for
all the boundary patches (see section 4.2.8 for more information).
OpenFOAM-11
U-24 Tutorials
For this pitzDailySteady case, the initial fields are set to be uniform. Here the pressure
is kinematic, and since the solution does not involve energy and thermodynamics, its
absolute value is not relevant, so is set to uniform 0 for convenience.
The boundary includes the upperWall, lowerWall, inlet and outlet patches. The
walls and inlet are both assigned the zeroGradient boundary condition for p, meaning “the
normal gradient of pressure is zero”. The outlet uses the fixedValue boundary condition
for p with value of uniform 0. The frontAndBack patch, describing the front and back
planes of the 2D case, is specified as empty.
The user can similarly examine the velocity field in the 0/U file. The dimensions are
those expected for velocity, the internal field is initialised as uniform zero, which in the
case of velocity must be expressed by 3 vector components, i.e. uniform (0 0 0) (see
section 4.2.5 for more information).
A no-slip condition is assumed on the walls, specified by a noSlip condition. The
inlet flow speed is 10 m/s in the x-direction so represented by a fixedValue condition
with value of uniform (10 0 0). The outlet reverts to the zeroGradient condition. The
frontAndBack patch must be set to empty.
First it includes the viscosityModel entry which is set to constant. With that model,
a single kinematic viscosity is then specified by the keyword nu, representing the Greek
symbol ν phonetically for the kinematic viscosity. The value is set to ν = 1 × 10−5 m2 s−1 .
|U|L
Re = (2.1)
ν
where |U| and L are the characteristic speed and length respectively and ν is the kinematic
viscosity. Using the inlet (or step) height L = 25.4 mm and |U| = 10 m/s, Re = 25400.
For flow in a pipe, transition typically occurs when Re ≈> 2000, so this case can be
assumed to be turbulent.
The momentumTransport file characterises the viscous stress in the fluid by a variety of
models, e.g. Newtonian and non-Newtonian fluids, turbulence, visco-elasticity and more.
For this example, the file includes the configuration of turbulence modelling as shown
below.
16
17 simulationType RAS;
18
19 RAS
20 {
OpenFOAM-11
2.1 Backward-facing step U-25
The type of simulation is first specified by the simulationType keyword. The RAS entry
indicates a Reynolds-averaged simulation, the standard form of turbulence modelling. The
RAS sub-dictionary includes the model entry which is set to the well-known k–ε model by
the kEpsilon entry. The turbulence keyword provides a switch to turn the modelling
on and off. The model coefficients have default values which can be overridden with
additional entries in the momentumTransport file. When the printCoeffs switch in on,
the coefficients are printed to the terminal when the case is run. The viscosityModel
entry confirms the fluid is modelled as Newtonian (which is the default model, so the
entry could be omitted).
The k–ε model solves transport equations for: k, the turbulent kinetic energy; and,
ε, the turbulent dissipation rate. The initial and boundary conditions for those fields are
configured in the 0/k and 0/epsilon files, respectfully.
In particular, the turbulent fields must be initialised with suitable internal and inlet
values. Turbulent kinetic energy k can be calculated by
3
k= (|U|I)2 (2.2)
2
from an estimate of turbulent intensity I = U′RMS /|U|, the ratio of the root-mean-square
(RMS) of turbulent fluctuations U′RMS to the mean flow speed |U|. This example uses an
estimate I = 5%, such that k = 1.5 × (10 × 0.05)2 = 0.375 m2 s−2 . In the 0/k file, 0.375
is used both for the initial internalField and the inlet value.
The turbulent dissipation rate ε can be calculated by
k 1.5
ε = Cµ0.75 . (2.3)
lm
from Cµ = 0.09 and an estimate of Prandtl mixing length lm . This example uses an
estimate lm = 10% × step height = 2.54 mm, such that ε = 0.090.75 × 0.3751.5 /0.00254 =
14.855 m2 s−3 . In the 0/epsilon file, 14.855 is used both for the initial internalField and
the inlet value.
The turbulence model is deployed with wall functions to model the behaviour at
wall boundaries. Wall functions are applied as boundary conditions on the individual
wall patches which enables different wall function models to be applied to different wall
regions. The choice of wall function models are specified through the turbulent viscosity
field, νt in the 0/nut file.
16
17 dimensions [0 2 -1 0 0 0 0];
18
19 internalField uniform 0;
20
21 boundaryField
22 {
23 inlet
24 {
OpenFOAM-11
U-26 Tutorials
25 type calculated;
26 value uniform 0;
27 }
28 outlet
29 {
30 type calculated;
31 value uniform 0;
32 }
33 upperWall
34 {
35 type nutkWallFunction;
36 value uniform 0;
37 }
38 lowerWall
39 {
40 type nutkWallFunction;
41 value uniform 0;
42 }
43 frontAndBack
44 {
45 type empty;
46 }
47 }
48
49
50 // ************************************************************************* //
This case uses standard wall functions, specified by the nutkWallFunction type on the
upperWall and lowerWall patches. Alternative wall function models include the rough
wall functions, specified through the nutRoughWallFunction keyword.
When wall functions are specified through boundary conditions in the 0/nut file, cor-
responding conditions must be applied to the wall patches for the turbulence fields. The
0/eps and 0/k files show that ε is assigned the epsilonWallFunction condition and k is as-
signed the kqRWallFunction condition at the wall patches. The latter is a generic boundary
condition that can be applied to any field that are of a turbulent kinetic energy type, e.g.
k, q or Reynolds Stress R.
2.1.7 Control
Input data relating to the control of time and reading and writing of the solution data
are read in from the controlDict file. The user should view this file; as a case control file,
it is located in the system directory.
16
17 application foamRun;
18
19 solver incompressibleFluid;
20
21 startFrom startTime;
22
23 startTime 0;
24
25 stopAt endTime;
26
27 endTime 2000;
28
29 deltaT 1;
30
31 writeControl timeStep;
32
33 writeInterval 100;
34
35 purgeWrite 0;
36
37 writeFormat ascii;
38
39 writePrecision 6;
40
41 writeCompression off;
42
43 timeFormat general;
44
45 timePrecision 6;
OpenFOAM-11
2.1 Backward-facing step U-27
46
47 runTimeModifiable true;
48
49 cacheTemporaryObjects
50 (
51 kEpsilon:G
52 );
53
54 functions
55 {
56 #includeFunc streamlinesLine
57 (
58 name=streamlines,
59 start=(-0.0205 0.001 0.00001),
60 end=(-0.0205 0.0251 0.00001),
61 nPoints=10,
62 fields=(p k U)
63 )
64
65 #includeFunc writeObjects(kEpsilon:G)
66 }
67
68 // ************************************************************************* //
The file first includes an application entry which is not used by OpenFOAM. It is
instead used by run scripts, named Allrun, which are accompany many of the example
cases. The following solver entry describes the solver module used for the simulation.
This example uses the incompressibleFluid module for steady or transient turbulent flow
of incompressible isothermal fluids with optional mesh motion and change.
The start/stop times and the time step for the run must be set. OpenFOAM provides
flexible options for time controls which are described in section 4.4. Like most cases, this
example starts the simulation at time t = 0 which instructs the solver to read its field
data from a directory named 0. Therefore we set the startFrom keyword to startTime
and then specify the startTime keyword to be 0.
The aim of the simulation is to reach the steady solution where the recirculation
region is fully developed adjacent to the step. The incompressibleFluid module can run as
a steady-state solver by setting the time derivatives ∂/∂t to zero in all the equations. This
is achieved by setting the ddtSchemes to steadyState in the fvSchemes file, discussed
later.
In this mode, the time step, represented by the keyword deltaT, is only used as a
time increment (since it is no longer used to discretise ∂/∂t). Its value does not affect the
solution, so for steady solutions it is set to 1 so that time simply represents the number
of solution steps.
The endTime keyword sets a time at which the solver application stops running. The
value of 2000 provides an adequate number of solution steps to enable the steady solution
to converge to a reasonable level of accuracy.
As the simulation progresses we wish to write results at intervals of time of interest
for visualisation and other post-processing. The writeControl keyword presents several
options for setting the time at which the results are written; here the timeStep option
specifies that results are written every nth time step where the value n is specified under
the writeInterval keyword. The interval of 100 means results are written at 100, 200,
etc.
OpenFOAM creates a new directory named after the current time, e.g. 100, on each
occasion that it writes a set of data, as discussed in full in section 4.1. It writes out the
results for each solution field, e.g. U, p, k, into the time directories.
OpenFOAM-11
U-28 Tutorials
• steady-state solution uses an algorithm based on SIMPLE whose controls are con-
figured in a SIMPLE sub-dictionary in the fvSolution file;
• the SIMPLE sub-dictionary contains the consistent switch which is set to yes,
applying the “consistent” form of the SIMPLE algorithm (SIMPLEC);
• SIMPLEC’s sensitive convergence generally makes it only reliable for cases with
simple geometries.
foamRun
The progress of the simulation is reported in the terminal window. It describes suc-
cessive solutions steps, giving the initial and final residuals for each equation, and con-
servation errors.
The SIMPLE algorithm controls in fvSolution include a residualControl sub-dictionary
with a set of tolerances for p, U and turbulence fields. The incompressibleFluid solver ter-
minates When the initial residuals for all fields fall below their respective tolerances. In
this example, the solver terminates at 287 iterations with the following statement.
Results from the simulation are written into time directories within the pitzDailySteady
case directory. The user can list the directory contents with the “ls” command to see
the time directories (100, 200 and 287) containing the results.
OpenFOAM-11
2.1 Backward-facing step U-29
• selecting the top of the Properties window (scroll up the panel if necessary) in
ParaView;
• toggling the Cache Mesh button at the top of the panel (under the Refresh Times
button;
The time selector is then updated with Time becoming a drop down menu with the time
directories from the case (0, 100, 200 and 287). In order to view the solution at 287, the
user can use the VCR Controls or Current Time Controls to change the current time
to 287.
2. select in Coloring
3. click the Rescale button to set the colour scale to the data range, if necessary.
The pressure field should appear as shown above, with the pressure increasing to a maxi-
mum at the contraction of the channel towards the outlet. With the point icon ( ), the
pressure field is interpolated across each cell to give a continuous appearance. Instead if
the user selects the cell icon, ( ), from the Coloring menu, a single value for pressure
will be attributed to each cell, represented by a single colour with no grading.
A colour legend is included which can be disabled by clicking the Toggle Color Legend
Visibility button at the left of the second row of buttons at the top of ParaView. These
buttons are part of the Active Variable Controls toolbar, shown in Figure 7.4). The
Edit Color Map button, second on the left in Active Variable Controls toolbar, opens
the Color Map Editor window, as shown in Figure 2.5, where the user can set a range of
attributes of the colour scale and the color bar.
OpenFOAM-11
U-30 Tutorials
Figure 2.4: Displaying pressure contours for the backward step case.
In particular, ParaView defaults to using a colour scale of blue to white to red rather
than the more common blue to green to red (rainbow). Therefore the first time that the
user executes ParaView, they may wish to change the colour scale. This can be done by
selecting the Choose Preset button (with the heart icon) in the Color Scale Editor. The
conventional color scale for CFD is Blue to Red Rainbow which is only listed if the user
types the name in the Search bar or checks the gearwheel to the right of that bar.
After selecting Blue to Red Rainbow and clicking Apply and Close, the user can click
the Save as Default button at the absolute bottom of the panel (file save symbol) so that
ParaView will always adopt this type of colour bar.
The user can also edit the color legend properties, such as text size, font selection and
numbering format for the scale, by clicking the Edit Color Legend Properties to the far
right of the search bar, as shown in Figure 2.5.
OpenFOAM-11
2.1 Backward-facing step U-31
Choose preset
Configure Color Bar
Save as Default
Figure 2.5: Color Map Editor.
OpenFOAM-11
U-32 Tutorials
With the Centers highlighted in the Pipeline Browser, the user should then select
Glyph from the Filters->Common menu (or the third row of buttons). The Properties
window panel should appear as shown in Figure 2.6.
When displaying velocity vectors, there are four principal settings required for the
glyphs:
• the glyph type, set to Arrow;
OpenFOAM-11
2.1 Backward-facing step U-33
window. The legend can be configured by clicking by the button furthest to the right of
the search box. This button opens the Edit Color Legend Properties window. The Advanced
Properties gearwheel button should be checked to the right of the search box.
Titles and labels can be fully configured. For Figure 2.7, the legend title is set to
Velocity U [m/s]. The labels are specified to 1 fixed decimal place by unchecking
Automatic Label Format and entering %-#6.1f in the Label Format text box. Add Range
Labels is also unchecked.
Sample output is shown in Figure 2.7, zooming in on part of the recirculation region
downstream of the step. At the lower wall, glyphs point in a direction opposing that of
the flow adjacent to the wall. This glitch is caused by these glyphs being drawn at the
face centres of the wall boundary patch, where the the velocity magnitude is 0 due to the
no-slip condition. Without any direction to the vectors, ParaView orientates the arrows
in a default x-direction. A quick way to remove these vectors is:
• go back to the pitzDailySteady.OpenFOAM module at the top of the Pipeline
Browser;
• click Apply.
OpenFOAM-11
U-34 Tutorials
2.1.15 Contours
Before drawing contour lines of the flow speed, turn off the display of the Glyph module
by highlighting it in the Pipeline Browser and clicking the eye button to its left. The user
should then highlight the Slice module and colour by velocity U. We will then aim to
draw contour lines on the slice at intervals of U of 1, 2, . . . , 10.
The contour lines can be drawn by applying the Contour filter to the slice. The filter
draws lines in 2D, or surfaces in 3D, along constant values of scalar quantities. Contours
cannot be drawn directly from U, since it is a vector, so we first need to generate a scalar
field of the magnitude of U.
The mag(U) field can be generated using post-processing with function objects, de-
scribed in section 7.3. The user should run the foamPostProcess utility, calling the mag
function object using the -func option as follows:
The utility loops over all time directories. For each time directory, it reads in U,
calculates mag(U) and writes it out as a field file back into the time directory. The
mag(U) field must then be loaded into ParaView by: first, from the pitzDailySteady-
.OpenFOAM in the Pipeline Browser, clicking Refresh Times; then, scrolling down to the
Fields panel, selecting mag(U) and clicking Apply.
The user should re-select the Slice module in the Pipeline Browser, then apply the
Contour filter. In the Properties panel, the user should select mag(U) from the Contour
By menu. Under Isosurfaces, the user should first delete the default value by clicking
the – button, then add a range of 10 values as shown in Figure 2.8. The contours can be
displayed with a Wireframe representation with solid black Coloring.
OpenFOAM-11
2.1 Backward-facing step U-35
OpenFOAM-11
U-36 Tutorials
lowerWall
inlet
Figure 2.10: Uniform flow at the inlet in the backward facing step.
the arrows by the the flow speed. In the Properties of the Glyph, scroll down to the
Scale panel and set Scale Array to U, with Scale By Magnitude and a Scale Factor
of 8e-05. The vectors are assigned a Solid Color of white.
The figure shows the inlet region adjacent to the lower wall boundary. At the left
of the image, the vectors show a uniform profile. Shear at the wall causes the flow to
decelerate, starting in the near-wall cell. The deceleration causes an increase in pressure,
which produces a driving gradient that redirects the flow slightly away from the wall, to
obey mass conservation.
In order to reduce the pressure increase, the boundary condition can be modified
so that the inlet velocity is no longer uniform. A flowRateInletVelocity boundary con-
dition is a general boundary condition for U, specifying flow at an inlet. Documen-
tation for this boundary condition can be viewed using the foamInfo script, a general
tool which provides documentation for applications, models and tools in OpenFOAM.
It is run for the flowRateInletVelocity boundary condition as follows (noting that the
name can sometimes be abbreviated for simplicity, here flowRateInlet, rather than
flowRateInletVelocity).
foamInfo flowRateInlet
It locates and prints the header file of the related code and extracts the Description and
Usage information from the file. It then identifies associated models, i.e. other boundary
conditions in this case, and lists example cases that use the model. The foamInfo script
is not perfect, but provides useful information quickly in at least nine times out of ten.
The documentation explains that the flowRateInletVelocity condition can specify the
flow by a massFlowRate, volumetricFlowRate or meanVelocity. The user should open
the 0/U in their editor and locate the boundary field entry for the inlet patch. The
condition with a meanVelocity can then be applied by changing the inlet sub-dictionary
as follows:
inlet
{
type flowRateInletVelocity; // modify
OpenFOAM-11
2.1 Backward-facing step U-37
The condition evaluates the velocity on the boundary, setting the value for all faces on
the boundary patch. The value entry is therefore redundant for OpenFOAM, but it can
be needed by ParaView to display initial values of initialised fields at patches. Therefore,
the value entry is retained for ParaView’s benefit.
After saving the 0/U file, the user can re-run the simulation to check first that the
flowRateInletVelocity emulates the original fixedValue condition. The controlDict file spec-
ifies that case starts from time 0 and it will overwrite previous results in time directories.
The user can test the new condition simply by re-running the foamRun solver.
foamRun
The solver runs as before, terminating at 287 iterations. The user can return to ParaView
and click the Refresh Times button in the pitzDailySteady.OpenFOAM module of the
Pipeline Browser. There is no change to the results, demonstrating that the flowRateIn-
letVelocity is setting a uniform value of (10 0 0) at this stage.
The user should now modify the flowRateInletVelocity condition in the 0/U file by
including a profile for the velocity. The documentation highlights two customised profile
function, turbulentBL and laminarBL, which provide power-law and quadtratic profiles
for fully-developed turbulent and laminar boundary layers, respectively. In this example,
add the turbulentBL profile to the boundary condition as follows:
inlet
{
type flowRateInletVelocity;
meanVelocity 10;
profile turbulentBL; // add
value uniform (10 0 0);
}
Before running the simulation again, it it recommended to delete the previous solution
time directories. The results should be deleted now because the solver will likely terminate
at a different time, so the results from the final time directory from the old case will not
be overwritten, potentially causing confusion.
The foamListTimes utility provides a quick, simple way to delete solution time direc-
tories, i.e. retaining the 0 directory. First run foamListTimes in the terminal as follows:
foamListTimes
This returns the list of the solution time directories, 100, 200 and 287, but not 0. The
listed directories can be deleted by including the -rm remove option to foamListTimes, i.e.
running the following command.
foamListTimes -rm
OpenFOAM-11
U-38 Tutorials
lowerWall
inlet
Figure 2.11: Turbulent boundary layer at the inlet in the backward facing step.
With the time directories containing the results now deleted, the foamRun solver should be
run as before. This time foamRun terminates at 277 iterations. The user should return to
ParaView and click the Refresh Times button in the pitzDailySteady.OpenFOAM module
of the Pipeline Browser.
The change in output times may create confusion for ParaView, causing it to query
times in the time selector with (?) symbols. The selector entries can be rebuilt by
reverting to time 0 or clicking Cache Mesh and Apply. The user can then select the last
time in the sequence (277). The velocity profile and pressure are updated as shown in
Figure 2.11. For pressure, the custom range is moved to −7 < p < −3. The velocity is no
longer uniform at the inlet, but forms a profile according to the turbulentBL function.
The velocity magnitude at the face adjacent to the lower wall is significantly reduced
from previously so the deceleration due to shear is also reduced in the near-wall cell. The
pressure difference between the left corner and surrounding cells is consequently not as
high, approximately +2 m2 s−2 (from -7 to -5) compared to +4 m2 s−2 (from -5 to -1)
previously.
model realizableKE;
The simulation can now be re-run using this model by deleting the solution time directories
and executing foamRun as follows.
OpenFOAM-11
2.1 Backward-facing step U-39
secondary vortex
velocity profile
foamListTimes -rm
foamRun
The solver terminates this time at 255 iterations. The user can now return to ParaView and
click Refresh Times to view the results at time 255. The results are shown in Figure 2.12
using the slice with the velocity field and the streamlines filters configured earlier.
The realizable k–ε model is less diffusive that the standard k–ε model. It captures a
secondary vortex at the base of the step which is approximately half the step height. The
recirculation region is also longer, with reattachment occurring at the point the lower wall
begins to taper towards the outlet.
The user can also test other turbulence models. The k–ω SST model is a popular
choice in industrial CFD which can be selected by the following setting in the momen-
tumTransport file.
model kOmegaSST;
OpenFOAM-11
U-40 Tutorials
Figure 2.14: Secondary vortex with k–ω SST model with limiting on grad(U).
The linearUpwind scheme interpolates fields from cell centres to faces by extrapolation
using the cell gradient. The grad(U) entry specifies the form of the gradient calculation,
using the scheme specified in the gradSchemes sub-dictionary. In the example case, it
includes only a default scheme for calculating all gradient terms in all equations.
In order to stabilise the secondary vortex, the cellLimited scheme can be applied
specifically to the discretisation of the velocity gradient grad(U). The syntax is shown
below.
gradSchemes
{
default Gauss linear;
OpenFOAM-11
2.2 Breaking of a dam U-41
After saving the fvSchemes file, the simulation can be re-run by deleting the solution time
directories and executing foamRun as before. With the cellLimited scheme applied, the
solution converges normally, with the solver terminating at 285 iterations. The secondary
vortex stabilises as shown in Figure 2.14.
0.584 m
water column
0.584 m
0.292 m
0.048 m
OpenFOAM-11
U-42 Tutorials
run
cp -r $FOAM_TUTORIALS/incompressibleVoF/damBreakLaminar/damBreak .
Go into the damBreak case directory and generate the mesh running blockMesh as de-
scribed previously. The damBreak mesh consist of five blocks; the blockMeshDict entries
are given below.
16 convertToMeters 0.146;
17
18 vertices
19 (
20 (0 0 0)
21 (2 0 0)
22 (2.16438 0 0)
23 (4 0 0)
24 (0 0.32876 0)
25 (2 0.32876 0)
26 (2.16438 0.32876 0)
27 (4 0.32876 0)
28 (0 4 0)
29 (2 4 0)
30 (2.16438 4 0)
31 (4 4 0)
32 (0 0 0.1)
33 (2 0 0.1)
34 (2.16438 0 0.1)
35 (4 0 0.1)
36 (0 0.32876 0.1)
37 (2 0.32876 0.1)
38 (2.16438 0.32876 0.1)
39 (4 0.32876 0.1)
40 (0 4 0.1)
41 (2 4 0.1)
42 (2.16438 4 0.1)
43 (4 4 0.1)
44 );
45
46 blocks
47 (
48 hex (0 1 5 4 12 13 17 16) (23 8 1) simpleGrading (1 1 1)
49 hex (2 3 7 6 14 15 19 18) (19 8 1) simpleGrading (1 1 1)
50 hex (4 5 9 8 16 17 21 20) (23 42 1) simpleGrading (1 1 1)
51 hex (5 6 10 9 17 18 22 21) (4 42 1) simpleGrading (1 1 1)
52 hex (6 7 11 10 18 19 23 22) (19 42 1) simpleGrading (1 1 1)
53 );
54
55 defaultPatch
56 {
57 type empty;
58 }
59
60 boundary
61 (
62 leftWall
63 {
64 type wall;
65 faces
66 (
67 (0 12 16 4)
68 (4 16 20 8)
69 );
70 }
71 rightWall
72 {
73 type wall;
74 faces
75 (
76 (7 19 15 3)
77 (11 23 19 7)
78 );
79 }
OpenFOAM-11
2.2 Breaking of a dam U-43
80 lowerWall
81 {
82 type wall;
83 faces
84 (
85 (0 1 13 12)
86 (1 5 17 13)
87 (5 6 18 17)
88 (2 14 18 6)
89 (2 3 15 14)
90 );
91 }
92 atmosphere
93 {
94 type patch;
95 faces
96 (
97 (8 20 21 9)
98 (9 21 22 10)
99 (10 22 23 11)
100 );
101 }
102 );
103
104
105 // ************************************************************************* //
The mesh is written into a set of files in a polyMesh directory in the constant directory.
The use can list the contents of the directory to reveal the set of files/
ls constant/polyMesh
The files include: points, a list of the cell vertices; faces, a list of the cell faces; owner and
neighbour, containing the indices of cells connected to a given face; boundary, a description
of the boundary patches.
cat constant/polyMesh/boundary
The file contains a list of five boundary patches: leftWall, rightWall, lowerWall,
atmosphere and defaultFaces. The user should notice the type of the patches. Firstly,
the atmosphere is a standard patch, i.e. has no special attributes, merely an entity on
which boundary conditions can be specified. Then, the defaultFaces patch is formed
of block faces that are omitted from the boundary sub-dictionary in the blockMeshDict
file. Those block faces form a patch whose properties are specified in a defaultPatch
sub-dictionary in the blockMeshDict file. In this case, the default type is set to empty
since the patch normal is in the direction we will not solve in this 2D case.
The leftWall, rightWall and lowerWall patches are each a wall. Like the generic
patch, the wall type contains no geometric or topological information about the mesh and
only differs from the plain patch in that it identifies the patch as a wall. This is required by
some modelling, e.g. turbulent wall functions and some turbulence models which include
the distance to the nearest wall in their calculations.
With VoF specifically, surface tension models can include wall adhesion at the contact
point between the interface and wall surface. Wall adhesion models can be applied through
a special boundary condition on the alpha (α) field, e.g. the constantAlphaContactAngle
boundary condition, which requires the user to specify a static contact angle, theta0.
OpenFOAM-11
U-44 Tutorials
This example ignores surface tension effects between the wall and interface. This can
be done can do this by setting the static contact angle, θ0 = 90◦ , but a simpler approach
is to apply the zeroGradient condition to alpha on the walls.
The top boundary is free to the atmosphere so needs to permit both outflow and inflow
according to the internal flow. We therefore use a combination of boundary conditions
for pressure and velocity that does this while maintaining stability. They are:
• inletOutlet applied to other fields, which is a zeroGradient condition when flow out-
wards, fixedValue when flow is inwards.
At all wall boundaries, the fixedFluxPressure boundary condition is applied to the pressure
field, which adjusts the pressure gradient so that the boundary flux matches the veloc-
ity boundary condition for solvers that include body forces such as gravity and surface
tension.
The defaultFaces patch representing the front and back planes of the 2D problem,
is, as usual, an empty type.
2.2.3 Phases
The fluid phases are specified in the phaseProperties file in the constant directory as follows:
16
17 phases (water air);
18
19 sigma 0.07;
20
21
22 // ************************************************************************* //
It lists two phases, water and air. Equations for phase fraction are solved for the phases
in the list, except the last phase listed, i.e. air in this case. Since there are only two
phases, only one phase fraction equation is solved in this case, for the water phase fraction
αwater , specified in the file alpha.water in the 0 directory.
The phaseProperties file also contains an entry for the surface tension between the two
phases, specified by the keyword sigma in units N m−1 .
This is done by running the setFields utility. It requires a setFieldsDict dictionary, located
in the system directory, whose entries for this case are shown below.
OpenFOAM-11
2.2 Breaking of a dam U-45
16
17 defaultFieldValues
18 (
19 volScalarFieldValue alpha.water 0
20 );
21
22 regions
23 (
24 boxToCell
25 {
26 box (0 0 -1) (0.1461 0.292 1);
27 fieldValues
28 (
29 volScalarFieldValue alpha.water 1
30 );
31 }
32 );
33
34
35 // ************************************************************************* //
The defaultFieldValues sets the default value of the fields, i.e. the value the field
takes unless specified otherwise in the regions list. That list contains sub-dictionaries
with fieldValues that override the defaults in a specified region. Regions are defined by
functions that define a set of points, faces, or cells. Here boxToCell creates a box defined
by minimum and maximum bounds that defines the set of cells of the water region. The
phase fraction αwater is specified as 1 in this region.
The setFields utility reads fields from file and, after re-calculating those fields, will
write them back to file. In the damBreak case, the alpha.water field is initially stored in
its original form with the name alpha.water.orig. A field file with the .orig extension
is read in when the actual file does not exist, so setFields will read alpha.water.orig
but write the resulting output to alpha.water (or alpha.water.gz if compression is
switched on). This way the original file is not overwritten, so can be reused.
The user should execute setFields like any other utility by:
setFields
Using paraFoam, check that the initial alpha.water field corresponds to the desired dis-
tribution as in Figure 2.16.
Phase fraction, α1
1.0
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0.0
OpenFOAM-11
U-46 Tutorials
If the viscosity does change according to the flow, e.g. as in non-Newtonian or visco-
elastic fluids, then those models are specified through the momentumProperties file, as
described in section 8.3.
2.2.6 Gravity
Gravitational acceleration is uniform across the domain and is specified in a file named
g in the constant directory. Unlike a normal field file, e.g. U and p, g is a uniformDimen-
sionedVectorField and so simply contains a set of dimensions and a value that represents
(0, 9.81, 0) m s−2 for this case:
16
17 dimensions [0 1 -2 0 0 0 0];
18 value (0 -9.81 0);
19
20
21 // ************************************************************************* //
OpenFOAM-11
2.2 Breaking of a dam U-47
the maximum Co < 1 at least; stricter limits exist depending on the choice of advection
scheme. Implicit solutions do not have the same stability limit of the maximum Co, but
temporal accuracy becomes more relevant as Co increased beyond 1.
Time step control is particularly important with interface-capturing. The incompress-
ibleVoF solver module uses the multidimensional universal limiter for explicit solution
(MULES), created by Henry Weller, to maintain boundedness of the phase fraction. Co
needs to be limited depending on the choice of MULES algorithm. With the original
explicit MULES algorithm, an upper limit of Co ≈ 0.25 for stability is typically required.
However, there is also the semi-implicit version of MULES, specified by the MULESCorr
switch in the fvSolution file. For semi-implicit MULES, there is really no upper limit in
Co for stability, but instead the level is determined by requirements of temporal accuracy.
In general it is difficult to specify a fixed time-step to satisfy the Co criterion since
|U| is changing from cell to cell during the simulation. Instead, automatic adjustment
of the time step is specified in the controlDict by switching adjustTimeStep to on and
specifying the maximum Co for the phase fields, maxAlphaCo, and other fields, maxCo. In
this example, the maxAlphaCo and maxCo are set to 1.0. The upper limit on time step
maxDeltaT can be set to a value that will not be exceeded in this simulation, e.g. 1.0.
By using automatic time step control, the steps themselves are never rounded to a
convenient value. Consequently if we request that OpenFOAM saves results at a fixed
number of time step intervals, the times at which results are saved are somewhat arbitrary.
However with automatic time step adjustment, results can be written at fixed times using
the adjustableRunTime option for writeControl in the controlDict dictionary. With this
option, the automatic time stepping procedure further adjusts their time steps so that it
‘hits’ on the exact times specified by the writeInterval, set to 0.05 in this example.
The controlDict dictionary entries are shown below.
16
17 application foamRun;
18
19 solver incompressibleVoF;
20
21 startFrom startTime;
22
23 startTime 0;
24
25 stopAt endTime;
26
27 endTime 1;
28
29 deltaT 0.001;
30
31 writeControl adjustableRunTime;
32
33 writeInterval 0.05;
34
35 purgeWrite 0;
36
37 writeFormat binary;
38
39 writePrecision 6;
40
41 writeCompression off;
42
43 timeFormat general;
44
45 timePrecision 6;
46
47 runTimeModifiable yes;
48
49 adjustTimeStep yes;
50
51 maxCo 1;
52 maxAlphaCo 1;
53
54 maxDeltaT 1;
55
56
57 // ************************************************************************* //
OpenFOAM-11
U-48 Tutorials
OpenFOAM-11
2.2 Breaking of a dam U-49
smoother symGaussSeidel;
tolerance 1e-8;
relTol 0;
}
MULES calculates two limiters to keep the phase fraction within the lower and upper
bounds of 0 and 1. The limiter calculation is iterative, with the number of iterations
specified by nLimiterIter. As a rule of thumb, nLimiterIter can be set to 3 + Co to
maintain boundedness.
The semi-implicit version of MULES is activated by the MULESCorr switch. It first
calculates an implicit, upwind solution before applying MULES as a higher-order correc-
tion. The linear solver must be configured for the implicit, upwind solution, through the
solver, smoother, tolerance and relTol parameters.
The nAlphaCorr keyword which controls the number of iterations of the phase fraction
equation within a solution step. The iteration is used to overcome nonlinearities in the
advection which are present in this case due to the interfaceCompression scheme.
cd $FOAM_RUN/damBreak
foamRun | tee log
The code will now be run interactively, with a copy of output stored in the log file.
2.2.12 Post-processing
Post-processing of the results can now be done in the usual way. The user can monitor
the development of the phase fraction alpha.water in time, e.g. see Figure 2.17.
run
foamCloneCase damBreak damBreakFine
Enter the new case directory and change the blocks description in the blockMeshDict
dictionary to
blocks
(
hex (0 1 5 4 12 13 17 16) (46 10 1) simpleGrading (1 1 1)
hex (2 3 7 6 14 15 19 18) (40 10 1) simpleGrading (1 1 1)
hex (4 5 9 8 16 17 21 20) (46 76 1) simpleGrading (1 2 1)
hex (5 6 10 9 17 18 22 21) (4 76 1) simpleGrading (1 2 1)
OpenFOAM-11
U-50 Tutorials
Here, the entry is presented as printed from the blockMeshDict file; in short the user must
change the mesh densities, e.g. the 46 10 1 entry, and some of the mesh grading entries
to 1 2 1. Once the dictionary is correct, generate the mesh by running blockMesh.
As the mesh has now changed from the damBreak example, the user must re-initialise
the phase field alpha.water in the 0 time directory since it contains a number of elements
that is inconsistent with the new mesh. Note that there is no need to change the U and
p_rgh fields since they are specified as uniform which is independent of the number of
elements in the field.
The user should then rerun the setFields utility. However, the mesh size is now incon-
sistent with the number of elements in the alpha.water file in the 0 directory, so the user
must delete that file so that setFields uses the original alpha.water.orig file.
rm 0/alpha.water
setFields
Parallel computing uses domain decomposition, in which the geometry and associ-
ated fields are broken into pieces and allocated to separate processors for solution. The
first step required to run a parallel case is therefore to decompose the domain using the
decomposePar utility. There is a dictionary associated with decomposePar named decom-
poseParDict which is located in the system directory. Also, sample dictionaries can be
found within the etc directory in the OpenFOAM installation, which can be copied to the
case directory by running the foamGet script, e.g. (you do not need to do this):
foamGet decomposeParDict
OpenFOAM-11
2.2 Breaking of a dam U-51
The first entry is numberOfSubdomains which specifies the number of subdomains into
which the case will be decomposed, usually corresponding to the number of processors
available for the case.
This example uses the simple method of decomposition. It requires the simpleCoeffs
to be configured according to the following criteria. The domain is split into pieces, or
subdomains, in the x, y and z directions, the number of subdomains in each direction
being given by the vector n. As this geometry is 2 dimensional, the 3rd direction, z, cannot
be split, hence nz must equal 1. The nx and ny components of n split the domain in the
x and y directions and must be specified so that the number of subdomains specified by
nx and ny equals the specified numberOfSubdomains, i.e. nx ny = numberOfSubdomains.
It is beneficial to keep the number of cell faces adjoining the subdomains to a minimum
so, for a square geometry, it is best to keep the split between the x and y directions should
be fairly even. For example, let us assume we wish to run on 4 processors. We would set
numberOfSubdomains to 4 and n to (2, 2, 1). The user should run decomposePar by
the following command.
decomposePar
The terminal output shows that the decomposition is distributed evenly between the sub-
domains. The decomposition writes the mesh and fields of each sub-domain into separate
sub-directories named processor<N>, where N is the sub-domain ID, e.g. 0, 1, 2, etc. The
user should list the files in the case directory to confirm that four directories processor0,
processor1, processor2 and processor3 exist.
This example presents running in parallel with the openMPI implementation of the
standard message-passing interface (MPI). The following command runs on 4 cores of a
local multi-processor CPU.
The user can consult section 3.4 for more details of how to run a case in parallel. For
example, the user may run on more nodes over a network by creating a file that lists the
host names of the machines on which the case is to be run as described in section 3.4.3.
ls processor0
Figure 2.18 shows the mesh from this sub-domain, following the decomposition of the
domain using the simple method.
OpenFOAM-11
U-52 Tutorials
Alternatively, the decomposed fields and mesh can be reassembled for post-processing
in serial. The reconstructPar utility takes the field files from time directories for the
processor sub-domain and builds equivalent field files for the complete domain. The
user should run the utility as follows.
reconstructPar
The fields are reconstructed are written to solution time directories in the case directory.
These fields can be visualised as normal in ParaView. The results from the fine mesh
are shown in Figure 2.19. The user can see that the resolution of interface has improved
significantly compared to the coarse mesh.
OpenFOAM-11
2.3 Stress analysis of a plate with a hole U-53
y
σ = 10 kPa σ = 10 kPa
symmetry plane x
R = 0.5 m
symmetry plane
4.0 m
Figure 2.20: Geometry of the plate with a hole.
The problem can be approximated as 2D since the load is applied in the plane of
the plate. In a Cartesian coordinate system there are two possible assumptions to take
in regard to the behaviour of the structure in the third dimension: (1) the plane stress
condition, in which the stress components acting out of the 2D plane are assumed to be
negligible; (2) the plane strain condition, in which the strain components out of the 2D
plane are assumed negligible. The plane stress condition is appropriate for solids whose
third dimension is thin as in this case; the plane strain condition is applicable for solids
where the third dimension is thick.
An analytical solution exists for loading of an infinitely large, thin plate with a circular
hole. The solution for the stress normal to the vertical plane of symmetry is
( )
R2 3R4
σ 1+ 2 + 4 for |y| ≥ R
(σxx )x=0 = 2y 2y (2.7)
0 for |y| < R
Results from the simulation will be compared with this solution. At the end of the
tutorial, the user can: investigate the sensitivity of the solution to mesh resolution and
mesh grading; and, increase the size of the plate in comparison to the hole to try to
estimate the error in comparing the analytical solution for an infinite plate to the solution
of this problem of a finite plate.
OpenFOAM-11
U-54 Tutorials
8 up 7 up 6
left
4 3 right
x2
9
x1 x2
left 0 4 x1 3
10 x2
x1 right
2
5 1
hole
y x2 x2
x 0 x1 1 x1 down 2
down
Figure 2.21: Block structure of the mesh for the plate with a hole.
The example uses the solidDisplacement modular solver. The user should go to their
run directory, copy the plateHole case from the $FOAM_TUTORIALS/solidDisplacement
directory and finally change into the plateHole case directory.
run
cp -r $FOAM_TUTORIALS/solidDisplacement/plateHole .
cd plateHole
OpenFOAM-11
2.3 Stress analysis of a plate with a hole U-55
23 (2 0.707107 0)
24 (0.707107 0.707107 0)
25 (0.353553 0.353553 0)
26 (2 2 0)
27 (0.707107 2 0)
28 (0 2 0)
29 (0 1 0)
30 (0 0.5 0)
31 (0.5 0 0.5)
32 (1 0 0.5)
33 (2 0 0.5)
34 (2 0.707107 0.5)
35 (0.707107 0.707107 0.5)
36 (0.353553 0.353553 0.5)
37 (2 2 0.5)
38 (0.707107 2 0.5)
39 (0 2 0.5)
40 (0 1 0.5)
41 (0 0.5 0.5)
42 );
43
44 blocks
45 (
46 hex (5 4 9 10 16 15 20 21) (10 10 1) simpleGrading (1 1 1)
47 hex (0 1 4 5 11 12 15 16) (10 10 1) simpleGrading (1 1 1)
48 hex (1 2 3 4 12 13 14 15) (20 10 1) simpleGrading (1 1 1)
49 hex (4 3 6 7 15 14 17 18) (20 20 1) simpleGrading (1 1 1)
50 hex (9 4 7 8 20 15 18 19) (10 20 1) simpleGrading (1 1 1)
51 );
52
53 edges
54 (
55 arc 0 5 (0.469846 0.17101 0)
56 arc 5 10 (0.17101 0.469846 0)
57 arc 1 4 (0.939693 0.34202 0)
58 arc 4 9 (0.34202 0.939693 0)
59 arc 11 16 (0.469846 0.17101 0.5)
60 arc 16 21 (0.17101 0.469846 0.5)
61 arc 12 15 (0.939693 0.34202 0.5)
62 arc 15 20 (0.34202 0.939693 0.5)
63 );
64
65 boundary
66 (
67 left
68 {
69 type symmetryPlane;
70 faces
71 (
72 (8 9 20 19)
73 (9 10 21 20)
74 );
75 }
76 right
77 {
78 type patch;
79 faces
80 (
81 (2 3 14 13)
82 (3 6 17 14)
83 );
84 }
85 down
86 {
87 type symmetryPlane;
88 faces
89 (
90 (0 1 12 11)
91 (1 2 13 12)
92 );
93 }
94 up
95 {
96 type patch;
97 faces
98 (
99 (7 8 19 18)
100 (6 7 18 17)
101 );
102 }
103 hole
104 {
105 type patch;
OpenFOAM-11
U-56 Tutorials
106 faces
107 (
108 (10 5 16 21)
109 (5 0 11 16)
110 );
111 }
112 frontAndBack
113 {
114 type empty;
115 faces
116 (
117 (10 9 4 5)
118 (5 4 1 0)
119 (1 4 3 2)
120 (4 7 6 3)
121 (4 9 8 7)
122 (21 16 15 20)
123 (16 11 12 15)
124 (12 13 14 15)
125 (15 14 17 18)
126 (15 18 19 20)
127 );
128 }
129 );
130
131
132 // ************************************************************************* //
Until now, we have only specified straight edges in the geometries of previous tutorials but
here we need to specify curved edges. These are specified under the edges keyword entry
which is a list of non-straight edges. The syntax of each list entry begins with the type of
curve, including arc, simpleSpline, polyLine etc., described further in section 5.4.3. In
this example, all the edges are circular and so can be specified by the arc keyword entry.
The following entries are the labels of the start and end vertices of the arc and a point
vector through which the circular arc passes.
The blocks in this blockMeshDict do not all have the same orientation. As can be seen
in Figure 2.21 the x2 direction of block 0 is equivalent to the −x1 direction for block 4.
This means care must be taken when defining the number and distribution of cells in each
block so that the cells match up at the block faces.
Six patches are defined: one for each side of the plate, one for the hole and one for the
front and back planes. The left and down patches are both a symmetry plane. Since this
is a geometric constraint, it is included in the definition of the mesh, rather than being
purely a specification on the boundary condition of the fields. Therefore they are defined
as such using a special symmetryPlane type as shown in the blockMeshDict.
The frontAndBack patch represents the plane which is ignored in a 2D case. Again
this is a geometric constraint so is defined within the mesh, using the empty type as shown
in the blockMeshDict. For further details of boundary types and geometric constraints,
the user should refer to section 5.3.
The remaining patches are of the regular patch type. The mesh should be generated
using blockMesh and can be viewed in paraFoam as described in section 2.1.3. It should
appear as in Figure 2.22.
OpenFOAM-11
2.3 Stress analysis of a plate with a hole U-57
21 {
22 left
23 {
24 type symmetryPlane;
25 }
26 right
27 {
28 type tractionDisplacement;
29 traction uniform (10000 0 0);
30 pressure uniform 0;
31 value uniform (0 0 0);
32 }
33 down
34 {
35 type symmetryPlane;
36 }
37 up
38 {
39 type tractionDisplacement;
40 traction uniform (0 0 0);
41 pressure uniform 0;
42 value uniform (0 0 0);
43 }
44 hole
45 {
46 type tractionDisplacement;
47 traction uniform (0 0 0);
48 pressure uniform 0;
49 value uniform (0 0 0);
50 }
51 frontAndBack
52 {
53 type empty;
54 }
55 }
56
57 // ************************************************************************* //
Firstly, it can be seen that the displacement initial conditions are set to (0, 0, 0) m. The
left and down patches must be both of symmetryPlane type since they are specified
as such in the mesh description in the constant/polyMesh/boundary file. Similarly the
frontAndBack patch is declared empty.
The other patches are traction boundary conditions, set by a specialist tractionDis-
placement boundary type. The traction boundary conditions are specified by a linear
combination of: (1) a boundary traction vector under keyword traction; (2) a pressure
that produces a traction normal to the boundary surface that is defined as negative when
pointing out of the surface, under keyword pressure. The up and hole patches are zero
OpenFOAM-11
U-58 Tutorials
traction so the boundary traction and pressure are set to zero. For the right patch the
traction should be (1e4, 0, 0) Pa and the pressure should be 0 Pa.
OpenFOAM-11
2.3 Stress analysis of a plate with a hole U-59
2.3.4 Control
As before, the information relating to the control of the solution procedure are read in
from the controlDict dictionary. For this case, the startTime is 0 s. The time step is
not important since this is a steady state case; in this situation it is best to set the time
step deltaT to 1 so it simply acts as an iteration counter for the steady-state case. The
endTime, set to 100, then acts as a limit on the number of iterations. The writeInterval
can be set to 20.
The controlDict entries are as follows:
16
17 application foamRun;
18
19 solver solidDisplacement;
20
21 startFrom startTime;
22
23 startTime 0;
24
25 stopAt endTime;
26
27 endTime 100;
28
29 deltaT 1;
30
31 writeControl timeStep;
32
33 writeInterval 20;
34
35 purgeWrite 0;
36
37 writeFormat ascii;
38
39 writePrecision 6;
40
41 writeCompression off;
42
43 timeFormat general;
44
45 timePrecision 6;
46
47 runTimeModifiable true;
48
49
50 // ************************************************************************* //
OpenFOAM-11
U-60 Tutorials
20 }
21
22 ddtSchemes
23 {
24 default Euler;
25 }
26
27 gradSchemes
28 {
29 default leastSquares;
30 }
31
32 divSchemes
33 {
34 default none;
35 div(sigmaD) Gauss linear;
36 }
37
38 laplacianSchemes
39 {
40 default Gauss linear corrected;
41 }
42
43 interpolationSchemes
44 {
45 default linear;
46 }
47
48 snGradSchemes
49 {
50 default none;
51 }
52
53 // ************************************************************************* //
The fvSolution dictionary in the system directory controls the linear equation solvers and
algorithms used in the solution. The user should first look at the solvers sub-dictionary
and notice that the choice of solver for D is GAMG. The solver tolerance should be set to
10−6 for this problem. The solver relative tolerance, denoted by relTol, sets the required
reduction in the residuals within each iteration. It is uneconomical to set a tight (low)
relative tolerance within each iteration since a lot of terms in each equation are explicit
and are updated as part of the segregated iterative procedure. Therefore a reasonable
value for the relative tolerance is 0.01, or possibly even higher, say 0.1, or in some cases
even 0.9 (as in this case).
16
17 solvers
18 {
19 "(D|e)"
20 {
21 solver GAMG;
22 tolerance 1e-06;
23 relTol 0.9;
24 smoother GaussSeidel;
25 nCellsInCoarsestLevel 20;
26 }
27 }
28
29 PIMPLE
30 {
31 compactNormalStress yes;
32 }
33
34
35 // ************************************************************************* //
OpenFOAM-11
2.3 Stress analysis of a plate with a hole U-61
The user should check the convergence information by viewing the generated log file. It
shows the number of iterations and the initial and final residuals of the displacement in
each direction being solved. The final residual should always be less than 0.9 times the
initial residual as this iteration tolerance set. By the end of the simulation, the initial
residuals have reduced towards the convergence tolerance of 10−6 .
2.3.7 Post-processing
The solidDisplacementFoam solver outputs the stress field σ as a symmetric tensor field
sigma. To post-process individual scalar field components, σxx , σxy etc., the user can
run the foamPostProcess utility, calling the components function object on the sigma field
using the -func option as follows:
Components named sigmaxx, sigmaxy etc. are written to time directories of the case.
The σxx stresses can be viewed in ParaView as shown in Figure 2.23.
30
25
σxx (kPa)
20
15
10
In order to compare the solution to the analytical solution of Equation 2.7, data of
σxx must be extracted along the left edge symmetry plane of our domain. The user may
generate the required graph data using the foamPostProcess utility with the graphUniform
function. Unlike earlier examples of foamPostProcess where no configuration is required,
this example includes a graphUniform file pre-configured in the system directory. The
sample line is set between (0.0, 0.5, 0.25) and (0.0, 2.0, 0.25), and the fields are specified
in the fields list:
9 Writes graph data for specified fields along a line, specified by start and
10 end points. A specified number of graph points are used, distributed
11 uniformly along the line.
12
13 \*---------------------------------------------------------------------------*/
14
15 start (0 0.5 0.25);
16 end (0 2 0.25);
OpenFOAM-11
U-62 Tutorials
35
30
17 nPoints 100;
18
19 fields (sigmaxx);
20
21 axis y;
22
23 #includeEtc "caseDicts/postProcessing/graphs/graphUniform.cfg"
24
25 // ************************************************************************* //
Data is written in raw 2 column format into files within time subdirectories of a post-
Processing/graphUniform directory, e.g. the data at t = 100 s is found within the file
graphUniform/100/line.xy. If the user has GnuPlot installed they launch it (by typing
gnuplot) and then plot both the numerical data and analytical solution as follows:
OpenFOAM-11
Chapter 3
The examples in Chapter 2 show that OpenFOAM provides a range of software ‘tools’
that are run from a terminal command line. The tools include applications which are ex-
ecutable programs written in C++, the base programming language of OpenFOAM. Ap-
plications obtain most of the functionality from OpenFOAM’s vast store of pre-compiled
libraries, also written in C++. Since OpenFOAM is open source software, users have the
freedom to create their own applications and libraries. Applications are generally split
into two categories:
• solvers, e.g. foamRun, that perform CFD calculations involving fluid dynamics, en-
ergy, etc.;
• utilities, e.g. blockMesh and foamPostProcess, that perform other tasks in CFD like
meshing and post-processing.
Prior to version 11 of OpenFOAM, there were many solvers, since separate ones were
written for various different types of flow, e.g. simpleFoam, pimpleFoam, etc. However,
most flow solvers are now written as modules, e.g. incompressibleFluid, incompressibleVoF
and e.g.solid which are loaded by the general foamRun (or foamMultiRun) solvers. Rather
than existing as an application, each solver module is compiled into a library of its own.
In addition to applications, the tools in OpenFOAM also include shell scripts, e.g.
paraFoam, foamInfo and foamGet. Many of the scripts help with the configuration of
cases.
This chapter gives an overview of applications and libraries, including their creation,
modification, compilation and execution.
“velocity field” can be replaced by a single symbol, e.g. U, and other symbols express
operations and functions, e.g. “the field of velocity magnitude” by |U|.
CFD deals with partial differential equations in 3 dimensions of space and time. The
equations contain: fields of scalars, vectors and tensors; tensor algebra; tensor calculus;
and, dimensional units. The solution to these equations involves discretisation procedures,
matrices, solvers, and solution algorithms.
Rather than program CFD in terms of intrinsic entities known to a computer, e.g.
bits, bytes, integers, floating point numbers, OpenFOAM provides classes that define the
entities encountered in CFD. For example, a velocity field can be defined by a vectorField
class, allowing a programmer to create an instance, or object, of that class. The object can
be created with the name U to mimic the symbol used in mathematics. Associated func-
tions can be created with names which also try to emulate the simplicity of mathematics,
e.g. mag(U) can represent |U|.
The class structure concentrates code development to contained regions of the code,
i.e. the classes themselves, thereby making the code easier to manage. New classes can be
derived or inherit properties from other classes, e.g. the vectorField can be derived from
a vector class and a Field class. C++ provides the mechanism of template classes such
that the template class Field<Type> can represent a field of any <Type>, e.g.scalar, vector,
tensor. The general features of the template class are passed on to any class created from
the template. Templating and inheritance reduce duplication of code and create class
hierarchies that impose an overall structure on the code.
A theme of the OpenFOAM design is that it has a syntax that closely resembles the
partial differential equations being solved. For example the equation
∂ρU
+ ∇ • ϕU − ∇ • µ∇U = −∇p
∂t
is represented by the code
solve
(
fvm::ddt(rho, U)
+ fvm::div(phi, U)
- fvm::laplacian(mu, U)
==
- fvc::grad(p)
);
The equation syntax is most evident in the code for solvers, both the modules and
solver applications. Users do not need a deep knowledge of C++ programming to interpret
the equations written in a solver. Instead, an understanding of the underlying equations,
models and solution method and algorithms is perhaps more helpful, which can be found
in Notes on Computational Fluid Dynamics: General Principles.
It does help to have a rudimentary understanding of the the principles behind object-
orientation and classes, and to have a basic knowledge of some C++ code syntax. To
program in OpenFOAM, there is often little need for a user to immerse themselves in
the code of any of the OpenFOAM classes. The essence of object-orientation is that the
user should not have to go through the code of each class they use; merely the knowledge
of the class’ existence and its functionality are sufficient to use the class. A description
of each class and its functions is supplied with the OpenFOAM distribution in HTML
documentation generated with Doxygen at https://cpp.openfoam.org
OpenFOAM-11
3.2 Compiling applications and libraries U-65
Compiled Compiled
newApp Linked nc.so
Executable -l option Library
OpenFOAM-11
U-66 Applications and libraries
known as the dependencies. With a dependency list, a compiler can check whether the
source files have been updated since their last compilation and selectively compile only
those that need to be.
Header files are included in the code using the #include directive, e.g.
#include "otherHeader.H";
This causes the compiler to suspend reading from the current file, to read the included file.
This mechanism allows any self-contained piece of code to be put into a header file and
included at the relevant location in the main code in order to improve code readability.
For example, in most OpenFOAM applications the code for creating fields and reading
field input data is included in a file createFields.H which is called at the beginning of the
code. In this way, header files are not solely used as class declarations.
It is wmake that performs the task of maintaining file dependency lists amongst other
functions listed below.
• Automatic generation and maintenance of file dependency lists, i.e. lists of files
which are included in the source files and hence on which they depend.
• Multi-option compilation and linkage, e.g. debug, optimised, parallel and profiling.
• Support for source code generation programs, e.g. lex, yacc, IDL, MOC.
OpenFOAM-11
3.2 Compiling applications and libraries U-67
newApp
newApp.C
otherHeader.H
Make
files
options
Figure 3.2: Directory structure for an application
5. other directories specified explicitly in the Make/options file with the -I option.
The Make/options file contains the full directory paths to locate header files using the
syntax:
EXE_INC = \
-I<directoryPath1> \
-I<directoryPath2> \
... \
-I<directoryPathN>
Notice first that the directory names are preceded by the -I flag and that the syntax uses
the \ to continue the EXE_INC across several lines, with no \ after the final entry.
The actual library files to be linked must be specified using the -l option and removing
the lib prefix and .so extension from the library file name, e.g. libnew.so is included with
the flag -lnew. By default, wmake loads the following libraries:
OpenFOAM-11
U-68 Applications and libraries
The Make/options file contains the full directory paths and library names using the syntax:
EXE_LIBS = \
-L<libraryPath> \
-l<library1> \
-l<library2> \
... \
-l<libraryN>
To summarise: the directory paths are preceded by the -L flag, the library names are
preceded by the -l flag.
newApp.C
EXE = $(FOAM_USER_APPBIN)/newApp
wmake <optionalDirectory>
The <optionalDirectory> is the directory path of the application that is being compiled.
Typically, wmake is executed from within the directory of the application being compiled,
in which case <optionalDirectory> can be omitted.
OpenFOAM-11
3.2 Compiling applications and libraries U-69
The environment variable settings for the compilation with wmake are listed below.
The environment variable settings relating to the choice of compiler and options withwmake
are listed below.
• $WM_CXXFLAGS: extra flags to the C++ compiler, e.g. -m64 -fPIC -std=c++0x.
OpenFOAM-11
U-70 Applications and libraries
• $WM_COMPILER: compiler being used, e.g. Gcc = gcc, Clang = LLVM Clang
wclean <optionalDirectory>
• in the files file, EXE = is replaced by LIB = and the target directory for the compiled
entity changes from $FOAM_APPBIN to $FOAM_LIBBIN (and an equivalent $FOAM_-
USER_LIBBIN directory);
When wmake is executed it additionally creates a directory named lnInclude that contains
soft links to all the files in the library. The lnInclude directory is deleted by the wclean
script when cleaning library source code.
OpenFOAM-11
3.2 Compiling applications and libraries U-71
1 /*---------------------------------------------------------------------------*\
2 ========= |
3 \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4 \\ / O peration | Website: https://openfoam.org
5 \\ / A nd | Copyright (C) 2022-2023 OpenFOAM Foundation
6 \\/ M anipulation |
7 -------------------------------------------------------------------------------
8 License
9 This file is part of OpenFOAM.
10
11 OpenFOAM is free software: you can redistribute it and/or modify it
12 under the terms of the GNU General Public License as published by
13 the Free Software Foundation, either version 3 of the License, or
14 (at your option) any later version.
15
16 OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
17 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19 for more details.
20
21 You should have received a copy of the GNU General Public License
22 along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
23
24 Application
25 foamRun
26
27 Description
28 Loads and executes an OpenFOAM solver module either specified by the
29 optional \c solver entry in the \c controlDict or as a command-line
30 argument.
31
32 Uses the flexible PIMPLE (PISO-SIMPLE) solution for time-resolved and
33 pseudo-transient and steady simulations.
34
35 Usage
36 \b foamRun [OPTION]
37
38 - \par -solver <name>
39 Solver name
40
41 - \par -libs '(\"lib1.so\" ... \"libN.so\")'
42 Specify the additional libraries loaded
43
44 Example usage:
45 - To run a \c rhoPimpleFoam case by specifying the solver on the
46 command line:
47 \verbatim
48 foamRun -solver fluid
49 \endverbatim
50
51 - To update and run a \c rhoPimpleFoam case add the following entries to
52 the controlDict:
53 \verbatim
54 application foamRun;
55
56 solver fluid;
57 \endverbatim
58 then execute \c foamRun
59
60 \*---------------------------------------------------------------------------*/
61
62 #include "argList.H"
63 #include "solver.H"
64 #include "pimpleSingleRegionControl.H"
65 #include "setDeltaT.H"
66
67 using namespace Foam;
68
69 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
70
71 int main(int argc, char *argv[])
72 {
73 argList::addOption
74 (
75 "solver",
76 "name",
77 "Solver name"
78 );
79
80 #include "setRootCase.H"
81 #include "createTime.H"
82
83 // Read the solverName from the optional solver entry in controlDict
OpenFOAM-11
U-72 Applications and libraries
84 word solverName
85 (
86 runTime.controlDict().lookupOrDefault("solver", word::null)
87 );
88
89 // Optionally reset the solver name from the -solver command-line argument
90 args.optionReadIfPresent("solver", solverName);
91
92 // Check the solverName has been set
93 if (solverName == word::null)
94 {
95 args.printUsage();
96
97 FatalErrorIn(args.executable())
98 << "solver not specified in the controlDict or on the command-line"
99 << exit(FatalError);
100 }
101 else
102 {
103 // Load the solver library
104 solver::load(solverName);
105 }
106
107 // Create the default single region mesh
108 #include "createMesh.H"
109
110 // Instantiate the selected solver
111 autoPtr<solver> solverPtr(solver::New(solverName, mesh));
112 solver& solver = solverPtr();
113
114 // Create the outer PIMPLE loop and control structure
115 pimpleSingleRegionControl pimple(solver.pimple);
116
117 // Set the initial time-step
118 setDeltaT(runTime, solver);
119
120 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
121
122 Info<< nl << "Starting time loop\n" << endl;
123
124 while (pimple.run(runTime))
125 {
126 solver.preSolve();
127
128 // Adjust the time-step according to the solver maxDeltaT
129 adjustDeltaT(runTime, solver);
130
131 runTime++;
132
133 Info<< "Time = " << runTime.userTimeName() << nl << endl;
134
135 // PIMPLE corrector loop
136 while (pimple.loop())
137 {
138 solver.moveMesh();
139 solver.fvModels().correct();
140 solver.prePredictor();
141 solver.momentumPredictor();
142 solver.thermophysicalPredictor();
143 solver.pressureCorrector();
144 solver.postCorrector();
145 }
146
147 solver.postSolve();
148
149 runTime.write();
150
151 Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s"
152 << " ClockTime = " << runTime.elapsedClockTime() << " s"
153 << nl << endl;
154 }
155
156 Info<< "End\n" << endl;
157
158 return 0;
159 }
160
161
162 // ************************************************************************* //
The code begins with a description of the application contained within comments over
OpenFOAM-11
3.2 Compiling applications and libraries U-73
1 line (//) and multiple lines (/*...*/). Following that, the code contains several #
include statements, e.g. # include "argList.H", which causes the compiler to suspend
reading from the current file, foamRun.C to read the argList.H file.
foamRun uses the finite volume numerics library and therefore requires the necessary
header files, specified by the EXE_INC = -I... option, and links to the libraries with the
EXE_LIBS = -l... option. The Make/options therefore contains the following:
1 EXE_INC = \
2 -I$(LIB_SRC)/finiteVolume/lnInclude
3
4 EXE_LIBS = \
5 -lfiniteVolume
foamRun contains the foamRun.C source and the executable is written to the $FOAM_-
APPBIN directory. The application uses functions to initialise and adjust the time step,
defined in the setDeltaT.C file. The Make/files therefore contains:
1 setDeltaT.C
2 foamRun.C
3
4 EXE = $(FOAM_APPBIN)/foamRun
Following the recommendations of section 3.2.5, the user can compile a separate version of
foamRun into their local $FOAM_USER_DIR directory as follows. First, the user should
copy the foamRun source code to a local directory, e.g. $FOAM_RUN.
cd $FOAM_RUN
cp -r $FOAM_SOLVERS/foamRun .
cd foamRun
wmake
The code should compile and produce a message similar to the following
If the user tries recompiling without making any changes to the code file, nothing will
happen. The user can compile the application from scratch by removing the dependency
list with
wclean
OpenFOAM-11
U-74 Applications and libraries
OpenFOAM-11
3.3 Running applications U-75
(as quoted string entries). For example, if a user wished to link the libraries new1 and
new2 at run-time, they would simply need to add the following to the case controlDict file:
libs
(
"libnew1.so"
"libnew2.so"
);
foamRun -help
If the application is executed from within a case directory, it will operate on that case.
Alternatively, the -case <caseDir> option allows the case to be specified directly so
that the application can be executed from anywhere in the filing system.
Like any UNIX/Linux executable, applications can be run as a background process,
i.e. one which does not have to be completed before the user can give the shell additional
commands. If the user wished to run the foamRun example as a background process and
output the case progress to a log file, they could enter:
OpenFOAM-11
U-76 Applications and libraries
foamGet decomposeParDict
The user has a choice of four methods of decomposition, specified by the method keyword
as described below.
simple Simple geometric decomposition in which the domain is split into pieces by di-
rection, e.g. 2 pieces in the x direction, 1 in y etc.
hierarchical Hierarchical geometric decomposition which is the same as simple except
the user specifies the order in which the directional split is done, e.g. first in the
y-direction, then the x-direction etc.
OpenFOAM-11
3.4 Running applications in parallel U-77
scotch Scotch decomposition which requires no geometric input from the user and at-
tempts to minimise the number of processor boundaries. The user can specify a
weighting for the decomposition between processors, through an optional process-
orWeights keyword which can be useful on machines with differing performance
between processors. There is also an optional keyword entry strategy that con-
trols the decomposition strategy through a complex string supplied to Scotch. For
more information, see the source code file: $FOAM_SRC/parallel/decompose/scotch-
Decomp/scotchDecomp.C
For each method there are a set of coefficients specified in a sub-dictionary of decom-
positionDict, named <method>Coeffs as shown in the dictionary listing. The full set of
keyword entries in the decomposeParDict dictionary are explained below:
decomposePar
OpenFOAM-11
U-78 Applications and libraries
A foamFormatConvert utility allows users to convert files between the collated and
uncollated formats, e.g.
When using the collated file handling, memory is allocated for the data in the thread.
maxThreadFileBufferSize sets the maximum size of memory that is allocated in bytes.
If the data exceeds this size, the write does not use threading.
Note: if threading is not enabled in the MPI, it must be disabled for collated file
handling by setting in the global etc/controlDict file:
maxThreadFileBufferSize 0;
OpenFOAM-11
3.4 Running applications in parallel U-79
aaa
bbb cpu=2
ccc
distributed yes;
and the roots entry is a list of root paths, <root0>, <root1>, . . . , for each node
roots
<nRoots>
(
"<root0>"
OpenFOAM-11
U-80 Applications and libraries
"<root1>"
...
);
reconstructPar
The user may post-process decomposed cases using the paraFoam post-processor, de-
scribed in section 7.1. The whole simulation can be post-processed by reconstructing the
case or alternatively it is possible to post-process a segment of the decomposed domain
individually by simply treating the individual processor directory as a case in its own
right.
OpenFOAM-11
3.5 Solver modules U-81
incompressibleDriftFlux Solver module for 2 incompressible fluids using the mixture ap-
proach with the drift-flux approximation for relative motion of the phases, with
optional mesh motion and mesh topology changes including adaptive re-meshing.
incompressibleVoF Solver module for for 2 incompressible, isothermal immiscible fluids us-
ing a VOF (volume of fluid) phase-fraction based interface capturing approach, with
optional mesh motion and mesh topology changes including adaptive re-meshing.
isothermalFluid Solver module for steady or transient turbulent flow of compressible iso-
thermal fluids with optional mesh motion and change.
multiphaseVoFSolver Base solver module for the solution of multiple immiscible fluids us-
ing a VOF (volume of fluid) phase-fraction based interface capturing approach, with
optional mesh motion and mesh topology changes including adaptive re-meshing.
OpenFOAM-11
U-82 Applications and libraries
OpenFOAM-11
3.7 Standard utilities U-83
laplacianFoam Solves a simple Laplace equation, e.g. for thermal diffusion in a solid.
dsmcFoam Direct simulation Monte Carlo (DSMC) solver for, transient, multi-species
flows.
3.7.1 Pre-processing
applyBoundaryLayer Apply a simplified boundary-layer model to the velocity and turbu-
lence fields based on the 1/7th power-law.
boxTurb Makes a box of turbulence which conforms to a given energy spectrum and is
divergence free.
OpenFOAM-11
U-84 Applications and libraries
changeDictionary Utility to change dictionary entries, e.g. can be used to change the
patch type in the field and polyMesh/boundary files.
createExternalCoupledPatchGeometry Application to generate the patch geometry (points
and faces) for use with the externalCoupled boundary condition.
dsmcInitialise Initialise a case for dsmcFoam by reading the initialisation dictionary system/-
dsmcInitialise.
engineSwirl Generates a swirling flow for engine calculations.
faceAgglomerate Agglomerate boundary faces using the pairPatchAgglomeration algo-
rithm. It writes a map from the fine to coarse grid.
foamSetupCHT Sets up a multi-region case using template files for material properties,
field and system files.
mapFields Maps volume fields from one mesh to another, reading and interpolating all
fields present in the time directory of both cases.
mapFieldsPar Maps volume fields from one mesh to another, reading and interpolating all
fields present in the time directory of both cases. Parallel and non-parallel cases are
handled without the need to reconstruct them first.
mdInitialise Initialises fields for a molecular dynamics (MD) simulation.
setAtmBoundaryLayer Applies atmospheric boundary layer models to the entire domain
for case initialisation.
setFields Set values on a selected set of cells/patchfaces through a dictionary.
setWaves Applies wave models to the entire domain for case initialisation using level sets
for second-order accuracy.
snappyHexMeshConfig Preconfigures blockMeshDict, surfaceFeaturesDict and snappyHex-
MeshDict files based on the case surface geometry files.
viewFactorsGen View factors are calculated based on a face agglomeration array (final-
Agglom generated by faceAgglomerate utility).
OpenFOAM-11
3.7 Standard utilities U-85
datToFoam Reads in a datToFoam mesh file and outputs a points file. Used in conjunction
with blockMesh.
foamToSurface Reads an OpenFOAM mesh and writes the boundaries in a surface format.
tetgenToFoam Converts .ele and .node and .face files, written by tetgen.
writeMeshObj For mesh debugging, writes mesh as three separate OBJ files for visualisa-
tion.
OpenFOAM-11
U-86 Applications and libraries
autoPatch Divides external faces into patches based on (user supplied) feature angle.
createBaffles Makes internal faces into boundary faces. Does not duplicate points, unlike
mergeOrSplitBaffles.
createPatch Utility to create patches out of selected boundary faces. Faces come either
from existing patches or from a faceSet.
insideCells Picks up cells with cell centre ’inside’ of surface. Requires surface to be closed
and singly connected.
mergeBaffles Detects faces that share points (baffles) and merges them into internal faces.
objToVTK Read obj line (not surface!) file and convert into vtk.
polyDualMesh Calculates the dual of a polyMesh. Adheres to all the feature and patch
edges.
renumberMesh Renumbers the cell list in order to reduce the bandwidth, reading and
renumbering all fields from all the time directories.
rotateMesh Rotates the mesh and fields from the direction n1 to direction n2.
setsToZones Add pointZones, faceZones or cellZones to the mesh from similar named
pointSets, faceSets or cellSets.
singleCellMesh Reads all fields and maps them to a mesh with all internal faces removed
(singleCellFvMesh) which gets written to region singleCell.
splitBaffles Detects faces that share points (baffles) and duplicates the points to separate
them.
OpenFOAM-11
3.7 Standard utilities U-87
transformPoints Transforms the mesh points in the polyMesh directory according to the
translate, rotate and scale options.
zipUpMesh Reads in a mesh with hanging vertices and zips up the cells to guarantee that
all polyhedral cells of valid shape are closed.
collapseEdges Collapses short edges and combines edges that are in line.
combinePatchFaces Checks for multiple patch faces on same cell and combines them.
Multiple patch faces can result from e.g. removal of refined neighbouring cells,
leaving 4 exposed faces with same owner.
PDRMesh Mesh and field preparation utility for PDR type simulations.
refinementLevel Tries to figure out what the refinement level is on refined Cartesian
meshes. Run BEFORE snapping.
3.7.6 Post-processing
engineCompRatio Calculate the geometric compression ratio. Note that if you have valves
and/or extra volumes it will not work, since it calculates the volume at BDC and
TCD.
noise Utility to perform noise analysis of pressure data using the noiseFFT library.
OpenFOAM-11
U-88 Applications and libraries
smapToFoam Translates a STAR-CD SMAP data file into OpenFOAM field format.
surfaceClean Removes baffles - collapses small edges, removing triangles. - converts sliver
triangles into split edges by projecting point onto base of triangle.
surfaceFeatures Identifies features in a surface geometry and writes them to file, based on
control parameters specified by the user.
surfaceHookUp Find close open edges and stitches the surface along them
surfaceInertia Calculates the inertia tensor, principal axes and moments of a command
line specified triSurface. Inertia can either be of the solid body or of a thin shell.
OpenFOAM-11
3.7 Standard utilities U-89
surfaceMeshImport Import from various third-party surface formats into surfMesh with
optional scaling or transformations (rotate/translate) on a coordinateSystem.
surfaceOrient Set normal consistent with respect to a user provided ‘outside’ point. If the
-inside option is used the point is considered inside.
surfacePointMerge Merges points on surface if they are within absolute distance. Since
absolute distance use with care!
surfaceSplitByTopology Strips any baffle parts of a surface. A baffle region is one which
is reached by walking from an open edge, and stopping when a multiply connected
edge is reached.
surfaceSubset A surface analysis tool which sub-sets the triSurface to choose only a
part of interest. Based on subsetMesh.
surfaceToPatch Reads surface and applies surface regioning to a mesh. Uses boundaryMesh
to do the hard work.
redistributePar Redistributes existing decomposed mesh and fields according to the current
settings in the decomposeParDict file.
OpenFOAM-11
U-90 Applications and libraries
equilibriumFlameT Calculates the equilibrium flame temperature for a given fuel and pres-
sure for a range of unburnt gas temperatures and equivalence ratios; the effects of
dissociation on O2, H2O and CO2 are included.
foamFormatConvert Converts all IOobjects associated with a case into the format specified
in the controlDict.
patchSummary Writes fields and boundary condition info for each patch at each requested
time instance.
OpenFOAM-11
Chapter 4
OpenFOAM cases
This chapter deals with the file structure and organisation of OpenFOAM cases. Normally,
a user would assign a name to a case, e.g. the tutorial case of aerodynamics of a motorbike
is simply named motorBike. This name becomes the name of a directory in which all the
case files and sub-directories are stored.
When running a simulation, a case directory can be located anywhere on a user’s
filing system. However, we recommend putting cases within a run subdirectory of the
user’s filing system, i.e.$HOME/OpenFOAM/${USER}-11 as described at the beginning
of chapter 2. The $FOAM_RUN environment variable is set to $HOME/OpenFOAM/-
${USER}-11/run by default and the user can quickly move to that directory by executing
a preset alias, run, at the command line.
The tutorial cases that accompany the OpenFOAM distribution provide useful exam-
ples of the case directory structures. The tutorials are located in the $FOAM_TUTORIALS
directory, reached quickly by executing the tut alias at the command line. Users can view
tutorial examples at their leisure while reading this chapter.
constant directory that contains a full description of the case mesh in a subdirectory
polyMesh and files specifying properties and models for the application concerned,
e.g. physicalProperties and momentumTransport.
system directory for setting parameters associated with the solution procedure itself. It
contains at least the following three files: controlDict where run control parame-
ters are set including start/end time, time step and parameters for data output;
fvSchemes where discretisation schemes used in the solution are selected; and, fv-
Solution where the equation solvers, tolerances and other algorithm controls are set
for the run.
‘time’ directories containing individual files of data for particular fields, e.g. velocity and
pressure. The data can be: either, initial values and boundary conditions that the
user must specify to define the problem; or, results written to file by OpenFOAM.
Fields must always be initialised, even when the solution does not strictly require
it, as in steady-state problems. The name of each time directory is based on the
simulated time at which the data is written and is described fully in section 4.4.
U-92 OpenFOAM cases
<case>
system
controlDict see section 4.4
fvSchemes see section 4.5
fvSolution see section 4.6
constant
. . . Properties see chapter 8
polyMesh see section 5.2
points
faces
owner
neighbour
boundary
time directories see section 4.2.8
Figure 4.1: Case directory structure
Since we usually start our simulations at time t = 0, the initial conditions are usually
stored in a directory named 0. For example, in the motorBike tutorial, the velocity
field U and pressure field p are initialised from files 0/U and 0/p respectively.
• Files have free form, with no particular meaning assigned to any column and no
need to indicate continuation across lines.
• A comment over multiple lines is done by enclosing the text between /* and */
delimiters.
4.2.2 Dictionaries
OpenFOAM mainly uses dictionaries to specify data, in which data entries are retrieved
by means of keywords. Each keyword entry follows the general format, beginning with
the keyword and ending in semi-colon (;).
OpenFOAM-11
4.2 Basic input/output file format U-93
<keyword> <dataEntry>;
Most data files, e.g. controlDict, are themselves dictionaries since they contain a series
of keyword entries. Any dictionary can contain one or more sub-dictionaries, usually
denoted by a dictionary name and its keyword entries contained within curly braces {}
as follows.
<dictionaryName>
{
... keyword entries ...
}
(Sub-)dictionaries can be nested within others, as shown in the following example. The
extract, from an fvSolution dictionary file, containing two dictionaries, solvers and PIMPLE.
The solvers dictionary contains nested sub-dictionary for different matrix equations based
on different solution variables, e.g. p, U and k (with some entries using regular expressions
described in section 4.2.12).
16
17 solvers
18 {
19 p
20 {
21 solver GAMG;
22 tolerance 1e-7;
23 relTol 0.01;
24
25 smoother DICGaussSeidel;
26
27 }
28
29 pFinal
30 {
31 $p;
32 relTol 0;
33 }
34
35 "(U|k|epsilon)"
36 {
37 solver smoothSolver;
38 smoother symGaussSeidel;
39 tolerance 1e-05;
40 relTol 0.1;
41 }
42
43 "(U|k|epsilon)Final"
44 {
45 $U;
46 relTol 0;
47 }
48 }
49
50 PIMPLE
51 {
52 nNonOrthogonalCorrectors 0;
53 nCorrectors 2;
54 }
55
56
57 // ************************************************************************* //
OpenFOAM-11
U-94 OpenFOAM cases
• class: class relating to the data, either dictionary or a field, e.g. volVectorField
FoamFile
{
format ascii;
class dictionary;
location "system";
object controlDict;
}
4.2.4 Lists
OpenFOAM applications contain lists, e.g. a list of vertex coordinates for a mesh de-
scription. Lists are commonly found in I/O and have a format of their own in which the
entries are contained within round braces ( ). When a user specifies a list in an input
file, e.g. the vertices list in a blockMeshDict file, it just includes the vertices keyword
and the data in ( ), e.g.
vertices
(
... entries ...
);
When OpenFOAM writes out a list, it invariably prefixes it with the number of ele-
ments in the list. For example the points file for the mesh in the pizDailySteady case con-
tains the following (abbreviated) list, where 25012 denotes the number of vertex points
in the mesh.
25012
(
(-0.0206 0 -0.0005)
(-0.01901716308 0 -0.0005)
... entries ...
);
OpenFOAM-11
4.2 Basic input/output file format U-95
In some cases, when OpenFOAM writes out a list, it further prefixes it with the class
name of the list. For example, the inGroups entry in a boundary file of a mesh contains
a list where each group name is a word. The entry for the lowerWall patch from the
pizDailySteady case is shown below, indicating the List<word> class with a single (1)
element.
lowerWall
{
type wall;
inGroups List<word> 1(wall); // Note!
nFaces 250;
startFace 24480;
}
In OpenFOAM, a tensor contains nine elements, such that the identity tensor can be
written:
( 1 0 0 0 1 0 0 0 1 )
The user can write the entry over multiple lines to give the “look” of a tensor as a 3 × 3
entity.
(
1 0 0
0 1 0
0 0 1
)
[0 2 -1 0 0 0 0]
OpenFOAM-11
U-96 OpenFOAM cases
where each of the values corresponds to the power of each of the base units of measurement
listed in sequence below:
The list includes base units for the Système International (SI) and the United States
Customary System (USCS) but OpenFOAM can be used with any system of units. All
that is required is that the input data is correct for the chosen set of units. The input data
may include physical constants, e.g. the Universal Gas Constant R, which are specified in a
DimensionedConstant sub-dictionary of main controlDict file of the OpenFOAM installation
($WM_PROJECT_DIR/etc/controlDict). By default these constants are set in SI units.
Those wishing to use the USCS or any other system of units should modify these constants
to their chosen set of units accordingly, as described in section 4.3.
nu nu [0 2 -1 0 0 0 0] 1e-5;
Note that the first nu is the keyword; the second nu is the word name stored in class word;
the next entry is the dimensionSet and the final entry is the scalar value.
Very often, however, the word and dimensionSet are specified in the code with default
values, so can be omitted from the I/O as shown below.
nu 1e-5;
4.2.8 Fields
Field files, e.g. U and p, that are read from and written into the time directories, possess
their own customised I/O with the following three key entries.
• internalField: values within the internal field, e.g. within each cell of a mesh.
• boundaryField: condition (type) and data for each patch of the mesh boundary.
OpenFOAM-11
4.2 Basic input/output file format U-97
The internalField can be specified in two ways. First, when the user edits a field file
to initialise it, they generally specify a single value across all elements, i.e. the cells (or
faces, points, depending on the type of field) of the mesh. A single value of 0 is denoted
by the uniform keyword as shown below.
internalField uniform 0;
When results are written out, fields cannot generally be represented by a single value.
The output uses the nonuniform keyword, followed by a suitable list of values. The
abbreviated example below is from an output p file for a mesh of 12225 cells.
OpenFOAM-11
U-98 OpenFOAM cases
a 10;
b $a;
subdictA
{
a 20;
}
b $subdictA/a;
• to traverse up one level of sub-dictionary, use the ‘..’ (double-dot) prefix, see below;
• to traverse to the top level dictionary use the ‘!’ (exclamation mark) prefix (most
useful), see below;
• to traverse into a separate file named otherFile, use ‘otherFile!’, see below;
• for multiple levels of macro substitution, each specified with the ‘$’ dollar syntax,
‘{}’ brackets are required to protect the expansion, see below.
When accessing parameters from another file, the $FOAM_CASE environment variable is
useful to specify the path to the file as described in Section 4.2.11 and illustrated below.
a 10;
b a;
c ${$b}; // returns 10, since $b returns "a", and $a returns 10
subdictA
{
a 20;
}
subdictB
{
// double-dot takes scope up 1 level, then into "subdictA" => 20
b $../subdictA/a;
subsubdict
OpenFOAM-11
4.2 Basic input/output file format U-99
{
// exclamation mark takes scope to top level => 10
b $!a;
pressure 1e+05;
In order to use this pressure for internal and initial boundary fields, the user could
simply include the initialConditions file using the #include directive, then use a macro
expansion on the pressure keyword, as follows.
#include "initialConditions"
internalField uniform $pressure;
boundaryField
{
patch1
{
type fixedValue;
value $internalField;
}
}
This example works if the included file is in the same directory as the file that includes
it. Otherwise, more generally the path to the file is required, e.g. if initialConditions is in
the constant directory:
#include "$FOAM_CASE/constant/initialConditions"
Here $FOAM_CASE represents is the path of the case directory as described in the following
section. The following special forms of the #include directive also exist.
• #includeEtc: reads a file with the $FOAM_ETC directory as the starting path.
OpenFOAM-11
U-100 OpenFOAM cases
#remove <keywordEntry>
#include "$FOAM_RUN/pitzDailySteady/0/U"
In addition to environment variables like $FOAM_RUN, set within the operating sys-
tem, a number of “internal” environment variables are recognised, including the following.
OpenFOAM-11
4.2 Basic input/output file format U-101
".*Wall"
{
type noSlip;
}
The other common regular expression uses () to group expressions. For example, to a
noSlip boundary condition on two wall patches named upper and lower, the user could
specify:
"(upper|lower)"
{
type noSlip;
}
p
{
solver PCG;
preconditioner DIC;
tolerance 1e-6;
relTol 0.05;
}
pFinal
{
$p;
relTol 0;
}
Where a data lookup matches both a keyword and a regular expression, the keyword
match takes precedence irrespective of the order of the entries.
OpenFOAM-11
U-102 OpenFOAM cases
The file contains several calculations that calculate vertex ordinates, e.g. y, z, etc., from
geometry dimensions, e.g. radius.
Calculations include standard C++ functions including unit conversions, e.g. degToRad,
and trigonometric functions, e.g. sin. They can also include OpenFOAM mathematical
functions if the relevant header files are included for those functions. The #calcInclude
directive enables header files to be included for use with #calc.
The aerofoilNACA0012Steady example, using the fluid solver module, sets the inlet ve-
locity using an angle of attack using the code below. The transform function is provided
by the transform.H header file, to rotate unit vectors by the angle of attack to set the lift
and drag directions.
angleOfAttack 5; // degs
#calcInclude "transform.H"
liftDir #calc "transform(Ry($angle), vector(0, 0, 1))";
dragDir #calc "transform(Ry($angle), vector(1, 0, 0))";
Dictionary entries constructed with #calc or #codeStream (see below) can use variables
that represent OpenFOAM classes, or types, such as vector, tensor, List, Field, string etc..
To create a typed variable, the type is specified inside angled brackets <>, immediately
after the $ symbol, e.g. $<vector>var or $<vector>{var} substitutes a variable named
var as a vector. The following example shows a calculation c = a • b using #calc.
a (1 2 3);
b (1 1 0);
c #calc "$<vector>a & $<vector>b";
OpenFOAM-11
4.2 Basic input/output file format U-103
c #calc "$(a)/$b";
The code string can also be delimited by #{. . . #} instead of quotation marks ". . . ".
The former delimiter supports code strings across multiple lines and avoids problems
with string typed variables that may contain quotation marks, as shown in the following
example.
s "field";
fieldName #calc
#{
$<string>s + "Name"
#};
Further examples can be found in files in the test/dictionary directory in the OpenFOAM
installation.
OpenFOAM-11
U-104 OpenFOAM cases
4.2.16 Conditionals
Input files support two conditional directives: #if. . . #else. . . #endif; and, #ifEq. . .
#else. . . #endif. The #if conditional reads a switch that can be generated by a #calc
directive, e.g.:
angle 65;
laplacianSchemes
{
#if #calc "${angle} < 75"
default Gauss linear corrected;
#else
default Gauss linear limited corrected 0.5;
#endif
}
The #ifEq compares a word or string, and executes based on a match, e.g.:
rotating
{
timeScheme ${${FOAM_CASE}/system/fvSchemes!ddtSchemes/default};
#ifeq $timeScheme steadyState
type MRFnoSlip;
#else
type movingWallVelocity;
#endif
value uniform (0 0 0);
}
OpenFOAM-11
4.4 Time and data input/output control U-105
DimensionedConstants
{
unitSet SI; // USCS
}
While a user could modify this setting in the etc/controlDict file in the installation,
it is better practice to use a file in their user directory. OpenFOAM provides a set of
directory locations, where global configuration files can be included, which it looks up in
an order of precedence. To list the locations, simply run the following command.
foamEtcFile -list
The listed locations include a local $HOME/.OpenFOAM directory and follow a descending
order of precedence, i.e. the last location listed (etc) is lowest precedence.
If a user therefore wished to work permanently in USCS units, they could maintain a
controlDict file in their $HOME/.OpenFOAM directory that includes the following entry.
DimensionedConstants
{
unitSet USCS;
}
OpenFOAM would read the unitSet entry from this file, but read all other controlDict
keyword entries from the global controlDict file.
Alternatively, if a user wished to work on a single case in USCS units, they could add
the same entry into the controlDict file in the system directory for their case. This file is
discussed in the next section.
OpenFOAM-11
U-106 OpenFOAM cases
41 writeCompression off;
42
43 timeFormat general;
44
45 timePrecision 6;
46
47 runTimeModifiable yes;
48
49 adjustTimeStep yes;
50
51 maxCo 5;
52
53 functions
54 {
55 #includeFunc patchAverage(patch=inlet, fields=(p U))
56 }
57
58 // ************************************************************************* //
4.4.1 Modules
solver Choice of solver module for the simulation, e.g. incompressibleFluid
regionSolvers Dictionary of solvers for different domain regions, e.g. heat transfer of
water flowing over a plate might use the fluid and solid modules as follows:
regionSolvers
{
water fluid;
plate solid;
}
libs List of additional libraries (existing on $LD_LIBRARY_PATH) to be loaded at run-
time, e.g. ("libNew1.so" "libNew2.so")
endTime End time for the simulation when stopAt endTime; is specified.
OpenFOAM-11
4.4 Time and data input/output control U-107
purgeWrite Integer representing a limit on the number of time directories that are stored
by overwriting time directories on a cyclic basis. For example, if the simulations
starts at t = 5s and ∆t = 1s, then with purgeWrite 2;, data is first written into 2
directories, 6 and 7, then when 8 is written, 6 is deleted, and so on so that only 2 new
results directories exists at any time. To disable the purging, specify purgeWrite
0; (default).
writeCompression Switch to specify whether files are compressed with gzip when writ-
ten: on/off (yes/no, true/false)
OpenFOAM-11
U-108 OpenFOAM cases
adjustTimeStep Switch used by some solvers to adjust the time step during the simula-
tion, usually according to maxCo.
• gradSchemes: gradient ∇Ψ
• divSchemes: divergence ∇ • Ψ
OpenFOAM-11
4.5 Numerical schemes U-109
Each keyword is the name of a sub-dictionary which contains terms of a particular type,
e.g. gradSchemes contains all the gradient derivative terms such as grad(p) (which rep-
resents ∇p). Further examples can be seen in the extract from an fvSchemes dictionary
below:
16
17 ddtSchemes
18 {
19 default Euler;
20 }
21
22 gradSchemes
23 {
24 default Gauss linear;
25 }
26
27 divSchemes
28 {
29 default none;
30
31 div(phi,U) Gauss linearUpwind grad(U);
32 div(phi,k) Gauss upwind;
33 div(phi,epsilon) Gauss upwind;
34 div(phi,R) Gauss upwind;
35 div(R) Gauss linear;
36 div(phi,nuTilda) Gauss upwind;
37
38 div((nuEff*dev2(T(grad(U))))) Gauss linear;
39 }
40
41 laplacianSchemes
42 {
43 default Gauss linear corrected;
44 }
45
46 interpolationSchemes
47 {
48 default linear;
49 }
50
51 snGradSchemes
52 {
53 default corrected;
54 }
55
56
57 // ************************************************************************* //
The example shows fvSchemes with 6 . . . Schemes subdictionaries, each containing key-
word entries including: a default entry; other entries for the particular term specified,
e.g. div(phi, k) for ∇ • (Uk). If a default scheme is specified in a particular . . . Schemes
sub-dictionary, it is assigned to all of the terms to which the sub-dictionary refers, e.g.
specifying a default in gradSchemes sets the scheme for all gradient terms in the appli-
cation, e.g. ∇p, ∇U. With a default specified, the specific terms are not required in
that sub-dictionary, i.e. the entries for grad(p), grad(U) are omitted in this example.
Specifying a particular will however override the default scheme.
The user can specify no default scheme by the none entry, as in the divSchemes in
the example above. The user is then obliged to specify all terms in that sub-dictionary
individually. Setting default to none ensures the user specifies all terms individually
which is common for divSchemes which requires precise configuration.
OpenFOAM includes a vast number of discretisation schemes, from which only a
few are typically recommended for real-world, engineering applications. The user can
get help with scheme selection by interrogating the tutorial cases for example scheme
settings. They should look at the schemes used in relevant cases, e.g. for running a large-
eddy simulation (LES), look at schemes used in tutorials running LES. Additionally,
foamSearch is a useful tool to list the schemes used in all the tutorials. For example,
OpenFOAM-11
U-110 OpenFOAM cases
to print all the default entries for ddtSchemes for cases in the $FOAM_TUTORIALS
directory, the user can type:
which returns:
default backward;
default CrankNicolson 0.9;
default Euler;
default localEuler;
default none;
default steadyState;
The schemes listed using foamSearch are described in the following sections.
generally ψ = 0.9 is used to stabilise the scheme for practical engineering problems.
Any second time derivative (∂ 2 /∂t2 ) terms are specified in the d2dt2Schemes sub-
dictionary. Only the Euler scheme is available for d2dt2Schemes.
OpenFOAM-11
4.5 Numerical schemes U-111
The Gauss entry specifies the standard finite volume discretisation with Gaussian inte-
gration which requires the interpolation of values from cell centres to face centres. The
interpolation scheme is then given by the linear entry, meaning linear interpolation or
central differencing.
In some tutorials cases, particular involving poorer quality meshes, the discretisation
of specific gradient terms is then overridden to improve boundedness and stability. The
terms that are overridden in those cases are the velocity gradient
They use the cellLimited scheme which limits the gradient such that when cell values
are extrapolated to faces using the calculated gradient, the face values do not fall outside
the bounds of values in surrounding cells. A limiting coefficient is specified after the
underlying scheme for which 1 guarantees boundedness and 0 applies no limiting; 1 is
invariably used.
Other schemes that are rarely used are as follows.
The treatment of advective terms is one of the major challenges in CFD numerics and
so the options are more extensive. The keyword identifier for the advective terms are
usually of the form div(phi,...), where phi denotes the (volumetric) flux of velocity
on the cell faces for constant-density flows and the mass flux for compressible flows,
e.g. div(phi,U) for the advection of velocity, div(phi,e) for the advection of internal
energy, etc. For advection of velocity, the user can run the foamSearch script to extract
the div(phi,U) keyword from all tutorials.
OpenFOAM-11
U-112 OpenFOAM cases
The schemes are all based on Gauss integration, using the flux phi and the advected
field being interpolated to the cell faces by one of a selection of schemes, e.g. linear,
linearUpwind, etc. There is a bounded variant of the discretisation, discussed later.
Ignoring ‘V’-schemes (with keywords ending “V”), and rarely-used schemes such as
Gauss cubic and vanLeerV, the interpolation schemes used in the tutorials are as follows.
• linear: second order, unbounded.
• linearUpwind: second order, upwind-biased, unbounded (but much less so than
linear), that requires discretisation of the velocity gradient to be specified.
• LUST: blended 75% linear/ 25%linearUpwind scheme, that requires discretisation
of the velocity gradient to be specified.
• limitedLinear: linear scheme that limits towards upwind in regions of rapidly
changing gradient; requires a coefficient, where 1 is strongest limiting, tending to-
wards linear as the coefficient tends to 0.
• upwind: first-order bounded, generally too inaccurate for velocity but more often
used for transport of scalar fields.
Example syntax for these schemes is as follows.
‘V’-schemes are specialised versions of schemes designed for vector fields. They differ
from conventional schemes by calculating a single limiter which is applied to all compo-
nents of the vectors, rather than calculating separate limiters for each component of the
vector. The ‘V’-schemes’ single limiter is calculated based on the direction of most rapidly
changing gradient, resulting in the strongest limiter being calculated which is most stable
but arguably less accurate. Example syntax is as follows.
The bounded variants of schemes relate to the treatment of the material time derivative
which can be expressed in terms of a spatial time derivative and convection, e.g. for field
e in incompressible flow
De ∂e ∂e
= + U • ∇e = + ∇ • (Ue) − (∇ • U)e (4.1)
Dt ∂t ∂t
For numerical solution of incompressible flows, ∇ • U = 0 at convergence, at which point
the third term on the right hand side is zero. Before convergence is reached, however,
∇ • U ̸= 0 and in some circumstances, particularly steady-state simulations, it is better
to include the third term within a numerical solution to help maintain boundedness of
the solution variable and promote better convergence. The bounded variant of the Gauss
scheme provides this, automatically including the discretisation of the third-term with the
advection term. Example syntax is as follows, as seen in fvSchemes files for steady-state
cases.
OpenFOAM-11
4.5 Numerical schemes U-113
The schemes used for advection of scalar fields are similar to those for advection
of velocity, although in general there is greater emphasis placed on boundedness than
accuracy when selecting the schemes. For example, a search for schemes for advection of
internal energy (e) reveals the following.
In comparison with advection of velocity, there are no cases set up to use linear. The
limitedLinear and upwind schemes are commonly used, with the additional appearance
of vanLeer, another limited scheme, with less strong limiting than limitedLinear.
There are specialised versions of the limited schemes for scalar fields that are commonly
bounded between 0 and 1, e.g. the laminar flame speed regress variable b. A search for
the discretisation used for advection in the laminar flame transport equation yields:
OpenFOAM-11
U-114 OpenFOAM cases
default corrected;
default limited corrected 0.33;
default limited corrected 0.5;
default orthogonal;
default uncorrected;
The basis of the gradient calculation at a face is to subtract the value at the cell
centre on one side of the face from the value in the centre on the other side and divide
by the distance. The calculation is second-order accurate for the gradient normal to the
face if the vector connecting the cell centres is orthogonal to the face, i.e. they are at
right-angles. This is the orthogonal scheme.
Orthogonality requires a regular mesh, typically aligned with the Cartesian co-ordinate
system, which does not generally occur with real world, engineering geometries. Therefore,
to maintain second-order accuracy, an explicit non-orthogonal correction can be added to
the orthogonal component, known as the corrected scheme. The correction increases in
size as the non-orthogonality, i.e. the angle α between the cell-cell vector and face normal
vector, increases.
As α tends towards 90◦ , typically beyond 75◦ , the explicit correction can be so large to
cause a solution to go unstable. The solution can be stabilised by applying the limited
scheme to the correction which requires a coefficient ψ, 0 ≤ ψ ≤ 1 where
0 corresponds to uncorrected,
0.333 non-orthogonal correction ≤ 0.5 × orthogonal part,
ψ= (4.2)
0.5 non-orthogonal correction ≤ orthogonal part,
1 corresponds to corrected.
Typically, psi is chosen to be 0.33 or 0.5, where 0.33 offers greater stability and 0.5 greater
accuracy.
The corrected scheme applies under-relaxation in which the implicit orthogonal cal-
culation is increased by cos−1 α, with an equivalent boost within the non-orthogonal cor-
rection. The uncorrected scheme is equivalent to the corrected scheme, without the
non-orthogonal correction, so is like orthogonal but with the additional cos−1 α under-
relaxation.
Generally the uncorrected and orthogonal schemes are only recommended for meshes
with very low non-orthogonality (e.g. maximum 5◦ ). The corrected scheme is generally
recommended, but for maximum non-orthogonality above 75◦ , limited may be required.
At non-orthogonality above 85◦ , convergence is generally hard to achieve.
OpenFOAM-11
4.6 Solution and algorithm control U-115
The user can search for the default scheme for laplacianSchemes in all the cases in the
$FOAM_TUTORIALS directory.
In all cases, the linear interpolation scheme is used for interpolation of the diffusiv-
ity. The cases uses the same array of snGradSchemes based on the maximum non-
orthogonality in the mesh, as described in section 4.5.4.
OpenFOAM-11
U-116 OpenFOAM cases
27 }
28
29 pFinal
30 {
31 $p;
32 relTol 0;
33 }
34
35 "(U|k|epsilon)"
36 {
37 solver smoothSolver;
38 smoother symGaussSeidel;
39 tolerance 1e-05;
40 relTol 0.1;
41 }
42
43 "(U|k|epsilon)Final"
44 {
45 $U;
46 relTol 0;
47 }
48 }
49
50 PIMPLE
51 {
52 nNonOrthogonalCorrectors 0;
53 nCorrectors 2;
54 }
55
56
57 // ************************************************************************* //
OpenFOAM-11
4.6 Solution and algorithm control U-117
The solvers distinguish between symmetric matrices and asymmetric matrices. The sym-
metry of the matrix depends on the terms of the equation being solved, e.g. time deriva-
tives and Laplacian terms form coefficients of a symmetric matrix, whereas an advective
derivative introduces asymmetry. If the user specifies a symmetric solver for an asymmet-
ric matrix, or vice versa, an error message will be written to advise the user accordingly,
e.g.
• the ratio of current to initial residuals falls below the solver relative tolerance,
relTol;
The solver tolerance should represent the level at which the residual is small enough
that the solution can be deemed sufficiently accurate. The solver relative tolerance limits
the relative improvement from initial to final solution. In transient simulations, it is usual
to set the solver relative tolerance to 0 to force the solution to converge to the solver
tolerance in each time step. The tolerances, tolerance and relTol must be specified in
the dictionaries for all solvers; maxIter is optional and defaults to a value of 1000.
Equations are very often solved multiple times within one solution step, or time step.
For example, when using the PIMPLE algorithm, a pressure equation is solved according
to the number specified by nCorrectors, as described in section 4.6.7. Where this occurs,
the solver is very often set up to use different settings when solving the particular equation
for the final time, specified by a keyword that adds Final to the field name. For example,
OpenFOAM-11
U-118 OpenFOAM cases
in the transient pitzDaily example for the incompressibleFluid solver, the solver settings for
pressure are as follows.
p
{
solver GAMG;
tolerance 1e-07;
relTol 0.01;
smoother DICGaussSeidel;
}
pFinal
{
$p;
relTol 0;
}
If the case is specified to solve pressure 4 times within one time step, then the first 3
solutions would use the settings for p with relTol of 0.01, so that the cost of solving each
equation is relatively low. Only when the equation is solved the final (4th) time, it solves
to a residual level specified by tolerance (since relTol is 0, effectively deactivating it)
for greater accuracy, but at greater cost.
OpenFOAM-11
4.6 Solution and algorithm control U-119
OpenFOAM-11
U-120 OpenFOAM cases
• No specified α: no under-relaxation.
An optimum choice of α is one that is small enough to ensure stable computation but
large enough to move the iterative process forward quickly; values of α as high as 0.9
can ensure stability in some cases and anything much below, say, 0.2 can be prohibitively
restrictive in slowing the iterative process.
Relaxation factors for under-relaxation of fields are specified within a field sub-dictionary;
relaxation factors for equation under-relaxation are within a equations sub-dictionary. An
example is shown below from a case with the incompressibleFluid solver module running
in steady-state mode. The factors are specified for pressure p, pressure U, and turbulent
fields grouped using a regular expression.
54 relaxationFactors
55 {
56 fields
57 {
58 p 0.3;
59 }
60 equations
61 {
62 U 0.7;
63 "(k|omega|epsilon).*" 0.7;
64 }
65 }
66
67 // ************************************************************************* //
For a transient case with the incompressibleFluid module, under-relaxation would simply
slow convergence of the solution within each time step. Instead, the following setting is
generally adopted to ensure diagonal equality which is generally required for convergence
of a matrix equation.
60 relaxationFactors
61 {
62 equations
63 {
64 ".*" 1;
65 }
66 }
67
68
69 // ************************************************************************* //
OpenFOAM-11
4.7 Case management tools U-121
Within in time, or solution, step, the algorithms solve a pressure equation, to enforce mass
conservation, with an explicit correction to velocity to satisfy momentum conservation.
They optionally begin each step by solving the momentum equation — the so-called
momentum predictor.
While all the algorithms solve the same governing equations (albeit in different forms),
the algorithms principally differ in how they loop over the equations. The looping is
controlled by input parameters that are listed below. They are set in a dictionary named
after the algorithm, i.e. SIMPLE, or PIMPLE.
• nCorrectors: used by PIMPLE, sets the number of times the algorithm solves the
pressure equation and momentum corrector in each step; typically set to 2 or 3.
OpenFOAM-11
U-122 OpenFOAM cases
foamListTimes -rm
The foamCleanCase script aims to reset the case files to their original state, removing
all files generated during a workflow including the meshing, post-processing. It deletes
directories including: postProcessing and VTK; the constant/polyMesh directory; processor
directories from parallel decomposition; and, dynamicCode for run-time compiled code.
The script is simply run as follows.
foamCleanCase
The foamCloneCase script creates a new case, by copying the 0, system and constant
directories from an existing case. The copied case is ready to run since the mesh is
copied through the constant directory. If the original case is set up to run in parallel, the
processor directories can also be copied using the -processor option. The basic command
is executed simply as follows, where oldCase refers to an existing case directory.
foamCloneCase oldCase newCase
foamDictionary system/fvSchemes
Without options, the utility prints the entries from the file, removing comments, e.g. as
follows for the fvSchemes file in the pitzDailySteady tutorial case.
FoamFile
{
format ascii;
class dictionary;
location "system";
object fvSchemes;
}
ddtSchemes
{
default steadyState;
}
gradSchemes
{
default Gauss linear;
grad(U) cellLimited Gauss linear 1;
}
divSchemes
{
default none;
div(phi,U) bounded Gauss linearUpwind grad(U);
turbulence bounded Gauss limitedLinear 1;
div(phi,k) $turbulence;
div(phi,epsilon) $turbulence;
div(phi,omega) $turbulence;
div(phi,v2) $turbulence;
div((nuEff*dev2(T(grad(U))))) Gauss linear;
div(nonlinearStress) Gauss linear;
}
OpenFOAM-11
4.7 Case management tools U-123
laplacianSchemes
{
default Gauss linear corrected;
}
interpolationSchemes
{
default linear;
}
snGradSchemes
{
default corrected;
}
The output includes the macros before expansion, indicated by the $ symbol, e.g. $tur-
bulence. The macros can be expanded by the -expand option as shown below
The -entry option prints the entry for a particular keyword, expanding the macros
by default, e.g. divSchemes in the example below
The “/” syntax allows access to keywords with levels of sub-dictionary. For example,
the div(phi,U) keyword can be accessed within the divSchemes sub-dictionary by the
following command.
The example removes the keyword and terminating semicolon, leaving just the data.
bounded Gauss linearUpwind grad(U)
The -keywords option prints only the keywords.
OpenFOAM-11
U-124 OpenFOAM cases
default
div(phi,U)
div(phi,k)
div(phi,epsilon)
div(phi,omega)
div(phi,v2)
div((nuEff*dev2(T(grad(U)))))
div(nonlinearStress)
foamDictionary can set entries with the -set option. If the user wishes to change the
div(phi,U) to the upwind scheme, they can enter the following.
An alternative “=” syntax can be used with the -set option which is particularly useful
when modifying multiple entries:
foamDictionary can add entries with the -add option. If the user wishes to add an
entry named turbulence to divSchemes with the upwind scheme, they can enter the
following.
The search shows GAMG to be the most common choice in all the tutorials.
64 solver GAMG;
2 solver PBiCGStab;
26 solver PCG;
5 solver smoothSolver;
OpenFOAM-11
4.7 Case management tools U-125
run
cp -r $FOAM_TUTORIALS/modules/incompressibleFluid/pitzDailySteady .
The mesh is generated for the case by going into the case directory and running blockMesh:
cd pitzDailySteady
blockMesh
The user might decide before running the simulation to configure some automatic post-
processing as described in section 7.2. The user can list the pre-configured function objects
by the following command.
foamPostProcess -list
From the output, the user could select the patchFlowRate function to monitor the flow
rate at the outlet patch. The patchFlowRate configuration file can be copied into the
system directory using foamGet:
foamGet patchFlowRate
In order to monitor the flow through the outlet patch, the patch entry in patchFlowRate
file should be set as follows:
patch outlet;
The patchFlowRate configuration is then included in the case by adding to the functions
sub-dictionary in the controlDict file:
functions
{
...
//#includeFunc writeObjects(kEpsilon:G) // existing entry
#includeFunc patchFlowRate
}
OpenFOAM-11
U-126 OpenFOAM cases
foamInfo incompressibleFluid
foamInfo flowRateInletVelocity
The output includes: the location of the source code header file for this boundary con-
dition; the description and usage details from the header file; a list of other models of
the same type, i.e. other boundary conditions; and, a list of example cases that use the
boundary condition. This example is demonstrated in section 2.1.17.
When the user requests information about a model with foamInfo, it attempts to
provide a list of other models in the “family”. For example, if the user requests information
about the kEpsilon turbulence model by
foamInfo kEpsilon
Model
This appears to be the 'kEpsilon' model of the 'RAS' family.
The models in the 'RAS' family are:
+ kEpsilon
+ kOmega
+ kOmega2006
+ kOmegaSST
+ kOmegaSSTLM
+ kOmegaSSTSAS
+ LaunderSharmaKE
+ LRR
+ RAS
+ realizableKE
+ RNGkEpsilon
+ SpalartAllmaras
+ SSG
+ v2f
It provides fairly complete lists for fvModels and fvConstraints, which can be demonstrated
by typing the following commands.
foamInfo clouds
foamInfo limitTemperature
It also lists options used in input files, e.g. for Function1 entries in boundary conditions,
searchableSurface entries in the configuration of snappyHexMesh. Users could try searching
for specific models within those families or the families themselves, e.g.
foamInfo linearRamp
foamInfo triSurfaceMesh
foamInfo Function1
foamInfo searchableSurfaces
OpenFOAM-11
4.7 Case management tools U-127
All the selection tables in OpenFOAM are listed by running foamToC with the -tables
option as shown below.
foamToC -tables
foamToC
OpenFOAM-11
U-128 OpenFOAM cases
By default foamToC loads all the libraries in OpenFOAM to produce a complete list of
tables. The user can control the libraries that are loaded with the following options.
• -noLibs: only loads the core libOpenFOAM.so library by default.
• -solver <solver>: only loads libraries associated with the specified solver module
<solver>.
BirdCarreau is in table
generalisedNewtonianViscosityModel libmomentumTransportModels.so
Having identified the table, the user can then list its contents using the -table option.
If the user wished to list the solver modules, they can run
foamToC -solvers
With turbulence models, a search for kEpsilon lists the following set of tables (the
corresponding libraries are not shown here).
kEpsilon is in table
RAS
RAScompressibleMomentumTransportModel
RASincompressibleMomentumTransportModel
RASphaseCompressibleMomentumTransportModel
RASphaseIncompressibleMomentumTransportModel
OpenFOAM-11
4.7 Case management tools U-129
The output indicates the model exists in different tables corresponding to both incom-
pressible and compressible flows, and both single phase and multi-phase flows (phase
indicates multi-phase in the table name). For single phase, incompressible flows, the
available RAS turbulence models can be listed as follows.
OpenFOAM-11
U-130 OpenFOAM cases
OpenFOAM-11
Chapter 5
This chapter describes all topics relating to the creation of meshes in OpenFOAM: sec-
tion 5.1 gives an overview of the way a mesh is be described in OpenFOAM; section 5.2
lists the basic data files that describe a mesh; section 5.3 discusses mesh boundaries and
introduces boundary conditions; section 5.4 covers the blockMesh utility for generating
simple meshes of blocks of hexahedral cells; section 5.5 covers the snappyHexMesh util-
ity for generating complex meshes of hexahedral and split-hexahedral cells automatically
from triangulated surface geometries; section 5.6 describes the options for conversion of
a mesh that has been generated by a third-party product into a format that OpenFOAM
can read.
• Internal faces, which connect two cells (and it can never be more than two). For
each internal face, the ordering of the point labels is such that the face normal
U-132 Mesh generation and conversion
2
3
Sf
4
0
Figure 5.1: Face area vector from point numbering on the face
points into the cell with the larger label, i.e. for cells labelled ‘2’ and ‘5’, the normal
points into ‘5’.
• Boundary faces, which belong to one cell since they coincide with the boundary
of the domain. A boundary face is therefore addressed by one cell(only) and a
boundary patch. The ordering of the point labels is such that the face normal
points outside of the computational domain.
A cell is a list of faces in arbitrary order. Under normal circumstances, cells must
have the properties listed below.
• The cells must be contiguous,i.e. completely cover the computational domain and
must not overlap one another.
• Every cell must be closed geometrically, such that when all face area vectors are
oriented to point outwards of the cell, their sum should equal the zero vector to
machine accuracy;
• Every cell must be closed topologically such that all the edges in a cell are used by
exactly two faces of the cell in question.
The boundary is formed by the boundary faces. It should be closed, i.e. the sum all
boundary face area vectors equates to zero to machine tolerance. It is split into regions
known as patches so that different boundary conditions can be applied to different parts
of the boundary. A patch is defined by the labels of the faces it contains.
OpenFOAM-11
5.3 Mesh boundary U-133
points a list of vectors describing the cell vertices, where the first vector in the list repre-
sents vertex 0, the second vector represents vertex 1, etc.;
faces a list of faces, each face being a list of indices to vertices in the points list, where
again, the first entry in the list represents face 0, etc.;
owner a list of owner cell labels, starting with the owner cell of face 0, then 1, 2, . . .
boundary a list of patches, containing a dictionary entry for each patch, declared using
the patch name.
Critically, the faces list is ordered so that all internal faces are listed first, followed by the
boundary faces. The boundary faces are themselves ordered so that they begin with the
faces in the first patch, followed by the second, etc. As a consequence the patch entries
in the boundary file are very compact, e.g.
inlet
{
type patch;
nFaces 30;
startFace 24170;
}
Due to the face ordering, the patch faces are simply described by: startFace, the index
into the face list of the first face in the patch; and, nFaces, the number of faces in the
patch.
OpenFOAM-11
U-134 Mesh generation and conversion
38 bottom
39 {
40 type symmetryPlane;
41 inGroups List<word> 1(symmetryPlane);
42 nFaces 60;
43 startFace 3630;
44 }
45 frontAndBack
46 {
47 type empty;
48 inGroups List<word> 1(empty);
49 nFaces 3600;
50 startFace 3690;
51 }
52 )
53
54 // ************************************************************************* //
A type entry is specified for every patch (inlet, outlet, etc.), with types assigned that
include patch, wall, symmetryPlane and empty. Some patches also include an inGroups
entry which is discussed in section 5.3.6.
OpenFOAM-11
5.3 Mesh boundary U-135
wedge patch 2
wedge patch 1
There is then a symmetry condition, which can be applied to any patch, including those
that are non-planar.
OpenFOAM-11
U-136 Mesh generation and conversion
top
{
type wall;
inGroups List<word> 1(wall);
nFaces 60;
startFace 3510;
}
The inGroups entry is optional. It specifies one or more patch groups to which a patch
can belong. A patch group is specified by a name which the user can choose. Group names
can be used to specify boundary conditions in field files, simplifying the configuration.
For example, if all inlet patches can be included in an inlet group, then one inlet entry
can specify a boundary condition for all the patches.
Every non-generic patch, i.e. one which is not patch type, is included in a patch group
of the same name as its type. For example, a patch of type wall is included in a wall
group, one of type symmetry is included in a symmetry group, etc. The use of group names
to specify boundary conditions in described further in chapter 6.
foamInfo -a symmetryPlane
The next example searches for snappyHexMeshDict files that specify the wall condition.
OpenFOAM-11
5.4 Mesh generation with the blockMesh utility U-137
• blocks: ordered list of vertex labels and mesh size, see section 5.4.4.
vertices
(
( 0 0 0 ) // vertex number 0
( 1 0 0.1) // vertex number 1
( 1.1 1 0.1) // vertex number 2
( 0 1 0.1) // vertex number 3
(-0.1 -0.1 1 ) // vertex number 4
( 1.3 0 1.2) // vertex number 5
( 1.4 1.1 1.3) // vertex number 6
( 0 1 1.1) // vertex number 7
);
The convertToMeters keyword specifies a scaling factor by which all vertex coordinates
in the mesh description are multiplied. For example,
convertToMeters 0.001;
means that all coordinates are multiplied by 0.001, i.e. the values quoted in the blockMesh-
Dict file are in mm.
OpenFOAM-11
U-138 Mesh generation and conversion
edges
(
arc 1 5 (1.1 0.0 0.5)
);
For the angle and axis specification of an arc, the syntax is of the form:
edges
(
arc 1 5 25 (0 1 0) // 25 degrees, y-normal
);
• vertices 5,6 and 7 are similarly found by moving in the x3 direction from vertices
1,2 and 3 respectively.
OpenFOAM-11
5.4 Mesh generation with the blockMesh utility U-139
7 2 6
6
7
5
4 3
10
11
9
8
3 1
2
x3 4 5
x2
0 x1 0 1
blocks
(
hex (0 1 2 3 4 5 6 7) // vertex numbers
(10 10 10) // numbers of cells in each direction
simpleGrading (1 2 3) // cell expansion ratios
);
It begins with the shape identifier of the block (defined in the $FOAM_ETC/cellModels
file). The shape is always hex since the blocks are always hexahedra. The list of vertex
numbers follows, ordered in the manner described above.
The second entry gives the number of cells in each of the x1 x2 and x3 directions for
that block. The third entry gives the cell expansion ratios for each direction in the block.
The expansion ratio enables the mesh to be graded, or refined, in specified directions. The
ratio is that of the width of the end cell δe along one edge of a block to the width of the
start cell δs along that edge, as shown in Figure 5.4.
There are two types of grading specification available in blockMesh. The most common
one is simpleGrading which specifies uniform expansions in the local x1 , x2 and x3
directions respectively with only 3 expansion ratios, e.g.
simpleGrading (1 2 3)
The more complex alternative is edgeGrading. This full cell expansion description gives
a ratio for each edge of the block, numbered according to the scheme shown in Figure 5.3
with the arrows representing the direction from first cell. . . to last cell e.g.
edgeGrading (1 1 1 1 2 2 2 2 3 3 3 3)
This example is directly equivalent to the simpleGrading example given above because
it uses a ratio of cell widths of 1 along edges 0-3, 2 along edges 4-7 and 3 along 8-11. Note
that it is possible to generate blocks with fewer than 8 vertices by collapsing one or more
pairs of vertices on top of each other, as described in section 5.4.10.
OpenFOAM-11
U-140 Mesh generation and conversion
δe
δs Expansion ratio = δe
δs
Expansion direction
Figure 5.4: Mesh grading along a block edge
blocks
(
hex (0 1 2 3 4 5 6 7) (100 300 100)
simpleGrading (1 2 3);
);
blocks
(
hex (0 1 2 3 4 5 6 7) (100 300 100)
simpleGrading
(
1 // x-direction expansion ratio
(
(0.2 0.3 4) // 20% y-dir, 30% cells, expansion = 4
(0.6 0.4 1) // 60% y-dir, 40% cells, expansion = 1
(0.2 0.3 0.25) // 20% y-dir, 30% cells, expansion = 0.25 (1/4)
)
3 // z-direction expansion ratio
)
);
OpenFOAM-11
5.4 Mesh generation with the blockMesh utility U-141
Both the fraction of the block and the fraction of the cells are normalized automatically.
They can be specified as percentages, fractions, absolute lengths, etc. and do not need to
sum to 100, 1, etc. The example above can be specified using percentages, e.g.
blocks
(
hex (0 1 2 3 4 5 6 7) (100 300 100)
simpleGrading
(
1
(
(20 30 4) // 20%, 30%...
(60 40 1)
(20 30 0.25)
)
3
)
);
defaultPatch
{
name frontAndBack;
type empty;
}
In absence of any of these entries a default patch uses the name defaultFaces and type
empty by default. This means that for a 2D, the user has the option to omit block faces
lying in the 2D plane, knowing that they will be collected into an empty patch as required.
Returning to the example block in Figure 5.3, if it has an inlet on the left face, an
output on the right face and the four other faces are walls then the patches could be
defined as follows:
OpenFOAM-11
U-142 Mesh generation and conversion
boundary // keyword
(
inlet // patch name
{
type patch; // patch type for patch 0
faces
(
(0 4 7 3) // block face in this patch
);
} // end of 0th patch definition
walls
{
type wall;
faces
(
(0 1 5 4)
(0 3 2 1)
(3 7 6 2)
(4 5 6 7)
);
}
);
Each block face is defined by a list of 4 vertex numbers. The list can begin with any
vertex but needs to follow a sequence through connecting edges, with no restriction on
the direction.
Where a patch type requires additional data in the resulting boundary file, the data is
simply added in the patch entry in blockMeshDict. For example, with the cyclic patch, the
user must specify the name of the related patch through the neighbourPatch keyword,
e.g.
left
{
type cyclic;
neighbourPatch right;
faces ((0 4 7 3));
}
right
OpenFOAM-11
5.4 Mesh generation with the blockMesh utility U-143
{
type cyclic;
neighbourPatch left;
faces ((1 5 6 2));
}
mergePatchPairs
(
( <masterPatch> <slavePatch> ) // merge patch pair 0
( <masterPatch> <slavePatch> ) // merge patch pair 1
...
)
• the faces of the master patch remain as originally defined, with all vertices in their
original location;
• the faces of the slave patch are projected onto the master patch where there is some
separation between slave and master patch;
• the location of any vertex of a slave face might be adjusted by blockMesh to eliminate
any face edge that is shorter than a minimum tolerance;
• if patches overlap as shown in Figure 5.5, each face that does not merge remains as
an external face of the original patch, on which boundary conditions must then be
applied;
• if all the faces of a patch are merged, then the patch itself will contain no faces and
is removed.
The consequence is that the original geometry of the slave patch will not necessarily be
completely preserved during merging. Therefore in a case, say, where a cylindrical block
is being connected to a larger block, it would be wise to the assign the master patch to the
cylinder, so that its cylindrical shape is correctly preserved. There are some additional
recommendations to ensure successful merge procedures:
OpenFOAM-11
U-144 Mesh generation and conversion
patch 1
patch 2
• in 2 dimensional geometries, the size of the cells in the third dimension, i.e. out of
the 2D plane, should be similar to the width/height of cells in the 2D plane;
• where a patch to be merged shares a common edge with another patch to be merged,
both should be declared as a master patch.
The user can then project vertices, edges and/or faces onto the cylinder surface with the
project keyword using example syntax shown below:
vertices
(
project (-1 -0.1 -1) (cylinder)
project ( 1 -0.1 -1) (cylinder)
...
);
edges
OpenFOAM-11
5.4 Mesh generation with the blockMesh utility U-145
(
project 0 1 (cylinder)
...
);
faces
(
project (0 4 7 3) cylinder
...
);
The use of this functionality is demonstrated in tutorials which can be located by searching
for the project keyword in all the blockMeshDict files by:
When a name is provided for a given entity, it can be used to replace the index. In the
example about, rather than specify the edge using vertex indices 0 and 1, the names v0
and v1 are used.
hex (0 1 2 3 4 5 5 4)
The same applies to the patches with the main consideration that the block face
containing the collapsed vertices, previously (4 5 6 7) now becomes (4 5 5 4). This is
a block face of zero area which creates a patch with no faces in the polyMesh, as the user
can see in a boundary file for such a case. The patch should be specified as empty in the
blockMeshDict and the boundary condition for any fields should consequently be empty
also.
OpenFOAM-11
U-146 Mesh generation and conversion
7 6
4 5
3
2
0 1
Figure 5.6: Creating a wedge shaped block with 6 vertices
blockMesh
Like many utilities, it can also be run using a configuration file named differently from
blockMeshDict. Several examples in the tutorials directory for example use the pitz-
Daily geometry. They use a common blockMesh configuration file named pitzDaily in
the $FOAM_TUTORIALS/resources/blockMesh. The meshes for these cases are generated
using the -dict option by
OpenFOAM-11
5.5 Mesh generation with the snappyHexMesh utility U-147
STL surface
• a background hex mesh which defines the extent of the computational domain and
a base level mesh density; typically generated using blockMesh, discussed in sec-
tion 5.5.2.
The snappyHexMeshDict dictionary includes: switches at the top level that control the
various stages of the meshing process; and, individual sub-directories for each process.
The entries are listed below.
OpenFOAM-11
U-148 Mesh generation and conversion
• the cell aspect ratio should be approximately 1, at least near surfaces at which
the subsequent snapping procedure is applied, otherwise the convergence of the
snapping procedure is slow, possibly to the point of failure;
• there must be at least one intersection of a cell edge with the tri-surface, i.e. a mesh
of one cell will not work.
OpenFOAM-11
5.5 Mesh generation with the snappyHexMesh utility U-149
• insidePoint: location vector inside the region to be meshed; vector must not
coincide with a cell face either before or during refinement.
The splitting process begins with cells being selected according to specified edge fea-
tures first within the domain as illustrated in Figure 5.9. The features list in the
castellatedMeshControls sub-dictionary permits dictionary entries containing a name of an
edgeMesh file and the level of refinement, e.g.:
features
(
{
file "features.eMesh"; // file containing edge mesh
level 2; // level of refinement
}
);
OpenFOAM-11
U-150 Mesh generation and conversion
The edgeMesh containing the features can be extracted from the tri-surface file using the
surfaceFeatures utility which specifies the tri-surface and controls such as included angle
through a surfaceFeaturesDict configuration file, examples of which can be found in several
tutorials and at $FOAM_ETC/caseDicts/surface/surfaceFeaturesDict. The utility is simply
run by executing the following in a terminal
surfaceFeatures
Following feature refinement, cells are selected for splitting in the locality of specified
surfaces as illustrated in Figure 5.10. The refinementSurfaces dictionary in castel-
latedMeshControls requires dictionary entries for each STL surface and a default level
specification of the minimum and maximum refinement in the form (<min> <max>).
The minimum level is applied generally across the surface; the maximum level is ap-
plied to cells that can see intersections that form an angle in excess of that specified by
resolveFeatureAngle.
The refinement can optionally be overridden on one or more specific region of an STL
surface. The region entries are collected in a regions sub-dictionary. The keyword for
each region entry is the name of the region itself and the refinement level is contained
within a further sub-dictionary. An example is given below:
refinementSurfaces
{
duct
{
level (2 2); // default (min max) refinement for whole surface
regions
{
leftOpening
{
level (3 3); // optional refinement for secondSolid region
}
}
}
}
OpenFOAM-11
5.5 Mesh generation with the snappyHexMesh utility U-151
• distance refines according to distance to the surface; and can accommodate differ-
ent levels at multiple distances with the levels keyword.
For the refinementRegions, the refinement level is specified by the level keyword
for inside and outside refinement. For distance refinement, the keyword is levels
OpenFOAM-11
U-152 Mesh generation and conversion
(plural!) which contains list of entries with the format (<distance> <level>). Exam-
ples are shown below:
refinementRegions
{
box
{
mode inside;
level 4; // refinement level 4
}
sphere
{ // refinement level 5 within 1.0 m
mode distance; // refinement level 3 within 2.0 m
levels ((1.0 5) (2.0 3)); // levels must be ordered nearest first
}
}
The example shows a refinement region inside the pipeWall surface in which a maximum
2 levels of refinement is guaranteed within a specified distance of 1000 from the wall. The
span-based refinement, specified by the insideSpan mode, enables the user to guarantee
at least 40 cellsAcrossSpan, i.e. across the pipe diameter.
OpenFOAM-11
5.5 Mesh generation with the snappyHexMesh utility U-153
2. solve for relaxation of the internal mesh with the latest displaced boundary vertices;
4. reduce the displacement of those vertices from their initial value (at 1) and repeat
from 2 until mesh quality is satisfied.
The method uses the settings in the snapControls sub-dictionary in snappyHexMeshDict,
listed below.
• nSmoothPatch: number of patch smoothing iterations before finding correspondence
to surface (typically 3).
2. solve for relaxation of the internal mesh with the latest projected boundary vertices;
3. check if validation criteria are satisfied otherwise reduce the projected thickness and
return to 2; if validation cannot be satisfied for any thickness, do not insert layers;
OpenFOAM-11
U-154 Mesh generation and conversion
5. the mesh is checked again; if the checks fail, layers are removed and we return to 2.
The layer addition procedure uses the settings in the addLayersControls sub-dictionary
in snappyHexMeshDict; entries are listed below. The user has the option of 4 different
layer thickness parameters — expansionRatio, finalLayerThickness, firstLayer-
Thickness, thickness — from which they must specify 2 only; more than 2, and the
problem is over-specified.
• relativeSizes: switch that sets whether the specified layer thicknesses are relative
to undistorted cell size outside layer or absolute.
• expansionRatio: expansion factor for layer mesh, increase in size from one layer
to the next.
• thickness: total thickness of all layers of cells, usually in combination with absolute
sizes according to the
• relativeSizes entry.
• nGrow: number of layers of connected faces that are not grown if points do not get
extruded; helps convergence of layer addition close to features.
OpenFOAM-11
5.5 Mesh generation with the snappyHexMesh utility U-155
• nRelaxedIter: max number of iterations after which the controls in the relaxed sub
dictionary of meshQuality are used (typically 20).
The layers sub-dictionary contains entries for each patch on which the layers are to be
applied and the number of surface layers required. The patch name is used because the
layers addition relates to the existing mesh, not the surface geometry; hence applied to a
patch, not a surface region. An example layers entry is as follows:
layers
{
sphere1_firstSolid
{
nSurfaceLayers 1;
}
maxY
{
nSurfaceLayers 1;
}
}
OpenFOAM-11
U-156 Mesh generation and conversion
• minVol: minimum cell pyramid volume (typically 1e-13, large negative number
disables).
• minArea: minimum face area (typically -1).
• minTwist: minimum face twist (typically 0.05).
• minDeterminant: minimum normalised cell determinant; 1 = hex; ≤ 0 = illegal cell
(typically 0.001).
• minFaceWeight: 0→0.5 (typically 0.05).
• minVolRatio: 0→1.0 (typically 0.01).
• minTriangleTwist: > 0 for Fluent compatibility (typically -1).
• nSmoothScale: number of error distribution iterations (typically 4).
• errorReduction: amount to scale back displacement at error points (typically 0.75).
• relaxed: sub-dictionary that can include modified values for the above keyword
entries to be used when nRelaxedIter is exceeded in the layer addition process.
5.6.1 fluentMeshToFoam
Fluent writes mesh data to a single file with a .msh extension. The file must be written
in ASCII format, which is not the default option in Fluent. It is possible to convert
single-stream Fluent meshes, including the 2 dimensional geometries. In OpenFOAM, 2
dimensional geometries are currently treated by defining a mesh in 3 dimensions, where
the front and back plane are defined as the empty boundary patch type. When reading
a 2 dimensional Fluent mesh, the converter automatically extrudes the mesh in the third
direction and adds the empty patch, naming it frontAndBackPlanes.
The following features should also be observed.
• The OpenFOAM converter will attempt to capture the Fluent boundary condition
definition as much as possible; however, since there is no clear, direct correspondence
between the OpenFOAM and Fluent boundary conditions, the user should check the
boundary conditions before running a case.
OpenFOAM-11
5.6 Mesh conversion U-157
• Multiple material meshes are not permitted. If multiple fluid materials exist, they
will be converted into a single OpenFOAM mesh; if a solid region is detected, the
converter will attempt to filter it out.
• Fluent allows the user to define a patch which is internal to the mesh, i.e. consists
of the faces with cells on both sides. Such patches are not allowed in OpenFOAM
and the converter will attempt to filter them out.
The procedure of converting a Fluent.msh file is first to create a new OpenFOAM case
by creating the necessary directories/files: the case directory containing a controlDict file
in a system subdirectory. Then at a command prompt the user should execute:
fluentMeshToFoam <meshFile>
where <meshFile> is the name of the .msh file, including the full or relative path.
5.6.2 starToFoam
This section describes how to convert a mesh generated on the STAR-CD code into a form
that can be read by OpenFOAM mesh classes. The mesh can be generated by any of the
packages supplied with STAR-CD, i.e.PROSTAR, SAMM, ProAM and their derivatives.
The converter accepts any single-stream mesh including integral and arbitrary couple
matching and all cell types are supported. The features that the converter does not
support are:
• sliding interfaces.
For multi-stream meshes, mesh conversion can be achieved by writing each individual
stream as a separate mesh and reassemble them in OpenFOAM.
OpenFOAM adopts a policy of only accepting input meshes that conform to the
fairly stringent validity criteria specified in section 5.1. It will simply not run using
invalid meshes and cannot convert a mesh that is itself invalid. The following sections
describe steps that must be taken when generating a mesh using a mesh generating
package supplied with STAR-CD to ensure that it can be converted to OpenFOAM format.
To avoid repetition in the remainder of the section, the mesh generation tools supplied
with STAR-CD will be referred to by the collective name STAR-CD.
We strongly recommend that the user run the STAR-CD mesh checking tools before
attempting a starToFoam conversion and, after conversion, the checkMesh utility should
be run on the newly converted mesh. Alternatively, starToFoam may itself issue warnings
containing PROSTAR commands that will enable the user to take a closer look at cells with
OpenFOAM-11
U-158 Mesh generation and conversion
problems. Problematic cells and matches should be checked and fixed before attempting
to use the mesh with OpenFOAM. Remember that an invalid mesh will not run with
OpenFOAM, but it may run in another environment that does not impose the validity
criteria.
Some problems of tolerance matching can be overcome by the use of a matching
tolerance in the converter. However, there is a limit to its effectiveness and an apparent
need to increase the matching tolerance from its default level indicates that the original
mesh suffers from inaccuracies.
When mesh generation in is completed, remove any extraneous vertices and compress
the cells boundary and vertex numbering, assuming that fluid cells have been created and
all other cells are discarded. This is done with the following PROSTAR commands:
The CSET should be empty. If this is not the case, examine the cells in CSET and adjust
the model. If the cells are genuinely not desired, they can be removed using the PROSTAR
command:
CDEL CSET
Before discarding these unwanted vertices, the unwanted boundary faces have to be col-
lected before purging:
If the BSET is not empty, the unwanted boundary faces can be deleted using:
BDEL BSET
At this time, the model should contain only the fluid cells and the supporting vertices,
as well as the defined boundary faces. All boundary faces should be fully supported by the
vertices of the cells, if this is not the case, carry on cleaning the geometry until everything
is clean.
By default, STAR-CD assigns wall boundaries to any boundary faces not explicitly
associated with a boundary region. The remaining boundary faces are collected into a
default boundary region, with the assigned boundary type 0. OpenFOAM deliberately
does not have a concept of a default boundary condition for undefined boundary faces
since it invites human error, e.g. there is no means of checking that we meant to give all
the unassociated faces the default condition.
Therefore all boundaries for each OpenFOAM mesh must be specified for a mesh to
be successfully converted. The default boundary needs to be transformed into a real
one using the procedure described below:
OpenFOAM-11
5.6 Mesh conversion U-159
2. Define an extra boundary region with the same parameters as the default region
0 and add all visible faces into the new region, say 10, by selecting a zone option
in the boundary tool and drawing a polygon around the entire screen draw of the
model. This can be done by issuing the following commands in PROSTAR:
RDEF 10 WALL
BZON 10 ALL
3. We shall remove all previously defined boundary types from the set. Go through
the boundary regions:
CHECK ALL
GEOM
Internal PROSTAR checking is performed by the last two commands, which may reveal
some other unforeseeable error(s). Also, take note of the scaling factor because PROSTAR
only applies the factor for STAR-CD and not the geometry. If the factor is not 1, use the
scalePoints utility in OpenFOAM.
Once the mesh is completed, place all the integral matches of the model into the couple
type 1. All other types will be used to indicate arbitrary matches.
OpenFOAM-11
U-160 Mesh generation and conversion
The components of the computational grid must then be written to their own files. This
is done using PROSTAR for boundaries by issuing the command
BWRITE
by default, this writes to a .23 file (versions prior to 3.0) or a .bnd file (versions 3.0 and
higher). For cells, the command
CWRITE
outputs the cells to a .14 or .cel file and for vertices, the command
VWRITE
outputs to file a .15 or .vrt file. The current default setting writes the files in ASCII
format. If couples are present, an additional couple file with the extension .cpl needs to
be written out by typing:
CPWRITE
After outputting to the three files, exit PROSTAR or close the files. Look through
the panels and take note of all STAR-CD sub-models, material and fluid properties used
– the material properties and mathematical model will need to be set up by creating and
editing OpenFOAM dictionary files.
The procedure of converting the PROSTAR files is first to create a new OpenFOAM
case by creating the necessary directories. The PROSTAR files must be stored within the
same directory and the user must change the file extensions: from .23, .14 and .15 (below
STAR-CD version 3.0), or .pcs, .cls and .vtx (STAR-CD version 3.0 and above); to .bnd,
.cel and .vrt respectively.
The .vrt file is written in columns of data of specified width, rather than free format. A
typical line of data might be as follows, giving a vertex number followed by the coordinates:
If the ordinates are written in scientific notation and are negative, there may be no space
between values, e.g.:
The starToFoam converter reads the data using spaces to delimit the ordinate values and
will therefore object when reading the previous example. Therefore, OpenFOAM includes
a simple script, foamCorrectVrt to insert a space between values where necessary, i.e. it
would convert the previous example to:
OpenFOAM-11
5.6 Mesh conversion U-161
The foamCorrectVrt script should therefore be executed if necessary before running the
starToFoam converter, by typing:
foamCorrectVrt <file>.vrt
The translator utility starToFoam can now be run to create the boundaries, cells and
points files necessary for a OpenFOAM run:
starToFoam <meshFilePrefix>
where <meshFilePrefix> is the name of the prefix of the mesh files, including the full or
relative path. After the utility has finished running, OpenFOAM boundary types should
be specified by editing the boundary file by hand.
5.6.3 gambitToFoam
GAMBIT writes mesh data to a single file with a .neu extension. The procedure of con-
verting a GAMBIT.neu file is first to create a new OpenFOAM case, then at a command
prompt, the user should execute:
gambitToFoam <meshFile>
where <meshFile> is the name of the .neu file, including the full or relative path.
The GAMBIT file format does not provide information about type of the boundary
patch, e.g. wall, symmetry plane, cyclic. Therefore all the patches have been created as
type patch. Please reset after mesh conversion as necessary.
5.6.4 ideasToFoam
OpenFOAM can convert a mesh generated by I-DEAS but written out in ANSYS format
as a .ans file. The procedure of converting the .ans file is first to create a new OpenFOAM
case, then at a command prompt, the user should execute:
ideasToFoam <meshFile>
where <meshFile> is the name of the .ans file, including the full or relative path.
5.6.5 cfx4ToFoam
CFX writes mesh data to a single file with a .geo extension. The mesh format in CFX is
block-structured, i.e. the mesh is specified as a set of blocks with glueing information and
the vertex locations. OpenFOAM will convert the mesh and capture the CFX boundary
condition as best as possible. The 3 dimensional ‘patch’ definition in CFX, containing
information about the porous, solid regions etc. is ignored with all regions being converted
into a single OpenFOAM mesh. CFX supports the concept of a ‘default’ patch, where
each external face without a defined boundary condition is treated as a wall. These faces
are collected by the converter and put into a defaultFaces patch in the OpenFOAM
mesh and given the type wall; of course, the patch type can be subsequently changed.
Like, OpenFOAM 2 dimensional geometries in CFX are created as 3 dimensional
meshes of 1 cell thickness. If a user wishes to run a 2 dimensional case on a mesh created
OpenFOAM-11
U-162 Mesh generation and conversion
by CFX, the boundary condition on the front and back planes should be set to empty;
the user should ensure that the boundary conditions on all other faces in the plane of the
calculation are set correctly. Currently there is no facility for creating an axi-symmetric
geometry from a 2 dimensional CFX mesh.
The procedure of converting a CFX.geo file is first to create a new OpenFOAM case,
then at a command prompt, the user should execute:
cfx4ToFoam <meshFile>
where <meshFile> is the name of the .geo file, including the full or relative path.
• the patch field data is left unaltered unless specified otherwise in the mapFieldsDict
dictionary.
The mapFieldsDict dictionary contain two lists that specify mapping of patch data. The
first list is patchMap that specifies mapping of data between pairs of target and source
patches that are geometrically coincident, as shown in Figure 5.15. The list contains
each pair of names of target patch (first) and source patch (second). The second list is
OpenFOAM-11
5.7 Mapping fields between different geometries U-163
cuttingPatches that contains names of target patches whose values are to be mapped
from the source internal field through which the target patch cuts. In the situation where
the target patch only cuts through part of the source internal field, e.g. bottom left target
patch in our example, those values within the internal field are mapped and those outside
remain unchanged. An example mapFieldsDict dictionary is shown below:
16
17 patchMap (lid movingWall);
18
19 cuttingPatches ();
20
21
22 // ************************************************************************* //
OpenFOAM-11
U-164 Mesh generation and conversion
OpenFOAM-11
Chapter 6
Boundary conditions
Boundary conditions are specified in field files, e.g. p, U, in time directories. The struc-
ture of these files is introduced in sections 2.1.4 and 4.2.8. They include three entries:
dimensions for the dimensional units; internalField for the initial internal field values;
and, boundaryField where the boundary conditions are specified. The boundaryField
requires an entry for each patch in the mesh. The patches are specified in the boundary
file; below is a sample file from a 2D incompressibleFluid example in OpenFOAM.
5
(
outlet
{
type patch;
nFaces 320;
startFace 198740;
}
up
{
type symmetry;
inGroups List<word> 1(symmetry);
nFaces 760;
startFace 199060;
}
hole
{
type wall;
inGroups List<word> 1(wall);
nFaces 1120;
startFace 199820;
}
frontAndBack
{
type empty;
inGroups List<word> 1(empty);
nFaces 200000;
startFace 200940;
}
inlet
{
type patch;
nFaces 320;
startFace 400940;
}
)
U-166 Boundary conditions
Then imagine the following boundaryField for a field, e.g. p, corresponding to the patches
above.
OpenFOAM-11
6.1 Patch selection in field files U-167
boundaryField
{
inlet
{
type zeroGradient;
}
".*Wall"
{
type zeroGradient;
}
outletSmall
{
type fixedValue;
value uniform 1;
}
outlet
{
type fixedValue;
value uniform 0;
}
}
In this example, the inlet field entry is read for the inlet patch, following rule 1 above
(matching patch name). Similarly, the outletSmall entry will be read for the patch of
the same name.
The outletMedium and outletLarge patches do not have matching entries in the field
file, so they instead the outlet entry will be applied (rule 2), since it matches the group
name to which the patches belong. Note that the outletSmall patch does not use the
outlet entry because a matching patch entry takes precedence over a matching group
entry.
Finally, the lowerWall and upperWall match the regular expression ".*Wall". Regu-
lar expressions are described in section 4.2.12; they must be included in double quotations
". . . ". The ".*" component matches any expression (including nothing), so matches the
wall patch names here. The regular expression could use word grouping to provide a more
precise match to the patch names, e.g.
"(lower|upper)Wall"
{
type zeroGradient;
}
Alternatively a patch entry could cover the wall patches taking advantage of the fact that
every non-generic patch is automatically placed in a group of the same name as its type,
as discussed in section 5.3.6. In this case, all wall patches are placed in a group named
wall, so the following entry would be read for both patches.
wall
{
type zeroGradient;
}
OpenFOAM-11
U-168 Boundary conditions
OpenFOAM-11
6.3 Basic boundary conditions U-169
69 {
70 type internal;
71 }
72
73
74 // ************************************************************************* //
The file exploits the fact that a patch which is a geometric constraint is automatically
included in a group of the constraint name, e.g. a symmetry patch is in a group named
symmetry. The entries therefore set a boundary type for each constraint group (to the
name of the group). All constraint conditions are covered by an entry for each condition.
The user can then include this file inside the boundaryField of their field files. Since
the file is in the $FOAM_ETC directory it can be included using the special #includeEtc
directive, e.g. in the boundaryField entry below.
boundaryField
{
inlet
{
type zeroGradient;
}
outlet
{
type fixedValue;
value uniform 0;
}
wall
{
type zeroGradient;
}
#includeEtc "caseDicts/setConstraintTypes"
}
With the setContraintTypes file included in the field files, the only patches that generally
need to be configured are: the generic patches, corresponding to open boundaries; and,
wall patches.
OpenFOAM-11
U-170 Boundary conditions
foamToC -scalarBCs
These produce long lists which the user can scan through. If the user wants more in-
formation of a particular condition, they can run the foamInfo script which provides a
description of the boundary condition and lists example cases where it is used. For ex-
ample, for the totalPressure boundary condition, run the following.
foamInfo totalPressure
In the following sections we will highlight some particular important, commonly used
boundary conditions.
OpenFOAM-11
6.4 Derived boundary conditions U-171
26
27 rightWall
28 {
29 type zeroGradient;
30 }
31
32 lowerWall
33 {
34 type zeroGradient;
35 }
36
37 atmosphere
38 {
39 type inletOutlet;
40 inletValue uniform 0;
41 value uniform 0;
42 }
43
44 defaultFaces
45 {
46 type empty;
47 }
48 }
49
50 // ************************************************************************* //
where the user specifies p0 through the p0 keyword. Solver applications which include
buoyancy effects, though a gravitational force ρg (per unit volume) source term, tend to
solve for a pressure field pρgh = p−ρ|g|∆h, where the hydrostatic component is subtracted
based on a height ∆h above some reference. For such solvers, e.g. interFoam, an equivalent
prghTotalPressure condition is applied which specifies:
p for outflow
0
pρgh = (6.3)
p0 − ρ|g|∆h − 1
ρ|U2 | for inflow (dynamic pressure, subsonic)
2
OpenFOAM-11
U-172 Boundary conditions
16
17 dimensions [0 1 -1 0 0 0 0];
18
19 internalField uniform (0 0 0);
20
21 boundaryField
22 {
23 leftWall
24 {
25 type noSlip;
26 }
27 rightWall
28 {
29 type noSlip;
30 }
31 lowerWall
32 {
33 type noSlip;
34 }
35 atmosphere
36 {
37 type pressureInletOutletVelocity;
38 value uniform (0 0 0);
39 }
40 defaultFaces
41 {
42 type empty;
43 }
44 }
45
46
47 // ************************************************************************* //
16 dimensions [1 -1 -2 0 0 0 0];
17
18 internalField uniform 0;
19
20 boundaryField
21 {
22 leftWall
23 {
24 type fixedFluxPressure;
25 value uniform 0;
26 }
27
28 rightWall
29 {
30 type fixedFluxPressure;
31 value uniform 0;
32 }
33
34 lowerWall
35 {
36 type fixedFluxPressure;
37 value uniform 0;
38 }
39
40 atmosphere
41 {
42 type prghTotalPressure;
43 p0 uniform 0;
44 }
45
46 defaultFaces
47 {
48 type empty;
49 }
50 }
51
52 // ************************************************************************* //
OpenFOAM-11
6.4 Derived boundary conditions U-173
• table: inline list of (time value) pairs; interpolates values linearly between times.
• scale: scales a given value function by a scalar scale function; both entries can be
themselves Function1; scale function is often a ramp function (below), with value
controlling the ramp value.
OpenFOAM-11
U-174 Boundary conditions
}
inlet
{
type uniformFixedValue;
uniformValue
{
type tableFile;
format csv;
nHeaderLine 4; // number of header lines
refColumn 0; // time column index
componentColumns (1); // data column index
separator ","; // optional (defaults to ",")
mergeSeparators no; // merge multiple separators
file "dataTable.csv";
}
}
inlet
{
type uniformFixedValue;
uniformValue
{
type square;
frequency 10;
amplitude 1;
scale 2; // Scale factor for wave
level 1; // Offset
}
}
inlet
{
type uniformFixedValue;
uniformValue
{
type sine;
frequency 10;
amplitude 1;
scale 2; // Scale factor for wave
level 1; // Offset
}
}
input // ramp from 0 -> 2, from t = 0 -> 0.4
{
type uniformFixedValue;
uniformValue
{
type scale;
scale linearRamp;
start 0;
duration 0.4;
value 2;
}
}
input // ramp from 2 -> 0, from t = 0 -> 0.4
{
type uniformFixedValue;
uniformValue
{
type scale;
scale reverseRamp;
ramp linearRamp;
start 0;
duration 0.4;
value 2;
}
}
inlet // pulse with value 2, from t = 0 -> 0.4
{
type uniformFixedValue;
OpenFOAM-11
6.4 Derived boundary conditions U-175
uniformValue
{
type scale;
scale squarePulse
start 0;
duration 0.4;
value 2;
}
}
inlet
{
type uniformFixedValue;
uniformValue coded;
name pulse;
codeInclude
#{
#include "mathematicalConstants.H"
#};
code
#{
return scalar
(
0.5*(1 - cos(constant::mathematical::twoPi*min(x/0.3, 1)))
);
#};
}
OpenFOAM-11
U-176 Boundary conditions
OpenFOAM-11
Chapter 7
Post-processing
ParaView is launched and opens the window shown in Figure 7.1. The case is controlled
from the left panel, which contains the following:
U-178 Post-processing
• The Pipeline Browser lists the modules opened in ParaView, where the selected
modules are highlighted in blue and the graphics for the given module can be en-
abled/disabled by clicking the eye button alongside;
• The Properties panel contains the input selections for the case, such as times, regions
and fields; it includes the Display panel that controls the visual representation of
the selected module, e.g. colours;
• Other panels can be selected from the View menu, including the Information panel
which gives case statistics such as mesh geometry and size.
ParaView operates a tree-based structure in which data can be filtered from the top-
level case module to create sets of sub-modules. For example, a contour plot of, say,
pressure could be a sub-module of the case module which contains all the pressure data.
The strength of ParaView is that the user can create a number of sub-modules and display
whichever ones they need to create the desired image or animation. For example, they
may add some solid geometry, mesh and velocity vectors, to a contour plot of pressure,
switching any of the items on and off as necessary.
The general operation of the system is based on the user making a selection and then
clicking the green Apply button in the Properties panel. The additional buttons are: the
Reset button which can be used to reset the settings if necessary; and, the Delete button
that will delete the active module.
OpenFOAM-11
7.1 ParaView/paraFoam graphical user interface (GUI) U-179
The Properties window for the case module includes the Parameters panel that contains the
settings for mesh, fields and global controls. The controls are described in Figure 7.2. The
user can select mesh and field data which is loaded for all time directories into ParaView.
The buttons in the Current Time Controls and VCR Controls toolbars then select the
time data to be displayed, as shown is section 7.1.4.
As with any operation in ParaView, the user must click Apply after making any changes
to any selections. The Apply button is highlighted in green to alert the user if changes have
been made but not accepted. This method of operation has the advantage of allowing the
user to make a number of selections before accepting them, which is particularly useful
in large cases where data processing is best kept to a minimum.
If new data is written to time directories while the user is running ParaView, the user
must load the additional time directories by checking the Refresh Times button. Where
there are occasions when the case data changes on file and ParaView needs to load the
changes, the user can also toggle the Cache Mesh button in the Parameters panel and
apply the changes.
OpenFOAM-11
U-180 Post-processing
OpenFOAM-11
7.1 ParaView/paraFoam graphical user interface (GUI) U-181
• the image can be made translucent by editing the value in the Opacity text box (1
= solid, 0 = invisible) in the Style panel.
OpenFOAM-11
U-182 Post-processing
levels set by the sliders, allows cases with large numbers of cells to be re-rendered quickly
during manipulation.
The Camera panel includes control settings for 3D and 2D movements. This presents
the user with a map of rotation, translate and zoom controls using the mouse in combi-
nation with Shift- and Control-keys. The map can be edited to suit by the user.
7.1.8 Streamlines
Streamlines are created by first creating tracer lines using the Stream Tracer filter. The
tracer Seed panel specifies a distribution of tracer points over a Line Source or Point
Cloud. The user can view the tracer source, e.g. the line, but it is displayed in white, so
they may need to change the background colour in order to see it.
The distance the tracer travels and the length of steps the tracer takes are specified in
the text boxes in the main Stream Tracer panel. The process of achieving desired tracer
lines is largely one of trial and error in which the tracer lines obviously appear smoother
as the step length is reduced but with the penalty of a longer calculation time.
Once the tracer lines have been created, the Tubes filter can be applied to the Tracer
module to produce high quality images. The tubes follow each tracer line and are not
strictly cylindrical but have a fixed number of sides and given radius. When the number
of sides is set above, say, 10, the tubes do however appear cylindrical, but again this adds
a computational cost.
OpenFOAM-11
7.2 Post-processing command line interface (CLI) U-183
Both approaches have advantages. Conventional post-processing allows the user to choose
how to analyse data after the results are obtained. Run-time processing offers greater
flexibility because it has access to all the data in the database of the run at all times,
rather than just the data written during the simulation. It also allows the user to monitor
processed data during a simulation and provides a greater level of convenience because
the processed results can be available immediately to the user when the simulation ends.
There are 3 methods of post-processing that cover the options described above.
OpenFOAM-11
U-184 Post-processing
• The case can be configured to include run-time processing during the simulation.
foamToC -functionObjects
The list represents the underlying post-processing functionality. Almost all the function-
ality is packaged into a set of configured tools that are conveniently integrated within the
post-processing CLI. Those tools are located in $FOAM_ETC/caseDicts/postProcessing
and are listed by running foamPostProcesswith the -list option.
foamPostProcess -list
functions
{
#includeFunc patchFlowRate
... other function objects here ...
}
That will include the functionality in the patchFlowRate configuration file, located in the
directory hierarchy beginning with $FOAM_ETC/caseDicts/postProcessing.
The configuration of patchFlowRate requires the name of the patch to be supplied.
Option 1 for doing this is that the user copies the patchFlowRate file into their case
system directory. The foamGet script copies the file conveniently, e.g.
foamGet patchFlowRate
The patch name can be edited in the copied file to be outlet. When the solver is run,
it will pick up an included function in the local case system directory, in precedence
over $FOAM_ETC/caseDicts/postProcessing. The flow rate through the patch will be
calculated and written out into a file within a directory named postProcessing.
Option 2 for specifying the patch name is to provide the name as an argument to the
patchFlowRate in the #includeFunc directive, using the syntax keyword=entry.
OpenFOAM-11
7.2 Post-processing command line interface (CLI) U-185
functions
{
#includeFunc patchFlowRate(patch=outlet)
... other function objects here ...
}
In the case where the keyword is field or fields, only the entry is needed when
specifying an argument to a function. For example, if the user wanted to calculate and
write out the magnitude of velocity into time directories during a simulation they could
simply add the following to the functions sub-dictionary in controlDict.
functions
{
#includeFunc mag(U)
... other function objects here ...
}
This works because the function’s argument U is represented by the keyword field, see
$FOAM_ETC/caseDicts/postProcessing/fields/mag.
Some functions require the setting of many parameters, e.g. to calculate forces and
generate elements for visualisation, etc. For those functions, it is more reliable and con-
venient to copy and configure the function using option 1 (above) rather than through
arguments.
run
cp -r $FOAM_TUTORIALS/incompressibleFluid/pitzDailySteady .
cd pitzDaily
./Allrun
Now the user can run execute post-processing functions with foamPostProcess. The -help
option provides a summary of its use.
foamPostProcess -help
Simple functions like mag can be executed using the -func option; text on the command
line generally needs to be quoted (". . . ") if it contains punctuation characters.
OpenFOAM-11
U-186 Post-processing
This operation calculates and writes the field of magnitude of velocity into a file named
mag(U) in each time directory. Similarly, the patchFlowRate example can be executed
using foamPostProcess.
Let us say the user now wants to calculate total pressure = p + |U|2 /2 for incompressible
flow with kinematic pressure, p. The function is available, named totalPressureIncompress-
ible, which requires a rhoInf parameter to be specified. The user could attempt first to
run as follows.
The error message is telling the user that the velocity field U is not loaded. For the
function to work, both the field needs to be loaded using the -field option as follows.
foamPostProcess -func "totalPressureIncompressible(rhoInf=1.2)" -field U
A more complex example is calculating wall shear stress using the wallShearStress
function.
Even loading relevant fields, the post-processing fails with the following message.
The message is telling us that the foamPostProcessutility has not constructed the necessary
models, i.e. a turbulence model, that the incompressibleFluid solver module used when
running the simulation. This is a situation where we need to post-process (as opposed
to run-time process) using the -solver option modelling will be available that the post-
processing function needs.
Note that no fields need to be supplied, e.g. using "-field U", because incompressibleFluid
module constructs and stores the required fields. Functions can also be selected by the
#includeFunc directive in functions in the controlDict file, instead of the -func option.
foamPostProcess -list
OpenFOAM-11
7.3 Post-processing functionality U-187
components Writes the component scalar fields (e.g. Ux, Uy, Uz) of a field (e.g. U).
CourantNo Calculates the Courant Number field from the flux field.
fieldAverage Calculates and writes the time averages of a given list of fields.
flowType Calculates and writes the flowType of velocity field where: -1 = rotational flow;
0 = simple shear flow; +1 = planar extensional flow.
Lambda2 Calculates and writes the second largest eigenvalue of the sum of the square of
the symmetrical and anti-symmetrical parts of the velocity gradient tensor.
MachNo Calculates the Mach Number field from the velocity field.
PecletNo Calculates the Peclet Number field from the flux field.
OpenFOAM-11
U-188 Post-processing
vorticity Calculates the vorticity field, i.e. the curl of the velocity field.
wallHeatFlux Calculates the heat flux at wall patches, outputting the data as a volVec-
torField.
wallShearStress Calculates the shear stress at wall patches, outputting the data as a vol-
VectorField.
writeCellCentres Writes the cell-centres volVectorField and the three component fields as
volScalarFields; useful for post-processing thresholding.
writeVTK Writes out specified objects in VTK format, e.g. fields, stored on the case
database.
yPlus Calculates the turbulence y+, outputting the data as a yPlus field.
divide From the first field, divide the remaining fields in the list.
subtract From the first field, subtracts the remaining fields in the list.
forcesCompressible Calculates pressure and viscous forces over specified patches for a case
where the solver is compressible (pressure is in units M/(LTˆ2), e.g. Pa).
forcesIncompressible Calculates pressure and viscous forces over specified patches for a
case where the solver is incompressible (pressure is kinematic, e.g. mˆ2/sˆ2).
OpenFOAM-11
7.3 Post-processing functionality U-189
graphUniform Writes graph data for specified fields along a line, specified by start and end
points. A specified number of graph points are used, distributed uniformly along
the line.
graphCellFace Writes graph data for specified fields along a line, specified by start and
end points. One graph point is generated on each face and in each cell that the line
intersects.
graphFace Writes graph data for specified fields along a line, specified by start and end
points. One graph point is generated on each face that the line intersects.
graphLayerAverage Generates plots of fields averaged over the layers in the mesh.
stopAtEmptyClouds Stops the run when all clouds are empty, i.e. have no particles.
cellMaxMag Writes out the maximum cell value magnitude for one or more fields.
cellMin Writes out the minimum cell value for one or more fields.
cellMinMag Writes out the maximum cell value magnitude for one or more fields.
OpenFOAM-11
U-190 Post-processing
7.3.8 Control
adjustTimeStepToChemistry Adjusts the time step to a chemistry model’s bulk chemical
time scales
stopAtClockTime Stops the run when the specified clock time in second has been reached
and optionally write results before stopping.
stopAtFile Stops the run when the file stop is created in the case directory.
stopAtTimeStep Stops the run if the time-step drops below the specified value in seconds
and optionally write results before stopping.
time Writes run time, CPU time and clock time and optionally the CPU and clock times
per time step.
writeObjects Writes out specified objects, e.g. fields, stored on the case database.
totalPressureCompressible Calculates the total pressure field in normal units, i.e. Pa in SI,
for a case where the solver is compressible.
totalPressureIncompressible Calculates the total pressure field for a case where the solver
is incompressible, in kinematic units, i.e. m2 /s2 in SI.
7.3.10 Combustion
Qdot Calculates and outputs the heat release rate for the current combustion model.
7.3.11 Multiphase
populationBalanceMoments Calculates and writes out integral (integer moments) or mean
properties (mean, variance, standard deviation) of a size distribution computed with
multiphaseEulerFoam. Requires solver post-processing.
phaseForces Calculates the blended interfacial forces acting on a given phase, i.e. drag,
virtual mass, lift, wall-lubrication and turbulent dispersion. Note that it works only
in solver post-processing mode and in combination with multiphaseEulerFoam. For
a simulation involving more than two phases, the accumulated force is calculated
by looping over all phasePairs the phase is a part of.
OpenFOAM-11
7.3 Post-processing functionality U-191
phaseMap Writes the phase-fraction map field alpha.map with incremental value ranges
for each phase e.g., with values 0 for water, 1 for air, 2 for oil, etc.
wallBoilingProperties Looks up wall boiling wall functions and collects and writes out out
fields of bubble departure diameter, bubble departure frequency, nucleation site
density, effective liquid fraction at the wall, quenching heat flux, and evaporative
heat flux.
7.3.12 Probes
boundaryProbes Writes out values of fields at a cloud of points, interpolated to specified
boundary patches.
interfaceHeight Reports the height of the interface above a set of locations. For each
location, it writes the vertical distance of the interface above both the location and
the lowest boundary. It also writes the point on the interface from which these
heights are computed.
probes Writes out values of fields from cells nearest to specified locations.
faceZoneFlowRate Calculates the flow rate through a specified face zone by summing
the flux on patch faces. For solvers where the flux is volumetric, the flow rate is
volumetric; where flux is mass flux, the flow rate is mass flow rate.
patchDifference Calculates the difference between the average values of fields on two spec-
ified patches. Calculates the average value of one or more fields on a patch.
patchFlowRate Calculates the flow rate through a specified patch by summing the flux on
patch faces. For solvers where the flux is volumetric, the flow rate is volumetric;
where flux is mass flux, the flow rate is mass flow rate.
triSurfaceDifference Calculates the difference between the average values of fields on two
specified triangulated surfaces.
OpenFOAM-11
U-192 Post-processing
7.3.14 Meshing
checkMesh Executes primitiveMesh::checkMesh to check the distortion of moving meshes.
phaseScalarTransport Solves a transport equation for a scalar field within one phase of a
multiphase simulation.
isoSurface Writes out iso-surface files with interpolated field data in VTK format.
patchSurface Writes out patch surface files with interpolated field data in VTK format.
streamlinesLine Writes out files of stream lines with interpolated field data in VTK format,
with initial points uniformly distributed along a line.
streamlinesPatch Writes out files of stream lines with interpolated field data in VTK
format, with initial points randomly selected within a patch.
streamlinesPoints Writes out files of stream lines with interpolated field data in VTK
format, with specified initial points.
streamlinesSphere Writes out files of stream lines with interpolated field data in VTK
format, with initial points randomly selected within a sphere.
• probes identifies the nearest cells to the probe locations and writes out the cell
values; data is written into a single file in time-value format, suitable for plotting a
graph.
OpenFOAM-11
7.4 Sampling and monitoring data U-193
• boundaryProbes and internalProbes interpolate field data to the probe locations, with
the locations being snapped onto boundaries for boundaryProbes; data sets are writ-
ten to separate files at scheduled write times (like fields). data.
Generally probes is more suitable for monitoring values at smaller numbers of locations,
whereas the other functions are typically for sampling at large numbers of locations.
As an example, the user could use the pitzDailySteady case set up in section 2.1. The
probes function is best configured by copying the file to the local system directory using
foamGet.
foamGet probes
The user can modify the probeLocations in the probes file as follows.
12
13 #includeEtc "caseDicts/postProcessing/probes/probes.cfg"
14
15 fields (p U);
16 probeLocations
17 (
18 (0.01 0 0)
19 );
20
21 // ************************************************************************* //
functions
{
#includeFunc probes
... other function objects here ...
}
When the simulation runs, time-value data is written into p and U files in postProcess-
ing/probes/0.
foamGet graphUniform
The start and end points of the line, along which data is sampled, should be edited; the
entries below provide a vertical line across the full height of the geometry 0.01 m beyond
the back step.
14
15 start (0.01 -0.025 0);
16 end (0.01 0.025 0);
17 nPoints 100;
18
19 fields (U p);
20
21 axis distance; // The independent variable of the graph. Can be "x",
22 // "y", "z", "xyz" (all coordinates written out), or
23 // "distance" (from the start point).
24
25 #includeEtc "caseDicts/postProcessing/graphs/graphUniform.cfg"
26
27 // ************************************************************************* //
OpenFOAM-11
U-194 Post-processing
functions
{
#includeFunc graphUniform
... other function objects here ...
}
The simulation can be then re-run or the user could run the post-processing with the
following command.
Either way, distance-value data is written into files in time directories within postProc-
essing/graphUniform. The user can quickly display the data for x-component of velocity,
Ux in the last time e.g. 285, by running gnuplot and plotting values.
gnuplot
gnuplot> set style data linespoints
gnuplot> plot "postProcessing/graphUniform/285/line_U.xy" u 2:1
This produces the graph shown in Figure 7.5. This graph corresponds to the velocity
inlet with a uniform profile, rather than a boundary layer profile. The formatting of the
graph is specified in configuration files in $FOAM_ETC/caseDicts/postProcessing/graphs.
The graphUniform.cfg file in that directory includes the configuration as follows.
8
9 #includeEtc "caseDicts/postProcessing/graphs/graph.cfg"
10
11 sets
12 (
13 line
14 {
15 type lineUniform;
16 axis $axis;
17 start $start;
18 end $end;
19 nPoints $nPoints;
20 }
21 );
22
23 // ************************************************************************* //
OpenFOAM-11
7.4 Sampling and monitoring data U-195
It shows that the sampling type is lineUniform, meaning the sampling uses a uniform
distribution of points along a line. The other parameters are included by macro expansion
from the main file and specify the line start and end, the number of points and the distance
parameter specified on the horizontal axis of the graph.
An alternative graph function object, graphCell, samples the data at locations nearest
to the cell centres. The user can copy that function object file and configure it as shown
below.
13
14 start (0.01 -0.025 0);
15 end (0.01 0.025 0);
16 fields (U p);
17
18 axis distance; // The independent variable of the graph. Can be "x",
19 // "y", "z", "xyz" (all coordinates written out), or
20 // "distance" (from the start point).
21
22 #includeEtc "caseDicts/postProcessing/graphs/graphCell.cfg"
23
24 // ************************************************************************* //
foamGet cutPlaneSurface
The file is configured by setting the origin and normal of the plane and the field data to
be sampled. We can edit the file to produce a cutting plane along the pitzDaily geometry,
normal to the z-direction.
16
17 fields (p U);
18
19 interpolate true; // If false, write cell data to the surface triangles.
20 // If true, write interpolated data at the surface points.
OpenFOAM-11
U-196 Post-processing
21
22 #includeEtc "caseDicts/postProcessing/surface/cutPlaneSurface.cfg"
23
24 // ************************************************************************* //
The function can be included as normal by adding the #includeFunc directive to functions
in the controlDict file. Alternatively, the user could test running the function using the
solver post-processing by the following command.
This produces VTK format files of the cutting plane with pressure and velocity data in
time directories in the postProcessing/cutPlaneSurface directory. The user can display
the cutting plane by opening ParaView (type paraview), then doing File->Open and
selecting one of the files, e.g. postProcessing/cutPlaneSurface/285/U_zNormal.vtk as shown
in Figure 7.7.
functions
{
#includeFunc residuals
... other function objects here ...
}
The default fields whose residuals are captured are p and U. Should the user wish to
configure other fields, they should make copy the residuals file in their system and edit
the fields entry accordingly. All functions files are within the $FOAM_ETC/caseDicts
directory. The residuals file can be located using foamInfo:
foamInfo residuals
It can then be copied into the system directory conveniently using foamGet:
OpenFOAM-11
7.5 Third-Party post-processing U-197
foamGet residuals
The user should then run foamMonitor using the -l option for a log scale y-axis on the
residuals file as follows. If the command is executed before the simulation is complete,
they can see the graph being updated live.
It produces the graph of residuals for pressure and velocity in Figure 7.8.
OpenFOAM-11
U-198 Post-processing
smapToFoam Translates a STAR-CD SMAP data file into OpenFOAM field format.
• converting the OpenFOAM data to EnSight format with the foamToEnsight utility;
• reading the OpenFOAM data directly into EnSight using the ensight74FoamExec
module.
The foamToEnsight utility converts data from OpenFOAM to EnSight file format. For a
given case, foamToEnsight is executed like any normal application. foamToEnsight creates
a directory named Ensight in the case directory, deleting any existing Ensight directory in
the process. The converter reads the data in all time directories and writes into a case file
and a set of data files. The case file is named EnSight_Case and contains details of the
data file names. Each data file has a name of the form EnSight_nn.ext, where nn is an
incremental counter starting from 1 for the first time directory, 2 for the second and so
on and ext is a file extension of the name of the field that the data refers to, as described
in the case file, e.g.T for temperature, mesh for the mesh. Once converted, the data can
be read into EnSight by the normal means:
1. from the EnSight GUI, the user should select Data (Reader) from the File menu;
3. the Format selector should be set to Case, the EnSight default setting;
EnSight provides the capability of using a user-defined module to read data from a
format other than the standard EnSight format. OpenFOAM includes its own reader
module ensightFoamReader that is compiled into a library named libuserd-foam. It is this
library that EnSight needs to use which means that it must be able to locate it on the
filing system as described in the following section.
In order to run the EnSight reader, it is necessary to set some environment variables
correctly. The settings are made in the bashrc (or cshrc) file in the $WM_PROJECT_DIR/-
etc/apps/ensightFoam directory. The environment variables associated with EnSight are
prefixed by $CEI_ or $ENSIGHT7_ and listed in Table 7.1. With a standard user setup,
only $CEI_HOME may need to be set manually, to the path of the EnSight installation.
The principal difficulty in using the EnSight reader lies in the fact that EnSight expects
that a case to be defined by the contents of a particular file, rather than a directory as it
is in OpenFOAM. Therefore in following the instructions for the using the reader below,
the user should pay particular attention to the details of case selection, since EnSight does
not permit selection of a directory name.
1. from the EnSight GUI, the user should select Data (Reader) from the File menu;
2. The user should now be able to select the OpenFOAM from the Format menu; if not,
there is a problem with the configuration described above.
OpenFOAM-11
7.5 Third-Party post-processing U-199
Environment variable
Description and options
$CEI_HOME Path where EnSight is installed, eg /usr/local/ensight, added
to the system path by default
$CEI_ARCH Machine architecture, from a choice of names cor-
responding to the machine directory names in
$CEI_HOME/ensight74/machines; default settings include
linux_2.4 and sgi_6.5_n32
$ENSIGHT7_READER Path that EnSight searches for the user defined libuserd-foam
reader library, set by default to $FOAM_LIBBIN
$ENSIGHT7_INPUT Set by default to dummy
3. The user should find their case directory from the File Selection window, highlight
one of top 2 entries in the Directories box ending in /. or /.. and click (Set)
Geometry.
4. The path field should now contain an entry for the case. The (Set) Geometry text
box should contain a ‘/’.
5. The user may now click Okay and EnSight will begin reading the data.
6. When the data is read, a new Data Part Loader window will appear, asking which
part(s) are to be read. The user should select Load all.
7. When the mesh is displayed in the EnSight window the user should close the Data
Part Loader window, since some features of EnSight will not work with this window
open.
OpenFOAM-11
U-200 Post-processing
OpenFOAM-11
Chapter 8
OpenFOAM includes a large range of solvers, each designed for a specific class of flow,
as described in section 3.6. Each solver uses a particular set of models which calculate
physical properties and simulate phenomena like transport, turbulence, thermal radiation,
etc.
From OpenFOAM v10 onwards, a distinction is made between material properties
and models for phenomena such as those mentioned above. Properties are specified
in physicalProperties file in the constant directory. In the case of fluids, properties in
physicalProperties relate to a fluid at rest. They are the properties you might look up
from a table in a book, so can be dependent on temperature T , based on some function.
Properties described in physicalProperties do not include any dependency on the flow
itself. For example, turbulence, visco-elasticity and the variation of viscosity ν with
strain-rate, are all specified in a momentumTransport file in the constant directory. This
chapter includes a description of models for viscosity which are dependent on strain-rate
in section 8.3 and turbulence models in section 8.2. Thermophysical models, which are
specified in the physicalProperties file (since they represent temperature dependency of
properties) are described in section 8.1.
thermoType
{
type hePsiThermo;
U-202 Models and physical properties
mixture pureMixture;
transport const;
thermo hConst;
equationOfState perfectGas;
specie specie;
energy sensibleEnthalpy;
}
The keyword entries specify the choice of thermophysical models, e.g. transport
constant (constant viscosity, thermal diffusion), equationOfState perfectGas , etc. In
addition there is a keyword entry named energy that allows the user to specify the form
of energy to be used in the solution and thermodynamics. The following sections explains
the entries and options in the thermoType package.
rhoThermo Thermophysical model for liquids and solids, used by the isothermalFilm and
film solver module.
psiThermo Thermophysical model for gases only, with fixed composition, used by the
shockFluid solver module.
OpenFOAM-11
8.1 Thermophysical models U-203
const assumes a constant µ and Prandtl number P r = cp µ/κ which is simply specified
by a two keywords, mu and Pr, respectively.
∑
N −1
µ= ai T i . (8.2)
i=0
logPolynomial calculates ln(µ) and ln(κ) as a function of ln(T ) from a polynomial of any
order N ; from which µ, κ are calculated by taking the exponential, e.g.:
∑
N −1
ln(µ) = ai [ln(T )]i . (8.3)
i=0
tabulated uses uniform tabulated data for viscosity and thermal conductivity as a function
of pressure and temperature.
OpenFOAM-11
U-204 Models and physical properties
icoTabulated uses non-uniform tabulated data for viscosity and thermal conductivity as
a function of temperature.
eConst assumes a constant cv and a heat of fusion Hf which is simply specified by a two
values cv Hf , given by keywords Cv and Hf.
∑
N −1
cv = ai T i . (8.6)
i=0
hConst assumes a constant cp and a heat of fusion Hf which is simply specified by a two
values cp Hf , given by keywords Cp and Hf.
∑
N −1
cp = ai T i . (8.8)
i=0
OpenFOAM-11
8.1 Thermophysical models U-205
OpenFOAM-11
U-206 Models and physical properties
OpenFOAM-11
8.1 Thermophysical models U-207
where ci and hif are the molar fraction and heat of formation, respectively, of specie
i. In most cases, we use the sensible form of energy, for which it is easier to account
for energy change due to reactions. Keyword entries for energy therefore include e.g.
sensibleEnthalpy, sensibleInternalEnergy and absoluteEnthalpy.
specie containing i.e. number of moles, nMoles, of the specie, and molecular weight,
molWeight in units of g/mol;
thermodynamics containing coefficients for the chosen thermodynamic model (see below);
transport containing coefficients for the chosen tranpsort model (see below).
The following is an example entry for a specie named fuel modelled using sutherland
transport and janaf thermodynamics:
fuel
{
specie
{
nMoles 1;
molWeight 16.0428;
}
thermodynamics
{
Tlow 200;
Thigh 6000;
Tcommon 1000;
highCpCoeffs (1.63543 0.0100844 -3.36924e-06 5.34973e-10
-3.15528e-14 -10005.6 9.9937);
lowCpCoeffs (5.14988 -0.013671 4.91801e-05 -4.84744e-08
1.66694e-11 -10246.6 -4.64132);
}
transport
{
As 1.67212e-06;
OpenFOAM-11
U-208 Models and physical properties
Ts 170.672;
}
}
The following is an example entry for a specie named air modelled using const transport
and hConst thermodynamics:
air
{
specie
{
nMoles 1;
molWeight 28.96;
}
thermodynamics
{
Cp 1004.5;
Hf 2.544e+06;
}
transport
{
mu 1.8e-05;
Pr 0.7;
}
}
OpenFOAM-11
8.2 Turbulence models U-209
The file shows the selected RAS simulation followed by the RAS sub-dictionary containing
the model selections, in particular the model which is set to kEpsilon. The choice of
RAS models is described in section 8.2.1 and more information can be found in Chapter
7 of Notes on Computational Fluid Dynamics: General Principles. The LES models are
listed in section 8.2.3.
Where the laminar option is selected, the sub-dictionary is optional and will default
to a Newtonian model, using the viscosity specified in the physicalProperties file. Other
models, including non-Newtonian and visco-elastic models, are described in section 8.3.
Non-Newtonian models can also be combined with turbulence models (whereas visco-
elastic models cannot).
For a general introduction to turbulence for CFD, the reader may also wish to consult
Chapter 6 of Notes on Computational Fluid Dynamics: General Principles.
Turbulence models can be listed by running foamToC with a relevant table listed from
the RAS or LES tables. For example, the RAS tables are listed by running the following
command.
This returns several sub-tables. The user can then list the models within one of those
tables, e.g. the incompressible models.
The RAS models used in the tutorials can be listed using foamSearch with the following
command. The lists of available models are given in the following sections.
Users can locate tutorials using a particular model, e.g. buoyantKEpsilon, using foamInfo.
foamInfo buoyantKEpsilon
OpenFOAM-11
U-210 Models and physical properties
LRR Launder, Reece and Rodi Reynolds-stress turbulence model for incompressible flows.
LaunderSharmaKE Launder and Sharma low-Reynolds k-epsilon turbulence model for in-
compressible flows.
LienCubicKE Lien cubic non-linear low-Reynolds k-epsilon turbulence models for incom-
pressible flows.
LienLeschziner Lien and Leschziner low-Reynolds number k-epsilon turbulence model for
incompressible flows.
SSG Speziale, Sarkar and Gatski Reynolds-stress turbulence model for incompressible
flows.
kOmega2006 Standard (2006) high Reynolds-number k-omega turbulence model for in-
compressible flows.
qZeta Gibson and Dafa’Alla’s q-zeta two-equation low-Re turbulence model for incom-
pressible flows
OpenFOAM-11
8.2 Turbulence models U-211
v2f Lien and Kalitzin’s v2-f turbulence model for incompressible flows, with a limit im-
posed on the turbulent viscosity given by Davidson et al.
For compressible flows, the RAS model can be chosen from the list below.
LRR Launder, Reece and Rodi Reynolds-stress turbulence model for compressible flows.
SSG Speziale, Sarkar and Gatski Reynolds-stress turbulence model for compressible flows.
kEpsilon Standard k-epsilon turbulence model for compressible flows including rapid dis-
tortion theory (RDT) based compression term.
kOmega2006 Standard (2006) high Reynolds-number k-omega turbulence model for com-
pressible flows.
v2f Lien and Kalitzin’s v2-f turbulence model for compressible flows, with a limit imposed
on the turbulent viscosity given by Davidson et al.
OpenFOAM-11
U-212 Models and physical properties
• <model>Coeffs:
The LES models used in the tutorials can be listed using foamSearch with the following
command. The lists of available models are given in the following sections.
OpenFOAM-11
8.3 Transport/rheology models U-213
There are a number of wall function models available in the release, e.g. nutWallFunction,
nutRoughWallFunction, nutUSpaldingWallFunction, nutkWallFunction and nutkAtm-
WallFunction. The user can get the full list of wall function models using foamInfo:
Within each wall function boundary condition the user can over-ride default settings for
E, κ and Cµ through optional E, kappa and Cmu keyword entries.
Having selected the particular wall functions on various wall patches in the nut file, the
user should select the following boundary conditions at wall patches for other turbulence
fields.
OpenFOAM-11
U-214 Models and physical properties
and visco-elastic models described in this section. These models are described as laminar,
located in $FOAM_SRC/MomentumTransportModels/momentumTransportModels/laminar,
including:
• a family of generalisedNewtonian
√ models for a non-uniform viscosity which is a func-
tion of strain rate γ̇ = 2| symm(∇U)|, described in sections 8.3.1, 8.3.2, 8.3.3,
8.3.4, 8.3.5 and 8.3.6;
• a set of visco-elastic models, including Maxwell, Giesekus and PTT (Phan-Thien &
Tanner), described in sections 8.3.7, 8.3.8 and 8.3.9, respectively;
simulationType RAS
RAS
{
model kEpsilon; // RAS model
turbulence on;
printCoeffs on;
While the viscosityModel entry is generally omitted when turbulence models are used,
it can be included to set any of the non-Newtonian generalisedNewtonian models.
When turbulence modelling is not selected, by setting the laminar simulation type,
the user can select any of the laminar models through the model keyword entry in the
laminar sub-dictionary, including the visco-elastic models. The laminar models are listed
by the following command.
If the generalisedNewtonian model is selected, the user must then specify the viscosity
model through the viscosityModel keyword as mentioned above. The viscosity models
are listed by the following command.
The example below shows how the the Bird-Carreau viscosity model is selected in a
configuration without turbulence modelling.
OpenFOAM-11
8.3 Transport/rheology models U-215
simulationType laminar
laminar
{
model generalisedNewtonian;
viscosityModel BirdCarreau;
// ... followed by the BirdCarreau parameters
}
The laminar models still use the viscosity property ν (nu) specified in the physicalProperties
file, e.g.
viscosityModel constant;
nu 1.5e-05;
This viscosity is a single value which is constant in time and uniform over the solution
domain. The non-Newtonian models adopt ν as the zero strain-rate viscosity ν0 . The
visco-elastic models incorporate a linear viscous stress using ν, in addition to stress cal-
culated by the respective models. The details of the models are provided in the following
sections.
where the coefficient a has a default value of 2. An example specification of the model in
momentumTransport is:
viscosityModel BirdCarreau;
nuInf 1e-05;
k 1;
n 0.5;
OpenFOAM-11
U-216 Models and physical properties
viscosityModel CrossPowerLaw;
nuInf 1e-05;
m 1;
n 0.5;
viscosityModel powerLaw;
nuMax 1e-03;
nuMin 1e-05;
k 1e-05;
n 0.5;
viscosityModel HerschelBulkley;
tau0 0.01;
k 0.001;
n 0.5;
OpenFOAM-11
8.3 Transport/rheology models U-217
viscosityModel Casson;
m 3.934986e-6;
tau0 2.9032e-6;
nuMax 13.3333e-6;
nuMin 3.9047e-6;
viscosityModel strainRateFunction;
simulationType laminar;
laminar
{
model Maxwell;
MaxwellCoeffs
{
nuM 0.002;
lambda 0.03;
}
}
OpenFOAM-11
U-218 Models and physical properties
simulationType laminar;
laminar
{
model Giesekus;
GiesekusCoeffs
{
nuM 0.002;
lambda 0.03;
alphaG 0.1;
}
}
The Giesekus model includes a multi-mode option where τ is a sum of stresses, each with
an associated relaxation time λ and mobility coefficient αG .
simulationType laminar;
laminar
{
model PTT;
OpenFOAM-11
8.3 Transport/rheology models U-219
PTTCoeffs
{
nuM 0.002;
lambda 0.03;
epsilon 0.25;
}
}
The PTT model includes a multi-mode option where τ is a sum of stresses, each with an
associated relaxation time λ and extensibility coefficient ε.
∂λ
+ ∇ • (Uλ) = a(1 − λ)b − cγ̇ d λ (8.30)
∂t
with model coefficients a, b, c and d. The viscosity ν is then calculated according to:
ν∞
ν= (8.31)
1 − Kλ2
√
where the parameter K = ν∞ /ν0 . The viscosities ν0 and ν∞ are limiting values corre-
sponding to λ = 1 and λ = 0.
An example specification of the model in momentumTransport is:
simulationType laminar;
laminar
{
model lambdaThixotropic;
lambdaThixotropicCoeffs
{
a 1;
b 2;
c 1e-3;
d 3;
nu0 0.1;
nuInf 1e-4;
}
}
OpenFOAM-11
U-220 Models and physical properties
OpenFOAM-11
Index U-221
Index
OpenFOAM-11
U-222 Index
OpenFOAM-11
Index U-223
OpenFOAM-11
U-224 Index
OpenFOAM-11
Index U-225
OpenFOAM-11
U-226 Index
OpenFOAM-11
Index U-227
OpenFOAM-11
U-228 Index
OpenFOAM-11
Index U-229
OpenFOAM-11
U-230 Index
OpenFOAM-11
Index U-231
OpenFOAM-11
U-232 Index
OpenFOAM-11
Index U-233
OpenFOAM-11
U-234 Index
OpenFOAM-11
Index U-235
OpenFOAM-11
U-236 Index
OpenFOAM-11
Index U-237
OpenFOAM-11
U-238 Index
OpenFOAM-11
Index U-239
OpenFOAM-11
U-240 Index
OpenFOAM-11
Index U-241
OpenFOAM-11