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

Last change on this file since 5091 was 5091, checked in by ole, 16 years ago

formatting

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