OpenFOAM A C++ Library For Complex Physics Simulations
OpenFOAM A C++ Library For Complex Physics Simulations
1. Introduction
Expansion of Computational Continuum Mechanics (CCM) in engineering
design is mirrored in the maturity of commercial simulation tools in the mar-
ket. In terms of numerical techniques, structural analysis is dominated by the
Finite Element Method (FEM), while fluid flow is regularly handled using the
Finite Volume Method (FVM) of discretisation. Leading software combines ac-
curate and robust numerics with an impressive range of physical models under a
general-purpose Graphical User Interface (GUI). Current simulation challenges
are related to integration and automation of simulation tools in a Computer
Aided Engineering (CAE) environment, including automatic geometry retrieval,
surface and volume meshing and sensitivity and optimisation studies.
In terms of solver settings and user expertise, Computational Fluid Dynam-
ics (CFD) is considerably behind structural analysis, making the problems of
∗ Correspondence to: Hrvoje Jasak, E-mail: h.jasak@wikki.co.uk.
1
2 H. Jasak, A. Jemcov and Ž. Tuković
software development and usability more acute. Range and quality of physical
models, solver settings and solution algorithms, as well as the lack of robust
automatic solution control brings considerable complexity to the user.
Current state of solver development aims to produce monolithic general-
purpose tools, trying to tackle all physical problems for all users. A number of
consequences arises:
• Monolithic software necessarily implies that for any set of physics only a
small subset of functionality is being used. The impact of unused or in-
compatible model combinations remains, typically in unnecessary memory
usage;
In spite of best efforts, all CCM needs will never be catered for in this
manner. This is particularly clear when one examines the true scope of con-
tinuum modelling, including non-traditional simulations, e.g. electromagnetics,
magneto-hydrodynamics; coupled simulations like 1-D/3-D network simulations
and fluid-structure interaction [1, 2] and even more general complex trans-
port/stress models [3, 4].
The limiting factor in such cases is not lack of industrial interest or physical
or numerical understanding, but a combination of complex software and closed
architecture. At the same time, one should appreciate that a bulk of physi-
cal modelling, discretisation, numerics and linear solver expertise implemented
in commercial CFD is a product of academic research available in open litera-
ture. The software provides an efficient solution framework, including geometry
handling, mesh generation, solution, post-processing and data analysis, while
OpenFOAM for Complex Physics 3
Object Families and Run-Time Selection. In many situations, one can recognise
sets of object that perform the same function, based on identical data. As an
example, consider a Gauss-Seidel linear equation solver and a preconditioned
Conjugate Gradient solver. Both operate on a linear system [A][x] = [b] to
reach its solution [x]. Each algorithm will have its own controls (number of
sweeps, solution tolerance, type of preconditioner) and different efficiency, but
functionally they play the same role in the software.
In object orientation, such cases form class families. In C++, they are en-
coded by class derivation and virtual functions. Here, the software recognises a
common interface and interchangeable functionality of family members and im-
plements them in isolation of each other, further breaking down the complexity.
Similar situation in various guises appears throughout the numerical simulation
software: consider multiple convection differencing schemes, gradient calculation
algorithms, boundary conditions, turbulence models etc.
types and can be validated only once. In practice, the C++ compiler oper-
ates on the generic code to automatically generate and optimise type-specific
implementation.
In numerics, examples of generic programming appear throughout the soft-
ware. Consider for example, a Dirichlet boundary condition: its functionality
is the same, no matter whether it operates on a scalar, vector or tensor field.
The same is true for convective and diffusive transport, gradient schemes, field
representation (independent of the mesh location and algebraic type) and many
others.
Combination of the above makes a strong baseline for efficient and versatile
software. It remains to be seen how objects are defined and how they interact
with each other in working software.
Some Common Myths: How Fast is Your C++? In late 1990s, a discussion
on computational overheads of object orientation and implications for “object-
oriented numerical simulation software” raged in the scientific community. The
basic argument was that code execution overheads associated with new program-
ming techniques make C++ prohibitively expensive for numerically intensive
codes.
Over the last 10 years, the exact opposite has been emphatically proven.
High-level language built through object orientation allow the software devel-
oper to split the problem into several levels and concentrate on efficiency where
it should naturally be resolved. Common and well-known rules apply: low-level
data layout must follow the computer architecture (packed arrays), loop opti-
misation is achieved by avoiding forking and function calls, vector- and pipeline
instruction and data organisation is enforced. If anything, a high-level type-safe
language like C++ makes this job easier: the user of generic container classes can
accept optimisation at zero cost as changes appear only in low-level object. Com-
bining this with inline instructions in C++ and careful use of virtual functions
[10] results in the code which at worst matches the performance of procedural
languages like Fortran and C but in a more convenient interface. Ultimately, it
is the skill of the programmer and not the programming language that drives
the efficiency, which is probably more true in a complex and expressive language
like C++.
solve
(
fvm::ddt(k)
+ fvm::div(phi, k)
- fvm::laplacian(nu() + nut, k)
== nut*magSqr(symm(fvc::grad(U)))
- fvm::Sp(epsilon/k, k)
);
Correspondence between Eqn. (1) and Fig. 1. is clear, even with limited
programming knowledge and without reference to object-orientation or C++.
OpenFOAM is a substantial software package with extensive capabilities;
analysing it in detail is beyond the scope of this study. In what follows, we shall
work on recognising the main objects from the numerical modelling viewpoint
appearing in Fig. 1. and encoding them in software.
matic mesh motion, topological mesh changes (e.g. sliding interfaces, cell layer-
ing etc.) and adaptive mesh refinement perform the same function for both the
FVM and FEM. Implementing them centrally significantly improves the software
design and promotes code re-use.
Time Acting as Object Database. In the temporal dimension, things are simpler:
it is sufficient to track the time step count and time increment ∆t. Further to
this, there is a set of database operations associated with time-marching and
with related needs. For example, simulation data output should be performed
every n time-steps or x seconds of computational time, solver controls needs to be
updated in intervals etc. The time class in OpenFOAM handles both functions.
Field: List with Algebra. In field operations, one regularly operates on col-
lections of identical types, performing the same function. Thus, a field-based
dot-product of a and b involves looping over all elements in a list and storing
the result in another list. A Field class uses short-hand for implied looping
operations: for vector fields a and b:
scalarField c = a & b;
will perform the looping, calculate the dot-product and store the result into a
new field object called c.
and associated linear solvers is clear. It suffices to say that code organisation
as presented above allows the FEM and FVM discretisation to share sparse
matrix implementation and solver technology, resulting in considerable code re-
use. True benefit of such code organisation will become obvious when attempting
closely coupled simulation: sharing matrix format and implementation between
coupled solvers is extremely useful.
volVectorField g = fvc::grad(p);
creates a new FVM vector field of pressure gradient. Its boundary condi-
tions and cell values are calculated from p. Calculus operations in Fig. 1.
carry the fvc:: prefix, denoting Finite Volume Calculus;
OpenFOAM for Complex Physics 9
• Field calculus operations are used to create complex field expressions, in-
cluding field algebra (nu + nut) or calculus operations (fvc::grad(U)).
This is used to assemble the source terms and auxiliary fields;
The identical set of operations is performed in all CFD codes – the difference
in OpenFOAM is the clarity and flexibility of its programming implementation,
as shown in Fig. 1.
Looking at the high-level numerical simulation language we have assem-
bled, implementation of various complex physical models now looks very simple.
Fringe benefits from object orientation as implemented in OpenFOAM imply
considerable code re-use (mesh, matrix, field, linear solver, boundary condition)
and layered development. For example, internal implementation of a linear alge-
bra module may be changed, with minimal impact on the rest of the software –
an ideal software development situation.
way: standard k −ǫ model [12] and a Reynolds Stress Transport model [13] differ
only in the way how they perform their function.
Similar modelling libraries appear throughout the code: Newtonian and non-
Newtonian viscosity models, material property models, combustion models etc.
Model families are grouped into libraries and re-used by all relevant applications.
Quite apart from its advantages in complex physics modelling, the tool-kit
approach encourages development of auxiliary CCM tools not present in closed-
architecture packages or leading commercial software. A good example of this
is Proper Orthogonal Decomposition (POD), described below.
Consistency of the mathematical definition of field algebra with its C++
implementation allows arbitrary manipulation of computed fields to produce new
data fields. Performing algebraic operations such as addition and subtraction,
scaling, scalar products, etc. on the result enables easy computations of derived
quantities which aid in understanding the solution. In addition to visualising
vector components, streamlines and similar, one can easily assemble a reduced
order basis using the Proper Orthogonal Decomposition (POD) to represent
coherent structures in fluid flow [14, 15].
POD, also known as Principal Component Analysis or Karhunen Loève Ex-
pansion, is based on the computation of the best linear basis that describes the
dominant dynamics of the problem. Optimality of a POD basis is obtained from
the fact that the basis vectors Φ are obtained by maximising the following cost
OpenFOAM for Complex Physics 11
function: ³ ´
E |(U, Ψ)|2 E (|(U, Φ)|)
max = . (3)
Ψ (Ψ, Ψ) (Φ, Φ)
Here, symbol ( · , · ) represents the inner product in the L2 space, and E is the
mathematical expectation over a set of ensemble functions. This optimisation
problem can be solved by variational methods and the solution is given by:
Z 2π
R(x, x′ )Φ(x′ )dx′ = λΦ, (4)
0
where
R(x, x′ ) = E (U (x)U ∗ (x′ )) , (5)
where R is the auto-correlation function acting as a kernel of the integral equa-
tion in Eqn. (4).
Assuming that the ergodicity hypothesis holds [14], method of snapshots is
used to compute empirical eigenvectors of the problem in Eqn. (4). Due to
the ergodicity hypothesis, eigenvectors of the kernel R (x, x′ ) can be represented
through a linear combination of snapshots:
M
X
Φ= βi U i . (6)
i=1
Rβ = Λβ, (7)
Eigenvectors of the auto-correlation R define the POD basis since they are
ortho-normal and individual components of the eigenvalue vector Λ define the
importance of associated eigenvectors. If the eigenvalues are interpreted as the
mean flow energy of the field U (x, t) projected to a subspace spanned by the
POD vectors, the relative energy in the i-th basis vector is measured by:
λi
er = PM . (9)
k=1 λk
The relative energy er is used in the thresholding process by which eigenvec-
tors that represent negligible fraction of the total energy are eliminated, yielding
the truncated representation of the flow field:
N
X
U≈ αi Φi , (10)
i=1
12 H. Jasak, A. Jemcov and Ž. Tuković
where N ≪ M .
The newly computed basis in Eqn. (10) is used to represent the flow field in
the POD basis. Since the POD eigenvectors are directly related to the energy,
and assuming the truncation in Eqn. (10) is performed so that 99% percent
(or more) of the flow energy is retained, eigenvectors Φ represent the coherent
structures in flow field.
Coherent structures are the representation of the correlation of the given field
measured in energy norm, showing important spatial features during the time
period in which the snapshots were taken. This fact allows a new look into time
dependent computation results by revealing a sequence of coherent structures in
the flow that are not available if time averaging is used instead. This is of great
importance in DNS and LES data, where so far only time averaging was used to
compute correlations. Furthermore, since the POD basis represents the optimal
linear basis in which nonlinear problem can be represented, this procedure is
quite useful in producing reduced order models of the given problem through
Galerkin projection [15].
Advantage of OpenFOAM in the creation of a POD basis for any given prob-
lem is the existence of the field algebra that allows consistent implementation
of operations described above. Moreover, with the field algebra POD analysis
becomes an integral part of the library, removing the need for separate POD
development for a specific physics model.
5. Simulation Examples
In what follows we shall illustrate the capability of OpenFOAM at four levels:
Results summarised in this section have been reported in other topical publi-
cations – the reader is encouraged to consult the references for a more complete
description of methodology and results.
The lower part of the table includes the performance of some other acceler-
ated AMG solvers, namely Projective Forward Extrapolation (PFEAMG), Min-
imal Polynomial Extrapolation (MPEAMG) and Reduced Rank Extrapolation
(RREAMG), [18]. While the RREAMG solver produces substantial performance
improvement over standard AMG, it does so at considerable cost: the algorithm
allocates storage for 5-10 additional vectors of the size of the solution. The
CG-AMG solver is still substantially faster than the fastest vector sequence ex-
trapolation result, without the need for additional storage.
Table 2. lists the fastest linear solver setup for the fine mesh parallel test
for a serial, 2- and 4-CPU parallel run. Variation in performance is largest for
ICCG, but some parallel degradation is present for most solvers.
Figure 7. The first POD mode of pres- Figure 8. The first POD mode of ux field
sure field for turbulent flow over a forward- for turbulent flow over a forward-facing
facing step. step.
Figure 9. The first POD mode of uy field Figure 10. The first POD mode of uz field
for turbulent flow over a forward-facing for turbulent flow over a forward-facing
step. step.
Fluid Fluid
0.5
Vi (t) = V0 + Va sin(2πff t)
Vi (t) ff = fs = 1 Hz
ρs
ρf
= 100, 10, 1
Solid
Solid
2
0.5
0.2
Vi (t)
V0 a
ℜ= νf
= 300
0.5
2 a = 0.2
Y X
References
[1] A. K. Slone, K. Pericleous, C. Bailey, M. Cross, and C Bennett. A finite volume
unstructured mesh approach to dynamic fluid-structure interaction: an assessment
of the challenge of predicting the onset of flutter. Applied mathematical modelling,
28:211–239, 2004.
[2] W. A. Wall, C. Forster, M. Neumann, and E. Ramm. Advances in fluid-structure
interaction. In K Gurlebeck and C. Konke, editors, Proceedings of 17th inter-
national conference on the application of computer science and mathematics in
architecture and civil engineering, Weimar, Germany, 2006.
[3] M. Lostie, R. Peczalski, and J. Andrieu. Lumped model for sponge cake baking
during the crust and crumb period. J. food eng., 65(2):281–286, 2004.
[4] G. Franco. Development of a numerical code for the simulation of the process
of refractory concrete drying. Master’s thesis, Universitá degli studi di Trieste,
Faculty of Engineering, 2005.
20 H. Jasak, A. Jemcov and Ž. Tuković