Vous êtes sur la page 1sur 40

Decorating Boundary conditions (BC)s

Boundary Conditions Training

Tomislav Maric

OFW11 June 2016

Boundary Conditions Training 1


Decorating Boundary conditions (BC)s

Disclaimer

OpenFOAM and OpenCFD are registered trademarks of OpenCFD Limited,


the producer OpenFOAM software. All registered trademarks are property of
their respective owners. This offering is not approved or endorsed by OpenCFD
Limited, the producer of the OpenFOAM software and owner of the
OPENFOAM and OpenCFD trade marks. Jens Hpken, Tomislav Maric and
sourceflux are not associated to OpenCFD.

Jens Hpken, Tomislav Maric and sourceflux 2015. Unauthorized use and/or
duplication of this material without express and written permission from this
blogs author and/or owner is strictly prohibited. Excerpts and links may be used,
provided that full and clear credit is given to Jens Hpken, Tomislav Maric and
sourceflux with appropriate and specific direction to the original content.

Boundary Conditions Training 2


Decorating Boundary conditions (BC)s

Outline

Prerequisites

Stuff that is helpful to know before we begin


What are C++ templates?
How are C++ templates mainly used in OpenFOAM?
Does C++ template type lifting ring a bell?
What are preprocessor macros?
How is an object oriented OpenFOAM library structured?
Where and how are BCs applied in *[fF][oO][aA][mM]*?

Boundary Conditions Training Decorating Boundary conditions (BC)s Outline 3


Decorating Boundary conditions (BC)s

Outline

Learning goals

The difference between an OOD and a generic library.


What preprocessor macros actually do.
The workflow for coding generic libraries in OpenFOAM.
A fancy design pattern.
How to implement a generic BC library.
How to use the Decorator Pattern to change any BC at runtime.

All this, using Test Driven Development (TDD).

Boundary Conditions Training Decorating Boundary conditions (BC)s Outline 4


Decorating Boundary conditions (BC)s

A generic BC library

Motivation: BC oscillation added at runtime

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 5


Decorating Boundary conditions (BC)s

A generic BC library

Templates!

Transport equations are derived for tensor fields:


Mass conservation : scalar equation.
Momentum conservation : vector equation.
Viscoelastic model equations : tensor equation.
BCs encapsulated in classes : modularity, runtime flexibility.
DRY : Dont Repeat Yourself!
C++ Class Templates : classes generic for tensors.
Flexibility at compile time : static polymorphism.
BCs are selected at runtime.
Combining Object Oriented (OO) and Generic programming.
OpenFOAM macros compile-time + run-time polymorphism.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 6


Decorating Boundary conditions (BC)s

A generic BC library

General Workflow for Generic Libs


Prepare a test case as if you are already done.
Choose a solver/application that will use your BC.
Find its tutorial case, copy it and apply the BC.
Run the test application and watch it fail.
Run the solver.
Start from a similar class (this example: fvPatchField).
General case: Find the closest similar generic BC.
Use the macros to instantiate templates into actual code.
Check how other generic BCs are built - macros.
Compile the instantiated templates into an OO library.
Follow the file/naming structure.
Build libraries into FOAM_USER_LIBBIN
Link your application against the OO library.
In system/controlDict: libs("libmylibrary.so");
In Make/options if coding new apps (solver, testing,. . . ).
Clean up your code.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 7


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : specification

Oscillating Fixed Value Exists

Our task : add temporal oscillation to any existing BC.

What do we know
Oscillation : extends behavior of a BC.
Oscillating BC is a BC.
Why would we publicly inherit from fvPatchField?
It needs to know about the underlying BC:
Initialize the underlying BC.
Update the underlying BC.
Modify its values to account for oscillation.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 8


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : design

What do we have to decide


How to handle the existing BC that needs to be modified?
Inheritance?
We would need to know what to inherit from at compile time.
We want to add oscillation to a BC selected at run time.
Composition is the answer!
Compose an fvPatchField as a wrapped BC.
Build (select) the base BC using RTS.
Build (select) the wrapped BC using RTS.
Modify the wrapped BC by adding oscilllation.
Decorator Design Pattern : check out the code, it is self-documenting

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 9


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : Decorator Pattern

No worries. . .

fvPatchField 1..2
updateCoeffs()

fixedValueFvPatchField oscillatingFvPatchField
updateCoeffs() updateCoeffs()

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 10


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : Decorator Pattern

