source: anuga_core/documentation/user_manual/anuga_user_manual.tex @ 5657

Last change on this file since 5657 was 5657, checked in by ole, 15 years ago

Implemented default_boundary option in File_boundary and Field_boundary as
per ticket:293 and added a note in the user manual.

  • Property svn:keywords set to LastChangedDate LastChangedRevision LastChangedBy HeadURL Id
File size: 175.8 KB
RevLine 
[4123]1% Complete documentation on the extended LaTeX markup used for Python
2% documentation is available in ``Documenting Python'', which is part
3% of the standard documentation for Python.  It may be found online
4% at:
5%
6%     http://www.python.org/doc/current/doc/doc.html
7
8
9%labels
10%Sections and subsections \label{sec: }
11%Chapters \label{ch: }
12%Equations \label{eq: }
13%Figures \label{fig: }
14
15% Is latex failing with;
16% `modanuga_user_manual.ind' not found?
17% try this command-line
18%   makeindex modanuga_user_manual.idx
19% To produce the modanuga_user_manual.ind file.
20
21
22\documentclass{manual}
23
24\usepackage{graphicx}
25\usepackage{datetime}
26
27\input{definitions}
28
29\title{\anuga User Manual}
30\author{Geoscience Australia and the Australian National University}
31
32% Please at least include a long-lived email address;
33% the rest is at your discretion.
34\authoraddress{Geoscience Australia \\
35  Email: \email{ole.nielsen@ga.gov.au}
36}
37
38%Draft date
39
40% update before release!
41% Use an explicit date so that reformatting
42% doesn't cause a new date to be used.  Setting
43% the date to \today can be used during draft
44% stages to make it easier to handle versions.
45
46
47\longdate       % Make date format long using datetime.sty
48%\settimeformat{xxivtime} % 24 hour Format
49\settimeformat{oclock} % Verbose
50\date{\today, \ \currenttime}
51%\hyphenation{set\_datadir}
52
53\ifhtml
54\date{\today} % latex2html does not know about datetime
55\fi
56
57
58
59
[4785]60\input{version} % Get version info - this file may be modified by
[4953]61                % update_anuga_user_manual.py - if not a dummy
[4785]62                % will be used.
63               
64%\release{1.0}   % release version; this is used to define the
65%                % \version macro
[4123]66
67\makeindex          % tell \index to actually write the .idx file
68\makemodindex       % If this contains a lot of module sections.
69
70\setcounter{tocdepth}{3}
71\setcounter{secnumdepth}{3}
72
73
74\begin{document}
75\maketitle
76
77
78% This makes the contents more accessible from the front page of the HTML.
79\ifhtml
80\chapter*{Front Matter\label{front}}
81\fi
82
83%Subversion keywords:
84%
85%$LastChangedDate: 2008-08-14 00:26:06 +0000 (Thu, 14 Aug 2008) $
86%$LastChangedRevision: 5657 $
87%$LastChangedBy: ole $
88
89\input{copyright}
90
91
92\begin{abstract}
93\label{def:anuga}
94
95\noindent \anuga\index{\anuga} is a hydrodynamic modelling tool that
[5566]96allows users to model realistic flow problems in complex 2D geometries.
[4123]97Examples include dam breaks or the effects of natural hazards such
98as riverine flooding, storm surges and tsunami.
99
100The user must specify a study area represented by a mesh of triangular
101cells, the topography and bathymetry, frictional resistance, initial
102values for water level (called \emph{stage}\index{stage} within \anuga),
[5566]103boundary conditions and forces such as rainfall, stream flows, windstress or pressure gradients if applicable.
[4123]104
105\anuga tracks the evolution of water depth and horizontal momentum
106within each cell over time by solving the shallow water wave equation
107governing equation using a finite-volume method.
108
[4736]109\anuga also incorporates a mesh generator %, called \code{graphical
110                                %mesh generator},
[4123]111that
112allows the user to set up the geometry of the problem interactively as
113well as tools for interpolation and surface fitting, and a number of
114auxiliary tools for visualising and interrogating the model output.
115
116Most \anuga components are written in the object-oriented programming
117language Python and most users will interact with \anuga by writing
118small Python programs based on the \anuga library
119functions. Computationally intensive components are written for
120efficiency in C routines working directly with the Numerical Python
121structures.
122
123
124\end{abstract}
125
126\tableofcontents
127
128
129\chapter{Introduction}
130
131
132\section{Purpose}
133
134The purpose of this user manual is to introduce the new user to the
135inundation software, describe what it can do and give step-by-step
136instructions for setting up and running hydrodynamic simulations.
137
138\section{Scope}
139
140This manual covers only what is needed to operate the software after
141installation and configuration. It does not includes instructions
142for installing the software or detailed API documentation, both of
143which will be covered in separate publications and by documentation
144in the source code.
145
146\section{Audience}
147
[5129]148Readers are assumed to be familiar with the Python Programming language and
149its object oriented approach.
150Python tutorials include
151\url{http://docs.python.org/tut},
152\url{http://www.sthurlow.com/python}, and
[5130]153%\url{http://datamining.anu.edu.au/\%7e ole/work/teaching/ctac2006/exercise1.pdf}.
154\url{http://datamining.anu.edu.au/\~{}ole/work/teaching/ctac2006/exercise1.pdf}.
[5129]155
156
157Readers also need to have a general understanding of scientific modelling,
158as well as
[4123]159enough programming experience to adapt the code to different
[5129]160requirements.
[4123]161
[5129]162
163
[4123]164\pagebreak
165\chapter{Background}
166
167
168Modelling the effects on the built environment of natural hazards such
169as riverine flooding, storm surges and tsunami is critical for
170understanding their economic and social impact on our urban
171communities.  Geoscience Australia and the Australian National
172University are developing a hydrodynamic inundation modelling tool
173called \anuga to help simulate the impact of these hazards.
174
175The core of \anuga is the fluid dynamics module, called \code{shallow\_water},
176which is based on a finite-volume method for solving the Shallow Water
177Wave Equation.  The study area is represented by a mesh of triangular
178cells.  By solving the governing equation within each cell, water
179depth and horizontal momentum are tracked over time.
180
181A major capability of \anuga is that it can model the process of
182wetting and drying as water enters and leaves an area.  This means
183that it is suitable for simulating water flow onto a beach or dry land
184and around structures such as buildings.  \anuga is also capable
185of modelling hydraulic jumps due to the ability of the finite-volume
186method to accommodate discontinuities in the solution.
187
188To set up a particular scenario the user specifies the geometry
189(bathymetry and topography), the initial water level (stage),
190boundary conditions such as tide, and any forcing terms that may
[5506]191drive the system such as rain_fall, abstraction of water, wind stress or atmospheric pressure
[4123]192gradients. Gravity and frictional resistance from the different
193terrains in the model are represented by predefined forcing terms.
[5506]194See section \ref{sec:forcing terms} for details on forcing terms available in ANUGA.
[4123]195
[4673]196The built-in mesh generator, called \code{graphical\_mesh\_generator},
[4123]197allows the user to set up the geometry
198of the problem interactively and to identify boundary segments and
199regions using symbolic tags.  These tags may then be used to set the
200actual boundary conditions and attributes for different regions
201(e.g.\ the Manning friction coefficient) for each simulation.
202
203Most \anuga components are written in the object-oriented programming
204language Python.  Software written in Python can be produced quickly
205and can be readily adapted to changing requirements throughout its
206lifetime.  Computationally intensive components are written for
207efficiency in C routines working directly with the Numerical Python
208structures.  The animation tool developed for \anuga is based on
209OpenSceneGraph, an Open Source Software (OSS) component allowing high
210level interaction with sophisticated graphics primitives.
211See \cite{nielsen2005} for more background on \anuga.
212
213\chapter{Restrictions and limitations on \anuga}
214\label{ch:limitations}
215
216Although a powerful and flexible tool for hydrodynamic modelling, \anuga has a
217number of limitations that any potential user need to be aware of. They are
218
219\begin{itemize}
[4209]220  \item The mathematical model is the 2D shallow water wave equation.
221  As such it cannot resolve vertical convection and consequently not breaking
[4123]222  waves or 3D turbulence (e.g.\ vorticity).
[5566]223  %\item The surface is assumed to be open, e.g. \anuga cannot model
224  %flow under ceilings or in pipes
[4209]225  \item All spatial coordinates are assumed to be UTM (meters). As such,
226  ANUGA is unsuitable for modelling flows in areas larger than one UTM zone
227  (6 degrees wide).
[5566]228  \item Fluid is assumed to be inviscid - i.e.\ no kinematic viscosity included.
[4209]229  \item The finite volume is a very robust and flexible numerical technique,
230  but it is not the fastest method around. If the geometry is sufficiently
231  simple and if there is no need for wetting or drying, a finite-difference
[4123]232  method may be able to solve the problem faster than \anuga.
[4209]233  %\item Mesh resolutions near coastlines with steep gradients need to be...
234  \item Frictional resistance is implemented using Manning's formula, but
[4123]235  \anuga has not yet been fully validated in regard to bottom roughness
[5566]236  %\item ANUGA contains no tsunami-genic functionality relating to
237  %earthquakes.
[4123]238\end{itemize}
239
240
241
242\chapter{Getting Started}
243\label{ch:getstarted}
244
245This section is designed to assist the reader to get started with
246\anuga by working through some examples. Two examples are discussed;
[5566]247the first is a simple example to illustrate many of the concepts, and
[4123]248the second is a more realistic example.
249
250\section{A Simple Example}
251\label{sec:simpleexample}
252
253\subsection{Overview}
254
255What follows is a discussion of the structure and operation of a
256script called \file{runup.py}.
257
258This example carries out the solution of the shallow-water wave
259equation in the simple case of a configuration comprising a flat
260bed, sloping at a fixed angle in one direction and having a
261constant depth across each line in the perpendicular direction.
262
263The example demonstrates the basic ideas involved in setting up a
264complex scenario. In general the user specifies the geometry
265(bathymetry and topography), the initial water level, boundary
266conditions such as tide, and any forcing terms that may drive the
[5506]267system such as rain_fall, abstraction of water, wind stress or atmospheric pressure gradients.
[4123]268Frictional resistance from the different terrains in the model is
269represented by predefined forcing terms. In this example, the
270boundary is reflective on three sides and a time dependent wave on
271one side.
272
273The present example represents a simple scenario and does not
274include any forcing terms, nor is the data taken from a file as it
275would typically be.
276
277The conserved quantities involved in the
278problem are stage (absolute height of water surface),
279$x$-momentum and $y$-momentum. Other quantities
280involved in the computation are the friction and elevation.
281
282Water depth can be obtained through the equation
283
284\begin{tabular}{rcrcl}
285  \code{depth} &=& \code{stage} &$-$& \code{elevation}
286\end{tabular}
287
288
289\subsection{Outline of the Program}
290
291In outline, \file{runup.py} performs the following steps:
292
293\begin{enumerate}
294
295   \item Sets up a triangular mesh.
296
297   \item Sets certain parameters governing the mode of
298operation of the model-specifying, for instance, where to store the model output.
299
300   \item Inputs various quantities describing physical measurements, such
301as the elevation, to be specified at each mesh point (vertex).
302
303   \item Sets up the boundary conditions.
304
305   \item Carries out the evolution of the model through a series of time
306steps and outputs the results, providing a results file that can
307be visualised.
308
309\end{enumerate}
310
311\subsection{The Code}
312
313%FIXME: we are using the \code function here.
314%This should be used wherever possible
315For reference we include below the complete code listing for
316\file{runup.py}. Subsequent paragraphs provide a
317`commentary' that describes each step of the program and explains it
318significance.
319
320\verbatiminput{demos/runup.py}
321
322\subsection{Establishing the Mesh}\index{mesh, establishing}
323
324The first task is to set up the triangular mesh to be used for the
325scenario. This is carried out through the statement:
326
327{\small \begin{verbatim}
[4953]328    points, vertices, boundary = rectangular_cross(10, 10)
[4123]329\end{verbatim}}
330
[4953]331The function \function{rectangular_cross} is imported from a module
[4123]332\module{mesh\_factory} defined elsewhere. (\anuga also contains
333several other schemes that can be used for setting up meshes, but we
334shall not discuss these.) The above assignment sets up a $10 \times
33510$ rectangular mesh, triangulated in a regular way. The assignment
336
337{\small \begin{verbatim}
[4953]338    points, vertices, boundary = rectangular_cross(m, n)
[4123]339\end{verbatim}}
340
341returns:
342
343\begin{itemize}
344
345   \item a list \code{points} giving the coordinates of each mesh point,
346
347   \item a list \code{vertices} specifying the three vertices of each triangle, and
348
349   \item a dictionary \code{boundary} that stores the edges on
350   the boundary and associates each with one of the symbolic tags \code{`left'}, \code{`right'},
351   \code{`top'} or \code{`bottom'}.
352
353\end{itemize}
354
355(For more details on symbolic tags, see page
356\pageref{ref:tagdescription}.)
357
358An example of a general unstructured mesh and the associated data
359structures \code{points}, \code{vertices} and \code{boundary} is
360given in Section \ref{sec:meshexample}.
361
362
363
364
365\subsection{Initialising the Domain}
366
367These variables are then used to set up a data structure
368\code{domain}, through the assignment:
369
370{\small \begin{verbatim}
371    domain = Domain(points, vertices, boundary)
372\end{verbatim}}
373
374This creates an instance of the \class{Domain} class, which
375represents the domain of the simulation. Specific options are set at
376this point, including the basename for the output file and the
377directory to be used for data:
378
379{\small \begin{verbatim}
380    domain.set_name('runup')
381\end{verbatim}}
382
383{\small \begin{verbatim}
384    domain.set_datadir('.')
385\end{verbatim}}
386
387In addition, the following statement now specifies that the
388quantities \code{stage}, \code{xmomentum} and \code{ymomentum} are
389to be stored:
390
391{\small \begin{verbatim}
392    domain.set_quantities_to_be_stored(['stage', 'xmomentum',
393    'ymomentum'])
394\end{verbatim}}
395
396
397\subsection{Initial Conditions}
398
399The next task is to specify a number of quantities that we wish to
400set for each mesh point. The class \class{Domain} has a method
401\method{set\_quantity}, used to specify these quantities. It is a
402flexible method that allows the user to set quantities in a variety
403of ways---using constants, functions, numeric arrays, expressions
404involving other quantities, or arbitrary data points with associated
405values, all of which can be passed as arguments. All quantities can
406be initialised using \method{set\_quantity}. For a conserved
407quantity (such as \code{stage, xmomentum, ymomentum}) this is called
408an \emph{initial condition}. However, other quantities that aren't
409updated by the equation are also assigned values using the same
410interface. The code in the present example demonstrates a number of
411forms in which we can invoke \method{set\_quantity}.
412
413
414\subsubsection{Elevation}
415
416The elevation, or height of the bed, is set using a function,
417defined through the statements below, which is specific to this
418example and specifies a particularly simple initial configuration
419for demonstration purposes:
420
421{\small \begin{verbatim}
422    def f(x,y):
423        return -x/2
424\end{verbatim}}
425
426This simply associates an elevation with each point \code{(x, y)} of
427the plane.  It specifies that the bed slopes linearly in the
428\code{x} direction, with slope $-\frac{1}{2}$,  and is constant in
429the \code{y} direction.
430
431Once the function \function{f} is specified, the quantity
432\code{elevation} is assigned through the simple statement:
433
434{\small \begin{verbatim}
435    domain.set_quantity('elevation', f)
436\end{verbatim}}
437
[4953]438NOTE: If using function to set \code{elevation} it must be vector
[4743]439compatible. For example square root will not work.
[4123]440
441\subsubsection{Friction}
442
443The assignment of the friction quantity (a forcing term)
444demonstrates another way we can use \method{set\_quantity} to set
445quantities---namely, assign them to a constant numerical value:
446
447{\small \begin{verbatim}
448    domain.set_quantity('friction', 0.1)
449\end{verbatim}}
450
451This specifies that the Manning friction coefficient is set to 0.1
452at every mesh point.
453
454\subsubsection{Stage}
455
456The stage (the height of the water surface) is related to the
457elevation and the depth at any time by the equation
458
459{\small \begin{verbatim}
460    stage = elevation + depth
461\end{verbatim}}
462
463
464For this example, we simply assign a constant value to \code{stage},
465using the statement
466
467{\small \begin{verbatim}
468    domain.set_quantity('stage', -.4)
469\end{verbatim}}
470
471which specifies that the surface level is set to a height of $-0.4$,
472i.e. 0.4 units (m) below the zero level.
473
474Although it is not necessary for this example, it may be useful to
475digress here and mention a variant to this requirement, which allows
476us to illustrate another way to use \method{set\_quantity}---namely,
477incorporating an expression involving other quantities. Suppose,
478instead of setting a constant value for the stage, we wished to
479specify a constant value for the \emph{depth}. For such a case we
480need to specify that \code{stage} is everywhere obtained by adding
481that value to the value already specified for \code{elevation}. We
482would do this by means of the statements:
483
484{\small \begin{verbatim}
485    h = 0.05 # Constant depth
486    domain.set_quantity('stage', expression = 'elevation + %f' %h)
487\end{verbatim}}
488
489That is, the value of \code{stage} is set to $\code{h} = 0.05$ plus
490the value of \code{elevation} already defined.
491
492The reader will probably appreciate that this capability to
493incorporate expressions into statements using \method{set\_quantity}
[5508]494greatly expands its power.) See Section \ref{sec:initial conditions} for more
[4123]495details.
496
497\subsection{Boundary Conditions}\index{boundary conditions}
498
499The boundary conditions are specified as follows:
500
501{\small \begin{verbatim}
502    Br = Reflective_boundary(domain)
503
504    Bt = Transmissive_boundary(domain)
505
506    Bd = Dirichlet_boundary([0.2,0.,0.])
507
508    Bw = Time_boundary(domain=domain,
509                f=lambda t: [(0.1*sin(t*2*pi)-0.3), 0.0, 0.0])
510\end{verbatim}}
511
512The effect of these statements is to set up a selection of different
513alternative boundary conditions and store them in variables that can be
514assigned as needed. Each boundary condition specifies the
515behaviour at a boundary in terms of the behaviour in neighbouring
516elements. The boundary conditions introduced here may be briefly described as
517follows:
518
519\begin{itemize}
520    \item \textbf{Reflective boundary}\label{def:reflective boundary} Returns same \code{stage} as
521      as present in its neighbour volume but momentum vector
522      reversed 180 degrees (reflected).
523      Specific to the shallow water equation as it works with the
524      momentum quantities assumed to be the second and third conserved
525      quantities. A reflective boundary condition models a solid wall.
526    \item \textbf{Transmissive boundary}\label{def:transmissive boundary} Returns same conserved quantities as
527      those present in its neighbour volume. This is one way of modelling
528      outflow from a domain, but it should be used with caution if flow is
529      not steady state as replication of momentum at the boundary
530      may cause occasional spurious effects. If this occurs,
531      consider using e.g. a Dirichlet boundary condition.
532    \item \textbf{Dirichlet boundary}\label{def:dirichlet boundary} Specifies
533      constant values for stage, $x$-momentum and $y$-momentum at the boundary.
534    \item \textbf{Time boundary}\label{def:time boundary} Like a Dirichlet
535      boundary but with behaviour varying with time.
536\end{itemize}
537
538\label{ref:tagdescription}Before describing how these boundary
539conditions are assigned, we recall that a mesh is specified using
540three variables \code{points}, \code{vertices} and \code{boundary}.
541In the code we are discussing, these three variables are returned by
542the function \code{rectangular}; however, the example given in
543Section \ref{sec:realdataexample} illustrates another way of
544assigning the values, by means of the function
545\code{create\_mesh\_from\_regions}.
546
547These variables store the data determining the mesh as follows. (You
548may find that the example given in Section \ref{sec:meshexample}
549helps to clarify the following discussion, even though that example
550is a \emph{non-rectangular} mesh.)
551
552\begin{itemize}
553\item The variable \code{points} stores a list of 2-tuples giving the
554coordinates of the mesh points.
555
556\item The variable \code{vertices} stores a list of 3-tuples of
557numbers, representing vertices of triangles in the mesh. In this
558list, the triangle whose vertices are \code{points[i]},
559\code{points[j]}, \code{points[k]} is represented by the 3-tuple
560\code{(i, j, k)}.
561
562\item The variable \code{boundary} is a Python dictionary that
563not only stores the edges that make up the boundary but also assigns
564symbolic tags to these edges to distinguish different parts of the
565boundary. An edge with endpoints \code{points[i]} and
566\code{points[j]} is represented by the 2-tuple \code{(i, j)}. The
567keys for the dictionary are the 2-tuples \code{(i, j)} corresponding
568to boundary edges in the mesh, and the values are the tags are used
569to label them. In the present example, the value \code{boundary[(i,
570j)]} assigned to \code{(i, j)]} is one of the four tags
571\code{`left'}, \code{`right'}, \code{`top'} or \code{`bottom'},
572depending on whether the boundary edge represented by \code{(i, j)}
573occurs at the left, right, top or bottom of the rectangle bounding
574the mesh. The function \code{rectangular} automatically assigns
575these tags to the boundary edges when it generates the mesh.
576\end{itemize}
577
578The tags provide the means to assign different boundary conditions
579to an edge depending on which part of the boundary it belongs to.
580(In Section \ref{sec:realdataexample} we describe an example that
[4673]581uses different boundary tags --- in general, the possible tags are entirely selectable by the user when generating the mesh and not
582limited to `left', `right', `top' and `bottom' as in this example.)
583All segments in bounding polygon must be tagged. If a tag is not supplied, the default tag name 'exterior' will be assigned by ANUGA.
[4123]584
[4673]585
[4123]586Using the boundary objects described above, we assign a boundary
587condition to each part of the boundary by means of a statement like
588
589{\small \begin{verbatim}
590    domain.set_boundary({'left': Br, 'right': Bw, 'top': Br, 'bottom': Br})
591\end{verbatim}}
592
[4673]593It is critical that all tags are assoctiated with a boundary conditing in this statement. If not the program will halt with a statement like
594
595\begin{verbatim}
596
597Traceback (most recent call last):
598  File "mesh_test.py", line 114, in ?
599    domain.set_boundary({'west': Bi, 'east': Bo, 'north': Br, 'south': Br})
600  File "X:\inundation\sandpits\onielsen\anuga_core\source\anuga\abstract_2d_finite_volumes\domain.py", line 505, in set_boundary
601    raise msg
602ERROR (domain.py): Tag "exterior" has not been bound to a boundary object.
603All boundary tags defined in domain must appear in the supplied dictionary.
604The tags are: ['ocean', 'east', 'north', 'exterior', 'south']
[4953]605\end{verbatim}
[4673]606
607
608The command \code{set\_boundary} stipulates that, in the current example, the right
[4123]609boundary varies with time, as defined by the lambda function, while the other
610boundaries are all reflective.
611
612The reader may wish to experiment by varying the choice of boundary
613types for one or more of the boundaries. (In the case of \code{Bd}
614and \code{Bw}, the three arguments in each case represent the
615\code{stage}, $x$-momentum and $y$-momentum, respectively.)
616
617{\small \begin{verbatim}
618    Bw = Time_boundary(domain=domain,
619                       f=lambda t: [(0.1*sin(t*2*pi)-0.3), 0.0, 0.0])
620\end{verbatim}}
621
622
623
624\subsection{Evolution}\index{evolution}
625
626The final statement \nopagebreak[3]
627{\small \begin{verbatim}
628    for t in domain.evolve(yieldstep = 0.1, duration = 4.0):
629        print domain.timestepping_statistics()
630\end{verbatim}}
631
632causes the configuration of the domain to `evolve', over a series of
633steps indicated by the values of \code{yieldstep} and
634\code{duration}, which can be altered as required.  The value of
635\code{yieldstep} controls the time interval between successive model
636outputs.  Behind the scenes more time steps are generally taken.
637
638
639\subsection{Output}
640
641The output is a NetCDF file with the extension \code{.sww}. It
[4209]642contains stage and momentum information and can be used with the
643ANUGA viewer \code{animate} (see Section \ref{sec:animate})
[4123]644visualisation package
645to generate a visual display. See Section \ref{sec:file formats}
646(page \pageref{sec:file formats}) for more on NetCDF and other file
647formats.
648
649The following is a listing of the screen output seen by the user
650when this example is run:
651
652\verbatiminput{examples/runupoutput.txt}
653
654
655\section{How to Run the Code}
656
657The code can be run in various ways:
658
659\begin{itemize}
660  \item{from a Windows or Unix command line} as in\ \code{python runup.py}
661  \item{within the Python IDLE environment}
662  \item{within emacs}
663  \item{within Windows, by double-clicking the \code{runup.py}
664  file.}
665\end{itemize}
666
667
668\section{Exploring the Model Output}
669
670The following figures are screenshots from the \anuga visualisation
671tool \code{animate}. Figure \ref{fig:runupstart} shows the domain
672with water surface as specified by the initial condition, $t=0$.
673Figure \ref{fig:runup2} shows later snapshots for $t=2.3$ and
674$t=4$ where the system has been evolved and the wave is encroaching
675on the previously dry bed.  All figures are screenshots from an
676interactive animation tool called animate which is part of \anuga and
677distributed as in the package anuga\_viewer.
678Animate is described in more detail is Section \ref{sec:animate}.
679
680\begin{figure}[hbt]
681
682  \centerline{\includegraphics[width=75mm, height=75mm]
683    {graphics/bedslopestart.jpg}}
684
685  \caption{Runup example viewed with the ANUGA viewer}
686  \label{fig:runupstart}
687\end{figure}
688
689
690\begin{figure}[hbt]
691
692  \centerline{
693   \includegraphics[width=75mm, height=75mm]{graphics/bedslopeduring.jpg}
694    \includegraphics[width=75mm, height=75mm]{graphics/bedslopeend.jpg}
695   }
696
697  \caption{Runup example viewed with ANGUA viewer}
698  \label{fig:runup2}
699\end{figure}
700
701
702
703\clearpage
704
705%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
706
707\section{A slightly more complex example}
708\label{sec:channelexample}
709
710\subsection{Overview}
711
[4209]712The next example is about waterflow in a channel with varying boundary conditions and
[4123]713more complex topograhies. These examples build on the
714concepts introduced through the \file{runup.py} in Section \ref{sec:simpleexample}.
715The example will be built up through three progressively more complex scripts.
716
717\subsection{Overview}
718As in the case of \file{runup.py}, the actions carried
719out by the program can be organised according to this outline:
720
721\begin{enumerate}
722
723   \item Set up a triangular mesh.
724
725   \item Set certain parameters governing the mode of
726operation of the model---specifying, for instance, where to store the
727model output.
728
729   \item Set up initial conditions for various quantities such as the elevation, to be specified at each mesh point (vertex).
730
731   \item Set up the boundary conditions.
732
733   \item Carry out the evolution of the model through a series of time
734steps and output the results, providing a results file that can be
735visualised.
736
737\end{enumerate}
738
739
740\subsection{The Code}
741
742Here is the code for the first version of the channel flow \file{channel1.py}:
743
744\verbatiminput{demos/channel1.py}
745
746In discussing the details of this example, we follow the outline
747given above, discussing each major step of the code in turn.
748
749\subsection{Establishing the Mesh}\index{mesh, establishing}
750
[4209]751In this example we use a similar simple structured triangular mesh as in \code{runup.py}
752for simplicity, but this time we will use a symmetric one and also
[4123]753change the physical extent of the domain. The assignment
754
755{\small \begin{verbatim}
[4209]756    points, vertices, boundary = rectangular_cross(m, n,
[4123]757                                                   len1=length, len2=width)
758\end{verbatim}}
[4209]759returns a m x n mesh similar to the one used in the previous example, except that now the
760extent in the x and y directions are given by the value of \code{length} and \code{width}
[4123]761respectively.
762
[4209]763Defining m and n in terms of the extent as in this example provides a convenient way of
[4123]764controlling the resolution: By defining dx and dy to be the desired size of each hypothenuse in the mesh we can write the mesh generation as follows:
765
766{\small \begin{verbatim}
767length = 10.
768width = 5.
769dx = dy = 1           # Resolution: Length of subdivisions on both axes
770
771points, vertices, boundary = rectangular_cross(int(length/dx), int(width/dy),
772                                               len1=length, len2=width)
773\end{verbatim}}
774which yields a mesh of length=10m, width=5m with 1m spacings. To increase the resolution, as we will later in this example, one merely decrease the values of dx and dy.
775
776The rest of this script is as in the previous example.
777% except for an application of the 'expression' form of \code{set\_quantity} where we use the value of \code{elevation} to define the (dry) initial condition for \code{stage}:
778%{\small \begin{verbatim}
779%  domain.set_quantity('stage', expression='elevation')
780%\end{verbatim}}
781
782\section{Model Output}
783
784The following figure is a screenshot from the \anuga visualisation
785tool \code{animate} of output from this example.
786\begin{figure}[hbt]
787  \centerline{\includegraphics[height=75mm]
788    {graphics/channel1.png}}%
789
790  \caption{Simple channel example viewed with the ANUGA viewer.}
791  \label{fig:channel1}
792\end{figure}
793
794
795\subsection{Changing boundary conditions on the fly}
[4205]796\label{sec:change boundary}
[4123]797
798Here is the code for the second version of the channel flow \file{channel2.py}:
799\verbatiminput{demos/channel2.py}
[4209]800This example differs from the first version in that a constant outflow boundary condition has
801been defined
[4123]802{\small \begin{verbatim}
803    Bo = Dirichlet_boundary([-5, 0, 0]) # Outflow
804\end{verbatim}}
805and that it is applied to the right hand side boundary when the water level there exceeds 0m.
806{\small \begin{verbatim}
807for t in domain.evolve(yieldstep = 0.2, finaltime = 40.0):
808    domain.write_time()
809
[4209]810    if domain.get_quantity('stage').get_values(interpolation_points=[[10, 2.5]]) > 0:
[4123]811        print 'Stage > 0: Changing to outflow boundary'
812        domain.set_boundary({'right': Bo})
813\end{verbatim}}
[4206]814\label{sec:change boundary code}
[4123]815
816The if statement in the timestepping loop (evolve) gets the quantity
817\code{stage} and obtain the interpolated value at the point (10m,
8182.5m) which is on the right boundary. If the stage exceeds 0m a
819message is printed and the old boundary condition at tag 'right' is
[4209]820replaced by the outflow boundary using the method
821{\small \begin{verbatim}
[4123]822    domain.set_boundary({'right': Bo})
823\end{verbatim}}
[4209]824This type of dynamically varying boundary could for example be
825used to model the
826breakdown of a sluice door when water exceeds a certain level.
[4123]827
828\subsection{Output}
829
830The text output from this example looks like this
[4209]831{\small \begin{verbatim}
[4123]832...
833Time = 15.4000, delta t in [0.03789902, 0.03789916], steps=6 (6)
834Time = 15.6000, delta t in [0.03789896, 0.03789908], steps=6 (6)
835Time = 15.8000, delta t in [0.03789891, 0.03789903], steps=6 (6)
836Stage > 0: Changing to outflow boundary
837Time = 16.0000, delta t in [0.02709050, 0.03789898], steps=6 (6)
838Time = 16.2000, delta t in [0.03789892, 0.03789904], steps=6 (6)
839...
840\end{verbatim}}
841
842
843\subsection{Flow through more complex topograhies}
844
845Here is the code for the third version of the channel flow \file{channel3.py}:
846\verbatiminput{demos/channel3.py}
847
[4209]848This example differs from the first two versions in that the topography
[4123]849contains obstacles.
850
851This is accomplished here by defining the function \code{topography} as follows
852{\small \begin{verbatim}
853def topography(x,y):
854    """Complex topography defined by a function of vectors x and y
855    """
856
[4209]857    z = -x/10
858
[4123]859    N = len(x)
860    for i in range(N):
861
862        # Step
863        if 10 < x[i] < 12:
[4209]864            z[i] += 0.4 - 0.05*y[i]
865
[4123]866        # Constriction
867        if 27 < x[i] < 29 and y[i] > 3:
[4209]868            z[i] += 2
869
[4123]870        # Pole
871        if (x[i] - 34)**2 + (y[i] - 2)**2 < 0.4**2:
872            z[i] += 2
873
874    return z
875\end{verbatim}}
876
877In addition, changing the resolution to dx=dy=0.1 creates a finer mesh resolving the new featurse better.
878
879A screenshot of this model at time == 15s is
880\begin{figure}[hbt]
881
882  \centerline{\includegraphics[height=75mm]
883    {graphics/channel3.png}}
884
885  \caption{More complex flow in a channel}
886  \label{fig:channel3}
887\end{figure}
888
889
890
891
892\clearpage
893
894%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
895
896\section{An Example with Real Data}
897\label{sec:realdataexample} The following discussion builds on the
898concepts introduced through the \file{runup.py} example and
899introduces a second example, \file{runcairns.py}.  This refers to
[4953]900a {\bf hypothetical} scenario using real-life data,
[4875]901in which the domain of interest surrounds the
[4123]902Cairns region. Two scenarios are given; firstly, a
903hypothetical tsunami wave is generated by a submarine mass failure
904situated on the edge of the continental shelf, and secondly, a fixed wave
905of given amplitude and period is introduced through the boundary.
906
[4875]907{\bf
908Each scenario has been designed to generate a tsunami which will
[4953]909inundate the Cairns region. To achieve this, suitably large
[4875]910parameters were chosen and were not based on any known tsunami sources
911or realistic amplitudes.
912}
913
[4123]914\subsection{Overview}
915As in the case of \file{runup.py}, the actions carried
916out by the program can be organised according to this outline:
917
918\begin{enumerate}
919
920   \item Set up a triangular mesh.
921
922   \item Set certain parameters governing the mode of
923operation of the model---specifying, for instance, where to store the
924model output.
925
926   \item Input various quantities describing physical measurements, such
927as the elevation, to be specified at each mesh point (vertex).
928
929   \item Set up the boundary conditions.
930
931   \item Carry out the evolution of the model through a series of time
932steps and output the results, providing a results file that can be
933visualised.
934
935\end{enumerate}
936
937
938
939\subsection{The Code}
940
941Here is the code for \file{runcairns.py}:
942
943\verbatiminput{demos/cairns/runcairns.py}
944
945In discussing the details of this example, we follow the outline
946given above, discussing each major step of the code in turn.
947
948\subsection{Establishing the Mesh}\index{mesh, establishing}
949
950One obvious way that the present example differs from
951\file{runup.py} is in the use of a more complex method to
952create the mesh. Instead of imposing a mesh structure on a
953rectangular grid, the technique used for this example involves
954building mesh structures inside polygons specified by the user,
[4736]955using a mesh-generator.
[4123]956
[4736]957In its simplest form, the mesh-generator creates the mesh within a single
[4123]958polygon whose vertices are at geographical locations specified by
959the user. The user specifies the \emph{resolution}---that is, the
960maximal area of a triangle used for triangulation---and a triangular
961mesh is created inside the polygon using a mesh generation engine.
[4209]962On any given platform, the same mesh will be returned.
[4123]963%Figure
964%\ref{fig:pentagon} shows a simple example of this, in which the
965%triangulation is carried out within a pentagon.
966
967
968%\begin{figure}[hbt]
969
970%  \caption{Mesh points are created inside the polygon}
971  %\label{fig:pentagon}
972%\end{figure}
973
974Boundary tags are not restricted to \code{`left'}, \code{`bottom'},
975\code{`right'} and \code{`top'}, as in the case of
976\file{runup.py}. Instead the user specifies a list of
977tags appropriate to the configuration being modelled.
978
[4736]979In addition, the mesh-generator provides a way to adapt to geographic or
[4123]980other features in the landscape, whose presence may require an
981increase in resolution. This is done by allowing the user to specify
982a number of \emph{interior polygons}, each with a specified
983resolution. It is also
984possible to specify one or more `holes'---that is, areas bounded by
985polygons in which no triangulation is required.
986
987%\begin{figure}[hbt]
988%  \caption{Interior meshes with individual resolution}
989%  \label{fig:interior meshes}
990%\end{figure}
991
[4736]992In its general form, the mesh-generator takes for its input a bounding
[4123]993polygon and (optionally) a list of interior polygons. The user
994specifies resolutions, both for the bounding polygon and for each of
[4736]995the interior polygons. Given this data, the mesh-generator first creates a
[4123]996triangular mesh with varying resolution.
997
998The function used to implement this process is
999\function{create\_mesh\_from\_regions}. Its arguments include the
1000bounding polygon and its resolution, a list of boundary tags, and a
1001list of pairs \code{[polygon, resolution]}, specifying the interior
1002polygons and their resolutions.
1003
1004The resulting mesh is output to a \emph{mesh file}\index{mesh
1005file}\label{def:mesh file}. This term is used to describe a file of
1006a specific format used to store the data specifying a mesh. (There
1007are in fact two possible formats for such a file: it can either be a
1008binary file, with extension \code{.msh}, or an ASCII file, with
1009extension \code{.tsh}. In the present case, the binary file format
1010\code{.msh} is used. See Section \ref{sec:file formats} (page
1011\pageref{sec:file formats}) for more on file formats.)
1012
1013In practice, the details of the polygons used are read from a
1014separate file \file{project.py}. Here is a complete listing of
1015\file{project.py}:
1016
1017\verbatiminput{demos/cairns/project.py}
1018
1019Figure \ref{fig:cairns3d} illustrates the landscape of the region
1020for the Cairns example. Understanding the landscape is important in
[4209]1021determining the location and resolution of interior polygons. The
[4123]1022supporting data is found in the ASCII grid, \code{cairns.asc}, which
1023has been sourced from the publically available Australian Bathymetry
1024and Topography Grid 2005, \cite{grid250}. The required resolution
[4209]1025for inundation modelling will depend on the underlying topography and
[4123]1026bathymetry; as the terrain becomes more complex, the desired resolution
1027would decrease to the order of tens of metres.
1028
1029\begin{figure}[hbt]
1030\centerline{\includegraphics[scale=0.5]{graphics/cairns3.jpg}}
1031\caption{Landscape of the Cairns scenario.}
1032\label{fig:cairns3d}
1033
1034\end{figure}
1035The following statements are used to read in the specific polygons
1036from \code{project.cairns} and assign a defined resolution to
1037each polygon.
1038
1039{\small \begin{verbatim}
1040    islands_res = 100000
1041    cairns_res = 100000
1042    shallow_res = 500000
1043    interior_regions = [[project.poly_cairns, cairns_res],
1044                        [project.poly_island0, islands_res],
1045                        [project.poly_island1, islands_res],
1046                        [project.poly_island2, islands_res],
1047                        [project.poly_island3, islands_res],
1048                        [project.poly_shallow, shallow_res]]
1049\end{verbatim}}
1050
1051Figure \ref{fig:cairnspolys}
[4209]1052illustrates the polygons used for the Cairns scenario.
[4123]1053
1054\begin{figure}[hbt]
1055
1056  \centerline{\includegraphics[scale=0.5]
1057      {graphics/cairnsmodel.jpg}}
1058  \caption{Interior and bounding polygons for the Cairns example.}
1059  \label{fig:cairnspolys}
1060\end{figure}
1061
1062The statement
1063
1064
1065{\small \begin{verbatim}
[4209]1066remainder_res = 10000000
[4123]1067create_mesh_from_regions(project.bounding_polygon,
1068                         boundary_tags={'top': [0],
1069                                        'ocean_east': [1],
1070                                        'bottom': [2],
1071                                        'onshore': [3]},
1072                         maximum_triangle_area=remainder_res,
1073                         filename=meshname,
1074                         interior_regions=interior_regions,
1075                         use_cache=True,
1076                         verbose=True)
1077\end{verbatim}}
1078is then used to create the mesh, taking the bounding polygon to be
1079the polygon \code{bounding\_polygon} specified in \file{project.py}.
1080The argument \code{boundary\_tags} assigns a dictionary, whose keys
1081are the names of the boundary tags used for the bounding
1082polygon---\code{`top'}, \code{`ocean\_east'}, \code{`bottom'}, and
1083\code{`onshore'}--- and whose values identify the indices of the
[4953]1084segments associated with each of these tags.
1085The polygon may be arranged either clock-wise or counter clock-wise and the
[4818]1086indices refer to edges in the order they appear: Edge 0 connects vertex 0 and vertex 1, edge 1 connects vertex 1 and 2; and so forth.
1087(Here, the values associated with each boundary tag are one-element lists, but they can have as many indices as there are edges)
[4673]1088If polygons intersect, or edges coincide the resolution may be undefined in some regions.
[4953]1089Use the underlying mesh interface for such cases. See Section
[4674]1090\ref{sec:mesh interface}.
[4123]1091
[4953]1092Note that every point on each polygon defining the mesh will be used as vertices in triangles.
1093Consequently, polygons with points very close together will cause triangles with very small
[4691]1094areas to be generated irrespective of the requested resolution.
[4953]1095Make sure points on polygons are spaced to be no closer than the smallest resolution requested.
[4123]1096
1097
1098\subsection{Initialising the Domain}
1099
1100As with \file{runup.py}, once we have created the mesh, the next
1101step is to create the data structure \code{domain}. We did this for
1102\file{runup.py} by inputting lists of points and triangles and
1103specifying the boundary tags directly. However, in the present case,
1104we use a method that works directly with the mesh file
1105\code{meshname}, as follows:
1106
1107
1108{\small \begin{verbatim}
1109    domain = Domain(meshname, use_cache=True, verbose=True)
1110\end{verbatim}}
1111
1112Providing a filename instead of the lists used in \file{runup.py}
1113above causes \code{Domain} to convert a mesh file \code{meshname}
1114into an instance of \code{Domain}, allowing us to use methods like
1115\method{set\_quantity} to set quantities and to apply other
1116operations.
1117
1118%(In principle, the
1119%second argument of \function{pmesh\_to\_domain\_instance} can be any
1120%subclass of \class{Domain}, but for applications involving the
1121%shallow-water wave equation, the second argument of
1122%\function{pmesh\_to\_domain\_instance} can always be set simply to
1123%\class{Domain}.)
1124
1125The following statements specify a basename and data directory, and
1126identify quantities to be stored. For the first two, values are
1127taken from \file{project.py}.
1128
1129{\small \begin{verbatim}
1130    domain.set_name(project.basename)
1131    domain.set_datadir(project.outputdir)
1132    domain.set_quantities_to_be_stored(['stage', 'xmomentum',
1133        'ymomentum'])
1134\end{verbatim}}
1135
1136
1137\subsection{Initial Conditions}
1138Quantities for \file{runcairns.py} are set
1139using similar methods to those in \file{runup.py}. However,
1140in this case, many of the values are read from the auxiliary file
1141\file{project.py} or, in the case of \code{elevation}, from an
1142ancillary points file.
1143
1144
1145
1146\subsubsection{Stage}
1147
1148For the scenario we are modelling in this case, we use a callable
1149object \code{tsunami\_source}, assigned by means of a function
1150\function{slide\_tsunami}. This is similar to how we set elevation in
1151\file{runup.py} using a function---however, in this case the
1152function is both more complex and more interesting.
1153
1154The function returns the water displacement for all \code{x} and
1155\code{y} in the domain. The water displacement is a double Gaussian
1156function that depends on the characteristics of the slide (length,
1157width, thickness, slope, etc), its location (origin) and the depth at that
[4209]1158location. For this example, we choose to apply the slide function
[4875]1159at a specified time into the simulation. {\bf Note, the parameters used
[4953]1160in this example have been deliberately chosen to generate a suitably
[4875]1161large amplitude tsunami which would inundate the Cairns region.}
[4123]1162
1163\subsubsection{Friction}
1164
1165We assign the friction exactly as we did for \file{runup.py}:
1166
1167{\small \begin{verbatim}
1168    domain.set_quantity('friction', 0.0)
1169\end{verbatim}}
1170
1171
1172\subsubsection{Elevation}
1173
1174The elevation is specified by reading data from a file:
1175
1176{\small \begin{verbatim}
1177    domain.set_quantity('elevation',
1178                        filename = project.dem_name + '.pts',
1179                        use_cache = True,
1180                        verbose = True)
1181\end{verbatim}}
1182
1183%However, before this step can be executed, some preliminary steps
1184%are needed to prepare the file from which the data is taken. Two
1185%source files are used for this data---their names are specified in
1186%the file \file{project.py}, in the variables \code{coarsedemname}
1187%and \code{finedemname}. They contain `coarse' and `fine' data,
1188%respectively---that is, data sampled at widely spaced points over a
1189%large region and data sampled at closely spaced points over a
1190%smaller subregion. The data in these files is combined through the
1191%statement
1192
1193%{\small \begin{verbatim}
1194%combine_rectangular_points_files(project.finedemname + '.pts',
1195%                                 project.coarsedemname + '.pts',
1196%                                 project.combineddemname + '.pts')
1197%\end{verbatim}}
1198%The effect of this is simply to combine the datasets by eliminating
1199%any coarse data associated with points inside the smaller region
1200%common to both datasets. The name to be assigned to the resulting
1201%dataset is also derived from the name stored in the variable
1202%\code{combinedname} in the file \file{project.py}.
1203
1204\subsection{Boundary Conditions}\index{boundary conditions}
1205
1206Setting boundaries follows a similar pattern to the one used for
1207\file{runup.py}, except that in this case we need to associate a
1208boundary type with each of the
1209boundary tag names introduced when we established the mesh. In place of the four
1210boundary types introduced for \file{runup.py}, we use the reflective
1211boundary for each of the
1212eight tagged segments defined by \code{create_mesh_from_regions}:
1213
1214{\small \begin{verbatim}
1215Bd = Dirichlet_boundary([0.0,0.0,0.0])
1216domain.set_boundary( {'ocean_east': Bd, 'bottom': Bd, 'onshore': Bd,
1217                          'top': Bd} )
1218\end{verbatim}}
1219
1220\subsection{Evolution}
1221
1222With the basics established, the running of the `evolve' step is
1223very similar to the corresponding step in \file{runup.py}. For the slide
[4209]1224scenario,
[4123]1225the simulation is run for 5000 seconds with the output stored every ten seconds.
1226For this example, we choose to apply the slide at 60 seconds into the simulation.
1227
1228{\small \begin{verbatim}
1229    import time t0 = time.time()
1230
[4209]1231
1232    for t in domain.evolve(yieldstep = 10, finaltime = 60):
[4123]1233            domain.write_time()
[4209]1234            domain.write_boundary_statistics(tags = 'ocean_east')
1235
[4123]1236        # add slide
1237        thisstagestep = domain.get_quantity('stage')
1238        if allclose(t, 60):
1239            slide = Quantity(domain)
1240            slide.set_values(tsunami_source)
1241            domain.set_quantity('stage', slide + thisstagestep)
[4209]1242
1243        for t in domain.evolve(yieldstep = 10, finaltime = 5000,
[4123]1244                               skip_initial_step = True):
1245            domain.write_time()
1246        domain.write_boundary_statistics(tags = 'ocean_east')
1247\end{verbatim}}
1248
[4209]1249For the fixed wave scenario, the simulation is run to 10000 seconds,
[4123]1250with the first half of the simulation stored at two minute intervals,
1251and the second half of the simulation stored at ten second intervals.
1252This functionality is especially convenient as it allows the detailed
1253parts of the simulation to be viewed at higher time resolution.
1254
1255
1256{\small \begin{verbatim}
1257
1258# save every two mins leading up to wave approaching land
[4209]1259    for t in domain.evolve(yieldstep = 120, finaltime = 5000):
[4123]1260        domain.write_time()
[4209]1261        domain.write_boundary_statistics(tags = 'ocean_east')
[4123]1262
1263    # save every 30 secs as wave starts inundating ashore
[4209]1264    for t in domain.evolve(yieldstep = 10, finaltime = 10000,
[4123]1265                           skip_initial_step = True):
1266        domain.write_time()
1267        domain.write_boundary_statistics(tags = 'ocean_east')
[4209]1268
[4123]1269\end{verbatim}}
1270
1271\section{Exploring the Model Output}
1272
1273Now that the scenario has been run, the user can view the output in a number of ways.
1274As described earlier, the user may run animate to view a three-dimensional representation
1275of the simulation.
1276
1277The user may also be interested in a maximum inundation map. This simply shows the
[4209]1278maximum water depth over the domain and is achieved with the function sww2dem (described in
[4207]1279Section \ref{sec:basicfileconversions}).
[4123]1280\file{ExportResults.py} demonstrates how this function can be used:
1281
1282\verbatiminput{demos/cairns/ExportResults.py}
1283
1284The script generates an maximum water depth ASCII grid at a defined
1285resolution (here 100 m$^2$) which can then be viewed in a GIS environment, for
1286example. The parameters used in the function are defined in \file{project.py}.
1287Figures \ref{fig:maxdepthcairnsslide} and \ref{fig:maxdepthcairnsfixedwave} show
[4209]1288the maximum water depth within the defined region for the slide and fixed wave scenario
[4875]1289respectively. {\bf Note, these inundation maps have been based on purely hypothetical
1290scenarios and were designed explicitly for demonstration purposes only.}
[4123]1291The user could develop a maximum absolute momentum or other expressions which can be
[4209]1292derived from the quantities.
[4869]1293It must be noted here that depth is more meaningful when the elevation is positive
[4870]1294(\code{depth} = \code{stage} $-$ \code{elevation}) as it describes the water height
[4869]1295above the available elevation. When the elevation is negative, depth is meauring the
[4953]1296water height from the sea floor. With this in mind, maximum inundation maps are
1297typically "clipped" to the coastline. However, the data input here did not contain a
[4869]1298coastline.
[4123]1299
1300\begin{figure}[hbt]
1301\centerline{\includegraphics[scale=0.5]{graphics/slidedepth.jpg}}
[4875]1302\caption{Maximum inundation map for the Cairns slide scenario. \bf Note, this
1303inundaiton map has been based on a purely hypothetical scenario which was
1304designed explictiy for demonstration purposes only.}
[4123]1305\label{fig:maxdepthcairnsslide}
1306\end{figure}
1307
1308\begin{figure}[hbt]
1309\centerline{\includegraphics[scale=0.5]{graphics/fixedwavedepth.jpg}}
[4953]1310\caption{Maximum inundation map for the Cairns fixed wave scenario.
[4875]1311\bf Note, this
1312inundaiton map has been based on a purely hypothetical scenario which was
1313designed explictiy for demonstration purposes only.}
[4123]1314\label{fig:maxdepthcairnsfixedwave}
1315\end{figure}
1316
1317The user may also be interested in interrogating the solution at a particular spatial
1318location to understand the behaviour of the system through time. To do this, the user
1319must first define the locations of interest. A number of locations have been
[4209]1320identified for the Cairns scenario, as shown in Figure \ref{fig:cairnsgauges}.
[4123]1321
1322\begin{figure}[hbt]
1323\centerline{\includegraphics[scale=0.5]{graphics/cairnsgauges.jpg}}
1324\caption{Point locations to show time series information for the Cairns scenario.}
1325\label{fig:cairnsgauges}
1326\end{figure}
1327
1328These locations
1329must be stored in either a .csv or .txt file. The corresponding .csv file for
1330the gauges shown in Figure \ref{fig:cairnsgauges} is \file{gauges.csv}
1331
[4871]1332\verbatiminput{demos/cairns/gauges.csv}
[4123]1333
1334Header information has been included to identify the location in terms of eastings and
1335northings, and each gauge is given a name. The elevation column can be zero here.
[4945]1336This information is then passed to the function \code{sww2csv_gauges} (shown in
[4953]1337\file{GetTimeseries.py} which generates the csv files for each point location. The csv files
1338can then be used in \code{csv2timeseries_graphs} to create the timeseries plot for each desired
[4949]1339quantity. \code{csv2timeseries_graphs} relies on \code{pylab} to be installed which is not part
[4945]1340of the standard \code{anuga} release, however it can be downloaded and installed from \code{http://matplotlib.sourceforge.net/}
[4123]1341
1342\verbatiminput{demos/cairns/GetTimeseries.py}
1343
[4945]1344Here, the time series for the quantities stage, depth and speed will be generated for
1345each gauge defined in the gauge file. As described earlier, depth is more meaningful
[4953]1346for onshore gauges, and stage is more appropriate for offshore gauges.
[4123]1347
[4869]1348As an example output,
[4953]1349Figure \ref{fig:reef} shows the time series for the quantity stage for the
1350Elford Reef location for each scenario (the elevation at this location is negative,
[4949]1351therefore stage is the more appropriate quantity to plot). Note the large negative stage value when the slide was
[4875]1352introduced. This is due to the double gaussian form of the initial surface
1353displacement of the slide. By contrast, the time series for depth is shown for the onshore location of the Cairns
[4945]1354Airport in Figure \ref{fig:airportboth}.
[4869]1355
[4123]1356\begin{figure}[hbt]
[4948]1357\centerline{\includegraphics[scale=0.5]{graphics/gaugeElfordReefstage.png}}
[4953]1358\caption{Time series information of the quantity stage for the Elford Reef location for the
[4869]1359fixed wave and slide scenario.}
[4123]1360\label{fig:reef}
1361\end{figure}
1362
1363\begin{figure}[hbt]
[4948]1364\centerline{\includegraphics[scale=0.5]{graphics/gaugeCairnsAirportdepth.png}}
[4953]1365\caption{Time series information of the quantity depth for the Cairns Airport
[4869]1366location for the slide and fixed wave scenario.}
1367\label{fig:airportboth}
[4123]1368\end{figure}
1369
1370
1371%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1372%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1373
1374\chapter{\anuga Public Interface}
1375\label{ch:interface}
1376
1377This chapter gives an overview of the features of \anuga available
1378to the user at the public interface. These are grouped under the
1379following headings, which correspond to the outline of the examples
1380described in Chapter \ref{ch:getstarted}:
1381
1382\begin{itemize}
[5508]1383    \item Establishing the Mesh: Section \ref{sec:establishing the mesh}
1384    \item Initialising the Domain: Section \ref{sec:initialising the domain}
1385    \item Specifying the Quantities: Section \ref{sec:quantitis}
1386    \item Initial Conditions: Section \ref{sec:initial conditions}
1387    \item Boundary Conditions: Section \ref{sec:boundary conditions}
1388    \item Forcing Terms: Section \ref{sec:forcing terms}
1389    \item Evolution: Section \ref{sec:evolution}
[4123]1390\end{itemize}
1391
1392The listings are intended merely to give the reader an idea of what
1393each feature is, where to find it and how it can be used---they do
1394not give full specifications; for these the reader
1395may consult the code. The code for every function or class contains
1396a documentation string, or `docstring', that specifies the precise
1397syntax for its use. This appears immediately after the line
1398introducing the code, between two sets of triple quotes.
1399
1400Each listing also describes the location of the module in which
1401the code for the feature being described can be found. All modules
1402are in the folder \file{inundation} or one of its subfolders, and the
1403location of each module is described relative to \file{inundation}. Rather
1404than using pathnames, whose syntax depends on the operating system,
1405we use the format adopted for importing the function or class for
1406use in Python code. For example, suppose we wish to specify that the
1407function \function{create\_mesh\_from\_regions} is in a module called
1408\module{mesh\_interface} in a subfolder of \module{inundation} called
1409\code{pmesh}. In Linux or Unix syntax, the pathname of the file
1410containing the function, relative to \file{inundation}, would be
1411
1412\begin{center}
1413%    \code{pmesh/mesh\_interface.py}
1414    \code{pmesh}$\slash$\code{mesh\_interface.py}
1415\end{center}
[4674]1416\label{sec:mesh interface}
[4123]1417
1418while in Windows syntax it would be
1419
1420\begin{center}
1421    \code{pmesh}$\backslash$\code{mesh\_interface.py}
1422\end{center}
1423
1424Rather than using either of these forms, in this chapter we specify
1425the location simply as \code{pmesh.mesh\_interface}, in keeping with
1426the usage in the Python statement for importing the function,
1427namely:
1428\begin{center}
1429    \code{from pmesh.mesh\_interface import create\_mesh\_from\_regions}
1430\end{center}
1431
1432Each listing details the full set of parameters for the class or
1433function; however, the description is generally limited to the most
1434important parameters and the reader is again referred to the code
1435for more details.
1436
1437The following parameters are common to many functions and classes
1438and are omitted from the descriptions given below:
1439
1440%\begin{center}
1441\begin{tabular}{ll}  %\hline
1442%\textbf{Name } & \textbf{Description}\\
1443%\hline
1444\emph{use\_cache} & Specifies whether caching is to be used for improved performance. See Section \ref{sec:caching} for details on the underlying caching functionality\\
1445\emph{verbose} & If \code{True}, provides detailed terminal output
1446to the user\\  % \hline
1447\end{tabular}
1448%\end{center}
1449
[5508]1450\section{Mesh Generation}\index{Mesh!generation}
1451\label{sec:establishing the mesh}
[4123]1452Before discussing the part of the interface relating to mesh
1453generation, we begin with a description of a simple example of a
1454mesh and use it to describe how mesh data is stored.
1455
1456\label{sec:meshexample} Figure \ref{fig:simplemesh} represents a
1457very simple mesh comprising just 11 points and 10 triangles.
1458
1459
1460\begin{figure}[h]
1461  \begin{center}
1462    \includegraphics[width=90mm, height=90mm]{triangularmesh.jpg}
1463  \end{center}
1464
1465  \caption{A simple mesh}
1466  \label{fig:simplemesh}
1467\end{figure}
1468
1469
1470The variables \code{points}, \code{vertices} and \code{boundary}
1471represent the data displayed in Figure \ref{fig:simplemesh} as
1472follows. The list \code{points} stores the coordinates of the
1473points, and may be displayed schematically as in Table
1474\ref{tab:points}.
1475
1476
1477\begin{table}
1478  \begin{center}
1479    \begin{tabular}[t]{|c|cc|} \hline
1480      index & \code{x} & \code{y}\\  \hline
1481      0 & 1 & 1\\
1482      1 & 4 & 2\\
1483      2 & 8 & 1\\
1484      3 & 1 & 3\\
1485      4 & 5 & 5\\
1486      5 & 8 & 6\\
1487      6 & 11 & 5\\
1488      7 & 3 & 6\\
1489      8 & 1 & 8\\
1490      9 & 4 & 9\\
1491      10 & 10 & 7\\  \hline
1492    \end{tabular}
1493  \end{center}
1494
1495  \caption{Point coordinates for mesh in
1496    Figure \protect \ref{fig:simplemesh}}
1497  \label{tab:points}
1498\end{table}
1499
1500The list \code{vertices} specifies the triangles that make up the
1501mesh. It does this by specifying, for each triangle, the indices
1502(the numbers shown in the first column above) that correspond to the
1503three points at its vertices, taken in an anti-clockwise order
1504around the triangle. Thus, in the example shown in Figure
1505\ref{fig:simplemesh}, the variable \code{vertices} contains the
1506entries shown in Table \ref{tab:vertices}. The starting point is
1507arbitrary so triangle $(0,1,3)$ is considered the same as $(1,3,0)$
1508and $(3,0,1)$.
1509
1510
1511\begin{table}
1512  \begin{center}
1513    \begin{tabular}{|c|ccc|} \hline
1514      index & \multicolumn{3}{c|}{\code{vertices}}\\ \hline
1515      0 & 0 & 1 & 3\\
1516      1 & 1 & 2 & 4\\
1517      2 & 2 & 5 & 4\\
1518      3 & 2 & 6 & 5\\
1519      4 & 4 & 5 & 9\\
1520      5 & 4 & 9 & 7\\
1521      6 & 3 & 4 & 7\\
1522      7 & 7 & 9 & 8\\
1523      8 & 1 & 4 & 3\\
1524      9 & 5 & 10 & 9\\  \hline
1525    \end{tabular}
1526  \end{center}
1527
1528  \caption{Vertices for mesh in Figure \protect \ref{fig:simplemesh}}
1529  \label{tab:vertices}
1530\end{table}
1531
1532Finally, the variable \code{boundary} identifies the boundary
1533triangles and associates a tag with each.
1534
1535\refmodindex[pmesh.meshinterface]{pmesh.mesh\_interface}\label{sec:meshgeneration}
1536
1537\begin{funcdesc}  {create\_mesh\_from\_regions}{bounding_polygon,
1538                             boundary_tags,
1539                             maximum_triangle_area,
1540                             filename=None,
1541                             interior_regions=None,
1542                             poly_geo_reference=None,
1543                             mesh_geo_reference=None,
1544                             minimum_triangle_angle=28.0}
1545Module: \module{pmesh.mesh\_interface}
1546
1547This function allows a user to initiate the automatic creation of a
1548mesh inside a specified polygon (input \code{bounding_polygon}).
1549Among the parameters that can be set are the \emph{resolution}
1550(maximal area for any triangle in the mesh) and the minimal angle
1551allowable in any triangle. The user can specify a number of internal
[4736]1552polygons within each of which the resolution of the mesh can be
1553specified. \code{interior_regions} is a paired list containing the
1554interior polygon and its resolution.  Additionally, the user specifies
1555a list of boundary tags, one for each edge of the bounding polygon.
[4123]1556
1557\textbf{WARNING}. Note that the dictionary structure used for the
1558parameter \code{boundary\_tags} is different from that used for the
1559variable \code{boundary} that occurs in the specification of a mesh.
1560In the case of \code{boundary}, the tags are the \emph{values} of
1561the dictionary, whereas in the case of \code{boundary_tags}, the
1562tags are the \emph{keys} and the \emph{value} corresponding to a
1563particular tag is a list of numbers identifying boundary edges
1564labelled with that tag. Because of this, it is theoretically
1565possible to assign the same edge to more than one tag. However, an
1566attempt to do this will cause an error.
[4738]1567
1568\textbf{WARNING}. Do not have polygon lines cross or be on-top of each
1569    other. This can result in regions of unspecified resolutions. Do
1570    not have polygon close to each other. This can result in the area
1571    between the polygons having small triangles.  For more control
1572    over the mesh outline use the methods described below.
[4953]1573
[4123]1574\end{funcdesc}
1575
1576
1577
1578\subsection{Advanced mesh generation}
1579
1580For more control over the creation of the mesh outline, use the
[4209]1581methods of the class \class{Mesh}.
[4123]1582
1583
1584\begin{classdesc}  {Mesh}{userSegments=None,
1585                 userVertices=None,
1586                 holes=None,
1587                 regions=None}
1588Module: \module{pmesh.mesh}
1589
1590A class used to build a mesh outline and generate a two-dimensional
1591triangular mesh. The mesh outline is used to describe features on the
1592mesh, such as the mesh boundary. Many of this classes methods are used
1593to build a mesh outline, such as \code{add\_vertices} and
1594\code{add\_region\_from\_polygon}.
1595
1596\end{classdesc}
1597
1598
1599\subsubsection{Key Methods of Class Mesh}
1600
1601
1602\begin{methoddesc} {add\_hole}{x,y}
1603Module: \module{pmesh.mesh},  Class: \class{Mesh}
1604
1605This method is used to build the mesh outline.  It defines a hole,
1606when the boundary of the hole has already been defined, by selecting a
[4209]1607point within the boundary.
[4123]1608
1609\end{methoddesc}
1610
1611
1612\begin{methoddesc}  {add\_hole\_from\_polygon}{self, polygon, tags=None}
1613Module: \module{pmesh.mesh},  Class: \class{Mesh}
1614
1615This method is used to add a `hole' within a region ---that is, to
1616define a interior region where the triangular mesh will not be
1617generated---to a \class{Mesh} instance. The region boundary is described by
1618the polygon passed in.  Additionally, the user specifies a list of
1619boundary tags, one for each edge of the bounding polygon.
1620\end{methoddesc}
1621
1622
1623\begin{methoddesc}  {add\_points_and_segments}{self, points, segments,
1624    segment\_tags=None}
1625Module: \module{pmesh.mesh},  Class: \class{Mesh}
1626
1627This method is used to build the mesh outline. It adds points and
1628segments connecting the points.  A tag for each segment can optionally
1629be added.
1630
1631\end{methoddesc}
1632
1633\begin{methoddesc} {add\_region}{x,y}
1634Module: \module{pmesh.mesh},  Class: \class{Mesh}
1635
1636This method is used to build the mesh outline.  It defines a region,
1637when the boundary of the region has already been defined, by selecting
1638a point within the boundary.  A region instance is returned.  This can
1639be used to set the resolution.
1640
1641\end{methoddesc}
1642
[4953]1643\begin{methoddesc}  {add\_region\_from\_polygon}{self, polygon,
[4888]1644segment_tags=None, region_tag=None
[4123]1645                                max_triangle_area=None}
1646Module: \module{pmesh.mesh},  Class: \class{Mesh}
1647
1648This method is used to build the mesh outline.  It adds a region to a
1649\class{Mesh} instance.  Regions are commonly used to describe an area
1650with an increased density of triangles, by setting
1651\code{max_triangle_area}.  The
1652region boundary is described by the input \code{polygon}.  Additionally, the
1653user specifies a list of segment tags, one for each edge of the
[4888]1654bounding polygon.  The regional tag is set using  \code{region}.
[4123]1655
1656\end{methoddesc}
1657
1658
1659
1660
1661
1662\begin{methoddesc} {add\_vertices}{point_data}
1663Module: \module{pmesh.mesh},  Class: \class{Mesh}
1664
1665Add user vertices. The point_data can be a list of (x,y) values, a numeric
[4209]1666array or a geospatial_data instance.
[4123]1667\end{methoddesc}
1668
1669\begin{methoddesc} {auto\_segment}{raw_boundary=raw_boundary,
1670                    remove_holes=remove_holes,
1671                    smooth_indents=smooth_indents,
1672                    expand_pinch=expand_pinch}
1673Module: \module{pmesh.mesh},  Class: \class{Mesh}
1674
1675Add segments between some of the user vertices to give the vertices an
1676outline.  The outline is an alpha shape. This method is
1677useful since a set of user vertices need to be outlined by segments
1678before generate_mesh is called.
[4209]1679
[4123]1680\end{methoddesc}
1681
1682\begin{methoddesc}  {export\_mesh_file}{self,ofile}
1683Module: \module{pmesh.mesh},  Class: \class{Mesh}
1684
1685This method is used to save the mesh to a file. \code{ofile} is the
1686name of the mesh file to be written, including the extension.  Use
1687the extension \code{.msh} for the file to be in NetCDF format and
1688\code{.tsh} for the file to be ASCII format.
1689\end{methoddesc}
1690
1691\begin{methoddesc}  {generate\_mesh}{self,
1692                      maximum_triangle_area=None,
1693                      minimum_triangle_angle=28.0,
1694                      verbose=False}
1695Module: \module{pmesh.mesh},  Class: \class{Mesh}
1696
1697This method is used to generate the triangular mesh.  The  maximal
1698area of any triangle in the mesh can be specified, which is used to
1699control the triangle density, along with the
1700minimum angle in any triangle.
1701\end{methoddesc}
1702
1703
1704
[5207]1705\begin{methoddesc}  {import_ungenerate_file}{self,ofile, tag=None,
1706region_tag=None}
[4123]1707Module: \module{pmesh.mesh},  Class: \class{Mesh}
1708
[5207]1709This method is used to import a polygon file in the ungenerate format,
1710which is used by arcGIS. The polygons from the file are converted to
[4123]1711vertices and segments. \code{ofile} is the name of the polygon file.
1712\code{tag} is the tag given to all the polygon's segments.
[5207]1713\code{region_tag} is the tag given to all the polygon's segments.  If
1714it is a string the one value will be assigned to all regions.  If it
1715is a list the first value in the list will be applied to the first
[5650]1716polygon etc.  If \code{tag} is not given a value it defaults to None,
1717which means the segement will not effect the water flow, it will only
1718effect the mesh generation.
[4123]1719
1720This function can be used to import building footprints.
1721\end{methoddesc}
1722
1723%%%%%%
[5508]1724\section{Initialising the Domain}\index{Initialising the Domain}
1725\label{sec:initialising the domain}
[4123]1726
1727%Include description of the class Domain and the module domain.
1728
1729%FIXME (Ole): This is also defined in a later chapter
1730%\declaremodule{standard}{...domain}
1731
1732\begin{classdesc} {Domain} {source=None,
1733                 triangles=None,
1734                 boundary=None,
1735                 conserved_quantities=None,
1736                 other_quantities=None,
1737                 tagged_elements=None,
1738                 use_inscribed_circle=False,
1739                 mesh_filename=None,
1740                 use_cache=False,
1741                 verbose=False,
1742                 full_send_dict=None,
1743                 ghost_recv_dict=None,
1744                 processor=0,
1745                 numproc=1}
1746Module: \refmodule{abstract_2d_finite_volumes.domain}
1747
1748This class is used to create an instance of a data structure used to
1749store and manipulate data associated with a mesh. The mesh is
1750specified either by assigning the name of a mesh file to
1751\code{source} or by specifying the points, triangle and boundary of the
1752mesh.
1753\end{classdesc}
1754
1755\subsection{Key Methods of Domain}
1756
1757\begin{methoddesc} {set\_name}{name}
[4209]1758    Module: \refmodule{abstract\_2d\_finite\_volumes.domain},
1759    page \pageref{mod:domain}
[4123]1760
1761    Assigns the name \code{name} to the domain.
1762\end{methoddesc}
1763
1764\begin{methoddesc} {get\_name}{}
1765    Module: \module{abstract\_2d\_finite\_volumes.domain}
1766
1767    Returns the name assigned to the domain by \code{set\_name}. If no name has been
1768    assigned, returns \code{`domain'}.
1769\end{methoddesc}
1770
1771\begin{methoddesc} {set\_datadir}{name}
1772    Module: \module{abstract\_2d\_finite\_volumes.domain}
1773
[4209]1774    Specifies the directory used for SWW files, assigning it to the
[4123]1775    pathname \code{name}. The default value, before
1776    \code{set\_datadir} has been run, is the value \code{default\_datadir}
1777    specified in \code{config.py}.
1778
1779    Since different operating systems use different formats for specifying pathnames,
1780    it is necessary to specify path separators using the Python code \code{os.sep}, rather than
1781    the operating-specific ones such as `$\slash$' or `$\backslash$'.
1782    For this to work you will need to include the statement \code{import os}
1783    in your code, before the first appearance of \code{set\_datadir}.
1784
1785    For example, to set the data directory to a subdirectory
1786    \code{data} of the directory \code{project}, you could use
1787    the statements:
1788
1789    {\small \begin{verbatim}
1790        import os
1791        domain.set_datadir{'project' + os.sep + 'data'}
1792    \end{verbatim}}
1793\end{methoddesc}
1794
1795\begin{methoddesc} {get\_datadir}{}
1796    Module: \module{abstract\_2d\_finite\_volumes.domain}
1797
1798    Returns the data directory set by \code{set\_datadir} or,
1799    if \code{set\_datadir} has not
1800    been run, returns the value \code{default\_datadir} specified in
1801    \code{config.py}.
1802\end{methoddesc}
1803
[4258]1804
1805\begin{methoddesc} {set\_minimum_allowed_height}{}
1806    Module: \module{shallow\_water.shallow\_water\_domain}
1807
[4377]1808    Set the minimum depth (in meters) that will be recognised in
[4258]1809    the numerical scheme (including limiters and flux computations)
[4377]1810
1811    Default value is $10^{-3}$ m, but by setting this to a greater value,
1812    e.g.\ for large scale simulations, the computation time can be
1813    significantly reduced.
[4258]1814\end{methoddesc}
1815
1816
[4123]1817\begin{methoddesc} {set\_minimum_storable_height}{}
1818    Module: \module{shallow\_water.shallow\_water\_domain}
1819
1820    Sets the minimum depth that will be recognised when writing
1821    to an sww file. This is useful for removing thin water layers
1822    that seems to be caused by friction creep.
1823\end{methoddesc}
1824
1825
1826\begin{methoddesc} {set\_maximum_allowed_speed}{}
1827    Module: \module{shallow\_water.shallow\_water\_domain}
1828
1829    Set the maximum particle speed that is allowed in water
1830    shallower than minimum_allowed_height. This is useful for
1831    controlling speeds in very thin layers of water and at the same time
1832    allow some movement avoiding pooling of water.
1833\end{methoddesc}
1834
1835
1836\begin{methoddesc} {set\_time}{time=0.0}
1837    Module: \module{abstract\_2d\_finite\_volumes.domain}
1838
1839    Sets the initial time, in seconds, for the simulation. The
1840    default is 0.0.
1841\end{methoddesc}
1842
1843\begin{methoddesc} {set\_default\_order}{n}
1844    Sets the default (spatial) order to the value specified by
1845    \code{n}, which must be either 1 or 2. (Assigning any other value
1846    to \code{n} will cause an error.)
1847\end{methoddesc}
1848
1849
[4471]1850\begin{methoddesc} {set\_store\_vertices\_uniquely}{flag}
[4123]1851Decide whether vertex values should be stored uniquely as
1852computed in the model or whether they should be reduced to one
[4471]1853value per vertex using averaging.
[4782]1854
[4953]1855Triangles stored in the sww file can be discontinuous reflecting
1856the internal representation of the finite-volume scheme
1857(this is a feature allowing for arbitrary steepness).
1858However, for visual purposes and also for use with \code{Field\_boundary}
1859(and \code{File\_boundary}) it is often desirable to store triangles
1860with values at each vertex point as the average of the potentially
1861discontinuous numbers found at vertices of different triangles sharing the
1862same vertex location.
1863
1864Storing one way or the other is controlled in ANUGA through the method
[4782]1865\code{domain.store\_vertices\_uniquely}. Options are
[4953]1866\begin{itemize}
1867  \item \code{domain.store\_vertices\_uniquely(True)}: Allow discontinuities in the sww file
1868  \item \code{domain.store\_vertices\_uniquely(False)}: (Default).
1869  Average values
1870  to ensure continuity in sww file. The latter also makes for smaller
[4782]1871  sww files.
[4953]1872\end{itemize}
[4782]1873
[4123]1874\end{methoddesc}
1875
1876
1877% Structural methods
1878\begin{methoddesc}{get\_nodes}{absolute=False}
1879    Return x,y coordinates of all nodes in mesh.
1880
1881    The nodes are ordered in an Nx2 array where N is the number of nodes.
1882    This is the same format they were provided in the constructor
1883    i.e. without any duplication.
1884
1885    Boolean keyword argument absolute determines whether coordinates
1886    are to be made absolute by taking georeference into account
1887    Default is False as many parts of ANUGA expects relative coordinates.
1888\end{methoddesc}
1889
1890
1891\begin{methoddesc}{get\_vertex_coordinates}{absolute=False}
[4209]1892
1893    Return vertex coordinates for all triangles.
1894
[4123]1895    Return all vertex coordinates for all triangles as a 3*M x 2 array
1896    where the jth vertex of the ith triangle is located in row 3*i+j and
1897    M the number of triangles in the mesh.
1898
1899    Boolean keyword argument absolute determines whether coordinates
1900    are to be made absolute by taking georeference into account
1901    Default is False as many parts of ANUGA expects relative coordinates.
1902\end{methoddesc}
[4209]1903
1904
[4123]1905\begin{methoddesc}{get\_triangles}{indices=None}
1906
1907        Return Mx3 integer array where M is the number of triangles.
1908        Each row corresponds to one triangle and the three entries are
1909        indices into the mesh nodes which can be obtained using the method
1910        get\_nodes()
1911
1912        Optional argument, indices is the set of triangle ids of interest.
1913\end{methoddesc}
[4209]1914
[4123]1915\begin{methoddesc}{get\_disconnected\_triangles}{}
1916
1917Get mesh based on nodes obtained from get_vertex_coordinates.
1918
1919        Return array Mx3 array of integers where each row corresponds to
1920        a triangle. A triangle is a triplet of indices into
1921        point coordinates obtained from get_vertex_coordinates and each
1922        index appears only once.\\
1923
1924        This provides a mesh where no triangles share nodes
1925        (hence the name disconnected triangles) and different
1926        nodes may have the same coordinates.\\
1927
1928        This version of the mesh is useful for storing meshes with
1929        discontinuities at each node and is e.g. used for storing
1930        data in sww files.\\
1931
1932        The triangles created will have the format
1933
[4209]1934    {\small \begin{verbatim}
[4123]1935        [[0,1,2],
1936         [3,4,5],
1937         [6,7,8],
1938         ...
[4209]1939         [3*M-3 3*M-2 3*M-1]]
1940     \end{verbatim}}
[4123]1941\end{methoddesc}
1942
1943
1944
1945%%%%%%
[5508]1946\section{Initial Conditions}\index{Initial Conditions}
1947\label{sec:initial conditions}
[4123]1948In standard usage of partial differential equations, initial conditions
1949refers to the values associated to the system variables (the conserved
1950quantities here) for \code{time = 0}. In setting up a scenario script
1951as described in Sections \ref{sec:simpleexample} and \ref{sec:realdataexample},
1952\code{set_quantity} is used to define the initial conditions of variables
1953other than the conserved quantities, such as friction. Here, we use the terminology
1954of initial conditions to refer to initial values for variables which need
1955prescription to solve the shallow water wave equation. Further, it must be noted
1956that \code{set_quantity} does not necessarily have to be used in the initial
1957condition setting; it can be used at any time throughout the simulation.
1958
1959\begin{methoddesc}{set\_quantity}{name,
1960    numeric = None,
1961    quantity = None,
1962    function = None,
1963    geospatial_data = None,
1964    filename = None,
1965    attribute_name = None,
1966    alpha = None,
1967    location = 'vertices',
1968    indices = None,
1969    verbose = False,
1970    use_cache = False}
1971  Module: \module{abstract\_2d\_finite\_volumes.domain}
1972  (see also \module{abstract\_2d\_finite\_volumes.quantity.set\_values})
1973
1974This function is used to assign values to individual quantities for a
1975domain. It is very flexible and can be used with many data types: a
1976statement of the form \code{domain.set\_quantity(name, x)} can be used
1977to define a quantity having the name \code{name}, where the other
1978argument \code{x} can be any of the following:
1979
1980\begin{itemize}
1981\item a number, in which case all vertices in the mesh gets that for
1982the quantity in question.
1983\item a list of numbers or a Numeric array ordered the same way as the mesh vertices.
1984\item a function (e.g.\ see the samples introduced in Chapter 2)
1985\item an expression composed of other quantities and numbers, arrays, lists (for
1986example, a linear combination of quantities, such as
1987\code{domain.set\_quantity('stage','elevation'+x))}
1988\item the name of a file from which the data can be read. In this case, the optional argument attribute\_name will select which attribute to use from the file. If left out, set\_quantity will pick one. This is useful in cases where there is only one attribute.
[4209]1989\item a geospatial dataset (See Section \ref{sec:geospatial}).
[4123]1990Optional argument attribute\_name applies here as with files.
1991\end{itemize}
1992
1993
1994Exactly one of the arguments
1995  numeric, quantity, function, points, filename
1996must be present.
1997
1998
1999Set quantity will look at the type of the second argument (\code{numeric}) and
2000determine what action to take.
2001
2002Values can also be set using the appropriate keyword arguments.
2003If x is a function, for example, \code{domain.set\_quantity(name, x)}, \code{domain.set\_quantity(name, numeric=x)}, and \code{domain.set\_quantity(name, function=x)}
2004are all equivalent.
2005
2006
2007Other optional arguments are
2008\begin{itemize}
2009\item \code{indices} which is a list of ids of triangles to which set\_quantity should apply its assignment of values.
2010\item \code{location} determines which part of the triangles to assign
2011  to. Options are 'vertices' (default), 'edges', 'unique vertices', and 'centroids'.
2012\end{itemize}
2013
2014%%%
2015\anuga provides a number of predefined initial conditions to be used
[4209]2016with \code{set\_quantity}. See for example callable object
[4123]2017\code{slump\_tsunami} below.
2018
2019\end{methoddesc}
2020
2021
2022
2023
2024\begin{funcdesc}{set_region}{tag, quantity, X, location='vertices'}
2025  Module: \module{abstract\_2d\_finite\_volumes.domain}
[4209]2026
[4123]2027  (see also \module{abstract\_2d\_finite\_volumes.quantity.set\_values})
[4209]2028
[4123]2029This function is used to assign values to individual quantities given
[4209]2030a regional tag.   It is similar to \code{set\_quantity}.
[4736]2031For example, if in the mesh-generator a regional tag of 'ditch' was
[4123]2032used, set\_region can be used to set elevation of this region to
2033-10m. X is the constant or function to be applied to the quantity,
2034over the tagged region.  Location describes how the values will be
2035applied.  Options are 'vertices' (default), 'edges', 'unique
2036vertices', and 'centroids'.
2037
2038This method can also be called with a list of region objects.  This is
2039useful for adding quantities in regions, and having one quantity
2040value based on another quantity. See  \module{abstract\_2d\_finite\_volumes.region} for
2041more details.
2042\end{funcdesc}
2043
2044
2045
2046
2047\begin{funcdesc}{slump_tsunami}{length, depth, slope, width=None, thickness=None,
2048                x0=0.0, y0=0.0, alpha=0.0,
2049                gravity=9.8, gamma=1.85,
2050                massco=1, dragco=1, frictionco=0, psi=0,
2051                dx=None, kappa=3.0, kappad=0.8, zsmall=0.01,
2052                domain=None,
2053                verbose=False}
2054Module: \module{shallow\_water.smf}
2055
2056This function returns a callable object representing an initial water
2057displacement generated by a submarine sediment failure. These failures can take the form of
2058a submarine slump or slide. In the case of a slide, use \code{slide_tsunami} instead.
2059
2060The arguments include as a minimum, the slump or slide length, the water depth to the centre of sediment
2061mass, and the bathymetric slope. Other slump or slide parameters can be included if they are known.
2062\end{funcdesc}
2063
2064
2065%%%
2066\begin{funcdesc}{file\_function}{filename,
2067    domain = None,
2068    quantities = None,
2069    interpolation_points = None,
2070    verbose = False,
2071    use_cache = False}
2072Module: \module{abstract\_2d\_finite\_volumes.util}
2073
2074Reads the time history of spatial data for
2075specified interpolation points from a NetCDF file (\code{filename})
2076and returns
[5555]2077a callable object. \code{filename} could be a \code{sww} or \code{sts} file.
[4123]2078Returns interpolated values based on the input
2079file using the underlying \code{interpolation\_function}.
2080
2081\code{quantities} is either the name of a single quantity to be
2082interpolated or a list of such quantity names. In the second case, the resulting
2083function will return a tuple of values---one for each quantity.
2084
2085\code{interpolation\_points} is a list of absolute coordinates or a
2086geospatial object
2087for points at which values are sought.
2088
[5555]2089\code{boundary_polygon} is a list of coordinates specifying the vertices of the boundary. This must be the same polygon as used when calling \code{create_mesh_from_regions}. This argument can only be used when reading boundary data from the STS format.
2090
[4123]2091The model time stored within the file function can be accessed using
2092the method \code{f.get\_time()}
2093
2094
2095The underlying algorithm used is as follows:\\
2096Given a time series (i.e.\ a series of values associated with
[5555]2097different times), whose values are either just numbers, a set of
[4123]2098 numbers defined at the vertices of a triangular mesh (such as those
[5555]2099 stored in SWW files) or a set of
2100 numbers defined at a number of points on the boundary (such as those
2101 stored in STS files), \code{Interpolation\_function} is used to
[4123]2102 create a callable object that interpolates a value for an arbitrary
2103 time \code{t} within the model limits and possibly a point \code{(x,
2104 y)} within a mesh region.
2105
2106 The actual time series at which data is available is specified by
2107 means of an array \code{time} of monotonically increasing times. The
2108 quantities containing the values to be interpolated are specified in
2109 an array---or dictionary of arrays (used in conjunction with the
2110 optional argument \code{quantity\_names}) --- called
2111 \code{quantities}. The optional arguments \code{vertex\_coordinates}
2112 and \code{triangles} represent the spatial mesh associated with the
[5555]2113 quantity arrays. If omitted the function must be created using an STS file
2114 or a TMS file.
[4123]2115
2116 Since, in practice, values need to be computed at specified points,
2117 the syntax allows the user to specify, once and for all, a list
2118 \code{interpolation\_points} of points at which values are required.
2119 In this case, the function may be called using the form \code{f(t,
2120 id)}, where \code{id} is an index for the list
2121 \code{interpolation\_points}.
2122
2123
2124\end{funcdesc}
2125
2126%%%
2127%% \begin{classdesc}{Interpolation\_function}{self,
2128%%     time,
2129%%     quantities,
2130%%     quantity_names = None,
2131%%     vertex_coordinates = None,
2132%%     triangles = None,
2133%%     interpolation_points = None,
2134%%     verbose = False}
2135%% Module: \module{abstract\_2d\_finite\_volumes.least\_squares}
2136
2137%% Given a time series (i.e.\ a series of values associated with
2138%% different times), whose values are either just numbers or a set of
2139%% numbers defined at the vertices of a triangular mesh (such as those
2140%% stored in SWW files), \code{Interpolation\_function} is used to
2141%% create a callable object that interpolates a value for an arbitrary
2142%% time \code{t} within the model limits and possibly a point \code{(x,
2143%% y)} within a mesh region.
2144
2145%% The actual time series at which data is available is specified by
2146%% means of an array \code{time} of monotonically increasing times. The
2147%% quantities containing the values to be interpolated are specified in
2148%% an array---or dictionary of arrays (used in conjunction with the
2149%% optional argument \code{quantity\_names}) --- called
2150%% \code{quantities}. The optional arguments \code{vertex\_coordinates}
2151%% and \code{triangles} represent the spatial mesh associated with the
2152%% quantity arrays. If omitted the function created by
2153%% \code{Interpolation\_function} will be a function of \code{t} only.
2154
2155%% Since, in practice, values need to be computed at specified points,
2156%% the syntax allows the user to specify, once and for all, a list
2157%% \code{interpolation\_points} of points at which values are required.
2158%% In this case, the function may be called using the form \code{f(t,
2159%% id)}, where \code{id} is an index for the list
2160%% \code{interpolation\_points}.
2161
2162%% \end{classdesc}
2163
2164%%%
2165%\begin{funcdesc}{set\_region}{functions}
2166%[Low priority. Will be merged into set\_quantity]
2167
2168%Module:\module{abstract\_2d\_finite\_volumes.domain}
2169%\end{funcdesc}
2170
2171
2172
2173%%%%%%
2174\section{Boundary Conditions}\index{boundary conditions}
[5508]2175\label{sec:boundary conditions}
[4123]2176
2177\anuga provides a large number of predefined boundary conditions,
2178represented by objects such as \code{Reflective\_boundary(domain)} and
2179\code{Dirichlet\_boundary([0.2, 0.0, 0.0])}, described in the examples
2180in Chapter 2. Alternatively, you may prefer to ``roll your own'',
2181following the method explained in Section \ref{sec:roll your own}.
2182
2183These boundary objects may be used with the function \code{set\_boundary} described below
2184to assign boundary conditions according to the tags used to label boundary segments.
2185
2186\begin{methoddesc}{set\_boundary}{boundary_map}
2187Module: \module{abstract\_2d\_finite\_volumes.domain}
2188
2189This function allows you to assign a boundary object (corresponding to a
2190pre-defined or user-specified boundary condition) to every boundary segment that
2191has been assigned a particular tag.
2192
2193This is done by specifying a dictionary \code{boundary\_map}, whose values are the boundary objects
2194and whose keys are the symbolic tags.
2195
2196\end{methoddesc}
2197
2198\begin{methoddesc} {get\_boundary\_tags}{}
2199Module: \module{abstract\_2d\_finite\_volumes.domain}
2200
2201Returns a list of the available boundary tags.
2202\end{methoddesc}
2203
2204%%%
2205\subsection{Predefined boundary conditions}
2206
2207\begin{classdesc}{Reflective\_boundary}{Boundary}
2208Module: \module{shallow\_water}
2209
2210Reflective boundary returns same conserved quantities as those present in
2211the neighbouring volume but reflected.
2212
2213This class is specific to the shallow water equation as it works with the
2214momentum quantities assumed to be the second and third conserved quantities.
2215\end{classdesc}
2216
2217%%%
2218\begin{classdesc}{Transmissive\_boundary}{domain = None}
2219Module: \module{abstract\_2d\_finite\_volumes.generic\_boundary\_conditions}
2220
2221A transmissive boundary returns the same conserved quantities as
2222those present in the neighbouring volume.
2223
2224The underlying domain must be specified when the boundary is instantiated.
2225\end{classdesc}
2226
2227%%%
2228\begin{classdesc}{Dirichlet\_boundary}{conserved_quantities=None}
2229Module: \module{abstract\_2d\_finite\_volumes.generic\_boundary\_conditions}
2230
2231A Dirichlet boundary returns constant values for each of conserved
2232quantities. In the example of \code{Dirichlet\_boundary([0.2, 0.0, 0.0])},
2233the \code{stage} value at the boundary is 0.2 and the \code{xmomentum} and
2234\code{ymomentum} at the boundary are set to 0.0. The list must contain
2235a value for each conserved quantity.
2236\end{classdesc}
2237
2238%%%
2239\begin{classdesc}{Time\_boundary}{domain = None, f = None}
2240Module: \module{abstract\_2d\_finite\_volumes.generic\_boundary\_conditions}
2241
2242A time-dependent boundary returns values for the conserved
2243quantities as a function \code{f(t)} of time. The user must specify
2244the domain to get access to the model time.
2245\end{classdesc}
2246
2247%%%
2248\begin{classdesc}{File\_boundary}{Boundary}
2249Module: \module{abstract\_2d\_finite\_volumes.generic\_boundary\_conditions}
2250
[5555]2251This method may be used if the user wishes to apply a SWW file, STS file or
2252a time series file (TMS) to a boundary segment or segments.
[4123]2253The boundary values are obtained from a file and interpolated to the
2254appropriate segments for each conserved quantity.
[5657]2255
2256Optional argument \code{default_boundary} can be used to specify another boundary object to be used in case model time exceeds the time availabel in the file used by \code{File\_boundary}.
2257The default_boundary could be a simple Dirichlet condition or even another File\_boundary
2258typically using data pertaining to another time interval. 
[4123]2259\end{classdesc}
2260
2261
2262
2263%%%
2264\begin{classdesc}{Transmissive\_Momentum\_Set\_Stage\_boundary}{Boundary}
2265Module: \module{shallow\_water}
2266
2267This boundary returns same momentum conserved quantities as
2268those present in its neighbour volume but sets stage as in a Time\_boundary.
2269The underlying domain must be specified when boundary is instantiated
2270
2271This type of boundary is useful when stage is known at the boundary as a
2272function of time, but momenta (or speeds) aren't.
2273
2274This class is specific to the shallow water equation as it works with the
2275momentum quantities assumed to be the second and third conserved quantities.
2276\end{classdesc}
2277
2278
2279\begin{classdesc}{Dirichlet\_Discharge\_boundary}{Boundary}
2280Module: \module{shallow\_water}
2281
2282Sets stage (stage0)
2283Sets momentum (wh0) in the inward normal direction.
2284\end{classdesc}
2285
2286
2287
2288\subsection{User-defined boundary conditions}
2289\label{sec:roll your own}
2290
2291All boundary classes must inherit from the generic boundary class
[4209]2292\code{Boundary} and have a method called \code{evaluate} which must
[4123]2293take as inputs \code{self, vol\_id, edge\_id} where self refers to the
2294object itself and vol\_id and edge\_id are integers referring to
[4209]2295particular edges. The method must return a list of three floating point
2296numbers representing values for \code{stage},
[4123]2297\code{xmomentum} and \code{ymomentum}, respectively.
2298
[4209]2299The constructor of a particular boundary class may be used to specify
[4123]2300particular values or flags to be used by the \code{evaluate} method.
[4209]2301Please refer to the source code for the existing boundary conditions
[4123]2302for examples of how to implement boundary conditions.
2303
2304
2305
[5508]2306\section{Forcing Terms}\index{Forcing terms}
2307\label{sec:forcing terms}
[4123]2308
[5506]2309\anuga provides a number of predefined forcing functions to be used with simulations.
2310Gravity and friction are always calculated using the elevation and friction quantities, but the user may additionally add forcing terms to the list
[5507]2311\code{domain.forcing\_terms} and have them affect the model.
[5506]2312 
[5508]2313Currently, predefined forcing terms are
[4123]2314
[5507]2315\begin{funcdesc}{General\_forcing}{}
[5506]2316  Module: \module{shallow\_water.shallow\_water\_domain}
[4123]2317
[5506]2318  This is a general class to modify any quantity according to a given rate of change.
2319  Other specific forcing terms are based on this class but it can be used by itself as well (e.g.\ to modify momentum).
2320 
2321  The General\_forcing class takes as input:
2322  \begin{itemize} 
2323    \item \code{domain}: a reference to the domain being evolved
2324    \item \code{quantity\_name}: The name of the quantity that will be affected by this forcing term
2325    \item \code{rate}: The rate at which the quantity should change. The parameter \code{rate} can be eithe a constant or a
2326                function of time. Positive values indicate increases,
2327                negative values indicate decreases.
2328                The parametr \code{rate} can be \code{None} at initialisation but must be specified
2329                before forcing term is applied (i.e. simulation has started).
2330                The default value is 0.0 - i.e.\ no forcing.
2331    \item \code{center, radius}: Optionally restrict forcing to a circle with given center and radius.
2332    \item \code{polygon}: Optionally restrict forcing to an area enclosed by given polygon.             
2333  \end{itemize}
2334  Note specifying both center, radius and polygon will cause an exception to be thrown.
[5566]2335  Moreover, if the specified polygon or circle does not lie fully within the mesh boundary an Exception will be thrown.
[5507]2336
[5508]2337  \bigskip 
[5506]2338  Example:
2339  {\scriptsize \begin{verbatim} 
[5508]2340    P = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]] # Square polygon
2341 
2342    xmom = General_forcing(domain, 'xmomentum', polygon=P)
2343    ymom = General_forcing(domain, 'ymomentum', polygon=P)
[4123]2344
[5508]2345    xmom.rate = f
2346    ymom.rate = g
[5506]2347 
[5508]2348    domain.forcing_terms.append(xmom)
2349    domain.forcing_terms.append(ymom)   
[5507]2350  \end{verbatim}}
[5506]2351  Here, \code{f}, \code{g} are assumed to be defined as functions of time providing a time dependent rate of change for xmomentum and ymomentum respectively.
[5508]2352  P is assumed to be polygon, specified as a list of points.
[5506]2353 
2354\end{funcdesc} 
2355
2356
2357\begin{funcdesc}{Inflow}{}
2358  Module: \module{shallow\_water.shallow\_water\_domain}
2359
[5566]2360  This is a general class for inflow and abstraction of water according to a given rate of change.
[5506]2361  This class will always modify the \code{stage} quantity.
2362 
2363  Inflow is based on the General_forcing class so the functionality is similar.
2364 
2365  The Inflow class takes as input:
2366  \begin{itemize} 
2367    \item \code{domain}: a reference to the domain being evolved
2368    \item \code{rate}: The flow rate in $m^3/s$ at which the stage should change. The parameter \code{rate} can be eithe a constant or a
2369                function of time. Positive values indicate inflow,
2370                negative values indicate outflow.
2371               
2372                Note: The specified flow will be divided by the area of
2373                the inflow region and then applied to update the
2374                stage quantity.     
2375    \item \code{center, radius}: Optionally restrict forcing to a circle with given center and radius.
2376    \item \code{polygon}: Optionally restrict forcing to an area enclosed by given polygon.             
2377  \end{itemize}
[5507]2378
[5508]2379  \bigskip     
[5506]2380  Example:
2381  {\scriptsize \begin{verbatim} 
2382    hydrograph = Inflow(center=(320, 300), radius=10,
2383                        rate=file_function('QPMF_Rot_Sub13.tms'))
2384
2385    domain.forcing_terms.append(hydrograph)
[5507]2386  \end{verbatim}}
2387  Here, \code{'QPMF_Rot_Sub13.tms'} is assumed to be a NetCDF file in the format \code{tms} defining a timeseries for a hydrograph.
[5506]2388\end{funcdesc} 
2389
2390
2391\begin{funcdesc}{Rainfall}{}
2392  Module: \module{shallow\_water.shallow\_water\_domain}
2393
2394  This is a general class for implementing rainfall over the domain, possibly restricted to a given circle or polygon.
2395  This class will always modify the \code{stage} quantity.
2396 
2397  Rainfall is based on the General_forcing class so the functionality is similar.
2398 
2399  The Rainfall class takes as input:
2400  \begin{itemize} 
2401    \item \code{domain}: a reference to the domain being evolved
2402    \item \code{rate}: Total rain rate over the specified domain. 
2403                  Note: Raingauge Data needs to reflect the time step.
2404                  For example: if rain gauge is mm read every \code{dt} seconds, then the input
2405                  here is as \code{mm/dt} so 10 mm in 5 minutes becomes
2406                  10/(5x60) = 0.0333mm/s.
2407       
2408                  This parameter can be either a constant or a
2409                  function of time. Positive values indicate rain being added (or be used for general infiltration),
2410                  negative values indicate outflow at the specified rate (presumably this could model evaporation or abstraction).
2411    \item \code{center, radius}: Optionally restrict forcing to a circle with given center and radius.
2412    \item \code{polygon}: Optionally restrict forcing to an area enclosed by given polygon.             
2413  \end{itemize}
2414 
[5508]2415  \bigskip   
[5506]2416  Example:
2417  {\scriptsize \begin{verbatim} 
2418 
2419    catchmentrainfall = Rainfall(rain=file_function('Q100_2hr_Rain.tms')) 
2420    domain.forcing_terms.append(catchmentrainfall)
2421
[5507]2422  \end{verbatim}}
2423  Here, \code{'Q100_2hr_Rain.tms'} is assumed to be a NetCDF file in the format \code{tms} defining a timeseries for the rainfall.
[5506]2424\end{funcdesc} 
2425
2426
2427
2428\begin{funcdesc}{Culvert\_flow}{}
2429  Module: \module{culver\_flows.culvert\_class}
2430
2431  This is a general class for implementing flow through a culvert.
2432  This class modifies the quantities \code{stage, xmomentum, ymomentum} in areas at both ends of the culvert.
2433 
[5507]2434  The Culvert\_flow forcing term uses \code{Inflow} and {General\_forcing} to update the quantities. The flow drection is determined on-the-fly so
[5506]2435  openings are referenced simple as opening0 and opening1 with either being able to take the role as Inflow and Outflow.
2436 
2437  The Culvert\_flow class takes as input:
2438  \begin{itemize} 
2439    \item \code{domain}: a reference to the domain being evolved
2440    \item \code{label}: Short text naming the culvert
2441    \item \code{description}: Text describing it
2442    \item \code{end_point0}: Coordinates of one opening
2443    \item \code{end_point1}: Coordinates of other opening
2444    \item \code{width}:
2445    \item \code{height}:
2446    \item \code{diameter}:
2447    \item \code{manning}: Mannings Roughness for Culvert
2448    \item \code{invert_level0}: Invert level if not the same as the Elevation on the Domain
2449    \item \code{invert_level1}: Invert level if not the same as the Elevation on the Domain
2450    \item \code{culvert_routine}: Function specifying the calculation of flow based on energy difference between the two openings (see below)
2451  \end{itemize}
2452
[5566]2453  The user can specify different culvert routines. Hower ANUGA currently provides only one, namely the \code{boyd\_generalised\_culvert\_model} as used in the example below.
[5506]2454     
[5508]2455  \bigskip       
[5506]2456  Example:
2457  {\scriptsize \begin{verbatim} 
2458    from anuga.culvert_flows.culvert_class import Culvert_flow
2459    from anuga.culvert_flows.culvert_routines import boyd_generalised_culvert_model 
2460
2461    culvert1 = Culvert_flow(domain,
2462                           label='Culvert No. 1',
2463                           description='This culvert is a test unit 1.2m Wide by 0.75m High',   
2464                           end_point0=[9.0, 2.5],
2465                           end_point1=[13.0, 2.5],
2466                           width=1.20,height=0.75,
2467                           culvert_routine=boyd_generalised_culvert_model,       
2468                           verbose=True)
2469
2470    culvert2 = Culvert_flow(domain,
2471                           label='Culvert No. 2',
2472                           description='This culvert is a circular test with d=1.2m',   
2473                           end_point0=[9.0, 1.5],
2474                           end_point1=[30.0, 3.5],
2475                           diameter=1.20,
2476                           invert_level0=7,
2477                           culvert_routine=boyd_generalised_culvert_model,       
2478                           verbose=True)
2479                           
2480    domain.forcing_terms.append(culvert1)
2481    domain.forcing_terms.append(culvert2)
2482
2483   
[5507]2484  \end{verbatim}}
[5506]2485\end{funcdesc} 
2486
2487
2488
2489
2490
2491
[4123]2492\section{Evolution}\index{evolution}
[5508]2493\label{sec:evolution}
[4123]2494
2495  \begin{methoddesc}{evolve}{yieldstep = None, finaltime = None, duration = None, skip_initial_step = False}
2496
2497  Module: \module{abstract\_2d\_finite\_volumes.domain}
2498
2499  This function (a method of \class{domain}) is invoked once all the
2500  preliminaries have been completed, and causes the model to progress
2501  through successive steps in its evolution, storing results and
2502  outputting statistics whenever a user-specified period
2503  \code{yieldstep} is completed (generally during this period the
2504  model will evolve through several steps internally
2505  as the method forces the water speed to be calculated
2506  on successive new cells). The user
2507  specifies the total time period over which the evolution is to take
2508  place, by specifying values (in seconds) for either \code{duration}
2509  or \code{finaltime}, as well as the interval in seconds after which
2510  results are to be stored and statistics output.
2511
2512  You can include \method{evolve} in a statement of the type:
2513
2514  {\small \begin{verbatim}
2515      for t in domain.evolve(yieldstep, finaltime):
2516          <Do something with domain and t>
2517  \end{verbatim}}
2518
2519  \end{methoddesc}
2520
2521
2522
2523\subsection{Diagnostics}
[4554]2524\label{sec:diagnostics}
[4123]2525
2526
2527  \begin{funcdesc}{statistics}{}
2528  Module: \module{abstract\_2d\_finite\_volumes.domain}
2529
2530  \end{funcdesc}
2531
2532  \begin{funcdesc}{timestepping\_statistics}{}
2533  Module: \module{abstract\_2d\_finite\_volumes.domain}
2534
2535  Returns a string of the following type for each
2536  timestep:
2537
2538  \code{Time = 0.9000, delta t in [0.00598964, 0.01177388], steps=12
2539  (12)}
2540
2541  Here the numbers in \code{steps=12 (12)} indicate the number of steps taken and
[4369]2542  the number of first-order steps, respectively.\\
[4377]2543
2544  The optional keyword argument \code{track_speeds=True} will
2545  generate a histogram of speeds generated by each triangle. The
2546  speeds relate to the size of the timesteps used by ANUGA and
2547  this diagnostics may help pinpoint problem areas where excessive speeds
2548  are generated.
2549
[4123]2550  \end{funcdesc}
2551
2552
2553  \begin{funcdesc}{boundary\_statistics}{quantities = None, tags = None}
2554  Module: \module{abstract\_2d\_finite\_volumes.domain}
2555
2556  Returns a string of the following type when \code{quantities = 'stage'} and \code{tags = ['top', 'bottom']}:
2557
2558  {\small \begin{verbatim}
2559 Boundary values at time 0.5000:
2560    top:
2561        stage in [ -0.25821218,  -0.02499998]
2562    bottom:
2563        stage in [ -0.27098821,  -0.02499974]
2564  \end{verbatim}}
2565
2566  \end{funcdesc}
2567
2568
2569  \begin{funcdesc}{get\_quantity}{name, location='vertices', indices = None}
2570  Module: \module{abstract\_2d\_finite\_volumes.domain}
[4209]2571
[4123]2572  Allow access to individual quantities and their methods
2573
2574  \end{funcdesc}
2575
[4953]2576
[4705]2577  \begin{funcdesc}{set\_quantities\_to\_be\_monitored}{}
2578  Module: \module{abstract\_2d\_finite\_volumes.domain}
[4123]2579
[4953]2580  Selects quantities and derived quantities for which extrema attained at internal timesteps
[4705]2581  will be collected.
[4953]2582
2583  Information can be tracked in the evolve loop by printing \code{quantity\_statistics} and
[4705]2584  collected data will be stored in the sww file.
2585
[4953]2586  Optional parameters \code{polygon} and \code{time\_interval} may be specified to restrict the
[4705]2587  extremum computation.
[4953]2588  \end{funcdesc}
2589
[4705]2590  \begin{funcdesc}{quantity\_statistics}{}
2591  Module: \module{abstract\_2d\_finite\_volumes.domain}
2592
2593  Reports on extrema attained by selected quantities.
[4953]2594
[4705]2595  Returns a string of the following type for each
2596  timestep:
2597
[4953]2598  \begin{verbatim}
[4705]2599  Monitored quantities at time 1.0000:
2600    stage-elevation:
2601      values since time = 0.00 in [0.00000000, 0.30000000]
2602      minimum attained at time = 0.00000000, location = (0.16666667, 0.33333333)
2603      maximum attained at time = 0.00000000, location = (0.83333333, 0.16666667)
2604    ymomentum:
2605      values since time = 0.00 in [0.00000000, 0.06241221]
2606      minimum attained at time = 0.00000000, location = (0.33333333, 0.16666667)
2607      maximum attained at time = 0.22472667, location = (0.83333333, 0.66666667)
2608    xmomentum:
2609      values since time = 0.00 in [-0.06062178, 0.47886313]
2610      minimum attained at time = 0.00000000, location = (0.16666667, 0.33333333)
2611      maximum attained at time = 0.35103646, location = (0.83333333, 0.16666667)
[4953]2612  \end{verbatim}
[4705]2613
[4953]2614  The quantities (and derived quantities) listed here must be selected at model
[4705]2615  initialisation using the method \code{domain.set_quantities_to_be_monitored}.\\
[4953]2616
[4705]2617  The optional keyword argument \code{precision='\%.4f'} will
2618  determine the precision used for floating point values in the output.
[4953]2619  This diagnostics helps track extrema attained by the selected quantities
[4705]2620  at every internal timestep.
2621
2622  These values are also stored in the sww file for post processing.
2623
2624  \end{funcdesc}
2625
[4953]2626
2627
[4123]2628  \begin{funcdesc}{get\_values}{location='vertices', indices = None}
2629  Module: \module{abstract\_2d\_finite\_volumes.quantity}
2630
2631  Extract values for quantity as an array
2632
2633  \end{funcdesc}
2634
[4209]2635
[4123]2636  \begin{funcdesc}{get\_integral}{}
2637  Module: \module{abstract\_2d\_finite\_volumes.quantity}
2638
2639  Return computed integral over entire domain for this quantity
2640
2641  \end{funcdesc}
2642
2643
[4209]2644
2645
[4123]2646  \begin{funcdesc}{get\_maximum\_value}{indices = None}
2647  Module: \module{abstract\_2d\_finite\_volumes.quantity}
2648
2649  Return maximum value of quantity (on centroids)
2650
[4209]2651  Optional argument indices is the set of element ids that
[4123]2652  the operation applies to. If omitted all elements are considered.
2653
2654  We do not seek the maximum at vertices as each vertex can
[4209]2655  have multiple values - one for each triangle sharing it.
[4123]2656  \end{funcdesc}
2657
2658
[4209]2659
[4123]2660  \begin{funcdesc}{get\_maximum\_location}{indices = None}
2661  Module: \module{abstract\_2d\_finite\_volumes.quantity}
2662
2663  Return location of maximum value of quantity (on centroids)
2664
[4209]2665  Optional argument indices is the set of element ids that
[4123]2666  the operation applies to.
2667
2668  We do not seek the maximum at vertices as each vertex can
2669  have multiple values - one for each triangle sharing it.
2670
2671  If there are multiple cells with same maximum value, the
[4209]2672  first cell encountered in the triangle array is returned.
[4123]2673  \end{funcdesc}
2674
2675
[4209]2676
[4123]2677  \begin{funcdesc}{get\_wet\_elements}{indices=None}
[4209]2678  Module: \module{shallow\_water.shallow\_water\_domain}
[4123]2679
2680  Return indices for elements where h $>$ minimum_allowed_height
2681  Optional argument indices is the set of element ids that the operation applies to.
2682  \end{funcdesc}
2683
2684
2685  \begin{funcdesc}{get\_maximum\_inundation\_elevation}{indices=None}
[4209]2686  Module: \module{shallow\_water.shallow\_water\_domain}
[4123]2687
2688  Return highest elevation where h $>$ 0.\\
2689  Optional argument indices is the set of element ids that the operation applies to.\\
[4209]2690
2691  Example to find maximum runup elevation:\\
2692     z = domain.get_maximum_inundation_elevation()
[4123]2693  \end{funcdesc}
2694
2695
2696  \begin{funcdesc}{get\_maximum\_inundation\_location}{indices=None}
[4209]2697  Module: \module{shallow\_water.shallow\_water\_domain}
2698
[4123]2699  Return location (x,y) of highest elevation where h $>$ 0.\\
2700  Optional argument indices is the set of element ids that the operation applies to.\\
2701
2702  Example to find maximum runup location:\\
[4209]2703     x, y = domain.get_maximum_inundation_location()
[4123]2704  \end{funcdesc}
2705
[4209]2706
[4953]2707\section{Queries of SWW model output files}
2708After a model has been run, it is often useful to extract various information from the sww
[4554]2709output file (see Section \ref{sec:sww format}). This is typically more convenient than using the
[4953]2710diagnostics described in Section \ref{sec:diagnostics} which rely on the model running - something
2711that can be very time consuming. The sww files are easy and quick to read and offer much information
2712about the model results such as runup heights, time histories of selected quantities,
[4554]2713flow through cross sections and much more.
[4209]2714
[4953]2715\begin{funcdesc}{get\_maximum\_inundation\_elevation}{filename, polygon=None,
[4554]2716    time_interval=None, verbose=False}
2717  Module: \module{shallow\_water.data\_manager}
2718
[4556]2719  Return highest elevation where depth is positive ($h > 0$)
[4554]2720
[4953]2721  Example to find maximum runup elevation:\\
[4554]2722  max_runup = get_maximum_inundation_elevation(filename,
2723  polygon=None,
2724  time_interval=None,
2725  verbose=False)
2726
[4953]2727
2728  filename is a NetCDF sww file containing ANUGA model output.
[4554]2729  Optional arguments polygon and time_interval restricts the maximum runup calculation
2730  to a points that lie within the specified polygon and time interval.
2731
2732  If no inundation is found within polygon and time_interval the return value
2733  is None signifying "No Runup" or "Everything is dry".
2734
2735  See doc string for general function get_maximum_inundation_data for details.
2736\end{funcdesc}
2737
2738
[4953]2739\begin{funcdesc}{get\_maximum\_inundation\_location}{filename, polygon=None,
[4554]2740    time_interval=None, verbose=False}
2741  Module: \module{shallow\_water.data\_manager}
2742
[4556]2743  Return location (x,y) of highest elevation where depth is positive ($h > 0$)
[4554]2744
[4953]2745  Example to find maximum runup location:\\
[4554]2746  max_runup_location = get_maximum_inundation_location(filename,
2747  polygon=None,
2748  time_interval=None,
2749  verbose=False)
2750
[4953]2751
2752  filename is a NetCDF sww file containing ANUGA model output.
[4554]2753  Optional arguments polygon and time_interval restricts the maximum runup calculation
2754  to a points that lie within the specified polygon and time interval.
2755
2756  If no inundation is found within polygon and time_interval the return value
2757  is None signifying "No Runup" or "Everything is dry".
2758
2759  See doc string for general function get_maximum_inundation_data for details.
2760\end{funcdesc}
2761
2762
[4953]2763\begin{funcdesc}{sww2timeseries}{swwfiles, gauge_filename, production_dirs, report = None, reportname = None,
2764plot_quantity = None, generate_fig = False, surface = None, time_min = None, time_max = None, time_thinning = 1,
[4746]2765time_unit = None, title_on = None, use_cache = False, verbose = False}
2766
2767  Module: \module{anuga.abstract\_2d\_finite\_volumes.util}
[4953]2768
[4746]2769  Return csv files for the location in the \code{gauge_filename} and can also return plots of them
[4953]2770
[4746]2771  See doc string for general function sww2timeseries for details.
2772
[4554]2773\end{funcdesc}
2774
[4953]2775
[5288]2776\begin{funcdesc}{get\_flow\_through\_cross\_section}{filename, cross\_section, verbose=False}
2777  Module: \module{shallow\_water.data\_manager}
[4953]2778
[5566]2779  Obtain flow $[m^3/s]$ perpendicular to specified cross section.
[5288]2780
2781  Inputs:
2782  \begin{itemize} 
2783        \item filename: Name of sww file containing ANUGA model output.
2784        \item polyline: Representation of desired cross section - it may contain multiple
2785          sections allowing for complex shapes. Assume absolute UTM coordinates.
2786  \end{itemize} 
2787
2788  Output:
2789  \begin{itemize}
2790    \item time: All stored times in sww file
2791    \item Q: Hydrograph of total flow across given segments for all stored times.
2792  \end{itemize} 
2793 
2794  The normal flow is computed for each triangle intersected by the polyline and
2795  added up.  Multiple segments at different angles are specified the normal flows
2796  may partially cancel each other.
2797 
2798  Example to find flow through cross section:
2799 
2800  \begin{verbatim} 
2801  cross_section = [[x, 0], [x, width]]
2802  time, Q = get_flow_through_cross_section(filename,
2803                                           cross_section,
2804                                           verbose=False)
2805  \end{verbatim} 
2806
2807
2808  See doc string for general function get_maximum_inundation_data for details.
2809 
2810\end{funcdesc}
2811
2812
2813
[4123]2814\section{Other}
2815
2816  \begin{funcdesc}{domain.create\_quantity\_from\_expression}{string}
2817
2818  Handy for creating derived quantities on-the-fly as for example
[4209]2819  \begin{verbatim}
[4123]2820  Depth = domain.create_quantity_from_expression('stage-elevation')
2821
[4209]2822  exp = '(xmomentum*xmomentum + ymomentum*ymomentum)**0.5')
[4123]2823  Absolute_momentum = domain.create_quantity_from_expression(exp)
[4209]2824  \end{verbatim}
2825
[4123]2826  %See also \file{Analytical\_solution\_circular\_hydraulic\_jump.py} for an example of use.
2827  \end{funcdesc}
2828
2829
2830
2831
2832
2833%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2834%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2835
2836\chapter{\anuga System Architecture}
2837
2838
2839\section{File Formats}
2840\label{sec:file formats}
2841
2842\anuga makes use of a number of different file formats. The
2843following table lists all these formats, which are described in more
2844detail in the paragraphs below.
2845
2846\bigskip
2847
2848\begin{center}
2849
2850\begin{tabular}{|ll|}  \hline
2851
2852\textbf{Extension} & \textbf{Description} \\
2853\hline\hline
2854
[5555]2855\code{.sww} & NetCDF format for storing model output with mesh information
[4123]2856\code{f(t,x,y)}\\
2857
[5555]2858\code{.sts} & NetCDF format for storing model ouput \code{f(t,x,y)} without any mesh information\\
2859
[4123]2860\code{.tms} & NetCDF format for storing time series \code{f(t)}\\
2861
[4662]2862\code{.csv/.txt} & ASCII format called points csv for storing
2863arbitrary points and associated attributes\\
[4123]2864
2865\code{.pts} & NetCDF format for storing arbitrary points and
2866associated attributes\\
2867
2868\code{.asc} & ASCII format of regular DEMs as output from ArcView\\
2869
2870\code{.prj} & Associated ArcView file giving more metadata for
2871\code{.asc} format\\
2872
2873\code{.ers} & ERMapper header format of regular DEMs for ArcView\\
2874
2875\code{.dem} & NetCDF representation of regular DEM data\\
2876
2877\code{.tsh} & ASCII format for storing meshes and associated
2878boundary and region info\\
2879
2880\code{.msh} & NetCDF format for storing meshes and associated
2881boundary and region info\\
2882
2883\code{.nc} & Native ferret NetCDF format\\
2884
2885\code{.geo} & Houdinis ASCII geometry format (?) \\  \par \hline
2886%\caption{File formats used by \anuga}
2887\end{tabular}
2888
2889
2890\end{center}
2891
2892The above table shows the file extensions used to identify the
2893formats of files. However, typically, in referring to a format we
2894capitalise the extension and omit the initial full stop---thus, we
2895refer, for example, to `SWW files' or `PRJ files'.
2896
2897\bigskip
2898
2899A typical dataflow can be described as follows:
2900
2901\subsection{Manually Created Files}
2902
2903\begin{tabular}{ll}
2904ASC, PRJ & Digital elevation models (gridded)\\
2905NC & Model outputs for use as boundary conditions (e.g. from MOST)
2906\end{tabular}
2907
2908\subsection{Automatically Created Files}
2909
2910\begin{tabular}{ll}
2911ASC, PRJ  $\rightarrow$  DEM  $\rightarrow$  PTS & Convert
2912DEMs to native \code{.pts} file\\
2913
2914NC $\rightarrow$ SWW & Convert MOST boundary files to
2915boundary \code{.sww}\\
2916
2917PTS + TSH $\rightarrow$ TSH with elevation & Least squares fit\\
2918
2919TSH $\rightarrow$ SWW & Convert TSH to \code{.sww}-viewable using
2920\code{animate}\\
2921
2922TSH + Boundary SWW $\rightarrow$ SWW & Simulation using
2923\code{\anuga}\\
2924
2925Polygonal mesh outline $\rightarrow$ & TSH or MSH
2926\end{tabular}
2927
2928
2929
2930
2931\bigskip
2932
[5555]2933\subsection{SWW, STS and TMS Formats}
[4554]2934\label{sec:sww format}
[4123]2935
[5555]2936The SWW, STS and TMS formats are all NetCDF formats, and are of key
[4123]2937importance for \anuga.
2938
2939An SWW file is used for storing \anuga output and therefore pertains
2940to a set of points and a set of times at which a model is evaluated.
2941It contains, in addition to dimension information, the following
2942variables:
2943
2944\begin{itemize}
2945    \item \code{x} and \code{y}: coordinates of the points, represented as Numeric arrays
2946    \item \code{elevation}, a Numeric array storing bed-elevations
2947    \item \code{volumes}, a list specifying the points at the vertices of each of the
2948    triangles
2949    % Refer here to the example to be provided in describing the simple example
2950    \item \code{time}, a Numeric array containing times for model
2951    evaluation
2952\end{itemize}
2953
2954
[4209]2955The contents of an SWW file may be viewed using the anuga viewer
[4123]2956\code{animate}, which creates an on-screen geometric
2957representation. See section \ref{sec:animate} (page
2958\pageref{sec:animate}) in Appendix \ref{ch:supportingtools} for more
2959on \code{animate}.
2960
2961Alternatively, there are tools, such as \code{ncdump}, that allow
2962you to convert an NetCDF file into a readable format such as the
2963Class Definition Language (CDL). The following is an excerpt from a
2964CDL representation of the output file \file{runup.sww} generated
2965from running the simple example \file{runup.py} of
2966Chapter \ref{ch:getstarted}:
2967
2968\verbatiminput{examples/bedslopeexcerpt.cdl}
2969
2970The SWW format is used not only for output but also serves as input
2971for functions such as \function{file\_boundary} and
2972\function{file\_function}, described in Chapter \ref{ch:interface}.
2973
[5555]2974An STS file is used for storing a set of points and and associated set of times.
2975It contains, in addition to dimension information, the following
2976variables:
2977\begin{itemize}
2978    \item \code{x} and \code{y}: coordinates of the points, represented as Numeric arrays
2979    \item \code{elevation}, a Numeric array storing bed-elevations
2980    % Refer here to the example to be provided in describing the simple example
2981    \item \code{time}, a Numeric array containing times for model
2982    evaluation
2983\end{itemize}
2984The only difference between the STS format and the SWW format is the former does not contain a list specifying the points at the vertices of each of the triangles (\code{volumes}). Consequenlty information (arrays) stored within an STS file such as \code{elevation} can be accessed in exactly the same way as it would be extraced from an SWW file.
2985
[4123]2986A TMS file is used to store time series data that is independent of
2987position.
2988
2989
2990\subsection{Mesh File Formats}
2991
2992A mesh file is a file that has a specific format suited to
2993triangular meshes and their outlines. A mesh file can have one of
2994two formats: it can be either a TSH file, which is an ASCII file, or
2995an MSH file, which is a NetCDF file. A mesh file can be generated
2996from the function \function{create\_mesh\_from\_regions} (see
2997Section \ref{sec:meshgeneration}) and used to initialise a domain.
2998
2999A mesh file can define the outline of the mesh---the vertices and
3000line segments that enclose the region in which the mesh is
3001created---and the triangular mesh itself, which is specified by
3002listing the triangles and their vertices, and the segments, which
3003are those sides of the triangles that are associated with boundary
3004conditions.
3005
3006In addition, a mesh file may contain `holes' and/or `regions'. A
3007hole represents an area where no mesh is to be created, while a
3008region is a labelled area used for defining properties of a mesh,
3009such as friction values.  A hole or region is specified by a point
3010and bounded by a number of segments that enclose that point.
3011
3012A mesh file can also contain a georeference, which describes an
3013offset to be applied to $x$ and $y$ values---eg to the vertices.
3014
3015
3016\subsection{Formats for Storing Arbitrary Points and Attributes}
3017
3018
[4472]3019A CSV/TXT file is used to store data representing
3020arbitrary numerical attributes associated with a set of points.
3021
3022The format for an CSV/TXT file is:\\
3023%\begin{verbatim}
3024
3025            first line:     \code{[column names]}\\
3026            other lines:  \code{[x value], [y value], [attributes]}\\
3027
3028            for example:\\
3029            \code{x, y, elevation, friction}\\
3030            \code{0.6, 0.7, 4.9, 0.3}\\
3031            \code{1.9, 2.8, 5, 0.3}\\
3032            \code{2.7, 2.4, 5.2, 0.3}
3033
3034        The delimiter is a comma. The first two columns are assumed to
[4953]3035        be x, y coordinates.
[4472]3036       
3037
[4662]3038A PTS file is a NetCDF representation of the data held in an points CSV
[4123]3039file. If the data is associated with a set of $N$ points, then the
3040data is stored using an $N \times 2$ Numeric array of float
3041variables for the points and an $N \times 1$ Numeric array for each
3042attribute.
3043
3044%\end{verbatim}
3045
3046\subsection{ArcView Formats}
3047
3048Files of the three formats ASC, PRJ and ERS are all associated with
3049data from ArcView.
3050
3051An ASC file is an ASCII representation of DEM output from ArcView.
3052It contains a header with the following format:
3053
3054\begin{tabular}{l l}
3055\code{ncols}      &   \code{753}\\
3056\code{nrows}      &   \code{766}\\
3057\code{xllcorner}  &   \code{314036.58727982}\\
3058\code{yllcorner}  & \code{6224951.2960092}\\
3059\code{cellsize}   & \code{100}\\
3060\code{NODATA_value} & \code{-9999}
3061\end{tabular}
3062
3063The remainder of the file contains the elevation data for each grid point
3064in the grid defined by the above information.
3065
3066A PRJ file is an ArcView file used in conjunction with an ASC file
3067to represent metadata for a DEM.
3068
3069
3070\subsection{DEM Format}
3071
[5619]3072A DEM file in \anuga is a NetCDF representation of regular DEM data.
[4123]3073
3074
3075\subsection{Other Formats}
3076
3077
3078
3079
3080\subsection{Basic File Conversions}
3081\label{sec:basicfileconversions}
3082
3083  \begin{funcdesc}{sww2dem}{basename_in, basename_out = None,
3084            quantity = None,
3085            timestep = None,
3086            reduction = None,
3087            cellsize = 10,
[5632]3088            number_of_decimal_places = None,
[4123]3089            NODATA_value = -9999,
3090            easting_min = None,
3091            easting_max = None,
3092            northing_min = None,
3093            northing_max = None,
3094            expand_search = False,
3095            verbose = False,
3096            origin = None,
3097            datum = 'WGS84',
3098            format = 'ers'}
3099  Module: \module{shallow\_water.data\_manager}
3100
3101  Takes data from an SWW file \code{basename_in} and converts it to DEM format (ASC or
[5632]3102  ERS) of a desired grid size \code{cellsize} in metres. The user can select how
3103  many the decimal places the output data can be written to using \code{number_of_decimal_places},
3104  with the default being 3.
3105  The easting and northing values are used if the user wished to determine the output
3106  within a specified rectangular area. The \code{reduction} input refers to a function
[4123]3107  to reduce the quantities over all time step of the SWW file, example, maximum.
3108  \end{funcdesc}
3109
3110
3111  \begin{funcdesc}{dem2pts}{basename_in, basename_out=None,
3112            easting_min=None, easting_max=None,
3113            northing_min=None, northing_max=None,
3114            use_cache=False, verbose=False}
3115  Module: \module{shallow\_water.data\_manager}
3116
3117  Takes DEM data (a NetCDF file representation of data from a regular Digital
3118  Elevation Model) and converts it to PTS format.
3119  \end{funcdesc}
3120
[5555]3121  \begin{funcdesc}{urs2sts}{basename_in, basename_out=None,
3122            weights=None, verbose=False,
3123            origin=None,mean_stage=0.0,
3124            zscale=1.0, ordering_filename=None}
3125  Module: \module{shallow\_water.data\_manager}
[4123]3126
[5555]3127  Takes urs data in (timeseries data in mux2 format) and converts it to STS format.
3128  \end{funcdesc}
[4377]3129
[5555]3130
3131
[4265]3132%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3133%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[4123]3134
[4265]3135\chapter{\anuga mathematical background}
3136\label{cd:mathematical background}
3137
3138\section{Introduction}
3139
3140This chapter outlines the mathematics underpinning \anuga.
3141
[4377]3142
3143
[4265]3144\section{Model}
3145\label{sec:model}
3146
3147The shallow water wave equations are a system of differential
3148conservation equations which describe the flow of a thin layer of
3149fluid over terrain. The form of the equations are:
3150\[
3151\frac{\partial \UU}{\partial t}+\frac{\partial \EE}{\partial
3152x}+\frac{\partial \GG}{\partial y}=\SSS
3153\]
3154where $\UU=\left[ {{\begin{array}{*{20}c}
3155 h & {uh} & {vh} \\
3156\end{array} }} \right]^T$ is the vector of conserved quantities; water depth
3157$h$, $x$-momentum $uh$ and $y$-momentum $vh$. Other quantities
3158entering the system are bed elevation $z$ and stage (absolute water
3159level) $w$, where the relation $w = z + h$ holds true at all times.
3160The fluxes in the $x$ and $y$ directions, $\EE$ and $\GG$ are given
3161by
3162\[
3163\EE=\left[ {{\begin{array}{*{20}c}
3164 {uh} \hfill \\
3165 {u^2h+gh^2/2} \hfill \\
3166 {uvh} \hfill \\
3167\end{array} }} \right]\mbox{ and }\GG=\left[ {{\begin{array}{*{20}c}
3168 {vh} \hfill \\
3169 {vuh} \hfill \\
3170 {v^2h+gh^2/2} \hfill \\
3171\end{array} }} \right]
3172\]
3173and the source term (which includes gravity and friction) is given
3174by
3175\[
3176\SSS=\left[ {{\begin{array}{*{20}c}
3177 0 \hfill \\
3178 -{gh(z_{x} + S_{fx} )} \hfill \\
3179 -{gh(z_{y} + S_{fy} )} \hfill \\
3180\end{array} }} \right]
3181\]
3182where $S_f$ is the bed friction. The friction term is modelled using
3183Manning's resistance law
3184\[
3185S_{fx} =\frac{u\eta ^2\sqrt {u^2+v^2} }{h^{4/3}}\mbox{ and }S_{fy}
3186=\frac{v\eta ^2\sqrt {u^2+v^2} }{h^{4/3}}
3187\]
3188in which $\eta$ is the Manning resistance coefficient.
[5566]3189The model does not currently include consideration of kinematic viscosity.
[4265]3190
[4377]3191As demonstrated in our papers, \cite{ZR1999,nielsen2005} these
[5619]3192equations and their implementation in \anuga provide a reliable
[5566]3193model of general flows associated with inundation such as dam breaks
3194and tsunamis.
[4265]3195
3196\section{Finite Volume Method}
3197\label{sec:fvm}
3198
3199We use a finite-volume method for solving the shallow water wave
[4377]3200equations \cite{ZR1999}. The study area is represented by a mesh of
[4265]3201triangular cells as in Figure~\ref{fig:mesh} in which the conserved
3202quantities of  water depth $h$, and horizontal momentum $(uh, vh)$,
3203in each volume are to be determined. The size of the triangles may
3204be varied within the mesh to allow greater resolution in regions of
3205particular interest.
3206
3207\begin{figure}
3208\begin{center}
[4377]3209\includegraphics[width=8.0cm,keepaspectratio=true]{graphics/step-five}
[4265]3210\caption{Triangular mesh used in our finite volume method. Conserved
3211quantities $h$, $uh$ and $vh$ are associated with the centroid of
3212each triangular cell.} \label{fig:mesh}
3213\end{center}
3214\end{figure}
3215
3216The equations constituting the finite-volume method are obtained by
3217integrating the differential conservation equations over each
3218triangular cell of the mesh. Introducing some notation we use $i$ to
3219refer to the $i$th triangular cell $T_i$, and ${\cal N}(i)$ to the
3220set of indices referring to the cells neighbouring the $i$th cell.
3221Then $A_i$ is the area of the $i$th triangular cell and $l_{ij}$ is
3222the length of the edge between the $i$th and $j$th cells.
3223
3224By applying the divergence theorem we obtain for each volume an
3225equation which describes the rate of change of the average of the
3226conserved quantities within each cell, in terms of the fluxes across
3227the edges of the cells and the effect of the source terms. In
3228particular, rate equations associated with each cell have the form
3229$$
3230 \frac{d\UU_i }{dt}+ \frac1{A_i}\sum\limits_{j\in{\cal N}(i)} \HH_{ij} l_{ij} = \SSS_i
3231$$
3232where
3233\begin{itemize}
3234\item $\UU_i$ the vector of conserved quantities averaged over the $i$th cell,
3235\item $\SSS_i$ is the source term associated with the $i$th cell,
3236and
3237\item $\HH_{ij}$ is the outward normal flux of
3238material across the \textit{ij}th edge.
3239\end{itemize}
3240
3241
3242%\item $l_{ij}$ is the length of the edge between the $i$th and $j$th
3243%cells
3244%\item $m_{ij}$ is the midpoint of
3245%the \textit{ij}th edge,
3246%\item
3247%$\mathbf{n}_{ij} = (n_{ij,1} , n_{ij,2})$is the outward pointing
3248%normal along the \textit{ij}th edge, and The
3249
3250The flux $\HH_{ij}$ is evaluated using a numerical flux function
3251$\HH(\cdot, \cdot ; \ \cdot)$ which is consistent with the shallow
3252water flux in the sense that for all conservation vectors $\UU$ and normal vectors $\nn$
3253$$
3254H(\UU,\UU;\ \nn) = \EE(\UU) n_1 + \GG(\UU) n_2 .
3255$$
3256
3257Then
3258$$
3259\HH_{ij}  = \HH(\UU_i(m_{ij}),
3260\UU_j(m_{ij}); \mathbf{n}_{ij})
3261$$
3262where $m_{ij}$ is the midpoint of the \textit{ij}th edge and
3263$\mathbf{n}_{ij}$ is the outward pointing normal, with respect to the $i$th cell, on the
3264\textit{ij}th edge. The function $\UU_i(x)$ for $x \in
3265T_i$ is obtained from the vector $\UU_k$ of conserved average values for the $i$th and
3266neighbouring  cells.
3267
3268We use a second order reconstruction to produce a piece-wise linear
3269function construction of the conserved quantities for  all $x \in
3270T_i$ for each cell (see Figure~\ref{fig:mesh:reconstruct}. This
3271function is allowed to be discontinuous across the edges of the
3272cells, but the slope of this function is limited to avoid
3273artificially introduced oscillations.
3274
[4377]3275Godunov's method (see \cite{Toro1992}) involves calculating the
[4265]3276numerical flux function $\HH(\cdot, \cdot ; \ \cdot)$ by exactly
3277solving the corresponding one dimensional Riemann problem normal to
3278the edge. We use the central-upwind scheme of \cite{KurNP2001} to
3279calculate an approximation of the flux across each edge.
3280
3281\begin{figure}
3282\begin{center}
[4377]3283\includegraphics[width=8.0cm,keepaspectratio=true]{graphics/step-reconstruct}
[4265]3284\caption{From the values of the conserved quantities at the centroid
3285of the cell and its neighbouring cells, a discontinuous piecewise
3286linear reconstruction of the conserved quantities is obtained.}
3287\label{fig:mesh:reconstruct}
3288\end{center}
3289\end{figure}
3290
3291In the computations presented in this paper we use an explicit Euler
3292time stepping method with variable timestepping adapted to the
[5618]3293observed CFL condition:
[4265]3294
[5618]3295\begin{equation} 
[5621]3296  \Delta t = \min_{k,i=[0,1,2]}  \min \left( \frac{r_k}{v_{k,i}}, \frac{r_{n_{k,i}}}{v_{k,i}} \right )
[5618]3297  \label{eq:CFL condition}
3298\end{equation} 
[5620]3299where $r_k$ is the radius of the $k$'th triangle and $v_{k,i}$ is the maximal velocity across
3300edge joining triangle $k$ and it's $i$'th neighbour, triangle $n_{k,i}$, as calculated by the
3301numerical flux function
3302using the central upwind scheme of \cite{KurNP2001}. The symbol $r_{n_{k,i}}$  denotes the radius
3303of the $i$'th neighbour of triangle $k$. The radii are calculated as radii of the inscribed circles
3304of each triangle.
[4265]3305
3306\section{Flux limiting}
3307
[4377]3308The shallow water equations are solved numerically using a
[4265]3309finite volume method on unstructured triangular grid.
[4377]3310The upwind central scheme due to Kurganov and Petrova is used as an
[4265]3311approximate Riemann solver for the computation of inviscid flux functions.
[4377]3312This makes it possible to handle discontinuous solutions.
[4265]3313
[4377]3314To alleviate the problems associated with numerical instabilities due to
[4265]3315small water depths near a wet/dry boundary we employ a new flux limiter that
3316ensures that unphysical fluxes are never encounted.
3317
3318
[4377]3319Let $u$ and $v$ be the velocity components in the $x$ and $y$ direction,
[4265]3320$w$ the absolute water level (stage) and
[4377]3321$z$ the bed elevation. The latter are assumed to be relative to the
3322same height datum.
3323The conserved quantities tracked by ANUGA are momentum in the
3324$x$-direction ($\mu = uh$), momentum in the $y$-direction ($\nu = vh$)
[4265]3325and depth ($h = w-z$).
3326
[4377]3327The flux calculation requires access to the velocity vector $(u, v)$
[4265]3328where each component is obtained as $u = \mu/h$ and $v = \nu/h$ respectively.
[4377]3329In the presence of very small water depths, these calculations become
[4265]3330numerically unreliable and will typically cause unphysical speeds.
3331
[4377]3332We have employed a flux limiter which replaces the calculations above with
[4265]3333the limited approximations.
3334\begin{equation}
[4377]3335  \hat{u} = \frac{\mu}{h + h_0/h}, \bigskip \hat{v} = \frac{\nu}{h + h_0/h},
[4265]3336\end{equation}
[4377]3337where $h_0$ is a regularisation parameter that controls the minimal
[4265]3338magnitude of the denominator. Taking the limits we have for $\hat{u}$
3339\[
[4377]3340  \lim_{h \rightarrow 0} \hat{u} =
[4265]3341  \lim_{h \rightarrow 0} \frac{\mu}{h + h_0/h} = 0
3342\]
[4377]3343and
[4265]3344\[
[4377]3345  \lim_{h \rightarrow \infty} \hat{u} =
[4265]3346  \lim_{h \rightarrow \infty} \frac{\mu}{h + h_0/h} = \frac{\mu}{h} = u
3347\]
3348with similar results for $\hat{v}$.
3349
3350The maximal value of $\hat{u}$ is attained when $h+h_0/h$ is minimal or (by differentiating the denominator)
3351\[
3352  1 - h_0/h^2 = 0
3353\]
3354or
3355\[
3356  h_0 = h^2
3357\]
3358
3359
[4377]3360ANUGA has a global parameter $H_0$ that controls the minimal depth which
[4265]3361is considered in the various equations. This parameter is typically set to
3362$10^{-3}$. Setting
3363\[
3364  h_0 = H_0^2
3365\]
3366provides a reasonable balance between accurracy and stability. In fact,
3367setting $h=H_0$ will scale the predicted speed by a factor of $0.5$:
3368\[
3369  \left[ \frac{\mu}{h + h_0/h} \right]_{h = H_0} = \frac{\mu}{2 H_0}
3370\]
[4377]3371In general, for multiples of the minimal depth $N H_0$ one obtains
[4265]3372\[
[4377]3373  \left[ \frac{\mu}{h + h_0/h} \right]_{h = N H_0} =
[4265]3374  \frac{\mu}{H_0 (1 + 1/N^2)}
3375\]
[4377]3376which converges quadratically to the true value with the multiple N.
[4265]3377
3378
3379%The developed numerical model has been applied to several test cases as well as to real flows. Numerical tests prove the robustness and accuracy of the model.
3380
3381
3382
3383
3384
3385\section{Slope limiting}
3386A multidimensional slope-limiting technique is employed to achieve second-order spatial accuracy and to prevent spurious oscillations. This is using the MinMod limiter and is documented elsewhere.
3387
3388However close to the bed, the limiter must ensure that no negative depths occur. On the other hand, in deep water, the bed topography should be ignored for the purpose of the limiter.
3389
3390
3391Let $w, z, h$  be the stage, bed elevation and depth at the centroid and
3392let $w_i, z_i, h_i$ be the stage, bed elevation and depth at vertex $i$.
3393Define the minimal depth across all vertices as $\hmin$ as
3394\[
3395  \hmin = \min_i h_i
3396\]
3397
[4377]3398Let $\tilde{w_i}$ be the stage obtained from a gradient limiter
[4265]3399limiting on stage only. The corresponding depth is then defined as
3400\[
3401  \tilde{h_i} = \tilde{w_i} - z_i
3402\]
[4377]3403We would use this limiter in deep water which we will define (somewhat boldly)
[4265]3404as
3405\[
3406  \hmin \ge \epsilon
3407\]
3408
3409
[4377]3410Similarly, let $\bar{w_i}$ be the stage obtained from a gradient
[4265]3411limiter limiting on depth respecting the bed slope.
3412The corresponding depth is defined as
3413\[
3414  \bar{h_i} = \bar{w_i} - z_i
3415\]
3416
3417
3418We introduce the concept of a balanced stage $w_i$ which is obtained as
3419the linear combination
3420
3421\[
3422  w_i = \alpha \tilde{w_i} + (1-\alpha) \bar{w_i}
3423\]
3424or
3425\[
3426  w_i = z_i + \alpha \tilde{h_i} + (1-\alpha) \bar{h_i}
3427\]
3428where $\alpha \in [0, 1]$.
3429
[4377]3430Since $\tilde{w_i}$ is obtained in 'deep' water where the bedslope
3431is ignored we have immediately that
[4265]3432\[
3433  \alpha = 1 \mbox{ for } \hmin \ge \epsilon %or dz=0
3434\]
3435%where the maximal bed elevation range $dz$ is defined as
3436%\[
3437%  dz = \max_i |z_i - z|
3438%\]
3439
3440If $\hmin < \epsilon$ we want to use the 'shallow' limiter just enough that
3441no negative depths occur. Formally, we will require that
3442\[
3443  \alpha \tilde{h_i} + (1-\alpha) \bar{h_i} > \epsilon, \forall i
3444\]
[4377]3445or
3446\begin{equation}
[4265]3447  \alpha(\tilde{h_i} - \bar{h_i}) > \epsilon - \bar{h_i}, \forall i
3448  \label{eq:limiter bound}
[4377]3449\end{equation}
[4265]3450
3451There are two cases:
[4377]3452\begin{enumerate}
3453  \item $\bar{h_i} \le \tilde{h_i}$: The deep water (limited using stage)
3454  vertex is at least as far away from the bed than the shallow water
[4265]3455  (limited using depth). In this case we won't need any contribution from
[4404]3456  $\bar{h_i}$ and can accept any $\alpha$.
[4377]3457
[4265]3458  E.g.\ $\alpha=1$ reduces Equation \ref{eq:limiter bound} to
3459  \[
[4377]3460    \tilde{h_i} > \epsilon
[4265]3461  \]
3462  whereas $\alpha=0$ yields
3463  \[
[4377]3464    \bar{h_i} > \epsilon
[4265]3465  \]
3466  all well and good.
[4377]3467  \item $\bar{h_i} > \tilde{h_i}$: In this case the the deep water vertex is
3468  closer to the bed than the shallow water vertex or even below the bed.
[4404]3469  In this case we need to find an $\alpha$ that will ensure a positive depth.
[4377]3470  Rearranging Equation \ref{eq:limiter bound} and solving for $\alpha$ one
[4265]3471  obtains the bound
3472  \[
3473    \alpha < \frac{\epsilon - \bar{h_i}}{\tilde{h_i} - \bar{h_i}}, \forall i
[4377]3474  \]
3475\end{enumerate}
[4265]3476
[4377]3477Ensuring Equation \ref{eq:limiter bound} holds true for all vertices one
[4265]3478arrives at the definition
3479\[
3480  \alpha = \min_{i} \frac{\bar{h_i} - \epsilon}{\bar{h_i} - \tilde{h_i}}
3481\]
3482which will guarantee that no vertex 'cuts' through the bed. Finally, should
[4377]3483$\bar{h_i} < \epsilon$ and therefore $\alpha < 0$, we suggest setting
[4404]3484$\alpha=0$ and similarly capping $\alpha$ at 1 just in case.
[4265]3485
3486%Furthermore,
[4377]3487%dropping the $\epsilon$ ensures that alpha is always positive and also
[4265]3488%provides a numerical safety {??)
3489
3490
3491
[4377]3492
3493
[4123]3494%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3495%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3496
3497\chapter{Basic \anuga Assumptions}
3498
3499
3500Physical model time cannot be earlier than 1 Jan 1970 00:00:00.
3501If one wished to recreate scenarios prior to that date it must be done
3502using some relative time (e.g. 0).
3503
3504
3505All spatial data relates to the WGS84 datum (or GDA94) and has been
3506projected into UTM with false easting of 500000 and false northing of
35071000000 on the southern hemisphere (0 on the northern).
3508
[4953]3509It is assumed that all computations take place within one UTM zone and
3510all locations must consequently be specified in Cartesian coordinates
[4543]3511(eastings, northings) or (x,y) where the unit is metres.
[4123]3512
3513DEMs, meshes and boundary conditions can have different origins within
3514one UTM zone. However, the computation will use that of the mesh for
3515numerical stability.
3516
3517When generating a mesh it is assumed that polygons do not cross.
3518Having polygons tht cross can cause the mesh generation to fail or bad
3519meshes being produced.
3520
3521
3522%OLD
3523%The dataflow is: (See data_manager.py and from scenarios)
3524%
3525%
3526%Simulation scenarios
3527%--------------------%
3528%%
3529%
3530%Sub directories contain scrips and derived files for each simulation.
3531%The directory ../source_data contains large source files such as
3532%DEMs provided externally as well as MOST tsunami simulations to be used
3533%as boundary conditions.
3534%
3535%Manual steps are:
3536%  Creation of DEMs from argcview (.asc + .prj)
3537%  Creation of mesh from pmesh (.tsh)
3538%  Creation of tsunami simulations from MOST (.nc)
3539%%
3540%
3541%Typical scripted steps are%
3542%
3543%  prepare_dem.py:  Convert asc and prj files supplied by arcview to
3544%                   native dem and pts formats%
3545%
3546%  prepare_pts.py: Convert netcdf output from MOST to an sww file suitable
3547%                  as boundary condition%
3548%
3549%  prepare_mesh.py: Merge DEM (pts) and mesh (tsh) using least squares
3550%                   smoothing. The outputs are tsh files with elevation data.%
3551%
3552%  run_simulation.py: Use the above together with various parameters to
3553%                     run inundation simulation.
3554
3555
3556%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3557%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3558
3559\appendix
3560
3561\chapter{Supporting Tools}
3562\label{ch:supportingtools}
3563
3564This section describes a number of supporting tools, supplied with \anuga, that offer a
3565variety of types of functionality and enhance the basic capabilities of \anuga.
3566
3567\section{caching}
3568\label{sec:caching}
3569
[4209]3570The \code{cache} function is used to provide supervised caching of function
[4123]3571results. A Python function call of the form
3572
3573      {\small \begin{verbatim}
3574      result = func(arg1,...,argn)
3575      \end{verbatim}}
3576
3577  can be replaced by
3578
3579      {\small \begin{verbatim}
3580      from caching import cache
3581      result = cache(func,(arg1,...,argn))
3582      \end{verbatim}}
3583
3584  which returns the same output but reuses cached
3585  results if the function has been computed previously in the same context.
3586  \code{result} and the arguments can be simple types, tuples, list, dictionaries or
3587  objects, but not unhashable types such as functions or open file objects.
3588  The function \code{func} may be a member function of an object or a module.
3589
3590  This type of caching is particularly useful for computationally intensive
3591  functions with few frequently used combinations of input arguments. Note that
3592  if the inputs or output are very large caching may not save time because
3593  disc access may dominate the execution time.
3594
3595  If the function definition changes after a result has been cached, this will be
3596  detected by examining the functions \code{bytecode (co\_code, co\_consts,
3597  func\_defaults, co\_argcount)} and the function will be recomputed.
3598  However, caching will not detect changes in modules used by \code{func}.
3599  In this case cache must be cleared manually.
3600
3601  Options are set by means of the function \code{set\_option(key, value)},
3602  where \code{key} is a key associated with a
3603  Python dictionary \code{options}. This dictionary stores settings such as the name of
3604  the directory used, the maximum
3605  number of cached files allowed, and so on.
3606
3607  The \code{cache} function allows the user also to specify a list of dependent files. If any of these
3608  have been changed, the function is recomputed and the results stored again.
3609
3610  %Other features include support for compression and a capability to \ldots
3611
3612
3613   \textbf{USAGE:} \nopagebreak
3614
3615    {\small \begin{verbatim}
3616    result = cache(func, args, kwargs, dependencies, cachedir, verbose,
3617                   compression, evaluate, test, return_filename)
3618    \end{verbatim}}
3619
3620
3621\section{ANUGA viewer - animate}
3622\label{sec:animate}
3623 The output generated by \anuga may be viewed by
3624means of the visualisation tool \code{animate}, which takes the
3625\code{SWW} file output by \anuga and creates a visual representation
3626of the data. Examples may be seen in Figures \ref{fig:runupstart}
3627and \ref{fig:runup2}. To view an \code{SWW} file with
3628\code{animate} in the Windows environment, you can simply drag the
3629icon representing the file over an icon on the desktop for the
3630\code{animate} executable file (or a shortcut to it), or set up a
3631file association to make files with the extension \code{.sww} open
3632with \code{animate}. Alternatively, you can operate \code{animate}
3633from the command line, in both Windows and Linux environments.
3634
3635On successful operation, you will see an interactive moving-picture
3636display. You can use keys and the mouse to slow down, speed up or
3637stop the display, change the viewing position or carry out a number
3638of other simple operations. Help is also displayed when you press
3639the \code{h} key.
3640
3641The main keys operating the interactive screen are:\\
3642
3643\begin{center}
3644\begin{tabular}{|ll|}   \hline
3645
3646\code{w} & toggle wireframe \\
3647
3648space bar & start/stop\\
3649
3650up/down arrows & increase/decrease speed\\
3651
3652left/right arrows & direction in time \emph{(when running)}\\
3653& step through simulation \emph{(when stopped)}\\
3654
3655left mouse button & rotate\\
3656
3657middle mouse button & pan\\
3658
3659right mouse button & zoom\\  \hline
3660
3661\end{tabular}
3662\end{center}
3663
3664\vfill
3665
3666The following table describes how to operate animate from the command line:
3667
3668Usage: \code{animate [options] swwfile \ldots}\\  \nopagebreak
3669Options:\\  \nopagebreak
3670\begin{tabular}{ll}
3671  \code{--display <type>} & \code{MONITOR | POWERWALL | REALITY\_CENTER |}\\
3672                                    & \code{HEAD\_MOUNTED\_DISPLAY}\\
3673  \code{--rgba} & Request a RGBA colour buffer visual\\
3674  \code{--stencil} & Request a stencil buffer visual\\
3675  \code{--stereo} & Use default stereo mode which is \code{ANAGLYPHIC} if not \\
3676                                    & overridden by environmental variable\\
3677  \code{--stereo <mode>} & \code{ANAGLYPHIC | QUAD\_BUFFER | HORIZONTAL\_SPLIT |}\\
3678                                    & \code{VERTICAL\_SPLIT | LEFT\_EYE | RIGHT\_EYE |}\\
3679                                     & \code{ON | OFF} \\
3680  \code{-alphamax <float 0-1>} & Maximum transparency clamp value\\
3681  \code{-alphamin <float 0-1>} & Transparency value at \code{hmin}\\
3682\end{tabular}
3683
3684\begin{tabular}{ll}
3685  \code{-cullangle <float angle 0-90>} & Cull triangles steeper than this value\\
3686  \code{-help} & Display this information\\
3687  \code{-hmax <float>} & Height above which transparency is set to
3688                                     \code{alphamax}\\
3689\end{tabular}
3690
3691\begin{tabular}{ll}
3692
3693  \code{-hmin <float>} & Height below which transparency is set to
3694                                     zero\\
3695\end{tabular}
3696
3697\begin{tabular}{ll}
3698  \code{-lightpos <float>,<float>,<float>} & $x,y,z$ of bedslope directional light ($z$ is
3699                                     up, default is overhead)\\
3700\end{tabular}
3701
3702\begin{tabular}{ll}
3703  \code{-loop}  & Repeated (looped) playback of \code{.swm} files\\
3704
3705\end{tabular}
3706
3707\begin{tabular}{ll}
3708  \code{-movie <dirname>} & Save numbered images to named directory and
3709                                     quit\\
3710
3711  \code{-nosky} & Omit background sky\\
3712
3713
3714  \code{-scale <float>} & Vertical scale factor\\
3715  \code{-texture <file>} & Image to use for bedslope topography\\
3716  \code{-tps <rate>} & Timesteps per second\\
3717  \code{-version} & Revision number and creation (not compile)
3718                                     date\\
3719\end{tabular}
3720
3721\section{utilities/polygons}
3722
3723  \declaremodule{standard}{utilities.polygon}
3724  \refmodindex{utilities.polygon}
3725
[5088]3726  \begin{classdesc}{Polygon\_function}{regions, default=0.0, geo_reference=None}
[4123]3727  Module: \code{utilities.polygon}
3728
3729  Creates a callable object that returns one of a specified list of values when
3730  evaluated at a point \code{x, y}, depending on which polygon, from a specified list of polygons, the
3731  point belongs to. The parameter \code{regions} is a list of pairs
3732  \code{(P, v)}, where each \code{P} is a polygon and each \code{v}
3733  is either a constant value or a function of coordinates \code{x}
3734  and \code{y}, specifying the return value for a point inside \code{P}. The
[5088]3735  optional parameter \code{default} may be used to specify a value
3736  (or a function)
[4123]3737  for a point not lying inside any of the specified polygons. When a
3738  point lies in more than one polygon, the return value is taken to
3739  be the value for whichever of these polygon appears later in the
3740  list.
3741  %FIXME (Howard): CAN x, y BE VECTORS?
[5090]3742  The optional parameter geo\_reference refers to the status of points
3743  that are passed into the function. Typically they will be relative to
3744  some origin. In ANUGA, a typical call will take the form:
3745  {\small \begin{verbatim}
3746     set_quantity('elevation',
3747                  Polygon_function([(P1, v1), (P2, v2)],
[5091]3748                                   default=v3,
3749                                   geo_reference=domain.geo_reference))
[5090]3750  \end{verbatim}}
3751 
[4123]3752
3753  \end{classdesc}
3754
3755  \begin{funcdesc}{read\_polygon}{filename}
3756  Module: \code{utilities.polygon}
3757
3758  Reads the specified file and returns a polygon. Each
3759  line of the file must contain exactly two numbers, separated by a comma, which are interpreted
3760  as coordinates of one vertex of the polygon.
3761  \end{funcdesc}
3762
3763  \begin{funcdesc}{populate\_polygon}{polygon, number_of_points, seed = None, exclude = None}
3764  Module: \code{utilities.polygon}
3765
3766  Populates the interior of the specified polygon with the specified number of points,
3767  selected by means of a uniform distribution function.
3768  \end{funcdesc}
3769
3770  \begin{funcdesc}{point\_in\_polygon}{polygon, delta=1e-8}
3771  Module: \code{utilities.polygon}
3772
3773  Returns a point inside the specified polygon and close to the edge. The distance between
3774  the returned point and the nearest point of the polygon is less than $\sqrt{2}$ times the
3775  second argument \code{delta}, which is taken as $10^{-8}$ by default.
3776  \end{funcdesc}
3777
3778  \begin{funcdesc}{inside\_polygon}{points, polygon, closed = True, verbose = False}
3779  Module: \code{utilities.polygon}
3780
3781  Used to test whether the members of a list of points
3782  are inside the specified polygon. Returns a Numeric
3783  array comprising the indices of the points in the list that lie inside the polygon.
3784  (If none of the points are inside, returns \code{zeros((0,), 'l')}.)
3785  Points on the edges of the polygon are regarded as inside if
3786  \code{closed} is set to \code{True} or omitted; otherwise they are regarded as outside.
3787  \end{funcdesc}
3788
3789  \begin{funcdesc}{outside\_polygon}{points, polygon, closed = True, verbose = False}
3790  Module: \code{utilities.polygon}
3791
3792  Exactly like \code{inside\_polygon}, but with the words `inside' and `outside' interchanged.
3793  \end{funcdesc}
3794
3795  \begin{funcdesc}{is\_inside\_polygon}{point, polygon, closed=True, verbose=False}
3796  Module: \code{utilities.polygon}
3797
3798  Returns \code{True} if \code{point} is inside \code{polygon} or
3799  \code{False} otherwise. Points on the edges of the polygon are regarded as inside if
3800  \code{closed} is set to \code{True} or omitted; otherwise they are regarded as outside.
3801  \end{funcdesc}
3802
3803  \begin{funcdesc}{is\_outside\_polygon}{point, polygon, closed=True, verbose=False}
3804  Module: \code{utilities.polygon}
3805
3806  Exactly like \code{is\_outside\_polygon}, but with the words `inside' and `outside' interchanged.
3807  \end{funcdesc}
3808
3809  \begin{funcdesc}{point\_on\_line}{x, y, x0, y0, x1, y1}
3810  Module: \code{utilities.polygon}
3811
3812  Returns \code{True} or \code{False}, depending on whether the point with coordinates
3813  \code{x, y} is on the line passing through the points with coordinates \code{x0, y0}
3814  and \code{x1, y1} (extended if necessary at either end).
3815  \end{funcdesc}
3816
3817  \begin{funcdesc}{separate\_points\_by\_polygon}{points, polygon, closed = True, verbose = False}
3818    \indexedcode{separate\_points\_by\_polygon}
3819  Module: \code{utilities.polygon}
3820
3821  \end{funcdesc}
3822
3823  \begin{funcdesc}{polygon\_area}{polygon}
3824  Module: \code{utilities.polygon}
3825
3826  Returns area of arbitrary polygon (reference http://mathworld.wolfram.com/PolygonArea.html)
3827  \end{funcdesc}
3828
[5484]3829  \begin{funcdesc}{plot\_polygons}{polygons, style, figname, verbose = False}
3830    Module: \code{utilities.polygon}
3831 
3832    Plots each polygon contained in input polygon list, e.g.
3833   \code{polygons = [poly1, poly2, poly3]} where \code{poly1 = [[x11,y11],[x12,y12],[x13,y13]]}
3834   etc.  Each polygon can be closed for plotting purposes by assigning the style type to each
3835   polygon in the list, e.g. \code{style = ['line','line','line']}. The default will be a line
3836   type when \code{style = None}.
3837   The subsequent plot will be saved to \code{figname} or defaulted to \code{test_image.png}.
3838    The function returns a list containing the minimum and maximum of \code{x} and \code{y},
3839    i.e. \code{[x_{min}, x_{max}, y_{min}, y_{max}]}.
[4123]3840  \end{funcdesc}
3841
3842\section{coordinate\_transforms}
3843
3844\section{geospatial\_data}
3845\label{sec:geospatial}
3846
3847This describes a class that represents arbitrary point data in UTM
3848coordinates along with named attribute values.
3849
3850%FIXME (Ole): This gives a LaTeX error
3851%\declaremodule{standard}{geospatial_data}
3852%\refmodindex{geospatial_data}
3853
3854
3855
3856\begin{classdesc}{Geospatial\_data}
3857  {data_points = None,
3858    attributes = None,
3859    geo_reference = None,
3860    default_attribute_name = None,
3861    file_name = None}
3862Module: \code{geospatial\_data}
3863
3864This class is used to store a set of data points and associated
3865attributes, allowing these to be manipulated by methods defined for
3866the class.
3867
3868The data points are specified either by reading them from a NetCDF
[4662]3869or CSV file, identified through the parameter \code{file\_name}, or
[4123]3870by providing their \code{x}- and \code{y}-coordinates in metres,
3871either as a sequence of 2-tuples of floats or as an $M \times 2$
3872Numeric array of floats, where $M$ is the number of points.
3873Coordinates are interpreted relative to the origin specified by the
3874object \code{geo\_reference}, which contains data indicating the UTM
3875zone, easting and northing. If \code{geo\_reference} is not
3876specified, a default is used.
3877
3878Attributes are specified through the parameter \code{attributes},
3879set either to a list or array of length $M$ or to a dictionary whose
3880keys are the attribute names and whose values are lists or arrays of
3881length $M$. One of the attributes may be specified as the default
3882attribute, by assigning its name to \code{default\_attribute\_name}.
3883If no value is specified, the default attribute is taken to be the
3884first one.
[5566]3885
3886Note that the Geospatial\_data object currently reads entire datasets
3887into memory i.e.\ no memomry blocking takes place. 
[5619]3888For this we refer to the set\_quantity method which will read .pts and .csv files into \anuga using memory blocking allowing large files to be used.
[4123]3889\end{classdesc}
3890
3891
3892\begin{methoddesc}{import\_points\_file}{delimiter = None, verbose = False}
3893
3894\end{methoddesc}
3895
3896
3897\begin{methoddesc}{export\_points\_file}{ofile, absolute=False}
3898
3899\end{methoddesc}
3900
3901
[4646]3902\begin{methoddesc}{get\_data\_points}{absolute = True, as\_lat\_long =
3903    False}
3904    If \code{as\_lat\_long} is\code{True} the point information
[4953]3905    returned will be in Latitudes and Longitudes.
[4123]3906
3907\end{methoddesc}
3908
3909
3910\begin{methoddesc}{set\_attributes}{attributes}
3911
3912\end{methoddesc}
3913
3914
3915\begin{methoddesc}{get\_attributes}{attribute_name = None}
3916
3917\end{methoddesc}
3918
3919
3920\begin{methoddesc}{get\_all\_attributes}{}
3921
3922\end{methoddesc}
3923
3924
3925\begin{methoddesc}{set\_default\_attribute\_name}{default_attribute_name}
3926
3927\end{methoddesc}
3928
3929
3930\begin{methoddesc}{set\_geo\_reference}{geo_reference}
3931
3932\end{methoddesc}
3933
3934
3935\begin{methoddesc}{add}{}
3936
3937\end{methoddesc}
3938
3939
3940\begin{methoddesc}{clip}{}
3941Clip geospatial data by a polygon
3942
3943Inputs are \code{polygon} which is either a list of points, an Nx2 array or
[4209]3944a Geospatial data object and \code{closed}(optional) which determines
3945whether points on boundary should be regarded as belonging to the polygon
3946(\code{closed=True}) or not (\code{closed=False}).
[4123]3947Default is \code{closed=True}.
[4209]3948
3949Returns new Geospatial data object representing points
[4123]3950inside specified polygon.
3951\end{methoddesc}
3952
3953
[4488]3954\begin{methoddesc}{clip_outside}{}
3955Clip geospatial data by a polygon
3956
3957Inputs are \code{polygon} which is either a list of points, an Nx2 array or
3958a Geospatial data object and \code{closed}(optional) which determines
3959whether points on boundary should be regarded as belonging to the polygon
3960(\code{closed=True}) or not (\code{closed=False}).
3961Default is \code{closed=True}.
3962
3963Returns new Geospatial data object representing points
3964\emph{out}side specified polygon.
3965\end{methoddesc}
3966
[5143]3967\begin{methoddesc}{split}{factor=0.5, seed_num=None, verbose=False}
3968Returns two geospatial_data object, first is the size of the 'factor'
3969smaller the original and the second is the remainder. The two
3970new object are disjoin set of each other.
3971       
[5144]3972Points of the two new geospatial_data object are selected RANDOMLY.
[5143]3973       
[5144]3974Input - the (\code{factor}) which to split the object, if 0.1 then 10% of the
[5143]3975together object will be returned
3976       
3977Output - two geospatial_data objects that are disjoint sets of the original
3978\end{methoddesc}
[4488]3979
[5143]3980\begin{methoddesc}{find_optimal_smoothing_parameter}{data_file, alpha_list=None, mesh_file=None, boundary_poly=None, mesh_resolution=100000,
3981north_boundary=None, south_boundary=None, east_boundary=None, west_boundary=None, plot_name='all_alphas', split_factor=0.1, seed_num=None, cache=False, verbose=False}
3982
[5144]3983Removes a small random sample of points from 'data_file'. Creates
3984models from resulting points in 'data_file' with different alpha values from 'alpha_list' and cross validates
3985the predicted value to the previously removed point data. Returns the
3986alpha value which has the smallest covariance.
3987
3988data_file: must not contain points outside the boundaries defined
3989and it either a pts, txt or csv file.
3990   
3991alpha_list: the alpha values to test in a single list
3992   
3993mesh_file: name of the created mesh file or if passed in will read it.
3994NOTE, if there is a mesh file mesh_resolution, north_boundary, south... etc will be ignored.
3995   
3996mesh_resolution: the maximum area size for a triangle
3997   
3998north_boundary... west_boundary: the value of the boundary
3999   
4000plot_name: the name for the plot contain the results
4001   
4002seed_num: the seed to the random number generator
4003   
4004USAGE:
4005convariance_value, alpha = find_optimal_smoothing_parameter(data_file=fileName,
4006                                             alpha_list=[0.0001, 0.01, 1],
4007                                             mesh_file=None,
4008                                             mesh_resolution=3,
4009                                             north_boundary=5,
4010                                             south_boundary=-5,
4011                                             east_boundary=5,
4012                                             west_boundary=-5,
4013                                             plot_name='all_alphas',
4014                                             seed_num=100000,
4015                                             verbose=False)
4016   
4017OUTPUT: returns the minumum normalised covalance calculate AND the
4018alpha that created it. PLUS writes a plot of the results
4019           
4020NOTE: code will not work if the data_file extent is greater than the
4021boundary_polygon or any of the boundaries, eg north_boundary...west_boundary
[5143]4022\end{methoddesc}
4023
4024
4025
[4736]4026\section{Graphical Mesh Generator GUI}
[4953]4027The program \code{graphical\_mesh\_generator.py} in the pmesh module
[4123]4028allows the user to set up the mesh of the problem interactively.
4029It can be used to build the outline of a mesh or to visualise a mesh
4030automatically generated.
4031
[4736]4032Graphical Mesh Generator will let the user select various modes. The
4033current allowable modes are vertex, segment, hole or region.  The mode
4034describes what sort of object is added or selected in response to
4035mouse clicks.  When changing modes any prior selected objects become
4036deselected.