:pnode: image:images/tut_ico_cavity_pnode_icon.png[height=15]
:pcell: image:images/tut_ico_cavity_pcell_icon.png[height=15]

=== Lid-driven cavity flow
(((tutorials,lid-driven cavity flow)))(((lid-driven cavity flow)))
(((cavity flow)))

This tutorial will describe how to pre-process, run and post-process a case
involving isothermal, incompressible flow in a two-dimensional square domain.
The geometry is shown in <<fig_geomCavity>> in which all the boundaries of the
square are walls. The top wall moves in the math:[x]-direction at a speed of
math:[\unitfrac[1\]{m}{s}] while the other 3 are stationary. Initially, the
flow will be assumed laminar(((flow,laminar))) and will be solved on a uniform
mesh using the `ico`(((`ico` solver)))(((solver,`ico`))) 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 (((Reynolds number))) will be
increased and the `piso`(((`piso` solver))) (((solver,`piso`))) solver will be
used for turbulent,(((flow,turbulent))) isothermal, incompressible flow.

[[fig_geomCavity]]
.Geometry of the lid driven cavity
image::images/tut_ico_cavity_geometry.{gfx-fmt}[]

==== Pre-processing

Cases are setup in {project} by editing case files. Users should select an
editor of choice with which to do this, such as `emacs`, `vim`, `gedit`,
`kate`, `nedit`, 'etc.' Editing files is possible in {project} because the I/O
uses a dictionary format with keywords that convey sufficient meaning to be
understood by even the least experienced users.

A case being simulated involves data for mesh, fields, properties, control
parameters, 'etc.' As described in <<sec_fileStructureFoamCases>>, in {project}
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, 'e.g.' the first example case for this tutorial is
simply named `cavity`. In preparation of editing case files and running the
first `cavity` case, the user should change to the case directory

-------------------------------------------------------------------------------
$ cd '<tutorials>'/incompressible/icoFoam/cavity
-------------------------------------------------------------------------------

[[sec_cavityMesh]]
===== Mesh generation