We inherit from fvPatchField because the new BC is a BC.


We wrap another fvPatchField because we want to decorate any BC.
The decorator updates the wrapped object.
The decorator modifies the wrapped object values for oscillation

f ,w = 0f ,w cos(t)

We wrap the initial values : 0f ,w and keep them.


Becos we will hit 0 at some point in time.
The decorator is the actual BC from the solvers perspective.
So, the decorator assigns the wrapped values to itself

f ,d = f ,w

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 11


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : Test Driven Development (TDD)

RED : prepare a test case.


GREEN : make the test case work.
Make the first skeleton of a library compile.
Make the unit tests work : use simple reports.
Make the logic work : algorithms running.
REFACTOR : clean up the class.
Remove commented out code.
Reduce surplus dependencies.
Improve accuracy.
Profile/benchmark and optimize.
Repeat RED, GREEN, REFACTOR steps until:
the feature is running,
the feature provides quantitatively good results,
the code has been optimized for performance,
the code is cleaned up and documented.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 12


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : act as if oscillating BC decorator is implemented

We will use the mighty cavity test case for test driven development.
?> cp -r $FOAM_TUTORIALS/incompressible/icoFoam/cavity cavityOscillating
?> cd !$
Edit: 0/U
boundaryField
{
movingWall
{
type oscillating;
wrappedType
{
type fixedValue;
value uniform (1 0 0);
}
}
Execute: blockMesh, then icoFoam in the case directory.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 13


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : OpenFOAM RTS failures


--> FOAM FATAL IO ERROR:
Unknown patchField type oscillating for patch type wall

Valid patchField types are :

73
(
SRFFreestreamVelocity
SRFVelocity
activeBaffleVelocity
activePressureForceBaffleVelocity
advective
calculated
codedFixedValue

The RTS (described fully on our blog) lets you know:


oscillating BC is missing,
which BCs are available.
Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 14
Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : preparing a library


Prerequisites : Building an OpenFOAM library training / blog post.
Execute:
?> cd ..
?> mkdir extendedBoundaryConditions
?> cd !$
?> mkdir Make
?> touch Make/{files,options}
Edit: Make/options

EXE_INC = \
-I$(LIB_SRC)/finiteVolume/lnInclude \
-I$(LIB_SRC)/meshTools/lnInclude

EXE_LIBS = \
-lfiniteVolume \
-lmeshTools

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 15


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : preparing a library

Edit: Make/files

oscillatingFvPatchField/oscillatingFvPatchFields.C

LIB = $(FOAM_USER_LIBBIN)/libextendedBoundaryConditions

Time to start coding the BC.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 16


Decorating Boundary conditions (BC)s

A generic BC library

What do we keep, and what do we throw away?

Check out other BCs:


Which files do they have?
Which member functions do they implement?
updateCoeffs : updates boundary field values
value(Internal|Boundary)Coeffs : (Coeffs|Values) used by div
gradient(Internal|Boundary)Coeffs: (Coeffs|Values) used by laplacian
Described in detail also in the new book by Moukalled, Mangani and Darwish
[1].
What about RTS when inheriting from the base?
Described in our blog posts on RTS.
Delete all RTS related stuff from the derived class.
Remove the New selector.
Remove RTS table declaration and definition.
We want to add the derived type to the existing base RTS table.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 17


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : starting from fvPatchField

We start from fvPatchField to learn about BCs: starting from another


BC would require much less cleanup.
?> mkdir oscillatingFvPatchField
?> cd !$
?> cp $FOAM_SRC/finiteVolume/fields/fvPatchFields/fvPatchField/* .
?> rm *Mapper*
?> rm *New*
?> for file in fvPatch*; do mv $file ${file/fvPatch/oscillatingFvPatch}; done
?> sed -i 's/fvPatchField/oscillatingFvPatchField/g' *
What we just did: copy a bunch of files, rename them and replace the class names.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 18


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : fvPatchField inheritance

Edit: oscillatingFvPatchField.H
Delete existing include statements.
Add
#include "fvPatchField.H"

Delete all forward declaration lines.


Inherit from fvPatchField<Type>
template<class Type>
class oscillatingFvPatchField
:
public fvPatchField<Type>

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 19


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : class cleanup


Edit: oscillatingFvPatchField.H
Delete all private data members of fvPatchField.
Delete the typedef for the patch.
Shorten the type name:
//- Runtime type information
TypeName("oscillating");

Delete everything that should be done by the wrapped class:


RTS table declarations, selectors, arithmetic operators, mappers. . .
Leave all constructors and destructors as they are.
Delete all member function declarations except these:
write(Ostream&) const;
virtual void updateCoeffs();
virtual tmp<Field<Type> > valueInternalCoeffs(const...
virtual tmp<Field<Type> > valueBoundaryCoeffs(const...
virtual tmp<Field<Type> > gradientInternalCoeffs() const;
virtual tmp<Field<Type> > gradientBoundaryCoeffs()

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 20


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : class cleanup

Edit: oscillatingFvPatchField.H
Delete all arithmetic operators coming from fvPatchField.
Delete the member function bodies of:
valueInternalCoeffs
valueBoundaryCoeffs
gradientInternalCoeffs
gradientBoundaryCoeffs
fvPatchField is a class template: check the macros at the EOF.
They generate the definition of the virtual type() m-function.
They initialize the debug flag (class-static label).
They generate the definition for the internal RTS table class.
Now delete those macros : they are also re-used from fvPatchField.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 21


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : class cleanup


Edit: oscillatingFvPatchField.H
Time to wrap some boundary conditions:
template<class Type>
class oscillatingFvPatchField
:
public fvPatchField<Type>
{
// Wrapped boundary condition.
tmp<fvPatchField<Type> > wrappedTmp_;

// Initial wrapped boundary condition.


tmp<fvPatchField<Type> > wrappedInitialTmp_;

Remember the UML diagram?


One wrapped BC to bind them: wraps itself around another BC.
One wrapped BC to initialize them: prevents cos to zero the BC.

One inherited to rule them all: acts as the real BC.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 22


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : implementation
Edit: oscillatingFvPatchField.C
Forward all constructor calls:
namespace Foam {
template<class Type>
oscillatingFvPatchField<Type>::oscillatingFvPatchField
(
const fvPatch& p,
const DimensionedField<Type, volMesh>& iF
)
:
fvPatchField<Type>(p, iF),
wrappedTmp_(new fvPatchField<Type>(p, iF)),
wrappedInitialTmp_(new fvPatchField<Type>(p, iF))
{}
We have one base and two wrapped BCs to initialize.
Repeat for all constructors.
Extend Foam namespace and save time in typing Foam::.
Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 23
Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : implementation

Write down the wrapped values


template<class Type>
void oscillatingFvPatchField<Type>::write(Ostream& os) const
{
wrappedTmp_->write(os);
}

We could have also left this one out, since we are assigning values to
Decorator.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 24


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : implementation
Edit: oscillatingFvPatchField.C
Implement:
valueInternalCoeffs
valueBoundaryCoeffs
gradientInternalCoeffs
gradientBoundaryCoeffs
You will behave as the modified (decorated) wrapped BC:
template<class Type>
tmp<Field<Type> >
oscillatingFvPatchField<Type>::valueInternalCoeffs
(
const tmp<scalarField>& tsf
) const
{
return wrappedTmp_->valueInternalCoeffs(tsf);
}
Repeat for other m-functions.
Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 25
Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : implementation : updateCoeffs 1


void oscillatingFvPatchField<Type>::updateCoeffs()
{
if (this->updated())
{
return;
}

// Update the wrapped BC values.


wrappedTmp_->updateCoeffs();

// Get the wrapped BC fields


Field<Type>& wrappedInitialField = wrappedInitialTmp_();
Field<Type>& wrappedField = wrappedTmp_();

// Initialize the wrapped BC field only once.


if (runTime.timeIndex() == 1)
wrappedInitialField = wrappedField;
Update the wrapped BC and set the initial values.
Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 26
Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : implementation : updateCoeffs 2

// Modify the values of the wrapped BC.


const Time& runTime = this->db().time();
wrappedField =
wrappedInitialField
* cos(runTime.timeOutputValue() * M_PI);

// Assign the new field values to self.


fvPatchField<Type>::operator==(wrappedField);
}

fvPatchField<Type>::operator== : field value assignment

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 27


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : building the library : template instantiation

#include "oscillatingFvPatchFields.H"
#include "fvPatchFields.H"
#include "addToRunTimeSelectionTable.H"
#include "volFields.H"

namespace Foam
{
makePatchFields(oscillating);
}

What are we doing here and why are we doing it?

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 28


Decorating Boundary conditions (BC)s

A generic BC library

Instantiating class templates in OpenFOAM

C++ templates cannot be compiled.


They are used to instantiate code that is then compiled.
OpenFOAM uses macros to instantiate templates for tensors:
scalar, vector, sphericalTensor, symmetricTensor and tensor.
Often a single macro call is required.
The macro call is placed in a separate .C file.
More information: Building an OpenFOAM library Training / Blog Posts.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 29


Decorating Boundary conditions (BC)s

A generic BC library

Instantiating BC class templates : calling the macro

Create a new .C file : oscillatingFvPatchFields.C


Be careful: the file name is yourChosenClassName + s + .C.
It is a convention in OpenFOAM : also helps others understand your code.
File content for a BC:
namespace Foam
{
makePatchFields(oscillating);
}

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 30


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : building the library : typedefs


Edit : oscillatingFvPatchFields.H
#include "oscillatingFvPatchField.H"
#include "fieldTypes.H"

namespace Foam
{

makePatchTypeFieldTypedefs(oscillating);

} // End namespace Foam

What is stored in fieldTypes.H?


What are we doing here?
Why?

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 31


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : building the library : forward declaration

Edit : oscillatingFvPatchFieldsFwd.H
#include "fieldTypes.H"

template<class Type> class oscillatingFvPatchField;

makePatchTypeFieldTypedefs(oscillatingFvPatchField);

#endif

What for do we use forward declarations in C++?

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 32


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : building the library :

wmake the library anywhere in the sub-directory.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 33


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : using the library

Edit: system/controlDict
libs ("libextendedBoundaryConditions.so");

Our new library needs to be linked to the solver.


OpenFOAM has a linking system that allows case-specific linking.
A dynamic linking and loading system.
We must specify the library file name.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 34


Decorating Boundary conditions (BC)s

A generic BC library

An oscillating BC : results of using TDD

RED: program and run until the class is fully implemented.


Using TDD we can find out minimal interface requirements.
TDD makes you program from the perspective of the class user.
Coupling between classes happens on the client (solver) level.
Tests drive the class collaboration design.
Less cargo cult programming, more understanding.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 35


Decorating Boundary conditions (BC)s

A generic BC library

Instantiating BC class templates : compilation and running

Compile the library.


Edit the system/controlDict of the cavityOscillating case:
libs (libextendedBoundaryConditions.so);
Modify the output frequency and end time

endTime 6;
deltaT 0.01;
writeControl runTime;
writeInterval 0.1;

Run the icoFoam solver.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 36


Decorating Boundary conditions (BC)s

A generic BC library

Case setup: oscillating velocity BCs

wallUp
{
type oscillating;
wrappedType
{
type fixedValue;
value uniform (1 0 0);
}
}
wallRight
{
type oscillating;
wrappedType
{
type zeroGradient;
}
}

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 37


Decorating Boundary conditions (BC)s

A generic BC library

Case setup: oscillating velocity BCs


wallDown
{
type oscillating;
wrappedType
{
type codedFixedValue;
value uniform (0 0 0);
redirectType linearMap;

code
#{
const fvPatch& boundaryPatch = patch();
const vectorField& Cf = boundaryPatch.Cf();

vectorField& bcField = *this;

forAll(Cf, faceI)
{
// Quadratic ramp.
bcField[faceI] =
vector(-Foam::pow(Cf[faceI].x(), 2), 0, 0);
}
#};
}
}
Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 38
Decorating Boundary conditions (BC)s

A generic BC library

Conclusions

This workflow is the same for all generic libraries in OF.


A class template macros used to instaniate OO code.
OO code is compiled and used.
Decorator Pattern applies changes to many BCs at once.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 39


Decorating Boundary conditions (BC)s

A generic BC library

F. Moukalled, L. Mangani, and M. Darwish. The Finite Volume Method in


Computational Fluid Dynamics: An Advanced Introduction with
OpenFOAM and Matlab. Vol. 113. Springer International Publishing,
2016. Chap. The Finite Volume Mesh in OpenFOAM and uFVM. isbn:
9783319168739. doi: 10.1007/978-3-319-16874-6. url:
http://www.springer.com/978-3-319-16873-
9?wt_mc=ThirdParty.SpringerLink.3.EPR653.About_eBook.

Boundary Conditions Training Decorating Boundary conditions (BC)s A generic BC library 40

Vous aimerez peut-être aussi