OpenFOAM User Guide, Version 6 Open FOAMUser Guide V6
OpenFOAMUserGuide-A4
OpenFOAMUserGuide-A4
OpenFOAMUserGuide-A4
OpenFOAMUserGuide-A4
User Manual:
Open the PDF directly: View PDF .
Page Count: 237 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- Copyright Notice
- Trademarks
- Contents
- 1 Introduction
- 2 Tutorials
- 2.1 Lid-driven cavity flow
- 2.1.1 Pre-processing
- 2.1.2 Viewing the mesh
- 2.1.3 Running an application
- 2.1.4 Post-processing
- 2.1.5 Increasing the mesh resolution
- 2.1.6 Introducing mesh grading
- 2.1.7 Increasing the Reynolds number
- 2.1.8 High Reynolds number flow
- 2.1.9 Changing the case geometry
- 2.1.10 Post-processing the modified geometry
- 2.2 Stress analysis of a plate with a hole
- 2.3 Breaking of a dam
- 2.3.1 Mesh generation
- 2.3.2 Boundary conditions
- 2.3.3 Setting initial field
- 2.3.4 Fluid properties
- 2.3.5 Turbulence modelling
- 2.3.6 Time step control
- 2.3.7 Discretisation schemes
- 2.3.8 Linear-solver control
- 2.3.9 Running the code
- 2.3.10 Post-processing
- 2.3.11 Running in parallel
- 2.3.12 Post-processing a case run in parallel
- 2.1 Lid-driven cavity flow
- 3 Applications and libraries
- 3.1 The programming language of OpenFOAM
- 3.2 Compiling applications and libraries
- 3.3 Running applications
- 3.4 Running applications in parallel
- 3.5 Standard solvers
- 3.5.1 `Basic' CFD codes
- 3.5.2 Incompressible flow
- 3.5.3 Compressible flow
- 3.5.4 Multiphase flow
- 3.5.5 Direct numerical simulation (DNS)
- 3.5.6 Combustion
- 3.5.7 Heat transfer and buoyancy-driven flows
- 3.5.8 Particle-tracking flows
- 3.5.9 Discrete methods
- 3.5.10 Electromagnetics
- 3.5.11 Stress analysis of solids
- 3.5.12 Finance
- 3.6 Standard utilities
- 4 OpenFOAM cases
- 4.1 File structure of OpenFOAM cases
- 4.2 Basic input/output file format
- 4.2.1 General syntax rules
- 4.2.2 Dictionaries
- 4.2.3 The data file header
- 4.2.4 Lists
- 4.2.5 Scalars, vectors and tensors
- 4.2.6 Dimensional units
- 4.2.7 Dimensioned types
- 4.2.8 Fields
- 4.2.9 Macro expansion
- 4.2.10 Including files
- 4.2.11 Regular expressions
- 4.2.12 Keyword ordering
- 4.2.13 Inline calculations and code
- 4.3 Time and data input/output control
- 4.4 Numerical schemes
- 4.5 Solution and algorithm control
- 4.6 Case management tools
- 5 Mesh generation and conversion
- 5.1 Mesh description
- 5.2 Boundaries
- 5.3 Mesh generation with the blockMesh utility
- 5.4 Mesh generation with the snappyHexMesh utility
- 5.5 Mesh conversion
- 5.6 Mapping fields between different geometries
- 6 Post-processing
- 6.1 ParaView/paraFoam graphical user interface (GUI)
- 6.2 Post-processing command line interface (CLI)
- 6.3 Sampling and monitoring data
- 6.4 Third-Party post-processing
- 7 Models and physical properties
- Index

U-2
Copyright c
°2011-2018 OpenFOAM Foundation Ltd.
Author: Christopher J. Greenshields, CFD Direct Ltd.
This work is licensed under a
Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
Typeset in L
A
T
EX.
License
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CRE-
ATIVE COMMONS PUBLIC LICENSE (“CCPL” OR “LICENSE”). THE WORK IS PROTECTED
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 LI-
CENSE 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 cine-
matographic 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 (“synch-
ing”) will be considered an Adaptation for the purpose of this License.
b. “Collection” means a collection of literary or artistic works, such as encyclopedias and an-
thologies, or performances, phonograms or broadcasts, or other works or subject matter other
than works listed in Section 1(f) below, which, by reason of the selection and arrangement of
their contents, constitute intellectual creations, in which the Work is included in its entirety
in unmodified form along with one or more other contributions, each constituting separate
and independent works in themselves, which together are assembled into a collective whole.
A work that constitutes a Collection will not be considered an Adaptation (as defined above)
for the purposes 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, individuals,
entity or entities who created the Work or if no individual or entity can be identified, the
publisher; and in addition (i) in the case of a performance the actors, singers, musicians,
OpenFOAM-6

U-3
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 includ-
ing 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, archi-
tecture, 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 pre-
viously violated the terms of this License with respect to the Work, or who has received
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.
2. Fair Dealing Rights.
Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or
rights arising from limitations or exceptions that are provided for in connection with the copyright
protection under copyright law or other applicable laws.
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 Re-
produce the Work as incorporated in the Collections;
b. and, to Distribute and Publicly Perform the Work including as incorporated in Collections.
OpenFOAM-6

U-4
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 necessary
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 monetary
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 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.
OpenFOAM-6

U-5
d. For the avoidance of doubt:
i. Non-waivable Compulsory License Schemes. In those jurisdictions in which the
right to collect royalties through any statutory or compulsory licensing scheme cannot
be waived, the Licensor reserves the exclusive right to collect such royalties for any
exercise by You of the rights granted under this License;
ii. Waivable Compulsory License Schemes. In those jurisdictions in which the right
to collect royalties through any statutory or compulsory licensing scheme can be waived,
the Licensor reserves the exclusive right to collect such royalties for any exercise by You
of the rights granted under this License if Your exercise of such rights is for a purpose
or use which is otherwise than noncommercial as permitted under Section 4(b) and
otherwise waives the right to collect royalties through any statutory or compulsory
licensing scheme; and,
iii. Voluntary License Schemes. The Licensor reserves the right to collect royalties,
whether individually or, in the event that the Licensor is a member of a collecting
society that administers voluntary licensing schemes, via that society, from any exercise
by You of the rights granted under this License that is for a purpose or use which is
otherwise than noncommercial as permitted under Section 4(b).
e. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by
applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or
as part of any Collections, You must not distort, mutilate, modify or take other derogatory
action in relation to the Work which would be prejudicial to the Original Author’s honor or
reputation.
5. Representations, Warranties and Disclaimer
UNLESS OTHERWISE MUTUALLY AGREED BY THE PARTIES IN WRITING, LICENSOR
OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHER-
WISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBIL-
ITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE
OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF
ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW
THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY
TO YOU.
6. Limitation on Liability.
EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LI-
CENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDEN-
TAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS
LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED 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 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.
OpenFOAM-6

U-6
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-6

U-7
Trademarks
ANSYS is a registered trademark of ANSYS Inc.
CFX is a registered trademark of Ansys Inc.
CHEMKIN is a registered trademark of Reaction Design Corporation.
EnSight is a registered trademark of Computational Engineering International Ltd.
Fieldview is a registered trademark of Intelligent Light.
Fluent is a registered trademark of Ansys Inc.
GAMBIT is a registered trademark of Ansys Inc.
Icem-CFD is a registered trademark of Ansys Inc.
I-DEAS is a registered trademark of Structural Dynamics Research Corporation.
Linux is a registered trademark of Linus Torvalds.
OpenFOAM is a registered trademark of ESI Group.
ParaView is a registered trademark of Kitware.
STAR-CD is a registered trademark of CD-Adapco.
UNIX is a registered trademark of The Open Group.
OpenFOAM-6

U-8
OpenFOAM-6
Contents
Copyright Notice U-2
1. Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-2
2. Fair Dealing Rights. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-3
3. License Grant. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-3
4. Restrictions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-4
5. Representations, Warranties and Disclaimer . . . . . . . . . . . . . . . . . U-5
6. Limitation on Liability. . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-5
7. Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-5
8. Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-6
Trademarks U-7
Contents U-9
1 Introduction U-17
2 Tutorials U-19
2.1 Lid-driven cavity flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-20
2.1.1 Pre-processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-20
2.1.1.1 Mesh generation . . . . . . . . . . . . . . . . . . . . . U-21
2.1.1.2 Boundary and initial conditions . . . . . . . . . . . . . U-23
2.1.1.3 Physical properties . . . . . . . . . . . . . . . . . . . . U-24
2.1.1.4 Control . . . . . . . . . . . . . . . . . . . . . . . . . . U-24
2.1.1.5 Discretisation and linear-solver settings . . . . . . . . . U-25
2.1.2 Viewing the mesh . . . . . . . . . . . . . . . . . . . . . . . . . . U-26
2.1.3 Running an application . . . . . . . . . . . . . . . . . . . . . . . U-28
2.1.4 Post-processing . . . . . . . . . . . . . . . . . . . . . . . . . . . U-28
2.1.4.1 Colouring surfaces . . . . . . . . . . . . . . . . . . . . U-28
2.1.4.2 Cutting plane (slice) . . . . . . . . . . . . . . . . . . . U-30
2.1.4.3 Contours . . . . . . . . . . . . . . . . . . . . . . . . . U-30
2.1.4.4 Vector plots . . . . . . . . . . . . . . . . . . . . . . . . U-30
2.1.4.5 Streamline plots . . . . . . . . . . . . . . . . . . . . . U-33
2.1.5 Increasing the mesh resolution . . . . . . . . . . . . . . . . . . . U-33
2.1.5.1 Creating a new case using an existing case . . . . . . . U-33
2.1.5.2 Creating the finer mesh . . . . . . . . . . . . . . . . . U-35
2.1.5.3 Mapping the coarse mesh results onto the fine mesh . . U-35
2.1.5.4 Control adjustments . . . . . . . . . . . . . . . . . . . U-36
2.1.5.5 Running the code as a background process . . . . . . . U-36

U-10 Contents
2.1.5.6 Vector plot with the refined mesh . . . . . . . . . . . . U-36
2.1.5.7 Plotting graphs . . . . . . . . . . . . . . . . . . . . . . U-37
2.1.6 Introducing mesh grading . . . . . . . . . . . . . . . . . . . . . U-39
2.1.6.1 Creating the graded mesh . . . . . . . . . . . . . . . . U-40
2.1.6.2 Changing time and time step . . . . . . . . . . . . . . U-41
2.1.6.3 Mapping fields . . . . . . . . . . . . . . . . . . . . . . U-42
2.1.7 Increasing the Reynolds number . . . . . . . . . . . . . . . . . . U-42
2.1.7.1 Pre-processing . . . . . . . . . . . . . . . . . . . . . . U-43
2.1.7.2 Running the code . . . . . . . . . . . . . . . . . . . . . U-43
2.1.8 High Reynolds number flow . . . . . . . . . . . . . . . . . . . . U-44
2.1.8.1 Pre-processing . . . . . . . . . . . . . . . . . . . . . . U-44
2.1.8.2 Running the code . . . . . . . . . . . . . . . . . . . . . U-46
2.1.9 Changing the case geometry . . . . . . . . . . . . . . . . . . . . U-46
2.1.10 Post-processing the modified geometry . . . . . . . . . . . . . . U-50
2.2 Stress analysis of a plate with a hole . . . . . . . . . . . . . . . . . . . U-50
2.2.1 Mesh generation . . . . . . . . . . . . . . . . . . . . . . . . . . U-51
2.2.1.1 Boundary and initial conditions . . . . . . . . . . . . . U-54
2.2.1.2 Mechanical properties . . . . . . . . . . . . . . . . . . U-55
2.2.1.3 Thermal properties . . . . . . . . . . . . . . . . . . . . U-55
2.2.1.4 Control . . . . . . . . . . . . . . . . . . . . . . . . . . U-56
2.2.1.5 Discretisation schemes and linear-solver control . . . . U-56
2.2.2 Running the code . . . . . . . . . . . . . . . . . . . . . . . . . . U-58
2.2.3 Post-processing . . . . . . . . . . . . . . . . . . . . . . . . . . . U-58
2.2.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-60
2.2.4.1 Increasing mesh resolution . . . . . . . . . . . . . . . . U-60
2.2.4.2 Introducing mesh grading . . . . . . . . . . . . . . . . U-60
2.2.4.3 Changing the plate size . . . . . . . . . . . . . . . . . U-60
2.3 Breaking of a dam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-61
2.3.1 Mesh generation . . . . . . . . . . . . . . . . . . . . . . . . . . U-61
2.3.2 Boundary conditions . . . . . . . . . . . . . . . . . . . . . . . . U-63
2.3.3 Setting initial field . . . . . . . . . . . . . . . . . . . . . . . . . U-64
2.3.4 Fluid properties . . . . . . . . . . . . . . . . . . . . . . . . . . . U-65
2.3.5 Turbulence modelling . . . . . . . . . . . . . . . . . . . . . . . . U-66
2.3.6 Time step control . . . . . . . . . . . . . . . . . . . . . . . . . . U-66
2.3.7 Discretisation schemes . . . . . . . . . . . . . . . . . . . . . . . U-67
2.3.8 Linear-solver control . . . . . . . . . . . . . . . . . . . . . . . . U-68
2.3.9 Running the code . . . . . . . . . . . . . . . . . . . . . . . . . . U-68
2.3.10 Post-processing . . . . . . . . . . . . . . . . . . . . . . . . . . . U-68
2.3.11 Running in parallel . . . . . . . . . . . . . . . . . . . . . . . . . U-68
2.3.12 Post-processing a case run in parallel . . . . . . . . . . . . . . . U-71
3 Applications and libraries U-73
3.1 The programming language of OpenFOAM . . . . . . . . . . . . . . . . U-73
3.1.1 Language in general . . . . . . . . . . . . . . . . . . . . . . . . U-73
3.1.2 Object-orientation and C++ . . . . . . . . . . . . . . . . . . . . U-74
3.1.3 Equation representation . . . . . . . . . . . . . . . . . . . . . . U-74
3.1.4 Solver codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-75
3.2 Compiling applications and libraries . . . . . . . . . . . . . . . . . . . . U-75
OpenFOAM-6

Contents U-11
3.2.1 Header .H files . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-75
3.2.2 Compiling with wmake . . . . . . . . . . . . . . . . . . . . . . . U-77
3.2.2.1 Including headers . . . . . . . . . . . . . . . . . . . . . U-77
3.2.2.2 Linking to libraries . . . . . . . . . . . . . . . . . . . . U-78
3.2.2.3 Source files to be compiled . . . . . . . . . . . . . . . . U-79
3.2.2.4 Running wmake . . . . . . . . . . . . . . . . . . . . . . U-79
3.2.2.5 wmake environment variables . . . . . . . . . . . . . . U-79
3.2.3 Removing dependency lists: wclean . . . . . . . . . . . . . . . . U-79
3.2.4 Compiling libraries . . . . . . . . . . . . . . . . . . . . . . . . . U-81
3.2.5 Compilation example: the pisoFoam application . . . . . . . . . U-81
3.2.6 Debug messaging and optimisation switches . . . . . . . . . . . U-84
3.2.7 Linking new user-defined libraries to existing applications . . . . U-85
3.3 Running applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-85
3.4 Running applications in parallel . . . . . . . . . . . . . . . . . . . . . . U-86
3.4.1 Decomposition of mesh and initial field data . . . . . . . . . . . U-86
3.4.2 File input/output in parallel . . . . . . . . . . . . . . . . . . . . U-87
3.4.2.1 Selecting the file handler . . . . . . . . . . . . . . . . . U-89
3.4.2.2 Updating exisiting files . . . . . . . . . . . . . . . . . . U-89
3.4.2.3 Threading support . . . . . . . . . . . . . . . . . . . . U-89
3.4.3 Running a decomposed case . . . . . . . . . . . . . . . . . . . . U-90
3.4.4 Distributing data across several disks . . . . . . . . . . . . . . . U-90
3.4.5 Post-processing parallel processed cases . . . . . . . . . . . . . . U-91
3.4.5.1 Reconstructing mesh and data . . . . . . . . . . . . . U-91
3.4.5.2 Post-processing decomposed cases . . . . . . . . . . . . U-91
3.5 Standard solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-91
3.5.1 ‘Basic’ CFD codes . . . . . . . . . . . . . . . . . . . . . . . . . U-92
3.5.2 Incompressible flow . . . . . . . . . . . . . . . . . . . . . . . . . U-92
3.5.3 Compressible flow . . . . . . . . . . . . . . . . . . . . . . . . . U-92
3.5.4 Multiphase flow . . . . . . . . . . . . . . . . . . . . . . . . . . . U-93
3.5.5 Direct numerical simulation (DNS) . . . . . . . . . . . . . . . . U-94
3.5.6 Combustion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-94
3.5.7 Heat transfer and buoyancy-driven flows . . . . . . . . . . . . . U-95
3.5.8 Particle-tracking flows . . . . . . . . . . . . . . . . . . . . . . . U-95
3.5.9 Discrete methods . . . . . . . . . . . . . . . . . . . . . . . . . . U-96
3.5.10 Electromagnetics . . . . . . . . . . . . . . . . . . . . . . . . . . U-96
3.5.11 Stress analysis of solids . . . . . . . . . . . . . . . . . . . . . . U-97
3.5.12 Finance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-97
3.6 Standard utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-97
3.6.1 Pre-processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-97
3.6.2 Mesh generation . . . . . . . . . . . . . . . . . . . . . . . . . . U-98
3.6.3 Mesh conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . U-98
3.6.4 Mesh manipulation . . . . . . . . . . . . . . . . . . . . . . . . . U-99
3.6.5 Other mesh tools . . . . . . . . . . . . . . . . . . . . . . . . . . U-100
3.6.6 Post-processing . . . . . . . . . . . . . . . . . . . . . . . . . . . U-101
3.6.7 Post-processing data converters . . . . . . . . . . . . . . . . . . U-101
3.6.8 Surface mesh (e.g. OBJ/STL) tools . . . . . . . . . . . . . . . . U-102
3.6.9 Parallel processing . . . . . . . . . . . . . . . . . . . . . . . . . U-103
OpenFOAM-6

U-12 Contents
3.6.10 Thermophysical-related utilities . . . . . . . . . . . . . . . . . . U-103
3.6.11 Miscellaneous utilities . . . . . . . . . . . . . . . . . . . . . . . U-104
4 OpenFOAM cases U-105
4.1 File structure of OpenFOAM cases . . . . . . . . . . . . . . . . . . . . U-105
4.2 Basic input/output file format . . . . . . . . . . . . . . . . . . . . . . . U-106
4.2.1 General syntax rules . . . . . . . . . . . . . . . . . . . . . . . . U-106
4.2.2 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-107
4.2.3 The data file header . . . . . . . . . . . . . . . . . . . . . . . . U-107
4.2.4 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-108
4.2.5 Scalars, vectors and tensors . . . . . . . . . . . . . . . . . . . . U-109
4.2.6 Dimensional units . . . . . . . . . . . . . . . . . . . . . . . . . . U-109
4.2.7 Dimensioned types . . . . . . . . . . . . . . . . . . . . . . . . . U-110
4.2.8 Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-110
4.2.9 Macro expansion . . . . . . . . . . . . . . . . . . . . . . . . . . U-111
4.2.10 Including files . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-112
4.2.11 Regular expressions . . . . . . . . . . . . . . . . . . . . . . . . . U-113
4.2.12 Keyword ordering . . . . . . . . . . . . . . . . . . . . . . . . . . U-114
4.2.13 Inline calculations and code . . . . . . . . . . . . . . . . . . . . U-114
4.3 Time and data input/output control . . . . . . . . . . . . . . . . . . . U-115
4.3.1 Time control . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-116
4.3.2 Data writing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-116
4.3.3 Other settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-117
4.4 Numerical schemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-118
4.4.1 Time schemes . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-120
4.4.2 Gradient schemes . . . . . . . . . . . . . . . . . . . . . . . . . . U-120
4.4.3 Divergence schemes . . . . . . . . . . . . . . . . . . . . . . . . . U-121
4.4.4 Surface normal gradient schemes . . . . . . . . . . . . . . . . . U-123
4.4.5 Laplacian schemes . . . . . . . . . . . . . . . . . . . . . . . . . U-124
4.4.6 Interpolation schemes . . . . . . . . . . . . . . . . . . . . . . . . U-125
4.5 Solution and algorithm control . . . . . . . . . . . . . . . . . . . . . . . U-125
4.5.1 Linear solver control . . . . . . . . . . . . . . . . . . . . . . . . U-126
4.5.1.1 Solution tolerances . . . . . . . . . . . . . . . . . . . . U-127
4.5.1.2 Preconditioned conjugate gradient solvers . . . . . . . U-128
4.5.1.3 Smooth solvers . . . . . . . . . . . . . . . . . . . . . . U-128
4.5.1.4 Geometric-algebraic multi-grid solvers . . . . . . . . . U-129
4.5.2 Solution under-relaxation . . . . . . . . . . . . . . . . . . . . . U-130
4.5.3 PISO, SIMPLE and PIMPLE algorithms . . . . . . . . . . . . . U-131
4.5.4 Pressure referencing . . . . . . . . . . . . . . . . . . . . . . . . U-131
4.5.5 Other parameters . . . . . . . . . . . . . . . . . . . . . . . . . . U-131
4.6 Case management tools . . . . . . . . . . . . . . . . . . . . . . . . . . . U-132
4.6.1 File management scripts . . . . . . . . . . . . . . . . . . . . . . U-132
4.6.2 foamDictionary and foamSearch . . . . . . . . . . . . . . . . . . U-132
4.6.3 The foamGet script . . . . . . . . . . . . . . . . . . . . . . . . . U-134
4.6.4 The foamInfo script . . . . . . . . . . . . . . . . . . . . . . . . . U-135
OpenFOAM-6

Contents U-13
5 Mesh generation and conversion U-137
5.1 Mesh description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-137
5.1.1 Mesh specification and validity constraints . . . . . . . . . . . . U-137
5.1.1.1 Points . . . . . . . . . . . . . . . . . . . . . . . . . . . U-137
5.1.1.2 Faces . . . . . . . . . . . . . . . . . . . . . . . . . . . U-138
5.1.1.3 Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-138
5.1.1.4 Boundary . . . . . . . . . . . . . . . . . . . . . . . . . U-139
5.1.2 The polyMesh description . . . . . . . . . . . . . . . . . . . . . . U-139
5.1.3 Cell shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-140
5.1.4 1- and 2-dimensional and axi-symmetric problems . . . . . . . . U-140
5.2 Boundaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-140
5.2.1 Geometric (constraint) patch types . . . . . . . . . . . . . . . . U-143
5.2.2 Basic boundary conditions . . . . . . . . . . . . . . . . . . . . . U-144
5.2.3 Derived types . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-145
5.2.3.1 The inlet/outlet condition . . . . . . . . . . . . . . . . U-145
5.2.3.2 Entrainment boundary conditions . . . . . . . . . . . . U-146
5.2.3.3 Fixed flux pressure . . . . . . . . . . . . . . . . . . . . U-147
5.2.3.4 Time-varying boundary conditions . . . . . . . . . . . U-147
5.3 Mesh generation with the blockMesh utility . . . . . . . . . . . . . . . . U-149
5.3.1 Writing a blockMeshDict file . . . . . . . . . . . . . . . . . . . . U-151
5.3.1.1 The vertices . . . . . . . . . . . . . . . . . . . . . . . . U-151
5.3.1.2 The edges . . . . . . . . . . . . . . . . . . . . . . . . . U-152
5.3.1.3 The blocks . . . . . . . . . . . . . . . . . . . . . . . . U-152
5.3.1.4 Multi-grading of a block . . . . . . . . . . . . . . . . . U-153
5.3.1.5 The boundary . . . . . . . . . . . . . . . . . . . . . . . U-155
5.3.2 Multiple blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . U-156
5.3.3 Projection of vertices, edges and faces . . . . . . . . . . . . . . . U-158
5.3.4 Naming vertices, edges, faces and blocks . . . . . . . . . . . . . U-159
5.3.5 Creating blocks with fewer than 8 vertices . . . . . . . . . . . . U-159
5.3.6 Running blockMesh . . . . . . . . . . . . . . . . . . . . . . . . . U-159
5.4 Mesh generation with the snappyHexMesh utility . . . . . . . . . . . . U-160
5.4.1 The mesh generation process of snappyHexMesh . . . . . . . . . U-161
5.4.2 Creating the background hex mesh . . . . . . . . . . . . . . . . U-162
5.4.3 Cell splitting at feature edges and surfaces . . . . . . . . . . . . U-162
5.4.4 Cell removal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-164
5.4.5 Cell splitting in specified regions . . . . . . . . . . . . . . . . . . U-165
5.4.6 Snapping to surfaces . . . . . . . . . . . . . . . . . . . . . . . . U-165
5.4.7 Mesh layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-166
5.4.8 Mesh quality controls . . . . . . . . . . . . . . . . . . . . . . . . U-169
5.5 Mesh conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-170
5.5.1 fluentMeshToFoam . . . . . . . . . . . . . . . . . . . . . . . . . U-170
5.5.2 starToFoam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-171
5.5.2.1 General advice on conversion . . . . . . . . . . . . . . U-171
5.5.2.2 Eliminating extraneous data . . . . . . . . . . . . . . . U-171
5.5.2.3 Removing default boundary conditions . . . . . . . . . U-172
5.5.2.4 Renumbering the model . . . . . . . . . . . . . . . . . U-173
5.5.2.5 Writing out the mesh data . . . . . . . . . . . . . . . . U-173
OpenFOAM-6

U-14 Contents
5.5.2.6 Problems with the .vrt file . . . . . . . . . . . . . . . . U-174
5.5.2.7 Converting the mesh to OpenFOAM format . . . . . . U-175
5.5.3 gambitToFoam . . . . . . . . . . . . . . . . . . . . . . . . . . . U-175
5.5.4 ideasToFoam . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-175
5.5.5 cfx4ToFoam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-175
5.6 Mapping fields between different geometries . . . . . . . . . . . . . . . U-176
5.6.1 Mapping consistent fields . . . . . . . . . . . . . . . . . . . . . . U-176
5.6.2 Mapping inconsistent fields . . . . . . . . . . . . . . . . . . . . . U-176
5.6.3 Mapping parallel cases . . . . . . . . . . . . . . . . . . . . . . . U-177
6 Post-processing U-179
6.1 ParaView/paraFoam graphical user interface (GUI) . . . . . . . . . . . . U-179
6.1.1 Overview of ParaView/paraFoam . . . . . . . . . . . . . . . . . . U-179
6.1.2 The Parameters panel . . . . . . . . . . . . . . . . . . . . . . . . U-181
6.1.3 The Display panel . . . . . . . . . . . . . . . . . . . . . . . . . . U-182
6.1.4 The button toolbars . . . . . . . . . . . . . . . . . . . . . . . . U-183
6.1.5 Manipulating the view . . . . . . . . . . . . . . . . . . . . . . . U-183
6.1.5.1 View settings . . . . . . . . . . . . . . . . . . . . . . . U-183
6.1.5.2 General settings . . . . . . . . . . . . . . . . . . . . . U-184
6.1.6 Contour plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-184
6.1.6.1 Introducing a cutting plane . . . . . . . . . . . . . . . U-184
6.1.7 Vector plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-184
6.1.7.1 Plotting at cell centres . . . . . . . . . . . . . . . . . . U-185
6.1.8 Streamlines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-185
6.1.9 Image output . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-185
6.1.10 Animation output . . . . . . . . . . . . . . . . . . . . . . . . . . U-185
6.2 Post-processing command line interface (CLI) . . . . . . . . . . . . . . U-186
6.2.1 Post-processing functionality . . . . . . . . . . . . . . . . . . . . U-186
6.2.1.1 Field calculation . . . . . . . . . . . . . . . . . . . . . U-187
6.2.1.2 Flow rate calculation . . . . . . . . . . . . . . . . . . . U-188
6.2.1.3 Forces and force coefficients . . . . . . . . . . . . . . . U-188
6.2.1.4 Sampling for graph plotting . . . . . . . . . . . . . . . U-189
6.2.1.5 Lagrangian data . . . . . . . . . . . . . . . . . . . . . U-189
6.2.1.6 Monitoring minima and maxima . . . . . . . . . . . . U-189
6.2.1.7 Numerical data . . . . . . . . . . . . . . . . . . . . . . U-189
6.2.1.8 Pressure tools . . . . . . . . . . . . . . . . . . . . . . . U-189
6.2.1.9 Probes . . . . . . . . . . . . . . . . . . . . . . . . . . . U-190
6.2.1.10 ‘Pluggable’ solvers . . . . . . . . . . . . . . . . . . . . U-190
6.2.1.11 Visualisation tools . . . . . . . . . . . . . . . . . . . . U-190
6.2.2 Run-time data processing . . . . . . . . . . . . . . . . . . . . . U-190
6.2.3 The postProcess utility . . . . . . . . . . . . . . . . . . . . . . . U-191
6.2.4 Solver post-processing . . . . . . . . . . . . . . . . . . . . . . . U-192
6.3 Sampling and monitoring data . . . . . . . . . . . . . . . . . . . . . . . U-193
6.3.1 Probing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-193
6.3.2 Sampling for graphs . . . . . . . . . . . . . . . . . . . . . . . . U-194
6.3.3 Sampling for visualisation . . . . . . . . . . . . . . . . . . . . . U-196
6.3.4 Live monitoring of data . . . . . . . . . . . . . . . . . . . . . . U-197
6.4 Third-Party post-processing . . . . . . . . . . . . . . . . . . . . . . . . U-198
OpenFOAM-6

Contents U-15
6.4.1 Post-processing with Ensight . . . . . . . . . . . . . . . . . . . . U-199
6.4.1.1 Converting data to Ensight format . . . . . . . . . . . U-199
6.4.1.2 The ensightFoamReader reader module . . . . . . . . . U-199
7 Models and physical properties U-201
7.1 Thermophysical models . . . . . . . . . . . . . . . . . . . . . . . . . . . U-201
7.1.1 Thermophysical and mixture models . . . . . . . . . . . . . . . U-202
7.1.2 Transport model . . . . . . . . . . . . . . . . . . . . . . . . . . U-203
7.1.3 Thermodynamic models . . . . . . . . . . . . . . . . . . . . . . U-204
7.1.4 Composition of each constituent . . . . . . . . . . . . . . . . . . U-204
7.1.5 Equation of state . . . . . . . . . . . . . . . . . . . . . . . . . . U-205
7.1.6 Selection of energy variable . . . . . . . . . . . . . . . . . . . . U-206
7.1.7 Thermophysical property data . . . . . . . . . . . . . . . . . . . U-206
7.2 Turbulence models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-207
7.2.1 Reynolds-averaged simulation (RAS) modelling . . . . . . . . . U-208
7.2.1.1 Incompressible RAS turbulence models . . . . . . . . . U-208
7.2.1.2 Compressible RAS turbulence models . . . . . . . . . . U-209
7.2.2 Large eddy simulation (LES) modelling . . . . . . . . . . . . . . U-210
7.2.2.1 Incompressible LES turbulence models . . . . . . . . . U-210
7.2.2.2 Compressible LES turbulence models . . . . . . . . . . U-211
7.2.3 Model coefficients . . . . . . . . . . . . . . . . . . . . . . . . . . U-211
7.2.4 Wall functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-211
7.3 Transport/rheology models . . . . . . . . . . . . . . . . . . . . . . . . . U-212
7.3.1 Newtonian model . . . . . . . . . . . . . . . . . . . . . . . . . . U-212
7.3.2 Bird-Carreau model . . . . . . . . . . . . . . . . . . . . . . . . . U-213
7.3.3 Cross Power Law model . . . . . . . . . . . . . . . . . . . . . . U-213
7.3.4 Power Law model . . . . . . . . . . . . . . . . . . . . . . . . . . U-213
7.3.5 Herschel-Bulkley model . . . . . . . . . . . . . . . . . . . . . . . U-214
7.3.6 Casson model . . . . . . . . . . . . . . . . . . . . . . . . . . . . U-214
7.3.7 General strain-rate function . . . . . . . . . . . . . . . . . . . . U-215
Index U-217
OpenFOAM-6

U-16 Contents
OpenFOAM-6

Chapter 1
Introduction
This guide accompanies the release of version 6 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 2and later by a more
detailed description of the individual components that make up OpenFOAM.
OpenFOAM is a framework for developing application executables that use packaged
functionality contained within a collection of approximately 100 C+ libraries. OpenFOAM is
shipped with approximately 250 pre-built applications that fall into two categories: solvers,
that are each designed to solve a specific problem in fluid (or continuum) mechanics; and
utilities, that are designed to perform tasks that involve data manipulation. The solvers in
OpenFOAM cover a wide range of problems in fluid dynamics, as described in chapter 3.
Users can extend the collection of solvers, utilities and libraries in OpenFOAM, using
some pre-requisite knowledge of the underlying method, physics and programming tech-
niques involved.
OpenFOAM is supplied with pre- and post-processing environments. The interface to the
pre- and post-processing are themselves OpenFOAM utilities, thereby ensuring consistent
data handling across all environments. The overall structure of OpenFOAM is shown in
Figure 1.1. The pre-processing and running of OpenFOAM cases is described in chapter 4.
Applications
User
Tools
Meshing
Utilities Standard
Applications Others
e.g.EnSight
Post-processingSolvingPre-processing
Open Source Field Operation and Manipulation (OpenFOAM) C++ Library
ParaView
Figure 1.1: Overview of OpenFOAM structure.
In chapter 5, we cover both the generation of meshes using the mesh generator supplied
with OpenFOAM and conversion of mesh data generated by third-party products. Post-
processing is described in chapter 6and some aspects of physical modelling, e.g. transport
and thermophysical modelling, are described in in chapter 7.

U-18 Introduction
OpenFOAM-6
Chapter 2
Tutorials
In this chapter we shall describe in detail the process of setup, simulation and post-processing
for some OpenFOAM test cases, with the principal aim of introducing a user to the ba-
sic procedures of running OpenFOAM. The $FOAM_TUTORIALS directory contains many
more cases that demonstrate the use of all the solvers and many utilities supplied with
OpenFOAM.
Before attempting to run the tutorials, the user must first make sure that OpenFOAM
is installed correctly. Cases in the tutorials will be copied into the so-called run directory, an
OpenFOAM project directory in the user’s file system at $HOME/OpenFOAM/<USER>/-
run where <USER>is the account login name. The run directory is represented by the
$FOAM_RUN environment variable enabling the user to check its existence conveniently by
typing
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
The tutorial cases describe the use of the meshing and pre-processing utilities, case setup
and running OpenFOAM solvers and post-processing using ParaView.
Copies of all tutorials are available from the tutorials directory of the OpenFOAM instal-
lation. The tutorials are organised into a set of directories according to the type of flow and
then subdirectories according to solver. For example, all the simpleFoam cases are stored
within a subdirectory incompressible/simpleFoam, where incompressible indicates the type of
flow. The user can copy cases from the tutorials directory into their local run directory as
needed. For example to run the pitzDaily tutorial case for the simpleFoam solver, the user
can copy it to the run directory by typing:
cd $FOAM_RUN
cp -r $FOAM_TUTORIALS/incompressible/simpleFoam/pitzDaily .

U-20 Tutorials
2.1 Lid-driven cavity flow
This tutorial will describe how to pre-process, run and post-process a case involving isother-
mal, incompressible flow in a two-dimensional square domain. The geometry is shown in
Figure 2.1 in which all the boundaries of the square are walls. The top wall moves in the
x-direction at a speed of 1 m/s while the other 3 are stationary. Initially, the flow will be
assumed laminar and will be solved on a uniform mesh using the icoFoam solver for laminar,
isothermal, incompressible flow. During the course of the tutorial, the effect of increased
mesh resolution and mesh grading towards the walls will be investigated. Finally, the flow
Reynolds number will be increased and the pisoFoam solver will be used for turbulent,
isothermal, incompressible flow.
x
Ux=1 m/s
d=0.1 m
y
Figure 2.1: Geometry of the lid driven cavity.
2.1.1 Pre-processing
Cases are setup in OpenFOAM by editing case files. Users should select an editor of choice
with which to do this, such as emacs,vi,gedit,nedit,etc. Editing files is possible in Open-
FOAM because the I/O uses a dictionary format with keywords that convey sufficient mean-
ing to be understood by the users.
A case being simulated involves data for mesh, fields, properties, control parameters,
etc. As described in section 4.1, in OpenFOAM this data is stored in a set of files within a
case directory rather than in a single case file, as in many other CFD packages. The case
directory is given a suitably descriptive name. This tutorial consists of a set of cases located
in $FOAM_TUTORIALS/incompressible/icoFoam/cavity, the first of which is simply named
cavity. As a first step, the user should copy the cavity case directory to their run directory.
cd $FOAM_RUN
cp -r $FOAM_TUTORIALS/incompressible/icoFoam/cavity/cavity .
cd cavity
OpenFOAM-6

2.1 Lid-driven cavity flow U-21
2.1.1.1 Mesh generation
OpenFOAM always operates in a 3 dimensional Cartesian coordinate system and all geome-
tries are generated in 3 dimensions. OpenFOAM solves the case in 3 dimensions by default
but can be instructed to solve in 2 dimensions by specifying a ‘special’ empty boundary
condition on boundaries normal to the (3rd) dimension for which no solution is required.
The cavity domain consists of a square of side length d= 0.1 m in the x-yplane. A
uniform mesh of 20 by 20 cells will be used initially. The block structure is shown in
Figure 2.2. The mesh generator supplied with OpenFOAM, blockMesh, generates meshes
3 2
4 5
7 6
0
z
x1
y
Figure 2.2: Block structure of the mesh for the cavity.
from a description specified in an input dictionary, blockMeshDict located in the system (or
constant/polyMesh) directory for a given case. The blockMeshDict entries for this case are
as follows:
1/*--------------------------------*- C++ -*----------------------------------*\
2| ========= | |
3| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
4| \\ / O peration | Version: 6 |
5| \\ / A nd | Website: https://openfoam.org |
6| \\/ M anipulation | |
7\*---------------------------------------------------------------------------*/
8FoamFile
9{
10 version 2.0;
11 format ascii;
12 class dictionary;
13 object blockMeshDict;
14 }
15 //*************************************//
16
17 convertToMeters 0.1;
18
19 vertices
20 (
21 (0 0 0)
22 (1 0 0)
23 (1 1 0)
24 (0 1 0)
25 (0 0 0.1)
26 (1 0 0.1)
27 (1 1 0.1)
28 (0 1 0.1)
29 );
30
31 blocks
32 (
OpenFOAM-6

U-22 Tutorials
33 hex (0 1 2 3 4 5 6 7) (20 20 1) simpleGrading (1 1 1)
34 );
35
36 edges
37 (
38 );
39
40 boundary
41 (
42 movingWall
43 {
44 type wall;
45 faces
46 (
47 (3 7 6 2)
48 );
49 }
50 fixedWalls
51 {
52 type wall;
53 faces
54 (
55 (0 4 7 3)
56 (2 6 5 1)
57 (1 5 4 0)
58 );
59 }
60 frontAndBack
61 {
62 type empty;
63 faces
64 (
65 (0 3 2 1)
66 (4 5 6 7)
67 );
68 }
69 );
70
71 mergePatchPairs
72 (
73 );
74
75 // ************************************************************************* //
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 ({...}).
For the remainder of the manual:
For the sake of clarity and to save space, file headers, including the banner and
FoamFile sub-dictionary, will be removed from verbatim quoting of case files
The file first specifies coordinates of the block vertices; it then defines the blocks
(here, only 1) from the vertex labels and the number of cells within it; and finally, it defines
the boundary patches. The user is encouraged to consult section 5.3 to understand the
meaning of the entries in the blockMeshDict file.
The mesh is generated by running blockMesh on this blockMeshDict file. From within
the case directory, this is done, simply by typing in the terminal:
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 line in the file where the problem occurred. There should be no error messages
at this stage.
OpenFOAM-6

2.1 Lid-driven cavity flow U-23
2.1.1.2 Boundary and initial conditions
Once the mesh generation is complete, the user can look at this initial fields set up for this
case. The case is set up to start at time t= 0 s, so the initial field data is stored in a 0
sub-directory of the cavity directory. The 0sub-directory contains 2 files, pand U, one for
each of the pressure (p) and velocity (U) fields whose initial values and boundary conditions
must be set. Let us examine file p:
17 dimensions [0 2 -2 0 0 0 0];
18
19 internalField uniform 0;
20
21 boundaryField
22 {
23 movingWall
24 {
25 type zeroGradient;
26 }
27
28 fixedWalls
29 {
30 type zeroGradient;
31 }
32
33 frontAndBack
34 {
35 type empty;
36 }
37 }
38
39 // ************************************************************************* //
There are 3 principal entries in field data files:
dimensions specifies the dimensions of the field, here kinematic pressure, i.e. m2s−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 all the values of the field must be specified (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).
For this case cavity, the boundary consists of walls only, split into 2 patches named: (1)
fixedWalls for the fixed sides and base of the cavity; (2) movingWall for the moving top
of the cavity. As walls, both are given a zeroGradient boundary condition for p, meaning
“the normal gradient of pressure is zero”. The frontAndBack patch represents the front and
back planes of the 2D case and therefore must be set as empty.
In this case, as in most we encounter, the initial fields are set to be uniform. Here the
pressure is kinematic, and as an incompressible case, its absolute value is not relevant, so is
set to uniform 0 for convenience.
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).
The boundary field for velocity requires the same boundary condition for the frontAnd-
Back patch. The other patches are walls: a no-slip condition is assumed on the fixedWalls,
hence a noSlip condition. The top surface moves at a speed of 1 m/s in the x-direction so
requires a fixedValue condition with value of uniform (1 0 0).
OpenFOAM-6

U-24 Tutorials
2.1.1.3 Physical properties
The physical properties for the case are stored in dictionaries whose names are given the
suffix . . . Properties, located in the Dictionaries directory tree. For an icoFoam case, the
only property that must be specified is the kinematic viscosity which is stored from the
transportProperties dictionary. The user can check that the kinematic viscosity is set correctly
by opening the transportProperties dictionary to view/edit its entries. The keyword for
kinematic viscosity is nu, the phonetic label for the Greek symbol νby which it is represented
in equations. Initially this case will be run with a Reynolds number of 10, where the Reynolds
number is defined as:
Re =d|U|
ν(2.1)
where dand |U|are the characteristic length and velocity respectively and νis the kinematic
viscosity. Here d=0.1 m, |U|=1 m/s, so that for Re =10, ν=0.01 m2s−1. The correct
file entry for kinematic viscosity is thus specified below:
17
18 nu [0 2 -1 0 0 0 0] 0.01;
19
20
21 // ************************************************************************* //
2.1.1.4 Control
Input data relating to the control of time and reading and writing of the solution data are
read in from the controlDict dictionary. The user should view this file; as a case control file,
it is located in the system directory.
The start/stop times and the time step for the run must be set. OpenFOAM offers great
flexibility with time control which is described in full in section 4.3. In this tutorial we
wish to start the run at time t= 0 which means that OpenFOAM needs to read field data
from a directory named 0— see section 4.1 for more information of the case file structure.
Therefore we set the startFrom keyword to startTime and then specify the startTime
keyword to be 0.
For the end time, we wish to reach the steady state solution where the flow is circulating
around the cavity. As a general rule, the fluid should pass through the domain 10 times to
reach steady state in laminar flow. In this case the flow does not pass through this domain
as there is no inlet or outlet, so instead the end time can be set to the time taken for the
lid to travel ten times across the cavity, i.e. 1 s; in fact, with hindsight, we discover that
0.5 s is sufficient so we shall adopt this value. To specify this end time, we must specify the
stopAt keyword as endTime and then set the endTime keyword to 0.5.
Now we need to set the time step, represented by the keyword deltaT. To achieve
temporal accuracy and numerical stability when running icoFoam, a Courant number of less
than 1 is required. The Courant number is defined for one cell as:
Co =δt|U|
δx (2.2)
where δt is the time step, |U|is the magnitude of the velocity through that cell and δx is
the cell size in the direction of the velocity. The flow velocity varies across the domain and
we must ensure Co < 1everywhere. We therefore choose δt based on the worst case: the
maximum Co corresponding to the combined effect of a large flow velocity and small cell
OpenFOAM-6

2.1 Lid-driven cavity flow U-25
size. Here, the cell size is fixed across the domain so the maximum Co will occur next to
the lid where the velocity approaches 1 m s−1. The cell size is:
δx =d
n=0.1
20 = 0.005 m (2.3)
Therefore to achieve a Courant number less than or equal to 1 throughout the domain the
time step deltaT must be set to less than or equal to:
δt =Co δx
|U|=1×0.005
1= 0.005 s (2.4)
As the simulation progresses we wish to write results at certain intervals of time that we
can later view with a post-processing package. The writeControl keyword presents several
options for setting the time at which the results are written; here we select the timeStep
option which specifies that results are written every nth time step where the value nis
specified under the writeInterval keyword. Let us decide that we wish to write our
results at times 0.1, 0.2,. . . , 0.5 s. With a time step of 0.005 s, we therefore need to output
results at every 20th time time step and so we set writeInterval to 20.
OpenFOAM creates a new directory named after the current time,e.g. 0.1 s, on each
occasion that it writes a set of data, as discussed in full in section 4.1. In the icoFoam solver,
it writes out the results for each field, Uand p, into the time directories. For this case, the
entries in the controlDict are shown below:
17
18 application icoFoam;
19
20 startFrom startTime;
21
22 startTime 0;
23
24 stopAt endTime;
25
26 endTime 0.5;
27
28 deltaT 0.005;
29
30 writeControl timeStep;
31
32 writeInterval 20;
33
34 purgeWrite 0;
35
36 writeFormat ascii;
37
38 writePrecision 6;
39
40 writeCompression off;
41
42 timeFormat general;
43
44 timePrecision 6;
45
46 runTimeModifiable true;
47
48
49 // ************************************************************************* //
2.1.1.5 Discretisation and linear-solver settings
The user specifies the choice of finite volume discretisation schemes in the fvSchemes dictio-
nary in the system directory. The specification of the linear equation solvers and tolerances
and other algorithm controls is made in the fvSolution dictionary, similarly in the system
directory. The user is free to view these dictionaries but we do not need to discuss all their
OpenFOAM-6

U-26 Tutorials
entries at this stage except for pRefCell and pRefValue in the PISO sub-dictionary of the
fvSolution dictionary. In a closed incompressible system such as the cavity, pressure is rel-
ative: it is the pressure range that matters not the absolute values. In cases such as this,
the solver sets a reference level by pRefValue in cell pRefCell. In this example both are
set to 0. Changing either of these values will change the absolute pressure field, but not, of
course, the relative pressures or velocity field.
2.1.2 Viewing the mesh
Before the case is run it is a good idea to view the mesh to check for any errors. The mesh is
viewed in ParaView, the post-processing tool supplied with OpenFOAM. The ParaView post-
processing is conveniently launched on OpenFOAM case data by executing the paraFoam
script from within the case directory.
Any UNIX/Linux executable can be run in two ways: as a foreground process, i.e. one in
which the shell waits until the command has finished before giving a command prompt; as
a background process, which allows the shell to accept additional commands while it is still
running. Since it is 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 &
Alternatively, it can be launched from another directory location with an optional -case
argument giving the case directory, e.g.
paraFoam -case $FOAM_RUN/cavity &
This launches the ParaView window as shown in Figure 6.1. In the Pipeline Browser,
the user can see that ParaView has opened cavity.OpenFOAM, the module for the cavity
case. Before clicking the Apply button, the user needs to select some geometry from the
Mesh Parts panel. Because the case is small, it is easiest to select all the data by checking
the box adjacent to the Mesh Parts panel title, which automatically checks all individual
components within the respective panel. The user should then click the Apply button to
load the geometry into ParaView.
The user should then scroll down to the Display panel that controls the visual represen-
tation of the selected module. Within the Display panel the user should do the following as
shown in Figure 2.3:
1. in the Coloring section, select Solid Color;
2. click Edit (in Coloring) and select an appropriate colour e.g. black (for a white back-
ground);
3. select Wireframe from the Representation menu. The background colour can be set
in the View Render panel below the Display panel in the Properties window.
Especially the first time the user starts ParaView,it is recommended that they manipulate
the view as described in section 6.1.5. In particular, since this is a 2D case, it is recommended
that Use Parallel Projection is selected near the bottom of the View Render panel, available
only with the Advanced Properties gearwheel button pressed at the top of the Properties
OpenFOAM-6

2.1 Lid-driven cavity flow U-27
Set Solid Color,e.g. black
Select Wireframe
Scroll to Display title
Select Color by Solid Color
Figure 2.3: Viewing the mesh in paraFoam.
OpenFOAM-6

U-28 Tutorials
window, next to the search box. View Settings window selected from the Edit menu. The
Orientation Axes can be toggled on and off in the Annotation window or moved by drag and
drop with the mouse.
2.1.3 Running an application
Like any UNIX/Linux executable, OpenFOAM applications can be run either in the fore-
ground or background. On this occasion, we will run icoFoam in the foreground. The
icoFoam solver is executed either by entering the case directory and typing
icoFoam
at the command prompt, or with the optional -case argument giving the case directory,
e.g.
icoFoam -case $FOAM_RUN/cavity
The progress of the job is written to the terminal window. It tells the user the current
time, maximum Courant number, initial and final residuals for all fields.
2.1.4 Post-processing
As soon as results are written to time directories, they can be viewed using paraFoam.
Return to the paraFoam window and select the Properties panel for the cavity.OpenFOAM
case module. If the correct window panels for the case module do not seem to be present at
any time, please ensure that: cavity.OpenFOAM is highlighted in blue; eye button alongside
it is switched on to show the graphics are enabled;
To prepare paraFoam to display the data of interest, we must first load the data at the
required run time of 0.5 s. If the case was run while ParaView was open, the output data in
time directories will not be automatically loaded within ParaView. To load the data the user
should click Refresh Times at the top Properties window (scroll up the panel if necessary).
The time data will be loaded into ParaView.
In order to view the solution at t= 0.5s, the user can use the VCR Controls or Current
Time Controls to change the current time to 0.5. These are located in the toolbars at the
top of the ParaView window, as shown in Figure 6.4.
2.1.4.1 Colouring surfaces
To view pressure, the user should go to the Display panel since it controls the visual repre-
sentation of the selected module. To make a simple plot of pressure, the user should select
the following, as described in detail in Figure 2.4:
1. select Surface from the Representation menu;
2. select in Coloring
3. click the Rescale button to set the colour scale to the data range, if necessary.
OpenFOAM-6

2.1 Lid-driven cavity flow U-29
Scroll to Display title
Select Color by interpolated p
Select Surface
Rescale to Data Range
Figure 2.4: Displaying pressure contours for the cavity case.
Figure 2.5: Pressures in the cavity case.
OpenFOAM-6

U-30 Tutorials
The pressure field should appear as shown in Figure 2.5, with a region of low pressure at
the top left of the cavity and one of high pressure at the top right of the cavity.
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 so that each cell will be
denoted by a single colour with no grading.
A colour legend can be added by either by clicking the Toggle Color Legend Visibility
button in the Active Variable Controls toolbar or the Show button in the Coloring section
of the Display panel. The legend can be located in the image window by drag and drop
with the mouse. The Edit button, either in the Active Variable Controls toolbar or in
the Coloring panel of the Display panel, opens the Color Map Editor window, as shown in
Figure 2.6, where the user can set a range of attributes of the colour scale and the color bar.
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 and selecting Blue
to Red Rainbow. After clicking the OK confirmation button, the user can click the Save as
Default button at the bottom of the panel (disk drive 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.6.
2.1.4.2 Cutting plane (slice)
If the user rotates the image, by holding down the left mouse button in the image window
and moving the cursor, they can see that they have now coloured the complete geometry
surface by the pressure. In order to produce a genuine 2-dimensional contour plot the user
should first create a cutting plane, or ‘slice’. With the cavity.OpenFOAM module highlighted
in the Pipeline Browser, the user should select the Slice filter from the Filters menu in
the top menu of ParaView (accessible at the top of the screen on some systems). The Slice
filter can be initially found in the Common sub-menu, but once selected, it moves to the
Recent sub-menu, disappearing from the the Common sub-menu. The cutting plane should
be centred at (0.05,0.05,0.005) and its normal should be set to (0,0,1) (click the Z Normal
button).
2.1.4.3 Contours
Having generated the cutting plane, contours can be created using by applying the Contour
filter. With the Slice module highlighted in the Pipeline Browser, the user should select the
Contour filter. In the Properties panel, the user should select pressure from the Contour
By menu. Under Isosurfaces, the user could delete the default value with the minus
button, then add a range of 10 values. The contours can be displayed with a Wireframe
representation if the Coloring is solid or by a field, e.g. pressure.
2.1.4.4 Vector plots
Before we start to plot the vectors of the flow velocity, it may be useful to remove other
modules that have been created, e.g. using the Slice and Contour filters described above.
OpenFOAM-6

2.1 Lid-driven cavity flow U-31
Save as Default
Choose preset
Configure Color Bar
Figure 2.6: Color Map Editor.
These can: either be deleted entirely, by highlighting the relevant module in the Pipeline
Browser and clicking Delete in their respective Properties panel; or, be disabled by toggling
the eye button for the relevant module in the Pipeline Browser.
We now wish to generate a vector glyph for velocity at the centre of each cell. We first
need to filter the data to cell centres as described in section 6.1.7.1. With the cavity.Open-
FOAM module highlighted in the Pipeline Browser, the user should select Cell Centers from
the Filter->Alphabetical menu and then click Apply.
With these Centers highlighted in the Pipeline Browser, the user should then select Glyph
from the Filter->Common menu. The Properties window panel should appear as shown in
Figure 2.7. Note that newly selected filters are moved to the Filter->Recent menu and
are unavailable in the menus from where they were originally selected. In the resulting
Properties panel, the velocity field, U, must be selected from the vectors menu. The user
OpenFOAM-6

U-32 Tutorials
Open Properties panel
Select Scale Mode off
Specify Set Scale Factor 0.005
Select Glyph Type Arrow
Select vectors U
Figure 2.7: Properties panel for the Glyph filter.
Figure 2.8: Velocities in the cavity case.
OpenFOAM-6

2.1 Lid-driven cavity flow U-33
should set the Scale Mode for the glyphs to be off, with Set Scale Factor set to 0.005. On
clicking Apply, the glyphs appear but, probably as a single colour, e.g. white. The user
should colour the glyphs by velocity magnitude which, as usual, is controlled by setting
Color by U in the Display panel. The user can also select Show Color Legend in Edit Color
Map. The output is shown in Figure 2.8, in which uppercase Times Roman fonts are selected
for the Color Legend headings and the labels are specified to 2 fixed significant figures by
deselecting Automatic Label Format and entering %-#6.2f in the Label Format text box. The
background colour is set to white in the General panel of View Settings as described in
section 6.1.5.1.
Note that at the left and right walls, glyphs appear to indicate flow through the walls.
However, it is clear that, while the flow direction is normal to the wall, its magnitude is 0.
This slightly confusing situation is caused by ParaView choosing to orientate the glyphs in
the x-direction when the glyph scaling off and the velocity magnitude is 0.
2.1.4.5 Streamline plots
Again, before the user continues to post-process in ParaView, they should disable modules
such as those for the vector plot described above. We now wish to plot streamlines of velocity
as described in section 6.1.8. With the cavity.OpenFOAM module highlighted in the Pipeline
Browser, the user should then select Stream Tracer from the Filter menu and then click
Apply. The Properties window panel should appear as shown in Figure 2.9. The Seed points
should be specified along a High Resolution Line Source running vertically through the
centre of the geometry, i.e. from (0.05,0,0.005) to (0.05,0.1,0.005). For the image in this
guide we used: a point Resolution of 21; Maximum Step Length of 0.5; Initial Step Length
of 0.2; and, Integration Direction BOTH. The Runge-Kutta 4/5 IntegratorType was used
with default parameters.
On clicking Apply the tracer is generated. The user should then select Tube from the
Filter menu to produce high quality streamline images. For the image in this report, we
used: Num. sides 6; Radius 0.0003; and, Radius factor 10. The streamtubes are coloured by
velocity magnitude. On clicking Apply the image in Figure 2.10 should be produced.
2.1.5 Increasing the mesh resolution
The mesh resolution will now be increased by a factor of two in each direction. The results
from the coarser mesh will be mapped onto the finer mesh to use as initial conditions for
the problem. The solution from the finer mesh will then be compared with those from the
coarser mesh.
2.1.5.1 Creating a new case using an existing case
We now wish to create a new case named cavityFine that is created from cavity. The user
should therefore clone the cavity case and edit the necessary files. First the user should go
to the run directory, by typing
cd $FOAM_RUN
Note that there is also a convenient alias, named run, that reproduces the command above
to change directory to $FOAM_RUN, simply by typing run.
OpenFOAM-6

U-34 Tutorials
Set Integration Direction to BOTH
Set Initial Step Length to Cell Length 0.01
Specify Line Source and set points and resolution
Scroll to Properties title
Figure 2.9: Properties panel for the Stream Tracer filter.
Figure 2.10: Streamlines in the cavity case.
OpenFOAM-6

2.1 Lid-driven cavity flow U-35
The cavityFine case can be created by making a new case directory and copying the
relevant directories from the cavity case.
mkdir cavityFine
cp -r cavity/constant cavityFine
cp -r cavity/system cavityFine
The user can then prepare to run the new case by changing into the case directory.
cd cavityFine
2.1.5.2 Creating the finer mesh
We now wish to increase the number of cells in the mesh by using blockMesh. The user
should open the blockMeshDict file in the system directory in an editor and edit the block
specification. The blocks are specified in a list under the blocks keyword. The syntax of
the block definitions is described fully in section 5.3.1.3; at this stage it is sufficient to know
that following hex is first the list of vertices in the block, then a list (or vector) of numbers
of cells in each direction. This was originally set to (20 20 1) for the cavity case. The user
should now change this to (40 40 1) and save the file. The new refined mesh should then
be created by running blockMesh as before.
2.1.5.3 Mapping the coarse mesh results onto the fine mesh
The mapFields utility maps one or more fields relating to a given geometry onto the cor-
responding fields for another geometry. In our example, the fields are deemed ‘consistent’
because the geometry and the boundary types, or conditions, of both source and target fields
are identical. We use the -consistent command line option when executing mapFields in
this example.
The field data that mapFields maps is read from the time directory specified by startFrom
and startTime in the controlDict of the target case, i.e. those into which the results are
being mapped. In this example, we wish to map the final results of the coarser mesh from
case cavity onto the finer mesh of case cavityFine. Therefore, since these results are stored in
the 0.5 directory of cavity, the startTime should be set to 0.5 s in the controlDict dictionary
and startFrom should be set to startTime.
The case is ready to run mapFields. Typing mapFields -help quickly shows that map-
Fields requires the source case directory as an argument. We are using the -consistent
option, so the utility is executed from withing the cavityFine directory by
mapFields ../cavity -consistent
The utility should run with output to the terminal including:
Source: ".." "cavity"
Target: "." "cavityFine"
Create databases as time
Source time: 0.5
Target time: 0.5
OpenFOAM-6

U-36 Tutorials
Create meshes
Source mesh size: 400 Target mesh size: 1600
Consistently creating and mapping fields for time 0.5
interpolating p
interpolating U
End
2.1.5.4 Control adjustments
To maintain a Courant number of less that 1, as discussed in section 2.1.1.4, the time step
must now be halved since the size of all cells has halved. Therefore deltaT should be set to
to 0.0025 s in the controlDict dictionary. Field data is currently written out at an interval
of a fixed number of time steps. Here we demonstrate how to specify data output at fixed
intervals of time. Under the writeControl keyword in controlDict, instead of requesting
output by a fixed number of time steps with the timeStep entry, a fixed amount of run time
can be specified between the writing of results using the runTime entry. In this case the
user should specify output every 0.1 and therefore should set writeInterval to 0.1 and
writeControl to runTime. Finally, since the case is starting with a the solution obtained on
the coarse mesh we only need to run it for a short period to achieve reasonable convergence
to steady-state. Therefore the endTime should be set to 0.7 s. Make sure these settings are
correct and then save the file.
2.1.5.5 Running the code as a background process
The user should experience running icoFoam as a background process, redirecting the ter-
minal output to a log file that can be viewed later. From the cavityFine directory, the user
should execute:
icoFoam > log &
cat log
2.1.5.6 Vector plot with the refined mesh
The user can open multiple cases simultaneously in ParaView; essentially because each new
case is simply another module that appears in the Pipeline Browser. There is an inconvenience
when opening a new OpenFOAM case in ParaView because it expects that case data is
stored in a single file which has a file extension that enables it to establish the format.
However, OpenFOAM stores case data in multiple files without an extension in the name,
within a specific directory structure. The ParaView reader module works on the basis that,
when opening case data in OpenFOAM format, it is passed a dummy (empty) file with the
.OpenFOAM extension that resides in the case directory. The paraFoam script automatically
creates this file — hence, the cavity case module is called cavity.OpenFOAM.
If the user wishes to open a second case directly from within ParaView, they need to
create such a dummy file. They can do this ‘by hand’ or, more simply, use the paraFoam
script with the option -touch. For the cavityFine example, that involves executing from
the case directory:
OpenFOAM-6

2.1 Lid-driven cavity flow U-37
Select arc_length
Select U_x from Line Series
Select Line Source
Figure 2.11: Selecting fields for graph plotting.
paraFoam -touch
Now the cavityFine case can be loaded into ParaView by selecting Open from the File
menu, and having navigated to the cavityFine directory, opening cavityFine.OpenFOAM. The
user can now make a vector plot of the results from the refined mesh in ParaView. The plot
can be compared with the cavity case by enabling glyph images for both case simultaneously.
2.1.5.7 Plotting graphs
The user may wish to visualise the results by extracting some scalar measure of velocity and
plotting 2-dimensional graphs along lines through the domain. OpenFOAM is well equipped
for this kind of data manipulation. There are numerous utilities that do specialised data
manipulations, and the postProcess utility that includes a broad range of generic post-
OpenFOAM-6

U-38 Tutorials
processing functionality. The functions within postProcess can be listed by typing:
postProcess -list
The components and mag functions provide useful scalar measures of velocity. When the
components function is executed on a case, e.g. cavity, it reads in the velocity vector field
from each time directory and, in the corresponding time directories, writes scalar fields Ux,
Uy and Uz representing the x,yand zcomponents of velocity.
The user can run postProcess with the components function on both cavity and cavityFine
cases. For example, for the cavity case the user should go into the cavity directory and execute
postProcess as follows:
cd $FOAM_RUN/cavity
postProcess -func "components(U)"
The individual components can be plotted as a graph in ParaView. It is quick, convenient
and has reasonably good control over labelling and formatting, so the printed output is a
fairly good standard. However, to produce graphs for publication, users may prefer to write
raw data and plot it with a dedicated graphing tool, such as gnuplot or Grace/xmgr. To do
this, we recommend using the sampling tools, described in section 6.3.2 and section 2.2.3.
Before commencing plotting, the user needs to load the newly generated Ux,Uy and
Uz fields into ParaView. To do this, the user should click the Refresh Times at the top of
the Properties panel for the cavity.OpenFOAM module which will cause the new fields to
be loaded into ParaView and appear in the Volume Fields window. Ensure the new fields
are selected and the changes are applied, i.e. click Apply again if necessary. Also, data
is interpolated incorrectly at boundaries if the boundary regions are selected in the Mesh
Parts panel. Therefore the user should deselect the patches in the Mesh Parts panel, i.e.
movingWall,fixedWall and frontAndBack, and apply the changes.
Now, in order to display a graph in ParaView the user should select the module of
interest, e.g.cavity.OpenFOAM and apply the Plot Over Line filter from the Filter->Data
Analysis menu. This opens up a new XY Plot window below or beside the existing 3D View
window. A PlotOverLine module is created in which the user can specify the end points of
the line in the Properties panel. In this example, the user should position the line vertically
up the centre of the domain, i.e. from (0.05,0,0.005) to (0.05,0.1,0.005), in the Point1 and
Point2 text boxes. The Resolution can be set to 100.
On clicking Apply, a graph is generated in the XY Plot window. In the Display panel,
the user should set Attribute Mode to Point Data. The Use Data Array option can be
selected for the X Axis Data, taking the arc_length option so that the x-axis of the graph
represents distance from the base of the cavity.
The user can choose the fields to be displayed in the Line Series panel of the Display
window. From the list of scalar fields to be displayed, it can be seen that the magnitude
and components of vector fields are available by default, e.g. displayed as U_X, so that it was
not necessary to create Ux using the components function. Nevertheless, the user should
deselect all series except Ux (or U_x). A square colour box in the adjacent column to the
selected series indicates the line colour. The user can edit this most easily by a double click
of the mouse over that selection.
In order to format the graph, the user should modify the settings below the Line Series
panel, namely Line Color,Line Thickness,Line Style,Marker Style and Chart Axes.
OpenFOAM-6

2.1 Lid-driven cavity flow U-39
Figure 2.12: Plotting graphs in paraFoam.
Also the user can click one of the buttons above the top left corner of the XY Plot. The
third button, for example, allows the user to control View Settings in which the user can set
title and legend for each axis, for example. Also, the user can set font, colour and alignment
of the axes titles, and has several options for axis range and labels in linear or logarithmic
scales.
Figure 2.12 is a graph produced using ParaView. The user can produce a graph however
he/she wishes. For information, the graph in Figure 2.12 was produced with the options for
axes of: Standard type of Notation;Specify Axis Range selected; titles in Sans Serif 12
font. The graph is displayed as a set of points rather than a line by activating the Enable
Line Series button in the Display window. Note: if this button appears to be inactive by
being “greyed out”, it can be made active by selecting and deselecting the sets of variables
in the Line Series panel. Once the Enable Line Series button is selected, the Line Style and
Marker Style can be adjusted to the user’s preference.
2.1.6 Introducing mesh grading
The error in any solution will be more pronounced in regions where the form of the true
solution differ widely from the form assumed in the chosen numerical schemes. For example
a numerical scheme based on linear variations of variables over cells can only generate an
exact solution if the true solution is itself linear in form. The error is largest in regions
where the true solution deviates greatest from linear form, i.e. where the change in gradient
is largest. Error decreases with cell size.
It is useful to have an intuitive appreciation of the form of the solution before setting
up any problem. It is then possible to anticipate where the errors will be largest and to
grade the mesh so that the smallest cells are in these regions. In the cavity case the large
variations in velocity can be expected near a wall and so in this part of the tutorial the
mesh will be graded to be smaller in this region. By using the same number of cells, greater
accuracy can be achieved without a significant increase in computational cost.
A mesh of 20 ×20 cells with grading towards the walls will be created for the lid-driven
cavity problem and the results from the finer mesh of section 2.1.5.2 will then be mapped
onto the graded mesh to use as an initial condition. The results from the graded mesh will
be compared with those from the previous meshes. Since the changes to the blockMeshDict
OpenFOAM-6

U-40 Tutorials
0
z
x
y
3 4 5
6 87
1 2
1715
911
10
16
12 13 14
0 1
2 3
Figure 2.13: Block structure of the graded mesh for the cavity (block numbers encircled).
dictionary are fairly substantial, the case used for this part of the tutorial, cavityGrade,
is supplied in the $FOAM_TUTORIALS/incompressible/icoFoam/cavity directory. The user
should copy the cavityGrade case into the run directory, then follow the steps below.
2.1.6.1 Creating the graded mesh
The mesh now needs 4 blocks as different mesh grading is needed on the left and right and
top and bottom of the domain. The block structure for this mesh is shown in Figure 2.13.
The user can view the blockMeshDict file in the system subdirectory of cavityGrade; for
completeness the key elements of the blockMeshDict file are also reproduced below. Each
block now has 10 cells in the xand ydirections and the ratio between largest and smallest
cells is 2.
17 convertToMeters 0.1;
18
19 vertices
20 (
21 (0 0 0)
22 (0.5 0 0)
23 (1 0 0)
24 (0 0.5 0)
25 (0.5 0.5 0)
26 (1 0.5 0)
27 (0 1 0)
28 (0.5 1 0)
29 (1 1 0)
30 (0 0 0.1)
31 (0.5 0 0.1)
32 (1 0 0.1)
33 (0 0.5 0.1)
34 (0.5 0.5 0.1)
35 (1 0.5 0.1)
36 (0 1 0.1)
37 (0.5 1 0.1)
38 (1 1 0.1)
39 );
40
41 blocks
42 (
43 hex (0 1 4 3 9 10 13 12) (10 10 1) simpleGrading (2 2 1)
44 hex (1 2 5 4 10 11 14 13) (10 10 1) simpleGrading (0.5 2 1)
45 hex (3 4 7 6 12 13 16 15) (10 10 1) simpleGrading (2 0.5 1)
46 hex (4 5 8 7 13 14 17 16) (10 10 1) simpleGrading (0.5 0.5 1)
47 );
48
OpenFOAM-6

2.1 Lid-driven cavity flow U-41
49 edges
50 (
51 );
52
53 boundary
54 (
55 movingWall
56 {
57 type wall;
58 faces
59 (
60 (6 15 16 7)
61 (7 16 17 8)
62 );
63 }
64 fixedWalls
65 {
66 type wall;
67 faces
68 (
69 (3 12 15 6)
70 (0 9 12 3)
71 (0 1 10 9)
72 (1 2 11 10)
73 (2 5 14 11)
74 (5 8 17 14)
75 );
76 }
77 frontAndBack
78 {
79 type empty;
80 faces
81 (
82 (0 3 4 1)
83 (1 4 5 2)
84 (3 6 7 4)
85 (4 7 8 5)
86 (9 10 13 12)
87 (10 11 14 13)
88 (12 13 16 15)
89 (13 14 17 16)
90 );
91 }
92 );
93
94 mergePatchPairs
95 (
96 );
97
98 // ************************************************************************* //
Once familiar with the blockMeshDict file for this case, the user can execute blockMesh from
the command line. The graded mesh can be viewed as before using paraFoam as described
in section 2.1.2.
2.1.6.2 Changing time and time step
The highest velocities and smallest cells are next to the lid, therefore the highest Courant
number will be generated next to the lid, for reasons given in section 2.1.1.4. It is therefore
useful to estimate the size of the cells next to the lid to calculate an appropriate time step
for this case.
When a nonuniform mesh grading is used, blockMesh calculates the cell sizes using a
geometric progression. Along a length l, if ncells are requested with a ratio of Rbetween
the last and first cells, the size of the smallest cell, δxs, is given by:
δxs=lr−1
αr −1(2.5)
where ris the ratio between one cell size and the next which is given by:
r=R1
n−1(2.6)
OpenFOAM-6

U-42 Tutorials
and
α=(Rfor R > 1,
1−r−n+r−1for R < 1.(2.7)
For the cavityGrade case the number of cells in each direction in a block is 10, the ratio
between largest and smallest cells is 2and the block height and width is 0.05 m. Therefore
the smallest cell length is 3.45 mm. From Equation 2.2, the time step should be less than 3.45
ms to maintain a Courant of less than 1. To ensure that results are written out at convenient
time intervals, the time step deltaT should be reduced to 2.5 ms and the writeInterval
set to 40 so that results are written out every 0.1 s. These settings can be viewed in the
cavityGrade/system/controlDict file.
The startTime needs to be set to that of the final conditions of the case cavityFine,i.e.
0.7. Since cavity and cavityFine converged well within the prescribed run time, we can set
the run time for case cavityGrade to 0.1 s, i.e. the endTime should be 0.8.
2.1.6.3 Mapping fields
As in section 2.1.5.3, use mapFields to map the final results from case cavityFine onto the
mesh for case cavityGrade. Enter the cavityGrade directory and execute mapFields by:
cd $FOAM_RUN/cavityGrade
mapFields ../cavityFine -consistent
Now run icoFoam from the case directory and monitor the run time information. View
the converged results for this case and compare with other results using post-processing
tools described previously in section 2.1.5.6 and section 2.1.5.7.
2.1.7 Increasing the Reynolds number
The cases solved so far have had a Reynolds number of 10. This is very low and leads to
a stable solution quickly with only small secondary vortices at the bottom corners of the
cavity. We will now increase the Reynolds number to 100, at which point the solution takes
a noticeably longer time to converge. The coarsest mesh in case cavity will be used initially.
The user should clone the cavity case and name it cavityHighRe. Rather than copying
individual directories (system,constant,etc.) as described previously, the foamCloneCase can
be used, which copies the relevant directories in one step. By default the 0time directory is
copied, but here the user can use the -latestTime option to copy the latest time directory,
0.5, which can be used as the initial field data for our simulation. The example also uses
the run alias as a quick way to change to the run directory.
run
foamCloneCase -latestTime cavity cavityHighRe
cd cavityHighRe
OpenFOAM-6

2.1 Lid-driven cavity flow U-43
2.1.7.1 Pre-processing
Go into the cavityHighRe case and edit the transportProperties dictionary in the constant
directory. Since the Reynolds number is required to be increased by a factor of 10, decrease
the kinematic viscosity by a factor of 10, i.e. to 1×10−3m2s−1. We now run this case by
restarting from the solution at the end of the cavity case run. To do this we can use the
option of setting the startFrom keyword to latestTime so that icoFoam takes as its initial
data the values stored in the directory corresponding to the most recent time, i.e. 0.5. The
endTime should be set to 2 s.
2.1.7.2 Running the code
Run icoFoam for this case from the case directory and view the run time information. When
running a job in the background, the following UNIX commands can be useful:
nohup enables a command to keep running after the user who issues the command has
logged out;
nice changes the priority of the job in the kernel’s scheduler; a niceness of -20 is the highest
priority and 19 is the lowest priority.
This is useful, for example, if a user wishes to set a case running on a remote machine and
does not wish to monitor it heavily, in which case they may wish to give it low priority
on the machine. In that case the nohup command allows the user to log out of a remote
machine he/she is running on and the job continues running, while nice can set the priority
to 19. For our case of interest, we can execute the command in this manner as follows:
nohup nice -n 19 icoFoam > log &
cat log
In previous runs you may have noticed that icoFoam stops solving for velocity Uquite quickly
but continues solving for pressure pfor a lot longer or until the end of the run. In practice,
once icoFoam stops solving for Uand the initial residual of pis less than the tolerance
set in the fvSolution dictionary (typically 10−6), the run has effectively converged and can
be stopped once the field data has been written out to a time directory. For example, at
convergence a sample of the log file from the run on the cavityHighRe case appears as follows
in which the velocity has already converged after 1.395 s and initial pressure residuals are
small; No Iterations 0 indicates that the solution of Uhas stopped:
1Time = 1.43
2
3Courant Number mean: 0.221921 max: 0.839902
4smoothSolver: Solving for Ux, Initial residual = 8.73381e-06, Final residual = 8.73381e-06, No Iterations 0
5smoothSolver: Solving for Uy, Initial residual = 9.89679e-06, Final residual = 9.89679e-06, No Iterations 0
6DICPCG: Solving for p, Initial residual = 3.67506e-06, Final residual = 8.62986e-07, No Iterations 4
7time step continuity errors : sum local = 6.57947e-09, global = -6.6679e-19, cumulative = -6.2539e-18
8DICPCG: Solving for p, Initial residual = 2.60898e-06, Final residual = 7.92532e-07, No Iterations 3
9time step continuity errors : sum local = 6.26199e-09, global = -1.02984e-18, cumulative = -7.28374e-18
10 ExecutionTime = 0.37 s ClockTime = 0 s
11
12 Time = 1.435
13
14 Courant Number mean: 0.221923 max: 0.839903
15 smoothSolver: Solving for Ux, Initial residual = 8.53935e-06, Final residual = 8.53935e-06, No Iterations 0
16 smoothSolver: Solving for Uy, Initial residual = 9.71405e-06, Final residual = 9.71405e-06, No Iterations 0
17 DICPCG: Solving for p, Initial residual = 4.0223e-06, Final residual = 9.89693e-07, No Iterations 3
18 time step continuity errors : sum local = 8.15199e-09, global = 5.33614e-19, cumulative = -6.75012e-18
19 DICPCG: Solving for p, Initial residual = 2.38807e-06, Final residual = 8.44595e-07, No Iterations 3
20 time step continuity errors : sum local = 7.48751e-09, global = -4.42707e-19, cumulative = -7.19283e-18
21 ExecutionTime = 0.37 s ClockTime = 0 s
OpenFOAM-6

U-44 Tutorials
2.1.8 High Reynolds number flow
View the results in paraFoam and display the velocity vectors. The secondary vortices in
the corners have increased in size. The user can then increase the Reynolds number further
by decreasing the viscosity and then rerun the case. The number of vortices increases so the
mesh resolution around them will need to increase in order to resolve the more complicated
flow patterns. In addition, as the Reynolds number increases the time to convergence
increases. The user should monitor residuals and extend the endTime accordingly to ensure
convergence.
The need to increase spatial and temporal resolution then becomes impractical as the
flow moves into the turbulent regime, where problems of solution stability may also occur. Of
course, many engineering problems have very high Reynolds numbers and it is infeasible to
bear the huge cost of solving the turbulent behaviour directly. Instead Reynolds-averaged
simulation (RAS) turbulence models are used to solve for the mean flow behaviour and
calculate the statistics of the fluctuations. The standard k−εmodel with wall functions
will be used in this tutorial to solve the lid-driven cavity case with a Reynolds number of
104. Two extra variables are solved for: k, the turbulent kinetic energy; and, ε, the turbulent
dissipation rate. The additional equations and models for turbulent flow are implemented
into a OpenFOAM solver called pisoFoam.
2.1.8.1 Pre-processing
Go back to the run directory and copy the cavity case in the $FOAM_RUN/tutorials/-
incompressible/pisoFoam/RAS directory (N.B: the pisoFoam/RAS directory), renaming it
cavityRAS to avoid a clash with the existing cavity tutorial. Go into the new case directory.
run
cp -r $FOAM_TUTORIALS/incompressible/pisoFoam/RAS/cavity cavityRAS
cd cavityRAS
Generate the mesh by running blockMesh as before. Mesh grading towards the wall is not
necessary when using the standard k−εmodel with wall functions since the flow in the
near wall cell is modelled, rather than having to be resolved.
A range of wall function models is available in OpenFOAM that are applied as boundary
conditions on individual patches. This 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, νtin the 0/nut file:
17
18 dimensions [0 2 -1 0 0 0 0];
19
20 internalField uniform 0;
21
22 boundaryField
23 {
24 movingWall
25 {
26 type nutkWallFunction;
27 value uniform 0;
28 }
29 fixedWalls
30 {
31 type nutkWallFunction;
32 value uniform 0;
33 }
34 frontAndBack
OpenFOAM-6

2.1 Lid-driven cavity flow U-45
35 {
36 type empty;
37 }
38 }
39
40
41 // ************************************************************************* //
This case uses standard wall functions, specified by the nutWallFunction type on the
movingWall and fixedWalls patches. Other wall function models include the rough wall
functions, specified though the nutRoughWallFunction keyword.
The user should now open the field files for kand ε(0/k and 0/epsilon) and examine
their boundary conditions. For a wall boundary condition, εis assigned a epsilonWallFunction
boundary condition and a kqRwallFunction boundary condition is assigned to k. 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,qor Reynolds Stress R. The initial values for kand εare set
using an estimated fluctuating component of velocity U′and a turbulent length scale, l.k
and εare defined in terms of these parameters as follows:
k=1
2U′•U′(2.8)
ε=C0.75
µk1.5
l(2.9)
where Cµis a constant of the k−εmodel equal to 0.09. For a Cartesian coordinate system,
kis given by:
k=1
2(U′2
x+U′2
y+U′2
z)(2.10)
where U′2
x,U′2
yand U′2
zare the fluctuating components of velocity in the x,yand z
directions respectively. Let us assume the initial turbulence is isotropic, i.e. U′2
x=U′2
y=
U′2
z, and equal to 5% of the lid velocity and that l, is equal to 5% of the box width, 0.1 m,
then kand εare given by:
U′
x=U′
y=U′
z=5
1001 m s−1(2.11)
⇒k=3
2µ5
100¶2
m2s−2= 3.75 ×10−3m2s−2(2.12)
ε=C0.75
µk1.5
l≈7.54 ×10−3m2s−3(2.13)
These form the initial conditions for kand ε. The initial conditions for Uand pare (0,0,0)
and 0 respectively as before.
Turbulence modelling includes a range of methods, e.g. RAS or large-eddy simulation
(LES), that are provided in OpenFOAM. The choice of turbulence modelling method is
selectable at run-time through the simulationType keyword in turbulenceProperties dictio-
nary. The user can view this file in the constant directory:
17
18 simulationType RAS;
19
20 RAS
21 {
22 RASModel kEpsilon;
23
OpenFOAM-6

U-46 Tutorials
24 turbulence on;
25
26 printCoeffs on;
27 }
28
29 // ************************************************************************* //
The options for simulationType are laminar,RAS and LES. With RAS selected in this case,
the choice of RAS modelling is specified in a RAS subdictionary. The turbulence model
is selected by the RASModel entry from a long list of available models that are listed in
Section 7.2.1.1. The kEpsilon model should be selected which is is the standard k−ε
model; the user should also ensure that turbulence calculation is switched on.
The coefficients for each turbulence model are stored within the respective code with
a set of default values. Setting the optional switch called printCoeffs to on will make
the default values be printed to standard output, i.e. the terminal, when the model is
called at run time. The coefficients are printed out as a sub-dictionary whose name is
that of the model name with the word Coeffs appended, e.g. kEpsilonCoeffs in the case
of the kEpsilon model. The coefficients of the model, e.g. kEpsilon, can be modified by
optionally including (copying and pasting) that sub-dictionary within the RAS sub-dictionary
and adjusting values accordingly.
The user should next set the laminar kinematic viscosity in the transportProperties dic-
tionary. To achieve a Reynolds number of 104, a kinematic viscosity of 10−5mis required
based on the Reynolds number definition given in Equation 2.1.
Finally the user should set the startTime,stopTime,deltaT and the writeInterval
in the controlDict. Set deltaT to 0.005 s to satisfy the Courant number restriction and the
endTime to 10 s.
2.1.8.2 Running the code
Execute pisoFoam by entering the case directory and typing “pisoFoam” in a terminal. In
this case, where the viscosity is low, the boundary layer next to the moving lid is very thin
and the cells next to the lid are comparatively large so the velocity at their centres are
much less than the lid velocity. In fact, after ≈100 time steps it becomes apparent that
the velocity in the cells adjacent to the lid reaches an upper limit of around 0.2 m s−1hence
the maximum Courant number does not rise much above 0.2. It is sensible to increase the
solution time by increasing the time step to a level where the Courant number is much closer
to 1. Therefore reset deltaT to 0.02 s and, on this occasion, set startFrom to latestTime.
This instructs pisoFoam to read the start data from the latest time directory, i.e.10.0. The
endTime should be set to 20 s since the run converges a lot slower than the laminar case.
Restart the run as before and monitor the convergence of the solution. View the results at
consecutive time steps as the solution progresses to see if the solution converges to a steady-
state or perhaps reaches some periodically oscillating state. In the latter case, convergence
may never occur but this does not mean the results are inaccurate.
2.1.9 Changing the case geometry
A user may wish to make changes to the geometry of a case and perform a new simulation.
It may be useful to retain some or all of the original solution as the starting conditions for
the new simulation. This is a little complex because the fields of the original solution are
not consistent with the fields of the new case. However the mapFields utility can map fields
that are inconsistent, either in terms of geometry or boundary types or both.
OpenFOAM-6

2.1 Lid-driven cavity flow U-47
As an example, let us copy the cavityClipped case from the tutorials directory in the user’s
run directory, and change into the cavityClipped directory:
run
cp -r $FOAM_TUTORIALS/incompressible/icoFoam/cavity/cavityClipped .
cd cavityClipped
The case consists of the standard cavity geometry but with a square of length 0.04 m removed
from the bottom right of the cavity, according to the blockMeshDict below:
17 convertToMeters 0.1;
18
19 vertices
20 (
21 (0 0 0)
22 (0.6 0 0)
23 (0 0.4 0)
24 (0.6 0.4 0)
25 (1 0.4 0)
26 (0 1 0)
27 (0.6 1 0)
28 (1 1 0)
29
30 (0 0 0.1)
31 (0.6 0 0.1)
32 (0 0.4 0.1)
33 (0.6 0.4 0.1)
34 (1 0.4 0.1)
35 (0 1 0.1)
36 (0.6 1 0.1)
37 (1 1 0.1)
38
39 );
40
41 blocks
42 (
43 hex (0 1 3 2 8 9 11 10) (12 8 1) simpleGrading (1 1 1)
44 hex (2 3 6 5 10 11 14 13) (12 12 1) simpleGrading (1 1 1)
45 hex (3 4 7 6 11 12 15 14) (8 12 1) simpleGrading (1 1 1)
46 );
47
48 edges
49 (
50 );
51
52 boundary
53 (
54 lid
55 {
56 type wall;
57 faces
58 (
59 (5 13 14 6)
60 (6 14 15 7)
61 );
62 }
63 fixedWalls
64 {
65 type wall;
66 faces
67 (
68 (0 8 10 2)
69 (2 10 13 5)
70 (7 15 12 4)
71 (4 12 11 3)
72 (3 11 9 1)
73 (1 9 8 0)
74 );
75 }
76 frontAndBack
77 {
78 type empty;
79 faces
80 (
81 (0 2 3 1)
OpenFOAM-6

U-48 Tutorials
82 (2 5 6 3)
83 (3 6 7 4)
84 (8 9 11 10)
85 (10 11 14 13)
86 (11 12 15 14)
87 );
88 }
89 );
90
91 mergePatchPairs
92 (
93 );
94
95 // ************************************************************************* //
Generate the mesh with blockMesh. The patches are set accordingly as in previous cavity
cases. For the sake of clarity in describing the field mapping process, the upper wall patch
is renamed lid, previously the movingWall patch of the original cavity.
In an inconsistent mapping, there is no guarantee that all the field data can be mapped
from the source case. The remaining data must come from field files in the target case itself.
Therefore field data must exist in the time directory of the target case before mapping
takes place. In the cavityClipped case the mapping is set to occur at time 0.5 s, since the
startTime is set to 0.5 s in the controlDict. Therefore the user needs to copy initial field
data to that directory, e.g. from time 0:
cp -r 0 0.5
Before mapping the data, the user should view the geometry and fields at 0.5 s.
Now we wish to map the velocity and pressure fields from cavity onto the new fields of
cavityClipped. Since the mapping is inconsistent, we need to edit the mapFieldsDict dictio-
nary, located in the system directory. The dictionary contains 2 keyword entries: patchMap
and cuttingPatches. The patchMap list contains a mapping of patches from the source
fields to the target fields. It is used if the user wishes a patch in the target field to inherit
values from a corresponding patch in the source field. In cavityClipped, we wish to inherit the
boundary values on the lid patch from movingWall in cavity so we must set the patchMap
as:
patchMap
(
lid movingWall
);
The cuttingPatches list contains names of target patches whose values are to be
mapped from the source internal field through which the target patch cuts. In this case, the
fixedWalls patch is a noSlip condition so the internal values cannot be interpolated to the
patch. Therefore the cuttingPatches list can simply be empty:
cuttingPatches
(
);
If the user does wish to interpolate internal values from the source case to the fixedWalls
patch in the target case, a fixedValue boundary condition needs to be specified on the patch,
OpenFOAM-6

2.1 Lid-driven cavity flow U-49
Figure 2.14: cavity solution velocity field mapped onto cavityClipped.
Figure 2.15: cavityClipped solution for velocity field.
OpenFOAM-6

U-50 Tutorials
whose value can then be overridden during the mapping process; the fixedWalls patch
then needs to be included in the cuttingPatches list.
The user should run mapFields, from within the cavityClipped directory:
mapFields ../cavity
The user can view the mapped field as shown in Figure 2.14. The fixedWalls patch has
not inherited values from the source case as we expected. The user can then run the case
with icoFoam.
2.1.10 Post-processing the modified geometry
Velocity glyphs can be generated for the case as normal, first at time 0.5 s and later at
time 0.6 s, to compare the initial and final solutions. In addition, we provide an outline of
the geometry which requires some care to generate for a 2D case. The user should select
Extract Block from the Filter menu and, in the Parameter panel, highlight the patches
of interest, namely the lid and fixedWalls. On clicking Apply, these items of geometry can be
displayed by selecting Wireframe in the Display panel. Figure 2.15 displays the patches in
black and shows vortices forming in the bottom corners of the modified geometry.
2.2 Stress analysis of a plate with a hole
This tutorial describes how to pre-process, run and post-process a case involving linear-
elastic, steady-state stress analysis on a square plate with a circular hole at its centre. The
plate dimensions are: side length 4 mand radius R=0.5 m. It is loaded with a uniform
traction of σ=10 kPa over its left and right faces as shown in Figure 2.16. Two symmetry
planes can be identified for this geometry and therefore the solution domain need only cover
a quarter of the geometry, shown by the shaded area in Figure 2.16.
The problem can be approximated as 2-dimensional 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
(σxx)x=0 =
σµ1 + R2
2y2+3R4
2y4¶for |y| ≥ R
0for |y|< R
(2.14)
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-6

2.2 Stress analysis of a plate with a hole U-51
xsymmetry plane
4.0 m
y
σ=10 kPa
σ=10 kPa
R=0.5 m
symmetry plane
Figure 2.16: Geometry of the plate with a hole.
2.2.1 Mesh generation
The domain consists of four blocks, some of which have arc-shaped edges. The block struc-
ture for the part of the mesh in the x−yplane is shown in Figure 2.17. As already mentioned
in section 2.1.1.1, all geometries are generated in 3 dimensions in OpenFOAM even if the
case is to be as a 2 dimensional problem. Therefore a dimension of the block in the z
direction has to be chosen; here, 0.5 mis selected. It does not affect the solution since the
traction boundary condition is specified as a stress rather than a force, thereby making the
solution independent of the cross-sectional area.
The user should change to the run directory and copy the plateHole case into it from
the $FOAM_TUTORIALS/stressAnalysis/solidDisplacementFoam directory. The user should
then go into the plateHole directory and open the blockMeshDict file in an editor, as listed
below
17 convertToMeters 1;
18
19 vertices
20 (
21 (0.5 0 0)
22 (1 0 0)
23 (2 0 0)
24 (2 0.707107 0)
25 (0.707107 0.707107 0)
26 (0.353553 0.353553 0)
27 (2 2 0)
28 (0.707107 2 0)
29 (0 2 0)
30 (0 1 0)
31 (0 0.5 0)
32 (0.5 0 0.5)
33 (1 0 0.5)
34 (2 0 0.5)
35 (2 0.707107 0.5)
36 (0.707107 0.707107 0.5)
37 (0.353553 0.353553 0.5)
38 (2 2 0.5)
39 (0.707107 2 0.5)
OpenFOAM-6

U-52 Tutorials
x
y x2
x1x1
x2
x2
x1
x1
x2
x2x1
left
left
up 7up
right
3
down
hole
0
down
right
6
9
8
4
10
10 2
5
2
1
4 3
Figure 2.17: Block structure of the mesh for the plate with a hole.
40 (0 2 0.5)
41 (0 1 0.5)
42 (0 0.5 0.5)
43 );
44
45 blocks
46 (
47 hex (5 4 9 10 16 15 20 21) (10 10 1) simpleGrading (1 1 1)
48 hex (0 1 4 5 11 12 15 16) (10 10 1) simpleGrading (1 1 1)
49 hex (1 2 3 4 12 13 14 15) (20 10 1) simpleGrading (1 1 1)
50 hex (4 3 6 7 15 14 17 18) (20 20 1) simpleGrading (1 1 1)
51 hex (9 4 7 8 20 15 18 19) (10 20 1) simpleGrading (1 1 1)
52 );
53
54 edges
55 (
56 arc 0 5 (0.469846 0.17101 0)
57 arc 5 10 (0.17101 0.469846 0)
58 arc 1 4 (0.939693 0.34202 0)
59 arc 4 9 (0.34202 0.939693 0)
60 arc 11 16 (0.469846 0.17101 0.5)
61 arc 16 21 (0.17101 0.469846 0.5)
62 arc 12 15 (0.939693 0.34202 0.5)
63 arc 15 20 (0.34202 0.939693 0.5)
64 );
65
66 boundary
67 (
68 left
69 {
70 type symmetryPlane;
71 faces
72 (
73 (8 9 20 19)
OpenFOAM-6

2.2 Stress analysis of a plate with a hole U-53
74 (9 10 21 20)
75 );
76 }
77 right
78 {
79 type patch;
80 faces
81 (
82 (2 3 14 13)
83 (3 6 17 14)
84 );
85 }
86 down
87 {
88 type symmetryPlane;
89 faces
90 (
91 (0 1 12 11)
92 (1 2 13 12)
93 );
94 }
95 up
96 {
97 type patch;
98 faces
99 (
100 (7 8 19 18)
101 (6 7 18 17)
102 );
103 }
104 hole
105 {
106 type patch;
107 faces
108 (
109 (10 5 16 21)
110 (5 0 11 16)
111 );
112 }
113 frontAndBack
114 {
115 type empty;
116 faces
117 (
118 (10 9 4 5)
119 (5 4 1 0)
120 (1 4 3 2)
121 (4 7 6 3)
122 (4 9 8 7)
123 (21 16 15 20)
124 (16 11 12 15)
125 (12 13 14 15)
126 (15 14 17 18)
127 (15 18 19 20)
128 );
129 }
130 );
131
132 mergePatchPairs
133 (
134 );
135
136 // ************************************************************************* //
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.3.1. 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.17 the x2direction of block 0 is equivalent to the −x1direction for block 4. This
means care must be taken when defining the number and distribution of cells in each block
OpenFOAM-6

U-54 Tutorials
so that the cells match up at the block faces.
6 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
ageometric 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.2.
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.2. It should
appear as in Figure 2.18.
Figure 2.18: Mesh of the hole in a plate problem.
2.2.1.1 Boundary and initial conditions
Once the mesh generation is complete, the initial field with boundary conditions must be
set. For a stress analysis case without thermal stresses, only displacement Dneeds to be set.
The 0/D is as follows:
17 dimensions [0 1 0 0 0 0 0];
18
19 internalField uniform (0 0 0);
20
21 boundaryField
22 {
23 left
24 {
25 type symmetryPlane;
26 }
27 right
28 {
29 type tractionDisplacement;
30 traction uniform (10000 0 0);
31 pressure uniform 0;
32 value uniform (0 0 0);
33 }
34 down
OpenFOAM-6

2.2 Stress analysis of a plate with a hole U-55
35 {
36 type symmetryPlane;
37 }
38 up
39 {
40 type tractionDisplacement;
41 traction uniform (0 0 0);
42 pressure uniform 0;
43 value uniform (0 0 0);
44 }
45 hole
46 {
47 type tractionDisplacement;
48 traction uniform (0 0 0);
49 pressure uniform 0;
50 value uniform (0 0 0);
51 }
52 frontAndBack
53 {
54 type empty;
55 }
56 }
57
58 // ************************************************************************* //
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 traction bound-
ary 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 traction so the boundary trac-
tion 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.
2.2.1.2 Mechanical properties
The physical properties for the case are set in the mechanicalProperties dictionary in the con-
stant directory. For this problem, we need to specify the mechanical properties of steel given
in Table 2.1. In the mechanical properties dictionary, the user must also set planeStress
to yes.
Property Units Keyword Value
Density kg m−3rho 7854
Young’s modulus Pa E2×1011
Poisson’s ratio — nu 0.3
Table 2.1: Mechanical properties for steel
2.2.1.3 Thermal properties
The temperature field variable Tis present in the solidDisplacementFoam solver since the user
may opt to solve a thermal equation that is coupled with the momentum equation through
the thermal stresses that are generated. The user specifies at run time whether OpenFOAM
OpenFOAM-6

U-56 Tutorials
should solve the thermal equation by the thermalStress switch in the thermalProperties
dictionary. This dictionary also sets the thermal properties for the case, e.g. for steel as
listed in Table 2.2.
Property Units Keyword Value
Specific heat capacity Jkg−1K−1C434
Thermal conductivity Wm−1K−1k60.5
Thermal expansion coeff. K−1alpha 1.1×10−5
Table 2.2: Thermal properties for steel
In this case we do not want to solve for the thermal equation. Therefore we must set
the thermalStress keyword entry to no in the thermalProperties dictionary.
2.2.1.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:
17
18 application solidDisplacementFoam;
19
20 startFrom startTime;
21
22 startTime 0;
23
24 stopAt endTime;
25
26 endTime 100;
27
28 deltaT 1;
29
30 writeControl timeStep;
31
32 writeInterval 20;
33
34 purgeWrite 0;
35
36 writeFormat ascii;
37
38 writePrecision 6;
39
40 writeCompression off;
41
42 timeFormat general;
43
44 timePrecision 6;
45
46 graphFormat raw;
47
48 runTimeModifiable true;
49
50
51 // ************************************************************************* //
2.2.1.5 Discretisation schemes and linear-solver control
Let us turn our attention to the fvSchemes dictionary. Firstly, the problem we are analysing
is steady-state so the user should select SteadyState for the time derivatives in timeScheme.
OpenFOAM-6

2.2 Stress analysis of a plate with a hole U-57
This essentially switches off the time derivative terms. Not all solvers, especially in fluid
dynamics, work for both steady-state and transient problems but solidDisplacementFoam
does work, since the base algorithm is the same for both types of simulation.
The momentum equation in linear-elastic stress analysis includes several explicit terms
containing the gradient of displacement. The calculations benefit from accurate and smooth
evaluation of the gradient. Normally, in the finite volume method the discretisation is based
on Gauss’s theorem The Gauss method is sufficiently accurate for most purposes but, in this
case, the least squares method will be used. The user should therefore open the fvSchemes
dictionary in the system directory and ensure the leastSquares method is selected for the
grad(U) gradient discretisation scheme in the gradSchemes sub-dictionary:
17
18 d2dt2Schemes
19 {
20 default steadyState;
21 }
22
23 ddtSchemes
24 {
25 default Euler;
26 }
27
28 gradSchemes
29 {
30 default leastSquares;
31 grad(D) leastSquares;
32 grad(T) leastSquares;
33 }
34
35 divSchemes
36 {
37 default none;
38 div(sigmaD) Gauss linear;
39 }
40
41 laplacianSchemes
42 {
43 default none;
44 laplacian(DD,D) Gauss linear corrected;
45 laplacian(DT,T) Gauss linear corrected;
46 }
47
48 interpolationSchemes
49 {
50 default linear;
51 }
52
53 snGradSchemes
54 {
55 default none;
56 }
57
58 // ************************************************************************* //
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 Dis GAMG. The solver tolerance should be set to
10−6for 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).
17
18 solvers
OpenFOAM-6

U-58 Tutorials
19 {
20 "(D|T)"
21 {
22 solver GAMG;
23 tolerance 1e-06;
24 relTol 0.9;
25 smoother GaussSeidel;
26 nCellsInCoarsestLevel 20;
27 }
28 }
29
30 stressAnalysis
31 {
32 compactNormalStress yes;
33 nCorrectors 1;
34 D 1e-06;
35 }
36
37
38 // ************************************************************************* //
The fvSolution dictionary contains a sub-dictionary, stressAnalysis that contains some control
parameters specific to the application solver. Firstly there is nCorrectors which specifies
the number of outer loops around the complete system of equations, including traction
boundary conditions within each time step. Since this problem is steady-state, we are
performing a set of iterations towards a converged solution with the ’time step’ acting
as an iteration counter. We can therefore set nCorrectors to 1.
The Dkeyword specifies a convergence tolerance for the outer iteration loop, i.e. sets a
level of initial residual below which solving will cease. It should be set to the desired solver
tolerance specified earlier, 10−6for this problem.
2.2.2 Running the code
The user should run the code here in the background from the command line as specified
below, so he/she can look at convergence information in the log file afterwards.
solidDisplacementFoam > log &
The user should check the convergence information by viewing the generated log file which
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. Once both initial residuals have dropped below the
convergence tolerance of 10−6the run has converged and can be stopped by killing the batch
job.
2.2.3 Post-processing
Post processing can be performed as in section 2.1.4. The solidDisplacementFoam solver
outputs the stress field σas a symmetric tensor field sigma. This is consistent with the way
variables are usually represented in OpenFOAM solvers by the mathematical symbol by
which they are represented; in the case of Greek symbols, the variable is named phonetically.
For post-processing individual scalar field components, σxx,σxy etc., can be generated
by running the postProcess utility as before in section 2.1.5.7, this time on sigma:
postProcess -func "components(sigma)"
OpenFOAM-6

2.2 Stress analysis of a plate with a hole U-59
0
5
10
15
20
25
30
σxx (kPa)
Figure 2.19: σxx stress field in the plate with hole.
Components named sigmaxx,sigmaxy etc. are written to time directories of the case. The
σxx stresses can be viewed in paraFoam as shown in Figure 2.19.
We would like to compare the analytical solution of Equation 2.14 to our solution.
We therefore must output a set of data of σxx along the left edge symmetry plane of our
domain. The user may generate the required graph data using the postProcess utility with
the singleGraph function. Unlike earlier examples of postProcess where no configuration
is required, this example includes a singleGraph 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:
9singleGraph
10 {
11 start (0 0.5 0.25);
12 end (0 2 0.25);
13 fields (sigmaxx);
14
15 #includeEtc "caseDicts/postProcessing/graphs/sampleDict.cfg"
16
17 setConfig
18 {
19 axis y;
20 }
21
22 // Must be last entry
23 #includeEtc "caseDicts/postProcessing/graphs/graph.cfg"
24 }
25
26 // ************************************************************************* //
The user should execute postProcessing with the singleGraph function:
postProcess -func "singleGraph"
Data is written is raw 2 column format into files within time subdirectories of a post-
Processing/singleGraph directory, e.g. the data at t= 100 s is found within the file sin-
gleGraph/100/line_sigmaxx.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:
plot [0.5:2] [0:] "postProcessing/singleGraph/100/line_sigmaxx.xy",
OpenFOAM-6

U-60 Tutorials
0
5
10
15
20
25
30
35
0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0
Stress (σxx)x=0 (kPa)
Distance, y(m)
Numerical prediction Analytical solution
Figure 2.20: Normal stress along the vertical symmetry (σxx)x=0
1e4*(1+(0.125/(x**2))+(0.09375/(x**4)))
An example plot is shown in Figure 2.20.
2.2.4 Exercises
The user may wish to experiment with solidDisplacementFoam by trying the following exer-
cises:
2.2.4.1 Increasing mesh resolution
Increase the mesh resolution in each of the xand ydirections. Use mapFields to map the
final coarse mesh results from section 2.2.3 to the initial conditions for the fine mesh.
2.2.4.2 Introducing mesh grading
Grade the mesh so that the cells near the hole are finer than those away from the hole.
Design the mesh so that the ratio of sizes between adjacent cells is no more than 1.1 and so
that the ratio of cell sizes between blocks is similar to the ratios within blocks. Mesh grading
is described in section 2.1.6. Again use mapFields to map the final coarse mesh results from
section 2.2.3 to the initial conditions for the graded mesh. Compare the results with those
from the analytical solution and previous calculations. Can this solution be improved upon
using the same number of cells with a different solution?
2.2.4.3 Changing the plate size
The analytical solution is for an infinitely large plate with a finite sized hole in it. Therefore
this solution is not completely accurate for a finite sized plate. To estimate the error,
increase the plate size while maintaining the hole size at the same value.
OpenFOAM-6

2.3 Breaking of a dam U-61
2.3 Breaking of a dam
In this tutorial we shall solve a problem of simplified dam break in 2 dimensions using the
interFoam.The feature of the problem is a transient flow of two fluids separated by a sharp
interface, or free surface. The two-phase algorithm in interFoam is based on the volume of
fluid (VOF) method in which a specie transport equation is used to determine the relative
volume fraction of the two phases, or phase fraction α, in each computational cell. Physical
properties are calculated as weighted averages based on this fraction. The nature of the
VOF method means that an interface between the species is not explicitly computed, but
rather emerges as a property of the phase fraction field. Since the phase fraction can have
any value between 0 and 1, the interface is never sharply defined, but occupies a volume
around the region where a sharp interface should exist.
The test setup consists of a column of water at rest located behind a membrane on the
left side of a tank. At time t= 0 s, the membrane is removed and the column of water
collapses. During the collapse, the water impacts an obstacle at the bottom of the tank
and creates a complicated flow structure, including several captured pockets of air. The
geometry and the initial setup is shown in Figure 2.21.
0.584 m
0.048 m
0.024 m
0.584 m
0.292 m
0.1459 m0.1461 m
water column
Figure 2.21: Geometry of the dam break.
2.3.1 Mesh generation
The user should go to their run directory and copy the damBreak case from the $FOAM_TUTO-
RIALS/multiphase/interFoam/laminar/damBreak directory, i.e.
run
cp -r $FOAM_TUTORIALS/multiphase/interFoam/laminar/damBreak/damBreak .
OpenFOAM-6

U-62 Tutorials
Go into the damBreak case directory and generate the mesh running blockMesh as described
previously. The damBreak mesh consist of 5 blocks; the blockMeshDict entries are given
below.
17 convertToMeters 0.146;
18
19 vertices
20 (
21 (0 0 0)
22 (2 0 0)
23 (2.16438 0 0)
24 (4 0 0)
25 (0 0.32876 0)
26 (2 0.32876 0)
27 (2.16438 0.32876 0)
28 (4 0.32876 0)
29 (0 4 0)
30 (2 4 0)
31 (2.16438 4 0)
32 (4 4 0)
33 (0 0 0.1)
34 (2 0 0.1)
35 (2.16438 0 0.1)
36 (4 0 0.1)
37 (0 0.32876 0.1)
38 (2 0.32876 0.1)
39 (2.16438 0.32876 0.1)
40 (4 0.32876 0.1)
41 (0 4 0.1)
42 (2 4 0.1)
43 (2.16438 4 0.1)
44 (4 4 0.1)
45 );
46
47 blocks
48 (
49 hex (0 1 5 4 12 13 17 16) (23 8 1) simpleGrading (1 1 1)
50 hex (2 3 7 6 14 15 19 18) (19 8 1) simpleGrading (1 1 1)
51 hex (4 5 9 8 16 17 21 20) (23 42 1) simpleGrading (1 1 1)
52 hex (5 6 10 9 17 18 22 21) (4 42 1) simpleGrading (1 1 1)
53 hex (6 7 11 10 18 19 23 22) (19 42 1) simpleGrading (1 1 1)
54 );
55
56 edges
57 (
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 }
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 }
OpenFOAM-6

2.3 Breaking of a dam U-63
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 mergePatchPairs
105 (
106 );
107
108 // ************************************************************************* //
2.3.2 Boundary conditions
The user can examine the boundary geometry generated by blockMesh by viewing the bound-
ary file in the constant/polyMesh directory. The file contains a list of 5 boundary patches:
leftWall,rightWall,lowerWall,atmosphere and defaultFaces. The user should notice
the type of the patches. The atmosphere is a standard patch,i.e. has no special attributes,
merely an entity on which boundary conditions can be specified. The defaultFaces patch
is 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, should an application need to know, e.g. to apply special wall surface modelling.
For example, the interFoam solver includes modelling of surface tension and 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.
In this tutorial we would like to ignore surface tension effects between the wall and
interface. We can do this by setting the static contact angle, θ0= 90◦. However, rather
than using the constantAlphaContactAngle boundary condition, the simpler zeroGradient can
be applied 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:
•totalPressure which is a fixedValue condition calculated from specified total pressure
p0 and local velocity U;
•pressureInletOutletVelocity, which applies zeroGradient on all components, except where
there is inflow, in which case a fixedValue condition is applied to the tangential com-
ponent;
•inletOutlet, which is a zeroGradient condition when flow outwards, 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 velocity
boundary condition for solvers that include body forces such as gravity and surface tension.
OpenFOAM-6

U-64 Tutorials
The defaultFaces patch representing the front and back planes of the 2D problem, is,
as usual, an empty type.
2.3.3 Setting initial field
Unlike the previous cases, we shall now specify a non-uniform initial condition for the phase
fraction αwater where
αwater =(1for the water phase
0for the air phase (2.15)
This will be done by running the setFields utility. It requires a setFieldsDict dictionary,
located in the system directory, whose entries for this case are shown below.
17
18 defaultFieldValues
19 (
20 volScalarFieldValue alpha.water 0
21 );
22
23 regions
24 (
25 boxToCell
26 {
27 box (0 0 -1) (0.1461 0.292 1);
28 fieldValues
29 (
30 volScalarFieldValue alpha.water 1
31 );
32 }
33 );
34
35
36 // ************************************************************************* //
The defaultFieldValues sets the default value of the fields, i.e. the value the field takes
unless specified otherwise in the regions sub-dictionary. That sub-dictionary contains a list
of subdictionaries containing fieldValues that override the defaults in a specified region.
The region creates a set of points, cells or faces based on some topological constraint. Here,
boxToCell creates a bounding box within a vector minimum and maximum to define the
set of cells of the water region. The phase fraction αwater is defined 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 tutorial, the alpha.water field is initially stored as a
backup named 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 therefore execute setFields like any other utility by:
setFields
Using paraFoam, check that the initial alpha.water field corresponds to the desired distri-
bution as in Figure 2.22.
OpenFOAM-6

2.3 Breaking of a dam U-65
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
Phase fraction, α1
Figure 2.22: Initial conditions for phase fraction alpha.water.
2.3.4 Fluid properties
Let us examine the transportProperties file in the constant directory. The dictionary first
contains the names of each fluid phase in the phases list, here water and air. The material
properties for each fluid are then separated into two dictionaries water and air. The trans-
port model for each phase is selected by the transportModel keyword. The user should
select Newtonian in which case the kinematic viscosity is single valued and specified under
the keyword nu. The viscosity parameters for other models, e.g.CrossPowerLaw, would oth-
erwise be specified as described in section 7.3. The density is specified under the keyword
rho.
The surface tension between the two phases is specified by the keyword sigma. The
values used in this tutorial are listed in Table 2.3.
water properties
Kinematic viscosity m2s−1nu 1.0×10−6
Density kg m−3rho 1.0×103
air properties
Kinematic viscosity m2s−1nu 1.48 ×10−5
Density kg m−3rho 1.0
Properties of both phases
Surface tension N m−1sigma 0.07
Table 2.3: Fluid properties for the damBreak tutorial
Gravitational acceleration is uniform across the domain and is specified in a file named
gin the constant directory. Unlike a normal field file, e.g. Uand p,gis a uniformDimen-
sionedVectorField and so simply contains a set of dimensions and a value that represents
(0,9.81,0) m s−2for this tutorial:
OpenFOAM-6

U-66 Tutorials
17
18 dimensions [0 1 -2 0 0 0 0];
19 value (0 -9.81 0);
20
21
22 // ************************************************************************* //
2.3.5 Turbulence modelling
As in the cavity example, the choice of turbulence modelling method is selectable at run-time
through the simulationType keyword in turbulenceProperties dictionary. In this example,
we wish to run without turbulence modelling so we set laminar:
17
18 simulationType laminar;
19
20
21 // ************************************************************************* //
2.3.6 Time step control
Time step control is an important issue in transient simulation and the surface-tracking
algorithm in interface capturing solvers. The Courant number Co needs to be limited
depending on the choice of algorithm: with the “explicit” MULES algorithm, an upper limit
of Co ≈0.25 for stability is typical in the region of the interface; but with “semi-implicit”
MULES, specified by the MULESCorr keyword in the fvSolution file, 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, so interFoam
offers automatic adjustment of the time step as standard in the controlDict. The user should
specify adjustTimeStep to be on and the the maximum Co for the phase fields, maxAlphaCo,
and other fields, maxCo, to be 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 even with automatic time step adjustment, OpenFOAM allows the user to specify
that results are written at fixed times; in this case OpenFOAM forces the automatic time
stepping procedure to adjust time steps so that it ‘hits’ on the exact times specified for write
output. The user selects this with the adjustableRunTime option for writeControl in the
controlDict dictionary. The controlDict dictionary entries should be:
17
18 application interFoam;
19
20 startFrom startTime;
21
22 startTime 0;
23
24 stopAt endTime;
25
26 endTime 1;
27
28 deltaT 0.001;
29
30 writeControl adjustableRunTime;
31
32 writeInterval 0.05;
33
34 purgeWrite 0;
35
OpenFOAM-6

2.3 Breaking of a dam U-67
36 writeFormat binary;
37
38 writePrecision 6;
39
40 writeCompression off;
41
42 timeFormat general;
43
44 timePrecision 6;
45
46 runTimeModifiable yes;
47
48 adjustTimeStep yes;
49
50 maxCo 1;
51 maxAlphaCo 1;
52
53 maxDeltaT 1;
54
55
56 // ************************************************************************* //
2.3.7 Discretisation schemes
The interFoam solver uses the multidimensional universal limiter for explicit solution (MULES)
method, created by Henry Weller, to maintain boundedness of the phase fraction indepen-
dent of underlying numerical scheme, mesh structure, etc. The choice of schemes for con-
vection are therfore not restricted to those that are strongly stable or bounded, e.g. upwind
differencing.
The convection schemes settings are made in the divSchemes sub-dictionary of the fv-
Schemes dictionary. In this example, the convection term in the momentum equation
(∇•(ρUU)), denoted by the div(rhoPhi,U) keyword, uses Gauss linearUpwind grad(U)
to produce good accuracy. Here, we have opted for best stability with φ= 1.0. The
∇•(Uα1)term, represented by the div(phi,alpha) keyword uses the vanLeer scheme.
The ∇•(Urbα1)term, represented by the div(phirb,alpha) keyword, can use second or-
der linear (central) differencing as boundedness is assured by the MULES algorithm.
The other discretised terms use commonly employed schemes so that the fvSchemes
dictionary entries should therefore be:
17
18 ddtSchemes
19 {
20 default Euler;
21 }
22
23 gradSchemes
24 {
25 default Gauss linear;
26 }
27
28 divSchemes
29 {
30 div(rhoPhi,U) Gauss linearUpwind grad(U);
31 div(phi,alpha) Gauss vanLeer;
32 div(phirb,alpha) Gauss linear;
33 div(((rho*nuEff)*dev2(T(grad(U))))) Gauss linear;
34 }
35
36 laplacianSchemes
37 {
38 default Gauss linear corrected;
39 }
40
41 interpolationSchemes
42 {
43 default linear;
44 }
45
OpenFOAM-6

U-68 Tutorials
46 snGradSchemes
47 {
48 default corrected;
49 }
50
51
52 // ************************************************************************* //
2.3.8 Linear-solver control
In the fvSolution file, the alpha.water sub-dictionary in solvers contains elements that are
specific to interFoam. Of particular interest are the nAlphaSubCycles and cAlpha keywords.
nAlphaSubCycles represents the number of sub-cycles within the αequation; sub-cycles are
additional solutions to an equation within a given time step. It is used to enable the solution
to be stable without reducing the time step and vastly increasing the solution time. Here
we specify 2 sub-cycles, which means that the αequation is solved in 2×half length time
steps within each actual time step.
The cAlpha keyword is a factor that controls the compression of the interface where: 0
corresponds to no compression; 1 corresponds to conservative compression; and, anything
larger than 1, relates to enhanced compression of the interface. We generally adopt a value
of 1.0 which is employed in this example.
2.3.9 Running the code
Running of the code has been described in detail in previous tutorials. Try the following,
that uses tee, a command that enables output to be written to both standard output and
files:
cd $FOAM_RUN/damBreak
interFoam | tee log
The code will now be run interactively, with a copy of output stored in the log file.
2.3.10 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.23.
2.3.11 Running in parallel
The results from the previous example are generated using a fairly coarse mesh. We now
wish to increase the mesh resolution and re-run the case. The new case will typically take
a few hours to run with a single processor so, should the user have access to multiple
processors, we can demonstrate the parallel processing capability of OpenFOAM.
The user should first clone the damBreak case, e.g. by
run
foamCloneCase damBreak damBreakFine
Enter the new case directory and change the blocks description in the blockMeshDict dic-
tionary to
OpenFOAM-6

2.3 Breaking of a dam U-69
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
Phase fraction, α1
(a) At t= 0.25 s.
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
Phase fraction, α1
(b) At t= 0.50 s.
Figure 2.23: Snapshots of phase α.
OpenFOAM-6

U-70 Tutorials
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)
hex (6 7 11 10 18 19 23 22) (40 76 1) simpleGrading (1 2 1)
);
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
121. 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 0time directory since it contains a number of elements that
is inconsistent with the new mesh. Note that there is no need to change the Uand p_rgh
fields since they are specified as uniform which is independent of the number of elements
in the field. We wish to initialise the field with a sharp interface, i.e. it elements would
have α= 1 or α= 0. Updating the field with mapFields may produce interpolated values
0< α < 1at the interface, so it is better to rerun the setFields utility.
The mesh size is now inconsistent with the number of elements in the alpha.water.gz file
in the 0directory, so the user must delete that file so that the original alpha.water.orig file
is used instead.
rm 0/alpha.water.gz
setFields
The method of parallel computing used by OpenFOAM is known as domain decomposi-
tion, in which the geometry and associated fields are broken into pieces and allocated to sep-
arate processors for solution. The first step required to run a parallel case is therefore to de-
compose the domain using the decomposePar utility. There is a dictionary associated with de-
composePar named decomposeParDict which is located in the system directory of the tutorial
case; also, like with many utilities, a default dictionary can be found in the directory of the
source code of the specific utility, i.e. in $FOAM_UTILITIES/parallelProcessing/decomposePar
for this case.
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.
In this tutorial, the method of decomposition should be simple and the corresponding
simpleCoeffs should be edited according to the following criteria. The domain is split
into pieces, or subdomains, in the x,yand zdirections, 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 nzmust equal 1. The nxand nycomponents of nsplit the domain
in the xand ydirections and must be specified so that the number of subdomains specified
by nxand nyequals the specified numberOfSubdomains,i.e. nxny=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 xand ydirections should be
fairly even. The delta keyword should be set to 0.001.
OpenFOAM-6

2.3 Breaking of a dam U-71
For example, let us assume we wish to run on 4 processors. We would set numberOf-
Subdomains to 4 and n= (2,2,1). The user should run decomposePar with:
decomposePar
The terminal output shows that the decomposition is distributed fairly even between the
processors.
The user should consult section 3.4 for details of how to run a case in parallel; in
this tutorial we merely present an example of running in parallel. We use the openMPI
implementation of the standard message-passing interface (MPI). As a test here, the user
can run in parallel on a single node, the local host only, by typing:
mpirun -np 4 interFoam -parallel >log &
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. The case
should run in the background and the user can follow its progress by monitoring the log file
as usual.
Figure 2.24: Mesh of processor 2 in parallel processed case.
2.3.12 Post-processing a case run in parallel
Once the case has completed running, the decomposed fields and mesh can be reassembled
for post-processing using the reconstructPar utility. Simply execute it from the command
line. The results from the fine mesh are shown in Figure 2.25. The user can see that the
resolution of interface has improved significantly compared to the coarse mesh.
The user may also post-process an individual region of the decomposed domain individ-
ually by simply treating the individual processor directory as a case in its own right. For
example if the user starts paraFoam by
paraFoam -case processor1
then processor1 will appear as a case module in ParaView. Figure 2.24 shows the mesh from
processor 1 following the decomposition of the domain using the simple method.
OpenFOAM-6

U-72 Tutorials
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
Phase fraction, α1
(a) At t= 0.25 s.
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0
Phase fraction, α1
(b) At t= 0.50 s.
Figure 2.25: Snapshots of phase αwith refined mesh.
OpenFOAM-6
Chapter 3
Applications and libraries
We should reiterate from the outset that OpenFOAM is a C++ library used primarily to
create executables, known as applications. OpenFOAM is distributed with a large set of
precompiled applications but users also have the freedom to create their own or modify
existing ones. Applications are split into two main categories:
solvers that are each designed to solve a specific problem in computational continuum
mechanics;
utilities that perform simple pre-and post-processing tasks, mainly involving data manip-
ulation and algebraic calculations.
OpenFOAM is divided into a set of precompiled libraries that are dynamically linked during
compilation of the solvers and utilities. Libraries such as those for physical models are
supplied as source code so that users may conveniently add their own models to the libraries.
This chapter gives an overview of solvers, utilities and libraries, their creation, modification,
compilation and execution.
3.1 The programming language of OpenFOAM
In order to understand the way in which the OpenFOAM library works, some background
knowledge of C++, the base language of OpenFOAM, is required; the necessary information
will be presented in this chapter. Before doing so, it is worthwhile addressing the concept of
language in general terms to explain some of the ideas behind object-oriented programming
and our choice of C++ as the main programming language of OpenFOAM.
3.1.1 Language in general
The success of verbal language and mathematics is based on efficiency, especially in express-
ing abstract concepts. For example, in fluid flow, we use the term “velocity field”, which has
meaning without any reference to the nature of the flow or any specific velocity data. The
term encapsulates the idea of movement with direction and magnitude and relates to other
physical properties. In mathematics, we can represent velocity field by a single symbol, e.g.
U, and express certain concepts using symbols, e.g. “the field of velocity magnitude” by
|U|. The advantage of mathematics over verbal language is its greater efficiency, making it
possible to express complex concepts with extreme clarity.

U-74 Applications and libraries
The problems that we wish to solve in continuum mechanics are not presented in terms of
intrinsic entities, or types, known to a computer, e.g. bits, bytes, integers. They are usually
presented first in verbal language, then as partial differential equations in 3 dimensions of
space and time. The equations contain the following concepts: scalars, vectors, tensors,
and fields thereof; tensor algebra; tensor calculus; dimensional units. The solution to these
equations involves discretisation procedures, matrices, solvers, and solution algorithms.
3.1.2 Object-orientation and C++
Progamming languages that are object-oriented, such as C++, provide the mechanism —
classes — to declare types and associated operations that are part of the verbal and mathe-
matical languages used in science and engineering. Our velocity field introduced earlier can
be represented in programming code by the symbol Uand “the field of velocity magnitude”
can be mag(U). The velocity is a vector field for which there should exist, in an object-
oriented code, a vectorField class. The velocity field Uwould then be an instance, or object,
of the vectorField class; hence the term object-oriented.
The clarity of having objects in programming that represent physical objects and abstract
entities should not be underestimated. 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.
3.1.3 Equation representation
A central theme of the OpenFOAM design is that the solver applications, written using the
OpenFOAM classes, have a syntax that closely resembles the partial differential equations
being solved. For example the equation
∂ρU
∂t +∇•φU− ∇ •µ∇U=−∇p
is represented by the code
solve
(
fvm::ddt(rho, U)
+ fvm::div(phi, U)
- fvm::laplacian(mu, U)
==
- fvc::grad(p)
);
This and other requirements demand that the principal programming language of Open-
FOAM has object-oriented features such as inheritance, template classes, virtual functions
and operator overloading. These features are not available in many languages that purport
OpenFOAM-6

3.2 Compiling applications and libraries U-75
to be object-orientated but actually have very limited object-orientated capability, such
as FORTRAN-90. C++, however, possesses all these features while having the additional
advantage that it is widely used with a standard specification so that reliable compilers
are available that produce efficient executables. It is therefore the primary language of
OpenFOAM.
3.1.4 Solver codes
Solver codes are largely procedural since they are a close representation of solution algo-
rithms and equations, which are themselves procedural in nature. Users do not need a deep
knowledge of object-orientation and C++ programming to write a solver but should know
the principles behind object-orientation and classes, and to have a basic knowledge of some
C++ code syntax. An understanding of the underlying equations, models and solution
method and algorithms is far more important.
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, its functions
etc. is supplied with the OpenFOAM distribution in HTML documentation generated with
Doxygen at https://cpp.openfoam.org
3.2 Compiling applications and libraries
Compilation is an integral part of application development that requires careful management
since every piece of code requires its own set instructions to access dependent components
of the OpenFOAM library. In UNIX/Linux systems these instructions are often organised
and delivered to the compiler using the standard UNIXmake utility. OpenFOAM uses its
own wmake compilation script that is based on make but is considerably more versatile
and easier to use (wmake can be used on any code, not only the OpenFOAM library). To
understand the compilation process, we first need to explain certain aspects of C++ and
its file structure, shown schematically in Figure 3.1. A class is defined through a set of
instructions such as object construction, data storage and class member functions. The file
that defines these functions — the class definition — takes a .C extension, e.g. a class nc
would be written in the file nc.C. This file can be compiled independently of other code into
a binary executable library file known as a shared object library with the .so file extension,
i.e.nc.so. When compiling a piece of code, say newApp.C, that uses the nc class, nc.C need
not be recompiled, rather newApp.C calls the nc.so library at runtime. This is known as
dynamic linking.
3.2.1 Header .H files
As a means of checking errors, the piece of code being compiled must know that the classes
it uses and the operations they perform actually exist. Therefore each class requires a class
declaration, contained in a header file with a .H file extension, e.g. nc.H, that includes the
names of the class and its functions. This file is included at the beginning of any piece
of code using the class, using the #include directive described below, including the class
declaration code itself. Any piece of .C code can resource any number of classes and must
OpenFOAM-6

U-76 Applications and libraries
int main()
...
...
return(0);
{
}
nc.so
Library
option-I
#include "nc.H"
Main code
Code...
Compiled
nc.H
nc.C
#include "nc.H"
nc class
Definition...
Compiled
Executable
Header file
Linked
option-l
newApp.C
newApp
Figure 3.1: Header files, source files, compilation and linking
begin by including all the .H files required to declare these classes. Those classes in turn
can resource other classes and so also begin by including the relevant .H files. By searching
recursively down the class hierarchy we can produce a complete list of header files for all the
classes on which the top level .C code ultimately depends; these .H files are 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-platform compilation and linkage, handled through appropriate directory struc-
ture.
•Multi-language compilation and linkage, e.g. C, C++, Java.
•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-6

3.2 Compiling applications and libraries U-77
•Simple syntax for source file lists.
•Automatic creation of source file lists for new codes.
•Simple handling of multiple shared or static libraries.
•Extensible to new machine types.
•Extremely portable, works on any machine with: make;sh,ksh or csh;lex,cc.
3.2.2 Compiling with wmake
OpenFOAM applications are organised using a standard convention that the source code
of each application is placed in a directory whose name is that of the application. The top
level source file then takes the application name with the .C extension. For example, the
source code for an application called newApp would reside is a directory newApp and the
top level file would be newApp.C as shown in Figure 3.2.wmake then requires the directory
newApp
newApp.C
otherHeader.H
Make
files
options
Figure 3.2: Directory structure for an application
must contain a Make subdirectory containing 2 files, options and files, that are described in
the following sections.
3.2.2.1 Including headers
The compiler searches for the included header files in the following order, specified with the
-I option in wmake:
1. the $WM_PROJECT_DIR/src/OpenFOAM/lnInclude directory;
2. a local lnInclude directory, i.e.newApp/lnInclude;
3. the local directory, i.e.newApp;
4. platform dependent paths set in files in the $WM_PROJECT_DIR/wmake/rules/-
$WM_ARCH/ directory, e.g./usr/X11/include and $(MPICH_ARCH_PATH)/include;
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:
OpenFOAM-6

U-78 Applications and libraries
EXE_INC = \
-I<directoryPath1>\
-I<directoryPath2>\
... \
-I<directoryPathN>
Notice first that the directory names are preceeded by the -I flag and that the syntax uses
the \to continue the EXE_INC across several lines, with no \after the final entry.
3.2.2.2 Linking to libraries
The compiler links to shared object library files in the following directory paths, specified
with the -L option in wmake:
1. the $FOAM_LIBBIN directory;
2. platform dependent paths set in files in the $WM_DIR/rules/$WM_ARCH/ directory,
e.g./usr/X11/lib and $(MPICH_ARCH_PATH)/lib;
3. other directories specified in the Make/options file.
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:
1. the libOpenFOAM.so library from the $FOAM_LIBBIN directory;
2. platform dependent libraries specified in set in files in the $WM_DIR/rules/$WM_ARCH/
directory, e.g. libm.so from /usr/X11/lib and liblam.so from $(LAM_ARCH_PATH)/lib;
3. other libraries specified in the Make/options file.
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 preceeded by the -L flag, the library names are
preceeded by the -l flag.
OpenFOAM-6

3.2 Compiling applications and libraries U-79
3.2.2.3 Source files to be compiled
The compiler requires a list of .C source files that must be compiled. The list must contain
the main .C file but also any other source files that are created for the specific application
but are not included in a class library. For example, users may create a new class or some
new functionality to an existing class for a particular application. The full list of .C source
files must be included in the Make/files file. For many applications the list only includes the
name of the main .C file, e.g. newApp.C in the case of our earlier example.
The Make/files file also includes a full path and name of the compiled executable, specified
by the EXE = syntax. Standard convention stipulates the name is that of the application,
i.e.newApp in our example. The OpenFOAM release offers two useful choices for path:
standard release applications are stored in $FOAM_APPBIN; applications developed by the
user are stored in $FOAM_USER_APPBIN.
If the user is developing their own applications, we recommend they create an applications
subdirectory in their $WM_PROJECT_USER_DIR directory containing the source code for
personal OpenFOAM applications. As with standard applications, the source code for each
OpenFOAM application should be stored within its own directory. The only difference
between a user application and one from the standard release is that the Make/files file
should specify that the user’s executables are written into their $FOAM_USER_APPBIN
directory. The Make/files file for our example would appear as follows:
newApp.C
EXE = $(FOAM_USER_APPBIN)/newApp
3.2.2.4 Running wmake
The wmake script is generally executed by typing:
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.
3.2.2.5 wmake environment variables
For information, the environment variable settings used by wmake are listed in Table 3.1.
3.2.3 Removing dependency lists: wclean
On execution, wmake builds a dependency list file with a .dep file extension, e.g. newApp.C.dep
in our example, in a $WM_OPTIONS sub-directory of the Make directory, e.g. Make/linux-
GccDPInt64Opt. If the user wishes to remove these files, e.g. after making code changes, the
user can run the wclean script by typing:
wclean <optionalDirectory>
OpenFOAM-6

U-80 Applications and libraries
Main paths
$WM_PROJECT_INST_DIR Full path to installation directory,
e.g.$HOME/OpenFOAM
$WM_PROJECT Name of the project being compiled: OpenFOAM
$WM_PROJECT_VERSION Version of the project being compiled: 6
$WM_PROJECT_DIR Full path to locate binary executables of OpenFOAM
release, e.g. $HOME/OpenFOAM/OpenFOAM-6
$WM_PROJECT_USER_DIR Full path to locate binary executables of the user e.g.
$HOME/OpenFOAM/${USER}-6
$WM_THIRD_PARTY_DIR Full path to the ThirdParty software directory e.g.
$HOME/OpenFOAM/ThirdParty-6
Other paths/settings
$WM_ARCH Machine architecture: linux,linux64,linuxIa64,
linuxARM7,linuxPPC64,linuxPPC64le
$WM_ARCH_OPTION 32 or 64 bit architecture
$WM_COMPILER Compiler being used: Gcc -gcc,ICC - Intel, Clang -
LLVM Clang
$WM_COMPILE_OPTION Compilation option: Debug - debugging, Opt optimisa-
tion.
$WM_COMPILER_TYPE Choice of compiler: system,ThirdParty - compiled in
ThirdParty directory
$WM_DIR Full path of the wmake directory
$WM_LABEL_SIZE 32 or 64 bit size for labels (integers)
$WM_LABEL_OPTION Int32 or Int64 compilation of labels
$WM_LINK_LANGUAGE Compiler used to link libraries and executables c++.
$WM_MPLIB Parallel communications library: SYSTEMOPENMPI - sys-
tem version of openMPI,OPENMPI,SYSTEMMPI,MPICH,
MPICH-GM,HPMPI,MPI,QSMPI,SGIMPI.
$WM_OPTIONS =$WM_ARCH...
$WM_COMPILER...
$WM_PRECISION_OPTION...
$WM_LABEL_OPTION...
$WM_COMPILE_OPTION
e.g. linuxGccDPInt64Opt
$WM_PRECISION_OPTION Precision of the compiled binares, SP, single precision
or DP, double precision
Table 3.1: Environment variable settings for wmake.
OpenFOAM-6

3.2 Compiling applications and libraries U-81
Again, the <optionalDirectory>is a path to the directory of the application that is being
compiled. Typically, wclean is executed from within the directory of the application, in
which case the path can be omitted.
3.2.4 Compiling libraries
When compiling a library, there are 2 critical differences in the configuration of the file in
the Make directory:
•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);
•in the options file, EXE_LIBS = is replaced by LIB_LIBS = to indicate libraries linked
to library being compiled.
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.
3.2.5 Compilation example: the pisoFoam application
The source code for application pisoFoam is in the $FOAM_APP/solvers/incompressible/piso-
Foam directory and the top level source file is named pisoFoam.C. The pisoFoam.C source
code is:
1/*---------------------------------------------------------------------------*\
2========= |
3\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4\\ / O peration |
5\\ / A nd | Copyright (C) 2011-2018 OpenFOAM Foundation
6\\/ M anipulation |
7-------------------------------------------------------------------------------
8License
9This 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 pisoFoam
26
27 Description
28 Transient solver for incompressible, turbulent flow, using the PISO
29 algorithm.
30
31 Sub-models include:
32 - turbulence modelling, i.e. laminar, RAS or LES
33 - run-time selectable MRF and finite volume options, e.g. explicit porosity
34
35 \*---------------------------------------------------------------------------*/
36
37 #include "fvCFD.H"
38 #include "singlePhaseTransportModel.H"
39 #include "turbulentTransportModel.H"
OpenFOAM-6

U-82 Applications and libraries
40 #include "pisoControl.H"
41 #include "fvOptions.H"
42
43 //*************************************//
44
45 int main(int argc, char *argv[])
46 {
47 #include "postProcess.H"
48
49 #include "setRootCaseLists.H"
50 #include "createTime.H"
51 #include "createMesh.H"
52 #include "createControl.H"
53 #include "createFields.H"
54 #include "initContinuityErrs.H"
55
56 turbulence->validate();
57
58 //***********************************//
59
60 Info<< "\nStarting time loop\n" << endl;
61
62 while (runTime.loop())
63 {
64 Info<< "Time = " << runTime.timeName() << nl << endl;
65
66 #include "CourantNo.H"
67
68 // Pressure-velocity PISO corrector
69 {
70 #include "UEqn.H"
71
72 // --- PISO loop
73 while (piso.correct())
74 {
75 #include "pEqn.H"
76 }
77 }
78
79 laminarTransport.correct();
80 turbulence->correct();
81
82 runTime.write();
83
84 Info<< "ExecutionTime = " << runTime.elapsedCpuTime() << " s"
85 << " ClockTime = " << runTime.elapsedClockTime() << " s"
86 << nl << endl;
87 }
88
89 Info<< "End\n" << endl;
90
91 return 0;
92 }
93
94
95 // ************************************************************************* //
The code begins with a brief description of the application contained within comments over 1
line (//) and multiple lines (/*...*/). Following that, the code contains several # include
statements, e.g. # include "fvCFD.H", which causes the compiler to suspend reading from
the current file, pisoFoam.C to read the fvCFD.H.
pisoFoam resources the turbulence and transport model libraries 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:
1EXE_INC = \
2-I$(LIB_SRC)/TurbulenceModels/turbulenceModels/lnInclude \
3-I$(LIB_SRC)/TurbulenceModels/incompressible/lnInclude \
4-I$(LIB_SRC)/transportModels \
5-I$(LIB_SRC)/transportModels/incompressible/singlePhaseTransportModel \
6-I$(LIB_SRC)/finiteVolume/lnInclude \
7-I$(LIB_SRC)/meshTools/lnInclude \
OpenFOAM-6

3.2 Compiling applications and libraries U-83
8-I$(LIB_SRC)/sampling/lnInclude
9
10 EXE_LIBS = \
11 -lturbulenceModels \
12 -lincompressibleTurbulenceModels \
13 -lincompressibleTransportModels \
14 -lfiniteVolume \
15 -lmeshTools \
16 -lfvOptions \
17 -lsampling
pisoFoam contains only the pisoFoam.C source and the executable is written to the $FOAM_-
APPBIN directory as all standard applications are. The Make/files therefore contains:
1pisoFoam.C
2
3EXE = $(FOAM_APPBIN)/pisoFoam
Following the recommendations of section 3.2.2.3, the user can compile a separate version
of pisoFoam into their local $FOAM_USER_DIR directory by the following:
•copying the pisoFoam source code to a local directory, e.g. $FOAM_RUN;
cd $FOAM_RUN
cp -r $FOAM_SOLVERS/incompressible/pisoFoam .
cd pisoFoam
•editing the Make/files file as follows;
1pisoFoam.C
2
3EXE = $(FOAM_USER_APPBIN)/pisoFoam
•executing wmake.
wmake
The code should compile and produce a message similar to the following
Making dependency list for source file pisoFoam.C
g++ -std=c++0x -m32...
...
-o ... platforms/linuxGccDPInt64Opt/bin/pisoFoam
The user can now try recompiling and will receive a message similar to the following to say
that the executable is up to date and compiling is not necessary:
make: ´
.../bin/pisoFoam´ is up to date.
The user can compile the application from scratch by removing the dependency list with
wclean
and running wmake.
OpenFOAM-6

U-84 Applications and libraries
3.2.6 Debug messaging and optimisation switches
OpenFOAM provides a system of messaging that is written during runtime, most of which
are to help debugging problems encountered during running of a OpenFOAM case. The
switches are listed in the $WM_PROJECT_DIR/etc/controlDict file; should the user wish
to change the settings they should make a copy to their $HOME directory, i.e. $HOME/-
.OpenFOAM/6/controlDict file. The list of possible switches is extensive and can be viewed
by running the foamDebugSwitches application. Most of the switches correspond to a class
or range of functionality and can be switched on by their inclusion in the controlDict file,
and by being set to 1. For example, OpenFOAM can perform the checking of dimensional
units in all calculations by setting the dimensionSet switch to 1. There are some switches
that control messaging at a higher level than most, listed in Table 3.2.
In addition, there are some switches that control certain operational and optimisa-
tion issues. These switches are also listed in Table 3.2. Of particular importance is
fileModificationSkew. OpenFOAM scans the write time of data files to check for mod-
ification. When running over a NFS with some disparity in the clock settings on different
machines, field data files appear to be modified ahead of time. This can cause a problem
if OpenFOAM views the files as newly modified and attempting to re-read this data. The
fileModificationSkew keyword is the time in seconds that OpenFOAM will subtract from
the file write time when assessing whether the file has been newly modified.
High level debugging switches - sub-dictionary DebugSwitches
level Overall level of debugging messaging for OpenFOAM- - 3 levels 0,
1,2
lduMatrix Messaging for solver convergence during a run - 3 levels 0,1,2
Optimisation switches - sub-dictionary OptimisationSwitches
fileModific-
ationSkew
A time in seconds that should be set higher than the maximum
delay in NFS updates and clock difference for running OpenFOAM
over a NFS.
fileModific-
ationChecking
Method of checking whether files have been modified during a
simulation, either reading the timeStamp or using inotify; ver-
sions that read only master-node data exist, timeStampMaster,
inotifyMaster.
commsType Parallel communications type: nonBlocking,scheduled,
blocking.
floatTransfer If 1, will compact numbers to float precision before transfer; de-
fault is 0
nProcsSimpleSum Optimises global sum for parallel processing; sets number of pro-
cessors above which hierarchical sum is performed rather than a
linear sum (default 16)
Table 3.2: Runtime message switches.
OpenFOAM-6

3.3 Running applications U-85
3.2.7 Linking new user-defined libraries to existing applications
The situation may arise that a user creates a new library, say new, and wishes the features
within that library to be available across a range of applications. For example, the user
may create a new boundary condition, compiled into new, that would need to be recognised
by a range of solver applications, pre- and post-processing utilities, mesh tools, etc. Under
normal circumstances, the user would need to recompile every application with the new
linked to it.
Instead there is a simple mechanism to link one or more shared object libraries dy-
namically at run-time in OpenFOAM. Simply add the optional keyword entry libs to the
controlDict file for a case and enter the full names of the libraries within a list (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"
);
3.3 Running applications
Each application is designed to be executed from a terminal command line, typically reading
and writing a set of data files associated with a particular case. The data files for a case are
stored in a directory named after the case as described in section 4.1; the directory name
with full path is here given the generic name <caseDir>.
For any application, the form of the command line entry for any can be found by simply
entering the application name at the command line with the -help option, e.g. typing
blockMesh -help
returns the usage
Usage: blockMesh [OPTIONS]
options:
-blockTopology write block edges and centres as .obj files
-case <dir> specify alternate case directory, default is the
cwd
-dict <file> specify alternative dictionary for the blockMesh
description
-noFunctionObjects do not execute functionObjects
-region <name> specify alternative mesh region
-srcDoc display source code in browser
-doc display application documentation in browser
-help print the usage
OpenFOAM-6

U-86 Applications and libraries
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 blockMesh example as a background process and
output the case progress to a log file, they could enter:
blockMesh > log &
3.4 Running applications in parallel
This section describes how to run OpenFOAM in parallel on distributed processors. The
method of parallel computing used by OpenFOAM is known as domain decomposition, in
which the geometry and associated fields are broken into pieces and allocated to separate
processors for solution. The process of parallel computation involves: decomposition of mesh
and fields; running the application in parallel; and, post-processing the decomposed case as
described in the following sections. The parallel running uses the public domain openMPI
implementation of the standard message passing interface (MPI) by default, although other
libraries can be used.
3.4.1 Decomposition of mesh and initial field data
The mesh and fields are decomposed using the decomposePar utility. The underlying aim
is to break up the domain with minimal effort but in such a way to guarantee an eco-
nomic solution. The geometry and fields are broken up according to a set of parameters
specified in a dictionary named decomposeParDict that must be located in the system di-
rectory of the case of interest. An example decomposeParDict dictionary is available from
the interFoam/damBreak tutorial if the user requires one; the dictionary entries within it are
reproduced below:
17
18 numberOfSubdomains 4;
19
20 method simple;
21
22 simpleCoeffs
23 {
24 n (2 2 1);
25 delta 0.001;
26 }
27
28 hierarchicalCoeffs
29 {
30 n (1 1 1);
31 delta 0.001;
32 order xyz;
33 }
34
35 manualCoeffs
36 {
37 dataFile "";
38 }
39
40 distributed no;
41
42 roots ( );
43
44
45 // ************************************************************************* //
OpenFOAM-6

3.4 Running applications in parallel U-87
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 direction,
e.g. 2 pieces in the xdirection, 1 in yetc.
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.
scotch Scotch decomposition which requires no geometric input from the user and attempts
to minimise the number of processor boundaries. The user can specify a weighting for
the decomposition between processors, through an optional processorWeights key-
word which can be useful on machines with differing performance between processors.
There is also an optional keyword entry strategy that controls the decomposition
strategy through a complex string supplied to Scotch. For more information, see the
source code file: $FOAM_SRC/parallel/decompose/scotchDecomp/scotchDecomp.C
manual Manual decomposition, where the user directly specifies the allocation of each cell
to a particular processor.
For each method there are a set of coefficients specified in a sub-dictionary of decomposi-
tionDict, named <method>Coeffs as shown in the dictionary listing. The full set of keyword
entries in the decomposeParDict dictionary are explained in Table 3.3.
The decomposePar utility is executed in the normal manner by typing
decomposePar
3.4.2 File input/output in parallel
Using standard file input/output completion, a set of subdirectories will have been created,
one for each processor, in the case directory. The directories are named processorNwhere
N= 0,1,...represents a processor number and contains a time directory, containing the de-
composed field descriptions, and a constant/polyMesh directory containing the decomposed
mesh description.
While this file structure is well-organised, for large parallel cases, it generates a large
number of files. In very large simulations, users can experience problems including hitting
limits on the number of open files imposed by the operating system.
As an alternative, the collated file format was introduced in OpenFOAM in which the
data for each decomposed field (and mesh) is collated into a single file that is written (and
read) on the master processor. The files are stored in a single directory named processors.
The file writing can be threaded allowing the simulation to continue running while the
data is being written to file — see below for details. NFS (Network File System) is not
needed when using the collated format and, additionally, there is a masterUncollated
option to write data with the original uncollated format without NFS.
The controls for the file handling are in the OptimisationSwitches of the global etc/-
controlDict file:
OpenFOAM-6

U-88 Applications and libraries
Compulsory entries
numberOfSubdomains Total number of subdomains N
method Method of decomposition simple/
hierarchical/
scotch/manual/
simpleCoeffs entries
nNumber of subdomains in x,y,z(nxnynz)
delta Cell skew factor Typically, 10−3
hierarchicalCoeffs entries
nNumber of subdomains in x,y,z(nxnynz)
delta Cell skew factor Typically, 10−3
order Order of decomposition xyz/xzy/yxz...
scotchCoeffs entries
processorWeights
(optional)
List of weighting factors for allocation
of cells to processors; <wt1>is the
weighting factor for processor 1, etc.;
weights are normalised so can take any
range of values.
(<wt1>...<wtN>)
strategy Decomposition strategy: optional and
complex
manualCoeffs entries
dataFile Name of file containing data of alloca-
tion of cells to processors
"<fileName>"
Distributed data entries (optional) — see section 3.4.4
distributed Is the data distributed across several
disks?
yes/no
roots Root paths to case directories; <rt1>
is the root path for node 1, etc.
(<rt1>...<rtN>)
Table 3.3: Keywords in decompositionDict dictionary.
OptimisationSwitches
{
...
//- Parallel IO file handler
// uncollated (default), collated or masterUncollated
fileHandler uncollated;
//- collated: thread buffer size for queued file writes.
// If set to 0 or not sufficient for the file size threading is not used.
// Default: 2e9
maxThreadFileBufferSize 2e9;
//- masterUncollated: non-blocking buffer size.
// If the file exceeds this buffer size scheduled transfer is used.
// Default: 2e9
OpenFOAM-6

3.4 Running applications in parallel U-89
maxMasterFileBufferSize 2e9;
}
3.4.2.1 Selecting the file handler
The fileHandler can be set for a specific simulation by:
•over-riding the global OptimisationSwitches {fileHandler ...;} in the case con-
trolDict file;
•using the -fileHandler command line argument to the solver;
•setting the $FOAM_FILEHANDLER environment variable.
3.4.2.2 Updating exisiting files
AfoamFormatConvert utility allows users to convert files between the collated and uncollated
formats, e.g.
mpirun -np 2 foamFormatConvert -parallel -fileHandler uncollated
An example case demonstrating the file handling methods is provided in:
$FOAM_TUTORIALS/IO/fileHandling
3.4.2.3 Threading support
Collated file handling runs faster with threading, especially on large cases. But it requires
threading support to be enabled in the underlying MPI. Without it, the simulation will
“hang” or crash. For openMPI, threading support is not set by default prior to version 2,
but is generally switched on from version 2 onwards. The user can check whether openMPI
is compiled with threading support by the following command:
ompi_info -c | grep -oE "MPI_THREAD_MULTIPLE[^,]*"
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;
When using the masterUncollated file handling, non-blocking MPI communication re-
quires a sufficiently large memory buffer on the master node. maxMasterFileBufferSize
sets the maximum size of the buffer. If the data exceeds this size, the system uses scheduled
communication.
OpenFOAM-6

U-90 Applications and libraries
3.4.3 Running a decomposed case
A decomposed OpenFOAM case is run in parallel using the openMPI implementation of
MPI.
openMPI can be run on a local multiprocessor machine very simply but when running
on machines across a network, a file must be created that contains the host names of
the machines. The file can be given any name and located at any path. In the following
description we shall refer to such a file by the generic name, including full path, <machines>.
The <machines>file contains the names of the machines listed one machine per line. The
names must correspond to a fully resolved hostname in the /etc/hosts file of the machine
on which the openMPI is run. The list must contain the name of the machine running the
openMPI. Where a machine node contains more than one processor, the node name may be
followed by the entry cpu=nwhere nis the number of processors openMPI should run on
that node.
For example, let us imagine a user wishes to run openMPI from machine aaa on the
following machines: aaa;bbb, which has 2 processors; and ccc. The <machines>would
contain:
aaa
bbb cpu=2
ccc
An application is run in parallel using mpirun.
mpirun --hostfile <machines>-np <nProcs>
<foamExec> <otherArgs>-parallel > log &
where: <nProcs>is the number of processors; <foamExec>is the executable, e.g.icoFoam;
and, the output is redirected to a file named log. For example, if icoFoam is run on 4 nodes,
specified in a file named machines, on the cavity tutorial in the $FOAM_RUN/tutorials/-
incompressible/icoFoam directory, then the following command should be executed:
mpirun --hostfile machines -np 4 icoFoam -parallel > log &
3.4.4 Distributing data across several disks
Data files may need to be distributed if, for example, if only local disks are used in order to
improve performance. In this case, the user may find that the root path to the case directory
may differ between machines. The paths must then be specified in the decomposeParDict
dictionary using distributed and roots keywords. The distributed entry should read
distributed yes;
and the roots entry is a list of root paths, <root0>,<root1>, . . . , for each node
roots
<nRoots>
(
OpenFOAM-6

3.5 Standard solvers U-91
"<root0>"
"<root1>"
...
);
where <nRoots>is the number of roots.
Each of the processorNdirectories should be placed in the case directory at each of
the root paths specified in the decomposeParDict dictionary. The system directory and files
within the constant directory must also be present in each case directory. Note: the files in
the constant directory are needed, but the polyMesh directory is not.
3.4.5 Post-processing parallel processed cases
When post-processing cases that have been run in parallel the user has two options:
•reconstruction of the mesh and field data to recreate the complete domain and fields,
which can be post-processed as normal;
•post-processing each segment of decomposed domain individually.
3.4.5.1 Reconstructing mesh and data
After a case has been run in parallel, it can be reconstructed for post-processing. The case
is reconstructed by merging the sets of time directories from each processorNdirectory into
a single set of time directories. The reconstructPar utility performs such a reconstruction by
executing the command:
reconstructPar
When the data is distributed across several disks, it must be first copied to the local case
directory for reconstruction.
3.4.5.2 Post-processing decomposed cases
The user may post-process decomposed cases using the paraFoam post-processor, described
in section 6.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.
3.5 Standard solvers
The solvers with the OpenFOAM distribution are in the $FOAM_SOLVERS directory,
reached quickly by typing sol at the command line. This directory is further subdivided into
several directories by category of continuum mechanics, e.g. incompressible flow, combustion
and solid body stress analysis. Each solver is given a name that is reasonably descriptive,
e.g.icoFoam solves incompressible, laminar flow. The current list of solvers distributed with
OpenFOAM is given in the following Sections.
OpenFOAM-6

U-92 Applications and libraries
3.5.1 ‘Basic’ CFD codes
laplacianFoam Solves a simple Laplace equation, e.g. for thermal diffusion in a solid.
potentialFoam Potential flow solver which solves for the velocity potential, to calculate the
flux-field, from which the velocity field is obtained by reconstructing the flux.
scalarTransportFoam Solves the steady or transient transport equation for a passive scalar.
3.5.2 Incompressible flow
adjointShapeOptimizationFoam Steady-state solver for incompressible, turbulent flow of non-
Newtonian fluids with optimisation of duct shape by applying "blockage" in regions
causing pressure loss as estimated using an adjoint formulation.
boundaryFoam Steady-state solver for incompressible, 1D turbulent flow, typically to gen-
erate boundary layer conditions at an inlet, for use in a simulation.
icoFoam Transient solver for incompressible, laminar flow of Newtonian fluids.
nonNewtonianIcoFoam Transient solver for incompressible, laminar flow of non-Newtonian
fluids.
pimpleFoam Transient solver for incompressible, turbulent flow of Newtonian fluids, with
optional mesh motion and mesh topology changes.
SRFPimpleFoam Large time-step transient solver for incompressible, turbulent flow in a
single rotating frame.
pisoFoam Transient solver for incompressible, turbulent flow, using the PISO algorithm.
shallowWaterFoam Transient solver for inviscid shallow-water equations with rotation.
simpleFoam Steady-state solver for incompressible, turbulent flow, using the SIMPLE algo-
rithm.
porousSimpleFoam Steady-state solver for incompressible, turbulent flow with implicit or
explicit porosity treatment and support for multiple reference frames (MRF).
SRFSimpleFoam Steady-state solver for incompressible, turbulent flow of non-Newtonian
fluids in a single rotating frame.
3.5.3 Compressible flow
rhoCentralFoam Density-based compressible flow solver based on central-upwind schemes of
Kurganov and Tadmor.
rhoCentralDyMFoam Density-based compressible flow solver based on central-upwind schemes
of Kurganov and Tadmor with support for mesh-motion and topology changes.
rhoPimpleFoam of compressible fluids for HVAC and similar applications, with optional
mesh motion and mesh topology changes.
OpenFOAM-6

3.5 Standard solvers U-93
rhoSimpleFoam Steady-state solver for turbulent flow of compressible fluids.
rhoPorousSimpleFoam Steady-state solver for turbulent flow of compressible fluids, with im-
plicit or explicit porosity treatment and optional sources.
sonicFoam Transient solver for trans-sonic/supersonic, turbulent flow of a compressible gas.
sonicDyMFoam Transient solver for trans-sonic/supersonic, turbulent flow of a compressible
gas, with optional mesh motion and mesh topology changes.
sonicLiquidFoam Transient solver for trans-sonic/supersonic, laminar flow of a compressible
liquid.
3.5.4 Multiphase flow
cavitatingFoam Transient cavitation code based on the homogeneous equilibrium model from
which the compressibility of the liquid/vapour "mixture" is obtained.
cavitatingDyMFoam Transient cavitation code based on the homogeneous equilibrium model
from which the compressibility of the liquid/vapour "mixture" is obtained, with op-
tional mesh motion and mesh topology changes.
compressibleInterFoam Solver for 2 compressible, non-isothermal immiscible fluids using a
VOF (volume of fluid) phase-fraction based interface capturing approach.
compressibleInterDyMFoam Solver for 2 compressible, non-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.
compressibleInterFilmFoam Solver for 2 compressible, non-isothermal immiscible fluids using
a VOF (volume of fluid) phase-fraction based interface capturing approach. [**]
compressibleMultiphaseInterFoam Solver for n compressible, non-isothermal immiscible fluids
using a VOF (volume of fluid) phase-fraction based interface capturing approach.
driftFluxFoam Solver for 2 incompressible fluids using the mixture approach with the drift-
flux approximation for relative motion of the phases.
interFoam Solver for 2 incompressible, isothermal immiscible fluids using a VOF (volume of
fluid) phase-fraction based interface capturing approach.
interDyMFoam Solver for 2 incompressible, isothermal immiscible fluids using a VOF (vol-
ume of fluid) phase-fraction based interface capturing approach, with optional mesh
motion and mesh topology changes including adaptive re-meshing.
interMixingFoam Solver for 3 incompressible fluids, two of which are miscible, using a VOF
method to capture the interface.
interPhaseChangeFoam Solver for 2 incompressible, isothermal immiscible fluids with phase-
change (e.g. cavitation). Uses a VOF (volume of fluid) phase-fraction based interface
capturing approach.
OpenFOAM-6

U-94 Applications and libraries
interPhaseChangeDyMFoam Solver for 2 incompressible, isothermal immiscible fluids with
phase-change (e.g. cavitation). Uses a VOF (volume of fluid) phase-fraction based
interface capturing approach, with optional mesh motion and mesh topology changes
including adaptive re-meshing.
multiphaseEulerFoam Solver for a system of many compressible fluid phases including heat-
transfer.
multiphaseInterFoam Solver for nincompressible fluids which captures the interfaces and
includes surface-tension and contact-angle effects for each phase, with optional mesh
motion and mesh topology changes.
potentialFreeSurfaceFoam Incompressible Navier-Stokes solver with inclusion of a wave height
field to enable single-phase free-surface approximations
potentialFreeSurfaceDyMFoam Incompressible Navier-Stokes solver with inclusion of a wave
height field to enable single-phase free-surface approximations, with optional mesh
motion and mesh topology changes.
reactingMultiphaseEulerFoam Solver for a system of any number of compressible fluid phases
with a common pressure, but otherwise separate properties. The type of phase model
is run time selectable and can optionally represent multiple species and in-phase re-
actions. The phase system is also run time selectable and can optionally represent
different types of momentun, heat and mass transfer.
reactingTwoPhaseEulerFoam Solver for a system of 2 compressible fluid phases with a com-
mon pressure, but otherwise separate properties. The type of phase model is run time
selectable and can optionally represent multiple species and in-phase reactions. The
phase system is also run time selectable and can optionally represent different types
of momentun, heat and mass transfer.
twoLiquidMixingFoam Solver for mixing 2 incompressible fluids.
twoPhaseEulerFoam Solver for a system of 2 compressible fluid phases with one phase dis-
persed, e.g. gas bubbles in a liquid including heat-transfer.
3.5.5 Direct numerical simulation (DNS)
dnsFoam Direct numerical simulation solver for boxes of isotropic turbulence.
3.5.6 Combustion
chemFoam Solver for chemistry problems, designed for use on single cell cases to provide
comparison against other chemistry solvers, that uses a single cell mesh, and fields
created from the initial conditions.
coldEngineFoam Solver for cold-flow in internal combustion engines.
engineFoam Transient solver for compressible, turbulent engine flow with a spray particle
cloud.
OpenFOAM-6

3.5 Standard solvers U-95
fireFoam Transient solver for fires and turbulent diffusion flames with reacting particle
clouds, surface film and pyrolysis modelling.
PDRFoam Solver for compressible premixed/partially-premixed combustion with turbulence
modelling.
reactingFoam Solver for combustion with chemical reactions.
rhoReactingBuoyantFoam Solver for combustion with chemical reactions using a density
based thermodynamics package with enhanced buoyancy treatment.
rhoReactingFoam Solver for combustion with chemical reactions using density based ther-
modynamics package.
XiengineFoam Solver for internal combustion engines using the b-Xi two-equation model.
XiFoam Solver for compressible premixed/partially-premixed combustion with turbulence
modelling.
3.5.7 Heat transfer and buoyancy-driven flows
buoyantBoussinesqPimpleFoam Transient solver for buoyant, turbulent flow of incompressible
fluids.
buoyantBoussinesqSimpleFoam Steady-state solver for buoyant, turbulent flow of incompress-
ible fluids.
buoyantPimpleFoam Transient solver for buoyant, turbulent flow of compressible fluids for
ventilation and heat-transfer.
buoyantSimpleFoam Steady-state solver for buoyant, turbulent flow of compressible fluids,
including radiation, for ventilation and heat-transfer.
chtMultiRegionFoam Solver for steady or transient fluid flow and solid heat conduction, with
conjugate heat transfer between regions, buoyancy effects, turbulence, reactions and
radiation modelling.
thermoFoam Solver for energy transport and thermodynamics on a frozen flow field.
3.5.8 Particle-tracking flows
coalChemistryFoam Transient solver for compressible, turbulent flow, with coal and lime-
stone particle clouds, an energy source, and combustion.
DPMFoam Transient solver for the coupled transport of a single kinematic particle cloud
including the effect of the volume fraction of particles on the continuous phase.
DPMDyMFoam Transient solver for the coupled transport of a single kinematic particle
cloud including the effect of the volume fraction of particles on the continuous phase,
with optional mesh motion and mesh topology changes.
OpenFOAM-6

U-96 Applications and libraries
MPPICFoam Transient solver for the coupled transport of a single kinematic particle cloud
including the effect of the volume fraction of particles on the continuous phase. Multi-
Phase Particle In Cell (MPPIC) modeling is used to represent collisions without re-
solving particle-particle interactions.
MPPICDyMFoam Transient solver for the coupled transport of a single kinematic particle
cloud including the effect of the volume fraction of particles on the continuous phase.
Multi-Phase Particle In Cell (MPPIC) modeling is used to represent collisions without
resolving particle-particle interactions, with optional mesh motion and mesh topology
changes.
icoUncoupledKinematicParcelFoam Transient solver for the passive transport of a single kine-
matic particle cloud.
icoUncoupledKinematicParcelDyMFoam Transient solver for the passive transport of a single
kinematic particle cloud, with optional mesh motion and mesh topology changes.
reactingParcelFoam Transient solver for compressible, turbulent flow with a reacting, multi-
phase particle cloud, and surface film modelling.
simpleReactingParcelFoam Steady state solver for compressible, turbulent flow with reacting,
multiphase particle clouds and optional sources/constraints.
sprayFoam Transient solver for compressible, turbulent flow with a spray particle cloud.
sprayDyMFoam Transient solver for compressible, turbulent flow with a spray particle cloud,
with optional mesh motion and mesh topology changes.
uncoupledKinematicParcelFoam Transient solver for the passive transport of a particle cloud.
uncoupledKinematicParcelDyMFoam Transient solver for the passive transport of a particle
cloud, with optional mesh motion and mesh topology changes.
3.5.9 Discrete methods
dsmcFoam Direct simulation Monte Carlo (DSMC) solver for, transient, multi-species flows.
mdEquilibrationFoam Solver to equilibrate and/or precondition molecular dynamics systems.
mdFoam Molecular dynamics solver for fluid dynamics.
3.5.10 Electromagnetics
electrostaticFoam Solver for electrostatics.
magneticFoam Solver for the magnetic field generated by permanent magnets.
mhdFoam Solver for magnetohydrodynamics (MHD): incompressible, laminar flow of a con-
ducting fluid under the influence of a magnetic field.
OpenFOAM-6

3.6 Standard utilities U-97
3.5.11 Stress analysis of solids
solidDisplacementFoam Transient segregated finite-volume solver of linear-elastic, small-strain
deformation of a solid body, with optional thermal diffusion and thermal stresses.
solidEquilibriumDisplacementFoam Steady-state segregated finite-volume solver of linear-elastic,
small-strain deformation of a solid body, with optional thermal diffusion and thermal
stresses.
3.5.12 Finance
financialFoam Solves the Black-Scholes equation to price commodities.
3.6 Standard utilities
The utilities with the OpenFOAM distribution are in the $FOAM_UTILITIES directory.
The names are reasonably descriptive, e.g. ideasToFoam converts mesh data from the for-
mat written by I-DEAS to the OpenFOAM format. The descriptions of current utilities
distributed with OpenFOAM are given in the following Sections.
3.6.1 Pre-processing
applyBoundaryLayer Apply a simplified b