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

Last change on this file since 4101 was 4101, checked in by ole, 18 years ago

Updated manual to reflect change in runcairns.py

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