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

Last change on this file since 3924 was 3924, checked in by sexton, 18 years ago

change figs from eps to jpg/png

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