{project} always operates in a 3 dimensional Cartesian
(((axes,right-handed rectangular Cartesian))) coordinate system
(((coordinate system))) and all geometries are generated in 3 dimensions.
{project} solves the case in 3 dimensions by default but can be instructed to
solve in 2 dimensions by specifying a 'special' +empty+
(((+empty+,boundary condition)))(((boundary condition,+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 math:[d=\unit[0.1\]{m}]
in the math:[x-y] plane. A uniform mesh of 20 by 20 cells will be used
initially. The block structure is shown in <<fig_cavityBlock>>.

[[fig_cavityBlock]]
.Block structure of the mesh for the cavity
image::images/tut_ico_cavity_block.{gfx-fmt}[]

The mesh generator supplied with {project}, `blockMesh`, generates meshes from
a description specified in an input dictionary,
filename:blockMeshDict[](((filename:blockMeshDict[],dictionary)))
(((dictionary,filename:blockMeshDict[]))) located in the
dirname:constant/polyMesh[] directory for a given case. The
filename:blockMeshDict[] entries for this case are as follows:

[source,'',numbered]
-------------------------------------------------------------------------------
include::{builddir}tutorials/assets/ico_cavity/blockMeshDict[]
-------------------------------------------------------------------------------

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`;
(((`vertices` keyword)))(((keyword,`vertices`))) it then defines the
`blocks`(((`blocks` keyword)))(((keyword,`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 <<sec_blockMeshGenerator>>
to understand the meaning of the entries in the filename:blockMeshDict[] file.

The mesh is generated by running `blockMesh` on this
filename:blockMeshDict[](((filename:blockMeshDict[],dictionary)))
(((dictionary,filename:blockMeshDict[]))) file. From within the case directory,
this is done, simply by typing in the terminal:

-------------------------------------------------------------------------------
$ freefoam blockMesh
-------------------------------------------------------------------------------

The running status of `blockMesh` is reported in the terminal window. Any
mistakes in the filename: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.

===== Boundary and initial conditions
(((boundary condition,setup)))

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
math:[t=\unit[0\]{s}], so the initial field data is stored in a dirname:0[]
sub-directory of the dirname:cavity[] directory. The dirname:0[] sub-directory
contains two files, filename:p[] and filename:U[], one for each of the pressure
(math:[p]) and velocity (math:[\U]) fields whose initial values and boundary
conditions must be set. Let us examine file filename:p[]:

[source,'']
-------------------------------------------------------------------------------
include::{builddir}tutorials/assets/ico_cavity/p[]
-------------------------------------------------------------------------------

There are 3 principal entries in field data files:

`dimensions`(((`dimensions` keyword)))(((keyword,`dimensions`)))::
  specifies the dimensions of the field, here 'kinematic' pressure, 'i.e.'
  math:[\unitfrac{m^2}{s^{2}}] (see <<sec_dimensionalUnits>> for more
  information);
`internalField`(((`internalField` keyword)))(((keyword,`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
      <<sec_fieldData>> for more information);
`boundaryField` (((`boundaryField` keyword)))(((keyword,`boundaryField`)))::
  the boundary field data that includes boundary conditions and data for all
  the boundary patches (see <<sec_fieldData>> 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 filename: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
<<sec_formatScalarsVectorsTensors>> for more information).

The boundary field for velocity requires the same boundary condition for the
`frontAndBack` patch. The other patches are walls: a no-slip condition is
assumed on the `fixedWalls`, hence a `fixedValue` condition with a
`value`(((`value` keyword)))(((keyword,`value`))) of `uniform (0 0 0)`. The top
surface moves at a speed of math:[\unitfrac[1\]{m}{s}] in the
math:[x]-direction so requires a `fixedValue` condition also but with
`uniform (1 0 0)`.

===== 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 `ico`(((`ico` solver)))(((solver,`ico`))) case, the only
property that must be specified is the kinematic viscosity which is stored from
the filename:transportProperties[]
(((filename:transportProperties[],dictionary)))
(((dictionary,filename:transportProperties[])))
dictionary. The user can check that the kinematic viscosity is set correctly by
opening the filename:transportProperties[] dictionary to view/edit its entries.
The keyword for kinematic viscosity is `nu`, the phonetic label for the Greek
symbol math:[\nu] by which it is represented in equations. Initially this case
will be run with a Reynolds number(((Reynolds number))) of 10, where the
Reynolds number is defined as:

[[eq_ReDefinition]]
.Definition of the Reynolds number
[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  Re = \frac{d |\U|}{\nu}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

where math:[d] and math:[|\U|] are the characteristic length and velocity
respectively and math:[\nu] is the kinematic
viscosity.(((viscosity,kinematic))) Here math:[d=\unit[0.1\]{m}],
math:[|\U|=\unitfrac[1\]{m}{s}], so that for math:[Re=10],
math:[\nu=\unitfrac[0.01\]{m^2}{s}]. The correct file entry for kinematic
viscosity is thus specified below:

[source,'']
-------------------------------------------------------------------------------
include::{builddir}tutorials/assets/ico_cavity/transportProperties[]
-------------------------------------------------------------------------------

[[sec_cavityControl]]
===== Control

Input data relating to the control of time and reading and writing of the
solution data are read in from the
filename:controlDict[](((filename:controlDict[],dictionary)))
(((dictionary,filename:controlDict[]))) dictionary. The user should view this
file; as a case control file, it is located in the dirname:system[] directory.

The start/stop times and the time step for the run must be set. {project}
offers great flexibility with time control which is described in full in
<<sec_controlDict>>. In this tutorial we wish to start the run at time
math:[t=\unit[0\]{s}] which means that {project} needs to read field data from
a directory named dirname:0[] &mdash; see <<sec_fileStructureFoamCases>> for
more information of the case file structure. Therefore we set the
`startFrom`(((`startFrom` keyword)))(((keyword,`startFrom`))) keyword to
`startTime`(((`startTime`,keyword entry)))(((keyword entry,`startTime`))) and
then specify the `startTime`(((`startTime` keyword)))(((keyword,`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.' math:[\unit[1\]{s}]; in fact, with hindsight,
we discover that math:[\unit[0.5\]{s}] is sufficient so we shall adopt this
value. To specify this end time, we must specify the `stopAt` keyword as
`endTime`(((`endTime` keyword)))(((keyword,`endTime`))) and then set the
`endTime`(((`endTime` keyword)))(((keyword,`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
`ico`,(((`ico` solver)))(((solver,`ico`))) a Courant number(((Courant number)))
of less than 1 is required. The Courant number is defined for one cell as:

[[eq_Courant]]
.Definition of the Courant number
[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  Co = \frac{\delta t |\U|}{\delta x}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

where math:[\delta t] is the time step,(((time step))) math:[|\U|] is the
magnitude of the velocity through that cell and math:[\delta x] is
the cell size in the direction of the velocity. The flow velocity
varies across the domain and we must ensure math:[Co<1] everywhere. We
therefore choose math:[\delta t] based on the worst case: the 'maximum'
math:[Co] corresponding to the combined effect of a large flow velocity and
small cell size. Here, the cell size is fixed across the domain so the maximum
math:[Co] will occur next to the lid where the velocity approaches
math:[\unitfrac[1\]{m}{s}]. The cell size is:

[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  \delta x = \frac{d}{n} = \frac{0.1}{20} = \unit[0.005]{m}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

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:

[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  \delta t = \frac{Co \delta x}{|\U|} = \frac{1\times 0.005}{1}
           = \unit[0.005]{s}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

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`(((`writeControl` keyword)))(((keyword,`writeControl`))) keyword
presents several options for setting the time at which the results are written;
here we select the `timeStep`(((`timeStep`,keyword entry)))
(((keyword entry,`timeStep`))) option which specifies that results are written
every math:[n]th time step where the value math:[n] is specified under the
`writeInterval`(((`writeInterval` keyword)))(((keyword,`writeInterval`)))
keyword. Let us decide that we wish to write our results at times
math:[\unit[0.1,0.2,...,0.5\]{s}]. With a time step of
math:[\unit[0.005\]{s}], we therefore need to output results at every 20th time
time step and so we set `writeInterval` to 20.

{project} creates a new directory 'named after the current time', 'e.g.'
math:[\unit[0.1\]{s}], on each occasion that it writes a set of data, as
discussed in full in <<sec_fileStructureFoamCases>>. In the `ico` solver, it
writes out the results for each field, `U`(((`U` field)))(((field,`U`))) and
`p`,(((`p` field)))(((field,`p`))) into the time directories. For this case,
the entries in the filename:controlDict[] are shown below:

[source,'']
-------------------------------------------------------------------------------
include::{builddir}tutorials/assets/ico_cavity/controlDict[]
-------------------------------------------------------------------------------

===== Discretisation and linear-solver settings

The user specifies the choice of finite volume discretisation schemes in the
filename:fvSchemes[] dictionary in the dirname:system[] directory. The
specification of the linear equation solvers and tolerances and other algorithm
controls is made in the filename:fvSolution[] dictionary, similarly in the
dirname:system[] directory. The user is free to view these dictionaries but we
do not need to discuss all their entries at this stage except for
`pRefCell`(((`pRefCell` keyword)))(((keyword,`pRefCell`))) and
`pRefValue`(((`pRefValue` keyword)))(((keyword,`pRefValue`))) in the
`PISO`(((`PISO`,dictionary)))(((dictionary,`PISO`))) sub-dictionary of the
filename:fvSolution[] dictionary. In a closed incompressible system such as the
cavity, pressure is relative: it is the pressure range that matters not the
absolute values. In cases such as this, the solver sets a reference level by
`pRefValue`(((`pRefValue` keyword)))(((keyword,`pRefValue`))) in cell
`pRefCell`.(((`pRefCell` keyword)))(((keyword,`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.

[[sec_cavityViewMesh]]
==== 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 `para`, a convenience-wrapper around 'ParaView',
supplied with {project}. The `para` (((`para`)))post-processing is started by
typing in the terminal from within the case directory

-------------------------------------------------------------------------------
$ freefoam para
-------------------------------------------------------------------------------

Alternatively, it can be launched from another directory location with an
optional `-case` argument giving the case directory, 'e.g.'

-------------------------------------------------------------------------------
$ freefoam para -case '<tutorials>'/incompressible/icoFoam/cavity
-------------------------------------------------------------------------------

This launches the 'ParaView' window as shown in <<fig_paraFoamCavityMesh>>. In
the guilabel:[Pipeline Browser], (((guilabel:[Pipeline Browser] window)))
(((window,guilabel:[Pipeline Browser]))) the user can see that 'ParaView' has
opened filename:cavity.foam[], the module for the `cavity` case. *Before
clicking the guibutton:[Apply] button*, the user needs to select some geometry
from the guilabel:[Region Status](((guilabel:[Region Status] window panel)))
(((window panel,guilabel:[Region Status]))) panel. Because the case is
small, it is easiest to select all the data by checking the box adjacent to the
guilabel:[Region Status] panel title, which automatically checks all individual
components within the respective panel. The user should then click the
guibutton:[Apply] button to load the geometry into 'ParaView'. There are some
general settings are applied as described in <<sec_paraviewViewSettings>>.
*Please consult this section about these settings*.

The user should then open the guilabel:[Display]
(((guilabel:[Display] window panel)))(((window panel,guilabel:[Display])))
panel that controls the visual representation of the selected module. Within
the guilabel:[Display] panel the user should do the following as shown in
<<fig_paraFoamCavityMesh>>: (1) set guilabel:[Color by Solid Color]; (2) click
guilabel:[Set Solid Color] and select an appropriate colour 'e.g.' black (for a
white background); (3) in the guilabel:[Style]
(((guilabel:[Style] window panel)))(((window panel,guilabel:[Style]))) panel,
select guilabel:[Wireframe] from the guilabel:[Representation] menu. The
background colour can be set with
menuselection:[Edit --> View Settings...].
(((menuselection:[Edit --> View Settings...],menu entry)))
(((menu entry,menuselection:[Edit --> View Settings...])))

[[fig_paraFoamCavityMesh]]
.Viewing the mesh in `para`
image::images/tut_ico_cavity_paraFoamCavityMesh.{gfx-fmt}[scaledwidth="50%"]

Especially the first time the user starts 'ParaView', *it is recommended* that
they manipulate the view as described in <<sec_manipulatingView>>. In
particular, since this is a 2D case, it is recommended that
guibutton:[Use Parallel Projection]
(((guibutton:[Use Parallel Projection] button)))
(((button,guibutton:[Use Parallel Projection]))) is selected in the
guilabel:[General] panel of the menuselection:[Edit --> View Settings...]
(((menuselection:[Edit --> View Settings...],menu entry)))
(((menu entry,menuselection:[Edit --> View Settings]))) dialog.
The guibutton:[Orientation Axes](((guibutton:[Orientation Axes] button)))
(((button,guibutton:[Orientation Axes]))) can be toggled on and off in the
guilabel:[Annotation](((guilabel:[Annotation] window panel)))
(((window panel,guilabel:[Annotation]))) panel of the same dialog or moved by
drag and drop with the mouse.

==== Running an application

Like any 'UNIX'/'Linux' executable, {project} applications can be run in two
ways: as a foreground process,(((foreground,process)))(((process,foreground)))
'i.e.' one in which the shell waits until the command has finished before
giving a command prompt; as a background
process,(((background,process)))(((process,background))) one which does not
have to be completed before the shell accepts additional commands.

On this occasion, we will run `ico`(((`ico` solver)))(((solver,`ico`))) in the
foreground. The `ico` solver is executed either by entering the case directory
and typing

-------------------------------------------------------------------------------
$ freefoam ico
-------------------------------------------------------------------------------

at the command prompt, or with the optional option:-case[] argument giving the
case directory, 'e.g.'

-------------------------------------------------------------------------------
$ freefoam ico -case '<tutorials>'/incompressible/icoFoam/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.

[[sec_cavityPost]]
==== Post-processing

As soon as results are written to time directories, they can be viewed using
+para+. Return to the +para+ window and select the
guilabel:[Properties](((guilabel:[Properties] window panel)))
(((window panel,guilabel:[Properties]))) panel for the guilabel:[cavity.foam]
case module. If the correct window panels for the case module do not seem to be
present at any time, please ensure that: guilabel:[cavity.foam] is highlighted
in blue; 'eye' button alongside it is switched on to show the graphics are
enabled;

To prepare `para` to display the data of interest, we must first load the data
at the required run time of math:[\unit[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 reload the data the user should
select guibutton:[Delete](((guibutton:[Delete] button)))
(((button,guibutton:[Delete]))) in the guilabel:[Properties] panel and
then load the guilabel:[<tutorials>/incompressible/icoFoam/cavity/cavity.foam]
file from the menu menuselection:[Files --> Recent Files] and click the green
guibutton:[Apply] button in the guilabel:[Properties] panel.

===== Isosurface and contour plots

To view pressure, the user should open the
guilabel:[Display](((guilabel:[Display] window panel)))
(((window panel,guilabel:[Display]))) panel since it that controls the visual
representation of the selected module. To make a simple plot of pressure, the
user should select the following, as described in detail in
<<fig_paraFoamCavityPContourDisplay>>: in the guilabel:[Style] panel, select
guilabel:[Surface] from the guilabel:[Representation] menu; in the
guilabel:[Color] panel, select guilabel:[Color by] {pnode} and
guibutton:[Rescale to Data Range].
(((guibutton:[Rescale to Data Range] button)))
(((button,guibutton:[Rescale to Data Range]))) Now in order to view the
solution at math:[t=\unit[0.5\]{s}], the user can use the
guilabel:[VCR Controls](((guilabel:[VCR Controls] menu)))
(((menu,guilabel:[VCR Controls]))) or guibutton:[Current Time Controls]
(((guibutton:[Current Time Controls] menu)))
(((menu,guibutton:[Current Time Controls]))) to change the current time to 0.5.
These are located in the toolbars below the menus at the top of the 'ParaView'
window, as shown in <<fig_paraviewToolbars>>. The pressure field solution has,
as expected, a region of low pressure at the top left of the cavity and one of
high pressure at the top right of the cavity as shown in
<<fig_pressureCavity>>.

[[fig_paraFoamCavityPContourDisplay]]
.Displaying pressure contours for the `cavity` case
image::images/tut_ico_cavity_paraFoamCavityPContourDisplay.{gfx-fmt}[scaledwidth="20%"]

[[fig_pressureCavity]]
.Pressures in the `cavity` case
image::images/tut_ico_cavity_pressureCavity.png[scaledwidth="37%"]

With the point icon ({pnode}) the pressure field is interpolated across each
cell to give a continuous appearance. Instead if the user selects the cell
icon, {pcell}, from the guilabel:[Color by] 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 bar can be included by either by clicking the
guibutton:[Toggle Color Legend Visibility] button in the
guilabel:[Active Variable Controls] toolbar, or by selecting
menuselection:[View --> Show Color Legend].
(((menuselection:[View --> Show Color Legend],menu entry)))
(((menu entry,menuselection:[View --> Show Color Legend]))) Clicking the
guibutton:[Edit Color Map] button, either in the
guilabel:[Active Variable Controls] toolbar or in the guilabel:[Color] panel of
the guilabel:[Display] window, the user can set a range of attributes of the
colour bar, such as text size, font selection and numbering format for the
scale. The colour bar can be located in the image window by drag and drop with
the mouse.

New versions of 'ParaView' default 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 guibutton:[Choose Preset] in the
guilabel:[Color Scale Editor] and selecting guilabel:[Blue to Red Rainbow].
After clicking the guibutton:[OK] confirmation button, the user can click the
guibutton:[Make Default] button so that 'ParaView' will always adopt this type
of colour bar.

If the user rotates the image, they can see that they have now coloured the
complete geometry surface by the pressure. In order to produce a genuine
contour plot the user should first create a cutting plane, or 'slice', through
the geometry using the +Slice+ filter as described in <<sec_cuttingPlane>>. The
cutting plane should be centred at math:[(0.05,0.05,0.005)] and its normal
should be set to math:[(0,0,1)]. Having generated the cutting plane, the
contours can be created using by the +Contour+ filter described in
<<sec_contourPlotParaview>>.

===== 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. These can: either be deleted entirely, by
highlighting the relevant module in the guilabel:[Pipeline Browser] and
clicking guibutton:[Delete] in their respective guilabel:[Properties] panel;
or, be disabled by toggling the 'eye' button for the relevant module in the
guilabel:[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
<<sec_plottingCellCentres>>. With the guilabel:[cavity.foam] module highlighted
in the guilabel:[Pipeline Browser], the user should select
menuselection:[Filters --> Alphabetical --> Cell Centers] and then click
guibutton:[Apply].

With the guilabel:[CellCenters1] module highlighted in the
guilabel:[Pipeline Browser], the user should then select
menuselection:[Filters --> Common --> Glyph]. The guilabel:[Properties] window
panel should appear as shown in <<fig_paraFoamCavityGlyphParameters>>. In the
resulting guilabel:[Properties] panel, the velocity field, guilabel:[U], is
automatically selected in the guilabel:[Vectors] dropdown, since it is the only
vector field present. By default the guilabel:[Scale Mode] for the glyphs will
be guilabel:[Vector Magnitude] of velocity but, since the we may wish to view
the velocities throughout the domain, the user should instead select
guilabel:[off] and guilabel:[Set Scale Factor] to 0.005. On clicking
guibutton:[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 guilabel:[Color by] to guilabel:[GlyphVector] in the
guilabel:[Display] panel. The user should also select
guibutton:[Show Color Legend] in the guilabel:[Color Legend] tab of the dialog
that appears after pressing the guibutton:[Edit Color Map] button. The output
is shown in <<fig_velocityCavity>>, in which uppercase Times Roman fonts are
selected for the guilabel:[Color Legend](((guilabel:[Color Legend] window)))
(((window,guilabel:[Color Legend]))) headings and the labels are specified to 2
fixed significant figures by deselecting guilabel:[Automatic Label Format] and
entering `%-#6.2f` in the guilabel:[Label Format] text box. The background
colour is set to white in the guilabel:[General] panel of
guilabel:[View Settings] as described in <<sec_paraviewViewSettings>>.

[[fig_paraFoamCavityGlyphParameters]]
.Properties panel for the `Glyph` filter
image::images/tut_ico_cavity_paraFoamCavityGlyphParameters.{gfx-fmt}[scaledwidth="20%"]

[[fig_velocityCavity]]
.Velocities in the `cavity` case
image::images/tut_ico_cavity_velocityCavity.png[scaledwidth="40%"]

Note that at the left and right walls, glyphs appear to indicate flow through
the walls. On closer examination, however, the user can see 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
math:[x]-direction when the glyph scaling is guilabel:[off] and the velocity
magnitude is 0.

===== 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 a streamlines of velocity as described in <<sec_streamlinesParaview>>.

With the guilabel:[cavity.foam] module highlighted in the
guilabel:[Pipeline Browser], the user should then select
menuselection:[Filters --> Common --> Stream Tracer] and then click
guibutton:[Apply]. The guilabel:[Properties] window panel should appear as
shown in <<fig_paraFoamCavityStreamTracerParameters>>. The guilabel:[Seed]
points should be specified along a guilabel:[Line Source] running vertically
through the centre of the geometry, 'i.e.' from math:[(0.05,0,0.005)] to
math:[(0.05,0.1,0.005)]. For the image in this guide we used: a point
guilabel:[Resolution] of 21; guilabel:[Maximum Streamline Length] of
0.5; guilabel:[Initial Step Length] by guilabel:[Cell Length] 0.01; and,
guilabel:[Integration Direction] guilabel:[BOTH]. The guilabel:[Runge-Kutta 2]
guilabel:[IntegratorType] was used with default parameters.

On clicking guibutton:[Apply] the tracer is generated. The user should then
select menuselection:[Filters --> Alphabetical --> Tube] to produce high
quality streamline images. For the image in this report, we used:
guilabel:[Number of sides] 6; guilabel:[Radius] 0.0003; and,
guilabel:[Radius factor] 10. The streamtubes are coloured by velocity
magnitude. On clicking guibutton:[Apply] the image in <<fig_streamlinesCavity>>
should be produced.


[[fig_paraFoamCavityStreamTracerParameters]]
.Properties panel for the `Stream Tracer` filter
image::images/tut_ico_cavity_paraFoamCavityStreamTracerParameters.{gfx-fmt}[scaledwidth="20%"]

[[fig_streamlinesCavity]]
.Streamlines in the dirname:cavity[] case
image::images/tut_ico_cavity_streamlinesCavity.png[scaledwidth="40%"]

==== Increasing the mesh resolution

The mesh resolution(((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.

===== 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 create a new case directory at the same
directory level as the `cavity` case, 'e.g.'

-------------------------------------------------------------------------------
$ cd '<tutorials>'/incompressible/icoFoam
$ mkdir cavityFine
-------------------------------------------------------------------------------

The user should then copy the base directories from the `cavity` case into
`cavityFine`, and then enter the `cavityFine` case.

-------------------------------------------------------------------------------
$ cp -r cavity/constant cavityFine
$ cp -r cavity/system cavityFine
$ cd cavityFine
-------------------------------------------------------------------------------

[[sec_cavityFinerMesh]]
===== Creating the finer mesh

We now wish to increase the number of cells in the mesh by using `blockMesh`.
The user should open the filename:blockMeshDict[] file in an editor and edit
the block specification. The blocks are specified in a list under the
`blocks`(((`blocks` keyword)))(((keyword,`blocks`))) keyword. The syntax of
the block definitions is described fully in <<sec_blockMeshBlocks>>; 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.

[[sec_cavityMapFields]]
===== Mapping the coarse mesh results onto the fine mesh

The +mapFields+(((+mapFields+ utility)))(((utility,+mapFields+))) utility maps
one or more fields relating to a given geometry onto the corresponding 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 option:-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`/`startTime` in the
filename:controlDict[](((filename:controlDict[],dictionary)))
(((dictionary,filename: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 dirname:0.5[]
directory of `cavity`, the `startTime` should be set to math:[\unit[0.5\]{s}]
in the filename:controlDict[] dictionary and `startFrom` should be set to
`startTime`.

The case is ready to run `mapFields`. Typing `freefoam mapFields -help` quickly
shows that `mapFields` requires the source case directory as an argument. We
are using the `-consistent` option, so the utility is executed from withing the
filename:cavityFine[] directory by

-------------------------------------------------------------------------------
$ freefoam mapFields ../cavity -consistent
-------------------------------------------------------------------------------

The utility should run with output to the terminal including:

-------------------------------------------------------------------------------
Source time: 0.5
Target time: 0.5
Create meshes

Source mesh size: 400   Target mesh size: 1600


Consistently creating and mapping fields for time 0.5

    interpolating p
    interpolating U

End
-------------------------------------------------------------------------------

===== Control adjustments

To maintain a Courant number of less that 1, as discussed in
<<sec_cavityControl>>, the time step must now be halved since the size of all
cells has halved. Therefore `deltaT` should be set to to
math:[\unit[0.0025\]{s}] in the filename: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 filename:controlDict[], instead of requesting output
by a fixed number of time steps with the `timeStep`
(((`timeStep`,keyword entry)))(((keyword entry,`timeStep`))) entry, a fixed
amount of run time can be specified between the writing of results using the
`runTime`(((`runTime`,keyword entry)))(((keyword entry,`runTime`))) entry. In
this case the user should specify output every 0.1 and therefore should set
`writeInterval`(((`writeInterval` keyword)))(((keyword,`writeInterval`))) to
`0.1` and `writeControl` to `runTime`.(((`runTime`,keyword entry)))
(((keyword entry,`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 math:[\unit[0.7\]{s}]. Make sure these settings are correct
and then save the file.

===== Running the code as a background process

The user should experience running `ico` as a background process, redirecting
the terminal output to a filename:log[] file that can be viewed later. From the
filename:cavityFine[] directory, the user should execute:

-------------------------------------------------------------------------------
$ freefoam ico > log &
$ cat log
-------------------------------------------------------------------------------

[[sec_cavityFineVector]]
===== 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
guilabel:[Pipeline Browser]. There is one minor inconvenience when opening a
new case in 'ParaView' because there is a prerequisite that the selected data
is a file with a name that has an extension. However, in {project}, each case
is stored in a multitude of files with no extensions within a specific
directory structure. The solution, that the `para` script performs
automatically, is to create a dummy file with the extension filename:.foam[]
&mdash; hence, the `cavity` case module is called guilabel:[cavity.foam].

However, if the user wishes to open another case directly from within
'ParaView', they need to create such a dummy file. For example, to load the
`cavityFine` case the file would be created by typing at the command prompt:

-------------------------------------------------------------------------------
$ cd '<tutorials>'/incompressible/icoFoam
$ touch cavityFine/cavityFine.foam
-------------------------------------------------------------------------------

Now the `cavityFine` case can be loaded into 'ParaView' by selecting
menuselection:[File --> Open], and having navigated the directory tree,
selecting guilabel:[cavityFine.foam]. 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.

[[sec_cavityFineGraphs]]
===== 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.
{project} is well equipped for this kind of data manipulation. There are
numerous utilities that do specialised data manipulations, and some, simpler
calculations are incorporated into a single utility
`calc`.(((`calc` utility)))(((utility,`calc`))) As a utility, it is unique in
that it is executed by

-------------------------------------------------------------------------------
$ freefoam calc '<calcType>' '<fieldName1 ... fieldNameN>'
-------------------------------------------------------------------------------

The calculator operation is specified in '<calcType>'; at the time of writing,
the following operations are implemented: `addSubtract`; `randomise`; `div`;
`components`; `mag`; `magGrad`; `magSqr`; `interpolate`. The user can obtain
the list of '<calcType>' by deliberately calling one that does not exist, so
that `calc` throws up an error message and lists the types available, 'e.g.'

-------------------------------------------------------------------------------
$ freefoam calc xxx
Selecting calcType xxx


--> FOAM FATAL ERROR:
    unknown calcType type xxx, constructor not in hash table

    Valid calcType selections are:

8
(
addSubtract
components
div
interpolate
mag
magGrad
magSqr
randomise
)
-------------------------------------------------------------------------------

The +components+ and +mag+ ++calcType++s provide useful scalar measures of
velocity. When +freefoam{nbsp}calc{nbsp}components U+ is run on a case, say
filename:cavity[], it reads in the velocity vector field from each time
directory and, in the corresponding time directories, writes scalar fields
filename:Ux[], filename:Uy[] and filename:Uz[] representing the math:[x],
math:[y] and math:[z] components of velocity. Similarly
+freefoam{nbsp}calc{nbsp}mag{nbsp}U+ writes a scalar field filename:magU[] to
each time directory representing the magnitude of velocity.

The user can run `calc` with the `components` `calcType` on both `cavity` and
`cavityFine` cases. For example, for the `cavity` case the user should do into
the filename:cavity[] directory and execute `calc` as follows:

-------------------------------------------------------------------------------
cd '<tutorials>'/incompressible/icoFoam/cavity
freefoam calc 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 `sample` utility, described in <<sec_sample>> and
<<sec_plateHolePost>>.

'Before commencing plotting', the user needs to load the newly generated
filename:Ux[], filename:Uy[] and filename:Uz[] fields by deleting and
re-opening the data source filename:cavity.foam[]. Data is interpolated
incorrectly at boundaries if the boundary regions are selected in the
guilabel:[Region Status] panel. Therefore the user should 'deselect the
patches' in the guilabel:[Region Status] panel, 'i.e.' guilabel:[movingWall],
guilabel:[fixedWall] and guilabel:[frontAndBack], and apply the changes.

Now, in order to display a graph in 'ParaView' the user should select the
module of interest, 'e.g.' guilabel:[cavity.foam] and apply the
menuselection:[Filters --> Data Analysis --> Plot Over Line] filter.
(((menuselection:[Filters --> Data Analysis --> Plot Over Line],menu entry)))
(((menu entry,menuselection:[Filters --> Data Analysis --> Plot Over Line])))
This opens up a new guilabel:[XY Plot] window beside the existing guilabel:[3D
View] window. A guilabel:[PlotOverLline1] module is created in which the user
can specify the end points of the line in the guilabel:[Properties] panel. In
this example, the user should position the line vertically up the centre of the
domain, 'i.e.' from math:[(0.05,0,0.005)] to math:[(0.05,0.1,0.005)], in the
guilabel:[Point1] and guilabel:[Point2] text boxes. The guilabel:[Resolution]
can be set to 100.

On clicking guibutton:[Apply], a graph is generated in the guilabel:[XY Plot]
window. In the guilabel:[Display] panel, the guibutton:[Use Data Array] option
can be selected for the guilabel:[X Axis Data], taking the
guilabel:[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 guilabel:[Line Series]
panel of the guilabel:[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 guilabel:[U (0)], so that it was
not necessary to create filename:Ux[] using `calc`. Nevertheless, the user
should deselect all series except guilabel:[Ux] (or guilabel:[U (0)]). 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 move over to the
guilabel:[XY Plot] itself and press the guibutton:[Edit View Options] button
in the top-left corner. A guilabel:[View Settings]
(((guilabel:[View Settings] window)))(((window,guilabel:[View Settings])))
window appears with guilabel:[General] settings for title and legend and menus
for each axis. The menu for each axis can be expanded by a double click (or
clicking the small `+` sign next to it) to reveal individual menus for
guilabel:[Layout] and guilabel:[Title], one for each axis. 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.

<<fig_paraFoamCavityGraph>> is a graph produced using 'ParaView'. The user can
produce a graph however he/she wishes. For information, the graph in
<<fig_paraFoamCavityGraph>> was produced with the options for axes of:
guilabel:[Fixed] type of guilabel:[Notation]; guilabel:[Specify Axis Range]
selected; titles in guilabel:[Sans Serif 12] font; guibutton:[Show Axis Grid]
and guibutton:[Show the Chart Legend When Available] disabled.
For the guilabel:[Right Axis] and guilabel:[Top Axis], guibutton:[Show Axis]
has been enabled and guibutton:[Show Axis Labels When Space is Available]
disabled. The graph is displayed as a set of points rather than a line by
setting guilabel:[Line Style](((guilabel:[Line Style] menu)))
(((menu, guilabel:[Line Style]))) to guilabel:[None] and
guilabel:[Marker Style](((guilabel:[Marker Style] menu)))
(((menu, guilabel:[Marker Style]))) to guilabel:[Square] in the
guilabel:[Display] panel.

.Selecting fields for graph plotting
image::images/tut_ico_cavity_paraFoamCavityGraphParameters.{gfx-fmt}[scaledwidth="20%"]

[[fig_paraFoamCavityGraph]]
.Plotting graphs in `para`
image::images/tut_ico_cavity_paraFoamCavityGraph.png[scaledwidth="40%"]

[[sec_cavityMeshGrade]]
==== 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 math:[20\times 20] cells with grading towards the walls will be
created for the lid-driven cavity problem and the results from the finer mesh
of <<sec_cavityFinerMesh>> 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
filename:blockMeshDict[] dictionary are fairly substantial, the case used for
this part of the tutorial, `cavityGrade`, is supplied in the
dirname:<tutorials>/incompressible/icoFoam[] directory.

===== 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 <<fig_cavityGradeBlock>>.


[[fig_cavityGradeBlock]]
.Block structure of the graded mesh for the cavity (block numbers encircled)
image::images/tut_ico_cavityGrade_block.{gfx-fmt}[]


The user can view the
filename:blockMeshDict[](((filename:blockMeshDict[],dictionary)))
(((dictionary,filename:blockMeshDict[])))
file in the dirname:constant/polyMesh[] subdirectory of `cavityGrade`; for
completeness the key elements of the filename:blockMeshDict[] file are also
reproduced below. Each block now has 10 cells in the math:[x] and math:[y]
directions and the ratio between largest and smallest cells is 2.

[source,'']
-------------------------------------------------------------------------------
include::{builddir}tutorials/assets/ico_cavityGrade/blockMeshDict[]
-------------------------------------------------------------------------------

Once familiar with the filename:blockMeshDict[] file for this case, the user
can execute `blockMesh` from the command line. The graded mesh can be viewed as
before using `para` as described in <<sec_cavityViewMesh>>.

===== 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
<<sec_cavityControl>>. 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`
(((`blockMesh` utility)))(((utility,`blockMesh`))) calculates the cell sizes
using a geometric progression. Along a length math:[l], if math:[n] cells are
requested with a ratio of math:[R] between the last and first cells, the size
of the smallest cell, math:[\delta x_s], is given by:

[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  \delta x_s = l\frac{r-1}{\alpha r-1}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

where math:[r] is the ratio between one cell size and the next
which is given by:

[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  r = R^\frac{1}{n-1}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

and

[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  \alpha = \begin{cases}
             R                        & \text{for $R>1$}\quad, \\
             1 - r^{-n} + \frac{1}{r} & \text{for $R<1$}\quad.
           \end{cases}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

For the `cavityGrade` case the number of cells in each direction in a block is
10, the ratio between largest and smallest cells is 2 and the block
height and width is math:[\unit[0.05\]{m}]. Therefore the smallest cell length
is math:[\unit[3.45\]{mm}]. From <<eq_Courant>>, the time step should be less
than math:[\unit[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 math:[\unit[2.5\]{ms}] and the `writeInterval`
set to 40 so that results are written out every math:[\unit[0.1\]{s}]. These
settings can be viewed in the filename: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 math:[\unit[0.1\]{s}], 'i.e.' the `endTime` should be math:[\unit[0.8\]{s}].

===== Mapping fields

As in <<sec_cavityMapFields>>, use `mapFields`(((`mapFields` utility)))
(((utility,`mapFields`))) to map the final results from case `cavityFine` onto
the mesh for case `cavityGrade`. Enter the dirname:cavityGrade[] directory
and execute `mapFields` by:

-------------------------------------------------------------------------------
$ cd '<tutorials>'/incompressible/icoFoam/cavityGrade
$ freefoam mapFields ../cavityFine -consistent
-------------------------------------------------------------------------------

Now run `ico` 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 <<sec_cavityFineVector>> and
<<sec_cavityFineGraphs>>.

==== 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 make a
copy of the `cavity` case and name it `cavityHighRe` by typing:

-------------------------------------------------------------------------------
$ cd '<tutorials>'/incompressible/icoFoam
$ cp -r cavity cavityHighRe
-------------------------------------------------------------------------------

===== Pre-processing

Enter the the `cavityHighRe` case and edit the
filename:transportProperties[](((filename:transportProperties[],dictionary)))
(((dictionary,filename:transportProperties[]))) dictionary. 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
math:[\unitfrac[1\times 10^{-3}\]{m^2}{s}]. We can now run this case by
restarting(((restart))) 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`(((`latestTime` keyword)))(((keyword,`latestTime`))) so that `ico`
takes as its initial data the values stored in the directory corresponding to
the most recent time, 'i.e.' dirname:0.5[]. The `endTime` should be set to
math:[\unit[2\]{s}].

===== Running the code

Run `ico` 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;
'GNU screen'::
  is similar to `nohup` in that it allows the user to log out of the machine
  without aborting the job. However, 'GNU screen' is also able to restore the
  whole session and has many other, very powerful capabilities. Refer to
  http://www.gnu.org/software/screen for more information.
`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. Only the superuser is
  allowed to decrease the nice-level of a running job or start jobs with a
  niceness below 0.

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:

-------------------------------------------------------------------------------
$ cd '<tutorials>'/incompressible/icoFoam/cavityHighRe
$ nohup nice -n 19 freefoam ico > log &
$ cat log
-------------------------------------------------------------------------------

In previous runs you may have noticed that `ico` stops solving for velocity `U`
quite quickly but continues solving for pressure `p` for a lot longer or until
the end of the run. In practice, once `ico` stops solving for `U` and the
initial residual of `p` is less than the tolerance set in the
filename:fvSolution[] dictionary (typically math:[10^{-6}]), the run has
effectively converged(((convergence))) and can be stopped once the field data
has been written out to a time directory. For example, at convergence a sample
of the filename:log[] file from the run on the `cavityHighRe` case appears as
follows in which the velocity has already converged after
math:[\unit[1.62\]{s}] and initial pressure residuals are small;
`No Iterations 0` indicates that the solution of `U` has stopped:

-------------------------------------------------------------------------------
Time = 1.63

Courant Number mean: 0.116835 max: 0.839923
DILUPBiCG:  Solving for Ux, Initial residual = 3.52304e-06, Final residual = 3.52304e-06, No Iterations 0
DILUPBiCG:  Solving for Uy, Initial residual = 4.06745e-06, Final residual = 4.06745e-06, No Iterations 0
DICPCG:  Solving for p, Initial residual = 2.04982e-06, Final residual = 5.22023e-07, No Iterations 3
time step continuity errors : sum local = 3.69808e-09, global = -2.67Time = 0.36 s  ClockTime = 0 s

Time = 1.635

Courant Number mean: 0.116836 max: 0.839924
DILUPBiCG:  Solving for Ux, Initial residual = 3.44807e-06, Final residual = 3.44807e-06, No Iterations 0
DILUPBiCG:  Solving for Uy, Initial residual = 3.9816e-06, Final residual = 3.9816e-06, No Iterations 0
DICPCG:  Solving for p, Initial residual = 2.01651e-06, Final residual = 5.02884e-07, No Iterations 3
time step continuity errors : sum local = 4.06551e-09, global = 4.39812e-19, cumulative = -8.85083e-18
-------------------------------------------------------------------------------

==== High Reynolds number flow

View the results in `para` and display the velocity vectors. The secondary
vortices in the corners have increased in size somewhat. 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 stress (RAS) turbulence
models(((turbulence model,RAS))) are used to solve for the mean flow behaviour
and calculate the statistics of the fluctuations. The standard {keps} 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: math:[k], the turbulent kinetic energy;
(((turbulence,kinetic energy))) and, math:[\varepsilon], the turbulent
dissipation rate.(((turbulence,dissipation))) The additional equations and
models for turbulent flow are implemented into a {project} solver called
`piso`.

===== Pre-processing

Change directory to the `cavity` case in the
dirname:<tutorials>/incompressible/pisoFoam/ras[] directory (make sure to use
the filename:ras[] subdirectory rather than the filename:les[] directory).
Generate the mesh by running `blockMesh` as before. Mesh grading towards the
wall is not necessary when using the standard {keps} 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 {project} 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, math:[\nu_t] in the
filename:0/nut[] file:

-------------------------------------------------------------------------------
include::{builddir}tutorials/assets/piso_cavity/nut[]
-------------------------------------------------------------------------------

This case uses standard wall functions, specified by the `nutWallFunction`
keyword entry one 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 math:[k] and math:[\varepsilon]
(filename:0/k[] and filename:0/epsilon[]) and examine their boundary
conditions. For a wall boundary condition,(((boundary condition,wall)))
math:[\varepsilon] is assigned a `epsilonWallFunction` boundary condition and a
`kqRwallFunction` boundary condition is assigned to math:[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.' math:[k], math:[q] or Reynolds Stress
math:[R]. The initial values for math:[k] and math:[\varepsilon] are set using
an estimated fluctuating component of velocity math:[\U^\prime] and a turbulent
length scale,(((turbulence,length scale))) math:[l]. math:[k] and
math:[\varepsilon] are defined in terms of these parameters as follows:

[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  k        & = \frac{1}{2}\overline{\U^\prime\cdot\U^\prime} \\
  \varepsilon & = \frac{C_\mu^\frac{3}{4} k^\frac{3}{2}}{l}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

where math:[C_\mu] is a constant of the {keps} model equal to 0.09. For a
Cartesian coordinate system, math:[k] is given by:

[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  k = \frac{1}{2}\left(U_x^{\prime 2} + U_y^{\prime 2} + U_z^{\prime 2}\right)
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

where math:[U_x^{\prime 2}], math:[U_y^{\prime 2}] and math:[U_z^{\prime 2}]
are the fluctuating components of velocity in the math:[x], math:[y] and
math:[z] directions respectively. Let us assume the initial turbulence is
isotropic, 'i.e.' math:[U_x^{\prime 2}=U_y^{\prime 2}=U_z^{\prime 2}], and
equal to 5% of the lid velocity and that math:[l], is equal to 20% of the box
width, math:[\unit[0.1\]{m}], then math:[k] and math:[\varepsilon] are given
by:

[math]
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
\begin{align*}
  U_x^{\prime 2} &= U_y^{\prime 2} = U_z^{\prime 2}
                     = \frac{5}{100}\unitfrac[1]{m}{s} \\
  \Rightarrow k  &= \frac{3}{2}\left(\frac{5}{100}\right)^2\unitfrac{m^2}{s^2}
                     = 3.75\times\unitfrac[10^{-3}]{m^2}{s^2} \\
  \varepsilon       &= \frac{C_\mu^\frac{3}{4} k^\frac{3}{2}}{l}
                     \approx 7.65\times\unitfrac[10^{-4}]{m^2}{s^3}
\end{align*}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

These form the initial conditions for math:[k] and math:[\varepsilon]. The
initial conditions for math:[U] and math:[p] are math:[(0,0,0)] and 0
respectively as before.

The choice of turbulence modelling method is selectable at run-time through the
`simulationType`(((`simulationType` keyword)))(((keyword,`simulationType`)))
keyword in filename:turbulenceProperties[]
(((filename:turbulenceProperties[],dictionary)))
(((dictionary,filename:turbulenceProperties[]))) dictionary. The user can view
this file in the filename:constant[] directory:

-------------------------------------------------------------------------------
include::{builddir}tutorials/assets/piso_cavity/turbulenceProperties[]
-------------------------------------------------------------------------------

The options for `simulationType`(((`simulationType` keyword)))
(((keyword,`simulationType`))) are
`laminar`,(((`laminar`,keyword entry)))(((keyword entry,`laminar`)))
`RASModel`(((`RASModel`,keyword entry)))(((keyword entry,`RASModel`))) and
`LESModel`.(((`LESModel`,keyword entry)))(((keyword entry,`LESModel`))) With
`RASModel` selected in this case, the choice of RAS modelling is specified in a
filename:RASProperties[] file, also in the filename:constant[] directory. The
turbulence model is selected by the `RASModel` entry from a long list of
available models that are listed in <<tab_turbulenceModelLibraries>>. The
`kEpsilon` model should be selected which is is the standard {keps} 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`(((`printCoeffs` keyword)))(((keyword,`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 that sub-dictionary within the RASProperties dictionary and adjusting
values accordingly.

The user should next set the laminar kinematic viscosity in the
filename:transportProperties[](((filename:transportProperties[],dictionary)))
(((dictionary,filename:transportProperties[]))) dictionary. To achieve a
Reynolds number of math:[10^4], a kinematic viscosity(((viscosity,kinematic)))
of math:[\unitfrac[10^{-5}\]{m^2}{s}] is required based on the Reynolds number
definition given in <<eq_ReDefinition>>.

Finally the user should set the `startTime`, `stopTime`, `deltaT` and the
`writeInterval` in the filename:controlDict[].
(((filename:controlDict[],dictionary)))(((dictionary,filename:controlDict[])))
Set `deltaT` to math:[\unit[0.005\]{s}] to satisfy the Courant number
restriction and the `endTime` to math:[\unit[10\]{s}].

===== Running the code

Execute `piso` by entering the case directory and typing `freefoam piso`. 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
math:[\approx] 100 time steps it becomes apparent that the velocity in the
cells adjacent to the lid reaches an upper limit of around
math:[\unitfrac[0.2\]{m}{s}] hence 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 math:[\unit[0.02\]{s}] and, on this occasion, set `startFrom`
to `latestTime`. This instructs `piso` to read the start data from the latest
time directory, 'i.e.' dirname:10.0[]. The `endTime` should be set to
math:[\unit[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.

==== 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`(((`mapFields` utility)))
(((utility,`mapFields`))) utility can map fields that are inconsistent, either
in terms of geometry or boundary types or both.

As an example, let us go to the
filename:<tutorials>/incompressible/icoFoam/cavityClipped[] case which consists
of the standard `cavity` geometry but with a square of length
math:[\unit[0.04\]{m}] removed from the bottom right of the cavity, according
to the filename:blockMeshDict[] below:

-------------------------------------------------------------------------------
include::{builddir}tutorials/assets/ico_cavityClipped/blockMeshDict[]
-------------------------------------------------------------------------------

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 math:[\unit[0.5\]{s}], since the
`startTime` is set to math:[\unit[0.5\]{s}] in the filename:controlDict[].
Therefore the user needs to copy initial field data to that directory, 'e.g.'
from time 0:

-------------------------------------------------------------------------------
$ cd '<tutorials>'/incompressible/icoFoam/cavityClipped
$ cp -r 0 0.5
-------------------------------------------------------------------------------

Before mapping the data, the user should view the geometry and fields at
math:[\unit[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 filename:mapFieldsDict[] dictionary, located
in the filename:system[] directory. The dictionary contains two 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 we will include the `fixedWalls` to demonstrate the interpolation
process.

-------------------------------------------------------------------------------
cuttingPatches
(
    fixedWalls
);
-------------------------------------------------------------------------------

Now the user should run `mapFields`, from within the dirname:cavityClipped[]
directory:

-------------------------------------------------------------------------------
$ freefoam mapFields ../cavity
-------------------------------------------------------------------------------

The user can view the mapped field as shown in <<fig_velocityCavityClipped>>.
The boundary patches have inherited values from the source case as we expected.
Having demonstrated this, however, we actually wish to reset the velocity on
the `fixedWalls` patch to math:[(0,0,0)]. Edit the `U` field, go to the
`fixedWalls` patch and change the field from `nonuniform` to `uniform (0 0 0)`.
The `nonuniform` field is a list of values that requires deleting in its
entirety. Now run the case with `ico`.

[[fig_velocityCavityClipped]]
.`cavity` solution velocity field mapped onto `cavityClipped`
image::images/tut_ico_cavityClipped_velocityCavityClipped.png[scaledwidth="40%"]

==== Post-processing the modified geometry

Velocity glyphs can be generated for the case as normal, first at time
math:[\unit[0.5\]{s}] and later at time math:[\unit[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
menuselection:[Filters --> Alphabetical --> Extract Block], in the
guilabel:[Properties] panel, highlight the patches of interest, namely the
guilabel:[lid] and guilabel:[fixedWalls]. This requires that the corresponding
patches have also been imported in the guilabel:[cavityClipped.foam] module. On
clicking guibutton:[Apply], these items of geometry can be displayed by
selecting guilabel:[Wireframe] in the guilabel:[Display] panel.
<<fig_velocityCavityClippedFinal>> displays the patches in black and shows
vortices forming in the bottom corners of the modified geometry.

[[fig_velocityCavityClippedFinal]]
.`cavityClipped` solution for velocity field
image::images/tut_ico_cavityClipped_velocityCavityClippedFinal.png[scaledwidth="40%"]
