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

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

Optimised compute_fluxes by disabling limitation of momentum perpendicular to the x-axis. Speeds calculated from the x-momentum are still being limited according to the _compute_speeds. All tests pass and the overall improvement is as follows:
For the simple profile compute_fluxes improved from 4.284s to 3.372s and the overall runtime of evolve from 10.909s to 9.941s. This is an overall speedup of more than 8%.

For the okushiri profile example the improvement of compute_fluxes is from 129.432s to 111.703s and the overall runtime was reduced from 312.336s to 293.286s or about 6% improvement. This is probably the more realistic profile.

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