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

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

Moved a few things in regard to the user manual

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