source: trunk/anuga_documentation/user_manual/anuga_user_manual.tex @ 9342

Last change on this file since 9342 was 8427, checked in by davies, 13 years ago

Adding the trapezoidal channel validation test, and editing the ANUGA manual

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