Index: /anuga_work/production/wa/busselton/2006/project.py
===================================================================
--- /anuga_work/production/wa/busselton/2006/project.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/2006/project.py	(revision 7411)
@@ -0,0 +1,139 @@
+# -*- coding: cp1252 -*-
+"""Common filenames and locations for topographic data, meshes and outputs.
+"""
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, is_inside_polygon, number_mesh_triangles
+#from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees, convert_points_from_latlon_to_utm
+from anuga.utilities.system_tools import get_user_name
+
+# file and system info
+#---------------------------------
+codename = 'project.py'
+
+home = getenv('INUNDATIONHOME') #Sandpit's parent dir   
+user = get_user_name()
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+home += sep +'data'
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',localtime()) #gets time for new dir
+gtime = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+#print 'gtime: ', gtime
+
+tide = 0.6
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'busselton'
+scenario = 'busselton_tsunami_scenario_2006'
+
+# onshore data provided by WA DLI
+onshore_name = 'DLI_orthophoto_DEM' # original
+#islands
+
+# AHO + DPI data
+coast_name = '100k_coastline'
+offshore_name = 'Bathymetry'
+
+#final topo name
+combined_name ='busselton_combined_elevation'
+combined_smaller_name = 'busselton_combined_elevation_smaller'
+
+
+topographies_in_dir = home+sep+state+sep+scenario+sep+'elevation_final'+sep+'points'+sep
+topographies_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'topographies'+sep
+topographies_time_dir = topographies_dir+build_time+sep
+
+#input topo file location
+onshore_in_dir_name = topographies_in_dir + onshore_name
+#island_in_dir_name = topographies_in_dir + island_name
+
+coast_in_dir_name = topographies_in_dir + coast_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+
+onshore_dir_name = topographies_dir + onshore_name
+#island_dir_name = topographies_dir + island_name
+
+coast_dir_name = topographies_dir + coast_name
+offshore_dir_name = topographies_dir + offshore_name
+
+#final topo files
+combined_dir_name = topographies_dir + combined_name
+combined_time_dir_name = topographies_time_dir + combined_name
+combined_smaller_dir_name = topographies_dir + combined_smaller_name
+
+meshes_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'meshes'+sep
+meshes_dir_name = meshes_dir + scenario_name
+
+polygons_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'polygons'+sep
+tide_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'tide_data'+sep
+
+boundaries_source = '????'
+#boundaries locations
+boundaries_in_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'boundaries'+sep+'urs'+sep+boundaries_source+sep
+boundaries_in_dir_name = boundaries_in_dir + scenario_name
+boundaries_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'boundaries'+sep
+boundaries_dir_name = boundaries_dir + scenario_name
+#boundaries_time_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'boundaries'+sep+build_time+sep
+#boundaries_time_dir_name = boundaries_time_dir + boundaries_name  #Used by post processing
+
+#output locations
+output_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'outputs'+sep
+output_build_time_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'outputs'+sep+build_time+sep
+output_run_time_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'outputs'+sep+run_time+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+gauge_name = '???.csv'
+gauges_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'gauges'+sep
+gauges_dir_name = gauges_dir + gauge_name
+
+buildings_filename = gauges_dir + 'Busselton_res_Project.csv'
+buildings_filename_out = 'Busselton_res_Project_modified.csv'
+
+###############################
+# Domain definitions
+###############################
+
+# bounding box for clipping MOST/URS output (much bigger than study area)
+
+# bounding polygon for study area
+poly_all = read_polygon(polygons_dir+'poly_all.csv')
+res_poly_all = 100000
+
+###################################################################
+# Clipping regions for export to asc and regions for clipping data
+###################################################################
+
+# exporting asc grid
+eastingmin = 406215.87
+eastingmax = 440208.78
+northingmin = 7983427.73
+northingmax = 8032834.52
+
+###############################
+# Interior region definitions
+###############################
+
+#digitized polygons
+poly_busselton1 = read_polygon(polygons_dir+'neg20_pos10_polygon.csv')
+res_busselton1 = 10000
+poly_busselton2 = read_polygon(polygons_dir+'neg5_pos5_poly_.csv')
+res_busselton2 = 500
+
+#plot_polygons([polyAll,poly_broome1,poly_broome2,poly_broome3],figname='boundingpoly2',verbose=False)
+
+interior_regions = [[poly_busselton1,res_busselton1],[poly_busselton2,res_busselton2]]
+
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+
+print 'min number triangles', trigs_min
+
+
Index: /anuga_work/production/wa/busselton/2006/run_busselton.py
===================================================================
--- /anuga_work/production/wa/busselton/2006/run_busselton.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/2006/run_busselton.py	(revision 7411)
@@ -0,0 +1,220 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from Numeric import allclose
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.geospatial_data.geospatial_data import *
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, copy_code_files
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga.utilities.polygon import plot_polygons, polygon_area
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+start_screen_catcher(project.output_run_time_dir, myid, numprocs)
+
+print 'time stamp: ',project.gtime
+print 'USER: ', project.user
+print 'min triangles', project.trigs_min
+
+# filenames
+boundaries_name = project.scenario
+meshes_dir_name = project.meshes_dir_name+'.msh'
+#boundaries_time_dir_name = project.boundaries_time_dir_name
+boundaries_dir_name = project.boundaries_dir_name
+
+tide = project.tide
+
+# creates copy of code in output dir
+if myid == 0:
+    copy_code_files(project.output_run_time_dir,__file__, 
+                 dirname(project.__file__)+sep+ project.__name__+'.py' )
+barrier()
+
+#--------------------------------------------------------------------------
+# Create the triangular mesh based on overall clipping polygon with a
+# tagged
+# boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#--------------------------------------------------------------------------
+
+if myid == 0:
+
+    print 'start create mesh from regions'
+#    interior_regions = [[project.poly_busselton1, project.res_bus1],
+#                    [project.poly_busselton2, project.res_bus2],
+#                    [project.poly_busselton3, project.res_bus3]]    
+
+#    from anuga.utilities.polygon import plot_polygons
+#    figname = project.output_run_time_dir + 'poly_pic'
+#    plot_polygons([project.poly_coast,project.poly_pipeline,project.poly_facility,
+#               project.bounding_polygon],
+#               figname,
+#               verbose = True)
+#    import sys; sys.exit()
+
+    print 'start create mesh from regions'
+    create_mesh_from_regions(project.poly_all,
+                         boundary_tags={'back': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14],
+                                        'side': [10,13], 'ocean': [11, 12]},
+                         maximum_triangle_area=project.res_poly_all,
+                         interior_regions=project.interior_regions,
+#                         filename=meshes_time_dir_name,
+                         filename=meshes_dir_name,
+                         use_cache=True,
+                         verbose=True)
+
+# to sync all processors are ready 
+barrier()
+
+#-------------------------------------------------------------------------
+# Setup computational domain
+#-------------------------------------------------------------------------
+print 'Setup computational domain'
+#domain = Domain(meshes_time_dir_name, use_cache=True, verbose=True)
+domain = Domain(meshes_dir_name, use_cache=True, verbose=True)
+print domain.statistics()
+'''
+print 'starting to create boundary conditions'
+boundaries_in_dir_name = project.boundaries_in_dir_name
+
+from anuga.shallow_water.data_manager import urs2sww, ferret2sww
+
+# put above distribute
+print 'boundary file is: ',boundaries_dir_name
+from caching import cache
+if myid == 0:
+    cache(ferret2sww,
+          (boundaries_in_dir_name,
+    #       boundaries_time_dir_name), 
+           boundaries_dir_name), 
+          {'verbose': True,
+           'minlat': project.south_boundary,
+           'maxlat': project.north_boundary,
+           'minlon': project.west_boundary,
+           'maxlon': project.east_boundary,
+#           'minlat': project.south,
+#           'maxlat': project.north,
+#           'minlon': project.west,
+#           'maxlon': project.east,
+           'mint': 0, 'maxt': 35100,
+           'origin': domain.geo_reference.get_origin(),
+           'mean_stage': project.tide,
+#           'zscale': 1,                 #Enhance tsunami
+           'fail_on_NaN': False},
+           verbose = True,
+           )
+barrier()
+'''
+
+#-------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------
+if myid == 0:
+
+    print 'Setup initial conditions'
+
+    domain.set_quantity('stage', tide)
+    domain.set_quantity('friction', 0.01) 
+    #combined_time_dir_name = project.topographies_dir+build_time+project.combined_name
+    print 'Start Set quantity'
+
+    domain.set_quantity('elevation', 
+#                    filename = project.combined_smaller_dir_name+'.xya',
+                    filename = project.combined_dir_name+'.pts',
+                    use_cache = True,
+                    verbose = True,
+                    alpha = 0.1)
+    print 'Finished Set quantity'
+barrier()
+
+#------------------------------------------------------
+# Distribute domain to implement parallelism !!!
+#------------------------------------------------------
+
+if numprocs > 1:
+    domain=distribute(domain)
+
+#------------------------------------------------------
+# Set domain parameters
+#------------------------------------------------------
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run_time_dir)
+domain.set_default_order(2) # Apply second order scheme
+domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+domain.set_store_vertices_uniquely(False)
+domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+
+#-------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------
+print 'Available boundary tags', domain.get_boundary_tags()
+
+print 'Reading Boundary file'
+print 'domain id', id(domain)
+#Bf = File_boundary(boundaries_dir_name + '.sww',
+#                  domain, time_thinning=5, use_cache=True, verbose=True)
+
+print 'finished reading boundary file'
+Br = Reflective_boundary(domain)
+Bd = Dirichlet_boundary([tide,0,0])
+Bo = Dirichlet_boundary([tide+5.0,0,0])
+
+print'set_boundary'
+domain.set_boundary({'back': Br,
+                     'side': Bd,
+                     'ocean': Bd}) 
+print'finish set boundary'
+
+#----------------------------------------------------------------------------
+# Evolve system through time
+#----------------------------------------------------------------------------
+
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = 60, finaltime = 10000):
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'ocean')
+    if allclose(t, 120):
+        domain.set_boundary({'back': Br, 'side': Bd, 'ocean': Bo})
+
+    if allclose(t, 1020):
+        domain.set_boundary({'back': Br, 'side': Bd, 'ocean': Bd})
+
+    
+print 'That took %.2f seconds' %(time.time()-t0)
+
Index: /anuga_work/production/wa/busselton/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/busselton/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,85 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\busselton_tsunami_scenario\\"
+output_dir="anuga\\outputs\\"
+
+time_dir1 = '20090130_165532_run_final_0.6_27255_extend_dt_kvanputt'
+####time_dir2 = '20081211_162311_run_final_0_27255_alpha0.1_kvanputt'
+####time_dir3 = '20081211_162346_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081211_162433_run_final_0.6_68693_alpha0.1_kvanputt'
+##time_dir5 = '20081211_162656_run_final_0.6_27283_alpha0.1_kvanputt'
+##time_dir6 = '20081211_162744_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1] #, time_dir2] #4, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+ 
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder = scenario_dir + output_dir + time_dir +'\\'
+    raster_gbd = folder + 'raster.gdb'
+    land = scenario_dir + "map_work\\Busselton.gdb\\Internal_polygons\\initial_conditions_extend"
+    ocean = scenario_dir + "map_work\\Busselton.gdb\\input_boundaries\\Ocean"
+
+    
+    print 'Process: Create File GDB'
+    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    print time_dir
+    
+    #replication dictionary
+    replicate = (('busselton', ''),('_', ''),('max','_M'),
+                 ('Busselton', 'Bus'),('Bunbury', 'Bun'),
+                 ('depth','_depth'),('speed', '_speed'),
+                 ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:12]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection' 
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+##        output_extract = output_DEM + '_E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+
Index: /anuga_work/production/wa/busselton/Arc_txt2feature_class.py
===================================================================
--- /anuga_work/production/wa/busselton/Arc_txt2feature_class.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/Arc_txt2feature_class.py	(revision 7411)
@@ -0,0 +1,54 @@
+# ---------------------------------------------------------------------------
+# txt2fc_field.py
+# Created on: Thu Nov 27 2008 01:48:26 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\busselton_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20081211_154006_run_final_0.6_27255_alpha0.1_kvanputt'
+##time_dir2 = '20081211_162311_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081211_162346_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081211_162433_run_final_0.6_68693_alpha0.1_kvanputt'
+##time_dir5 = '20081211_162656_run_final_0.6_27283_alpha0.1_kvanputt'
+##time_dir6 = '20081211_162744_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1] #4, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'busselton_runup.csv'
+    input_name = os.path.basename(input_dir_name)
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+    feature_class_name = input_name[:-4]
+
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "x", "y", layer, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM"
+                                   "['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT"
+                                   "['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting'"
+                                   ",500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER"
+                                   "['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "busselton_runup", "", "area area true true false 255 Text 0 0 ,First,#,busselton_runup.csv_Features,area,-1,-1;q q true true false 8 Double 0 0 ,First,#,busselton_runup.csv_Features,q,-1,-1;x x true true false 8 Double 0 0 ,First,#,busselton_runup.csv_Features,x,-1,-1;y y true true false 8 Double 0 0 ,First,#,busselton_runup.csv_Features,y,-1,-1", "")
+
+
+  
Index: /anuga_work/production/wa/busselton/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/busselton/Arc_txt2feature_class_res.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/Arc_txt2feature_class_res.py	(revision 7411)
@@ -0,0 +1,44 @@
+# ---------------------------------------------------------------------------
+# txt2fc_res.py
+# Created on: Mon Dec 01 2008 11:36:17 AM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\busselton_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+##time_dir1 = '20081211_154006_run_final_0.6_27255_alpha0.1_kvanputt'
+##time_dir2 = '20081211_162311_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081211_162346_run_final_0_68693_alpha0.1_kvanputt'
+time_dir4 = '20081211_162433_run_final_0.6_68693_alpha0.1_kvanputt'
+##time_dir5 = '20081211_162656_run_final_0.6_27283_alpha0.1_kvanputt'
+##time_dir6 = '20081211_162744_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir4] #4, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'busselton_res.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+    
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "longitude", "latitude", layer, "GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "busselton_res", "", "OBJECTID OBJECTID true true false 4 Long 0 10 ,First,#,busselton_res.csv_Features,OBJECTID,-1,-1;LONGITUDE LONGITUDE true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,LONGITUDE,-1,-1;LATITUDE LATITUDE true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,LATITUDE,-1,-1;STRUCT_INUNDATED STRUCT_INUNDATED true true false 4 Long 0 10 ,First,#,busselton_res.csv_Features,STRUCT_INUNDATED,-1,-1;STRUCT_DAMAGE_fraction STRUCT_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,STRUCT_DAMAGE_fraction,-1,-1;COLLAPSE_CSV_INFO COLLAPSE_CSV_INFO true true false 255 Text 0 0 ,First,#,busselton_res.csv_Features,COLLAPSE_CSV_INFO,-1,-1;MAX_DEPTH_m MAX_DEPTH_m true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,MAX_DEPTH_m,-1,-1;STRUCT_COLLAPSED STRUCT_COLLAPSED true true false 255 Text 0 0 ,First,#,busselton_res.csv_Features,STRUCT_COLLAPSED,-1,-1;STRUCT_LOSS STRUCT_LOSS true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,STRUCT_LOSS,-1,-1;CONTENTS_DAMAGE_fraction CONTENTS_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,CONTENTS_DAMAGE_fraction,-1,-1;CONTENTS_LOSS CONTENTS_LOSS true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,CONTENTS_LOSS,-1,-1", "")
+
Index: /anuga_work/production/wa/busselton/build_boundary_27255.py
===================================================================
--- /anuga_work/production/wa/busselton/build_boundary_27255.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/build_boundary_27255.py	(revision 7411)
@@ -0,0 +1,150 @@
+"""
+Script for building boundary to run a tsunami inundation scenario for busselton,
+WA, Australia.  The boundary is sourced from the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_busselton.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+# location of mux files
+# Note, this may change when all mux files are on the GA network
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+# Note, this is specific to the event and will be supplied by David.
+# In time, this will become more automated.
+urs_filenames = [
+    os.path.join(dir,'Java-0017-z.grd'),  
+    os.path.join(dir,'Java-0018-z.grd'),
+    os.path.join(dir,'Java-0019-z.grd'),
+    os.path.join(dir,'Java-0022-z.grd'),  
+    os.path.join(dir,'Java-0023-z.grd'),  
+    os.path.join(dir,'Java-0024-z.grd'),  
+    os.path.join(dir,'Java-0027-z.grd'),  
+    os.path.join(dir,'Java-0028-z.grd'),  
+    os.path.join(dir,'Java-0031-z.grd'),  
+    os.path.join(dir,'Java-0032-z.grd')]  
+ 
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 10: #change per event
+
+    weight_factor = 30.84050 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #------------------------------------------------------------------------------
+    # Get maxium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+    #------------------------------------------------------------------------------
+    # Get minium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+    #------------------------------------------------------------------------------
+    # End of the get gauges
+    #------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/busselton/build_boundary_27283.py
===================================================================
--- /anuga_work/production/wa/busselton/build_boundary_27283.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/build_boundary_27283.py	(revision 7411)
@@ -0,0 +1,186 @@
+"""
+Script for building boundary to run tsunami inundation scenario for busselton,
+WA, Australia.  The boundary is based on the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_busselton.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+urs_filenames = [
+    os.path.join(dir,'Java-0000-z.grd'),
+    os.path.join(dir,'Java-0001-z.grd'),
+    os.path.join(dir,'Java-0002-z.grd'),
+    os.path.join(dir,'Java-0003-z.grd'),
+    os.path.join(dir,'Java-0005-z.grd'), 
+    os.path.join(dir,'Java-0006-z.grd'), 
+    os.path.join(dir,'Java-0007-z.grd'), 
+    os.path.join(dir,'Java-0008-z.grd'), 
+    os.path.join(dir,'Java-0010-z.grd'), 
+    os.path.join(dir,'Java-0011-z.grd'), 
+    os.path.join(dir,'Java-0012-z.grd'), 
+    os.path.join(dir,'Java-0013-z.grd'),  
+    os.path.join(dir,'Java-0015-z.grd'),  
+    os.path.join(dir,'Java-0016-z.grd'),  
+    os.path.join(dir,'Java-0017-z.grd'),  
+    os.path.join(dir,'Java-0018-z.grd'),  
+    os.path.join(dir,'Java-0020-z.grd'),  
+    os.path.join(dir,'Java-0021-z.grd'),  
+    os.path.join(dir,'Java-0022-z.grd'),  
+    os.path.join(dir,'Java-0023-z.grd'),  
+    os.path.join(dir,'Java-0025-z.grd'),  
+    os.path.join(dir,'Java-0026-z.grd'),  
+    os.path.join(dir,'Java-0027-z.grd'),  
+    os.path.join(dir,'Java-0028-z.grd'),  
+    os.path.join(dir,'Java-0029-z.grd'),  
+    os.path.join(dir,'Java-0030-z.grd'),  
+    os.path.join(dir,'Java-0031-z.grd'),  
+    os.path.join(dir,'Java-0032-z.grd'),  
+    os.path.join(dir,'Java-0033-z.grd'),  
+    os.path.join(dir,'Java-0034-z.grd'),  
+    os.path.join(dir,'Java-0035-z.grd'),  
+    os.path.join(dir,'Java-0036-z.grd'),  
+    os.path.join(dir,'Java-0037-z.grd'),  
+    os.path.join(dir,'Java-0038-z.grd'),  
+    os.path.join(dir,'Java-0039-z.grd'),  
+    os.path.join(dir,'Java-0040-z.grd'),  
+    os.path.join(dir,'Java-0041-z.grd'),  
+    os.path.join(dir,'Java-0042-z.grd'),  
+    os.path.join(dir,'Java-0043-z.grd'),  
+    os.path.join(dir,'Java-0044-z.grd'),  
+    os.path.join(dir,'Java-0045-z.grd'),  
+    os.path.join(dir,'Java-0046-z.grd'),  
+    os.path.join(dir,'Java-0047-z.grd'),
+    os.path.join(dir,'Java-0048-z.grd')]    
+ 
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 44: #change per event
+
+# AS per David Burbidge email on Friday 4th July the mag 9.3 event
+# has 1m worth of slip on each sub fault therefore mutliple each unit
+# source by the slip (10.4544) and sum the 44 time series together to
+# get the time series for this event at the points on your boundary. 
+
+    weight_factor = 10.4544 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+#------------------------------------------------------------------------------
+# Get Maxium wave height throughout timeseries at each index point
+#------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+#------------------------------------------------------------------------------
+# Get Minium wave height throughout timeseries at each index point
+#------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+#------------------------------------------------------------------------------
+# End of the get gauges
+#------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/busselton/build_boundary_68693.py
===================================================================
--- /anuga_work/production/wa/busselton/build_boundary_68693.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/build_boundary_68693.py	(revision 7411)
@@ -0,0 +1,152 @@
+"""
+Script for building boundary to run a tsunami inundation scenario for onslow,
+WA, Australia.  The boundary is sourced from the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_onslow.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+# location of mux files
+# Note, this may change when all mux files are on the GA network
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+# Note, this is specific to the event and will be supplied by David.
+# In time, this will become more automated.
+urs_filenames = [
+    os.path.join(dir,'Sumatra-0026-z.grd'),
+    os.path.join(dir,'Sumatra-0027-z.grd'),
+    os.path.join(dir,'Sumatra-0028-z.grd'),
+    os.path.join(dir,'Sumatra-0029-z.grd'),
+    os.path.join(dir,'Sumatra-0030-z.grd'),
+    os.path.join(dir,'Sumatra-0031-z.grd'),
+    os.path.join(dir,'Sumatra-0033-z.grd'),
+    os.path.join(dir,'Sumatra-0034-z.grd'),
+    os.path.join(dir,'Sumatra-0035-z.grd'),
+    os.path.join(dir,'Sumatra-0037-z.grd'),
+    os.path.join(dir,'Sumatra-0038-z.grd'),
+    os.path.join(dir,'Sumatra-0039-z.grd')]
+        
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 12: #change per event
+
+    weight_factor = 27.3603 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #------------------------------------------------------------------------------
+    # Get maxium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+    #------------------------------------------------------------------------------
+    # Get minium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+    #------------------------------------------------------------------------------
+    # End of the get gauges
+    #------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/busselton/build_busselton.py
===================================================================
--- /anuga_work/production/wa/busselton/build_busselton.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/build_busselton.py	(revision 7411)
@@ -0,0 +1,136 @@
+"""
+Script for building the elevation data to run a tsunami inundation scenario
+for busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_busselton.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.geospatial_data.geospatial_data import *
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files
+
+# Application specific imports
+import project   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project.output_build_time_dir,__file__, 
+               dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+start_screen_catcher(project.output_build_time_dir)
+
+print 'USER:    ', project.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print "project.poly_all", project.poly_all
+print "project.combined_dir_name", project.combined_dir_name
+
+# input elevation directory filenames
+onshore_in_dir_name = project.onshore_in_dir_name
+coast_in_dir_name = project.coast_in_dir_name
+coast_in_dir_name1 = project.coast_in_dir_name1
+offshore_in_dir_name = project.offshore_in_dir_name
+offshore_in_dir_name1 = project.offshore_in_dir_name1
+offshore_in_dir_name2 = project.offshore_in_dir_name2
+offshore_in_dir_name3 = project.offshore_in_dir_name3
+offshore_in_dir_name4 = project.offshore_in_dir_name4
+offshore_in_dir_name5 = project.offshore_in_dir_name5
+offshore_in_dir_name6 = project.offshore_in_dir_name6
+offshore_in_dir_name7 = project.offshore_in_dir_name7
+
+# output elevation directory filenames
+onshore_dir_name = project.onshore_dir_name
+coast_dir_name = project.coast_dir_name
+coast_dir_name1 = project.coast_dir_name1
+offshore_dir_name = project.offshore_dir_name
+offshore_dir_name1 = project.offshore_dir_name1
+offshore_dir_name2 = project.offshore_dir_name2
+offshore_dir_name3 = project.offshore_dir_name3
+offshore_dir_name4 = project.offshore_dir_name4
+offshore_dir_name5 = project.offshore_dir_name5
+offshore_dir_name6 = project.offshore_dir_name6
+offshore_dir_name7 = project.offshore_dir_name7
+
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name, basename_out=onshore_dir_name, use_cache=True, verbose=True)
+convert_dem_from_ascii2netcdf(offshore_in_dir_name7, basename_out=offshore_dir_name7, use_cache=True, verbose=True)
+
+# creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name ,use_cache=True,verbose=True)
+dem2pts(offshore_dir_name7 ,use_cache=True,verbose=True)
+
+# create onshore pts files
+print'create Geospatial data1 objects from topographies'
+G1 = Geospatial_data(file_name = onshore_dir_name + '.pts')
+
+# create coastal and offshore pts files
+print'create Geospatial data2 objects from topographies'
+G2 = Geospatial_data(file_name = coast_in_dir_name)
+print'create Geospatial data3 objects from topographies'
+G3 = Geospatial_data(file_name = coast_in_dir_name1)
+print'create Geospatial data4 objects from topographies'
+G_off = Geospatial_data(file_name = offshore_in_dir_name)
+print'create Geospatial data5 objects from topographies'
+G_off1 = Geospatial_data(file_name = offshore_in_dir_name1)
+print'create Geospatial data6 objects from topographies'
+G_off2 = Geospatial_data(file_name = offshore_in_dir_name2)
+print'create Geospatial data7 objects from topographies'
+G_off3 = Geospatial_data(file_name = offshore_in_dir_name3)
+print'create Geospatial data8 objects from topographies'
+G_off4 = Geospatial_data(file_name = offshore_in_dir_name4)
+print'create Geospatial data9 objects from topographies'
+G_off5 = Geospatial_data(file_name = offshore_in_dir_name5)
+print'create Geospatial data9 objects from topographies'
+G_off6 = Geospatial_data(file_name = offshore_in_dir_name6)
+print'create Geospatial data9 objects from topographies'
+G_off7 = Geospatial_data(file_name = offshore_dir_name7 + '.pts')
+
+
+
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print'add all geospatial objects'
+G = G1 + G2 + G3 + G_off + G_off1 + G_off2 + G_off3 + G_off4 
+
+print'clip combined geospatial object by bounding polygon'
+G_clip = G.clip_outside(project.poly_aoi1)
+G_all = G_clip + G_off5 + G_off6 + G_off7
+G_clipped = G_all.clip(project.poly_all)
+
+print'export combined DEM file'
+if access(project.topographies_dir,F_OK) == 0:
+    mkdir (project.topographies_dir)
+G_clipped.export_points_file(project.combined_dir_name + '.pts')
+G_clipped.export_points_file(project.combined_dir_name + '.txt') #Use for comparision in ARC
+
Index: /anuga_work/production/wa/busselton/build_busselton_250m.py
===================================================================
--- /anuga_work/production/wa/busselton/build_busselton_250m.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/build_busselton_250m.py	(revision 7411)
@@ -0,0 +1,84 @@
+"""
+Script for building the elevation data to run a tsunami inundation scenario
+for busselton, WA, Australia.
+
+Input: elevation data from project_250m.py
+Output: pts file stored in project_250m.topographies_dir 
+The run_busselton.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.geospatial_data.geospatial_data import *
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files
+
+# Application specific imports
+import project_250m   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project_250m.output_build_time_dir,__file__, 
+               dirname(project_250m.__file__)+sep+ project_250m.__name__+'.py' )
+
+start_screen_catcher(project_250m.output_build_time_dir)
+
+print 'USER:    ', project_250m.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print "project_250m.poly_all", project_250m.poly_all
+print "project_250m.combined_dir_name", project_250m.combined_dir_name
+
+# input elevation directory filenames
+onshore_in_dir_name = project_250m.onshore_in_dir_name
+
+# output elevation directory filenames
+onshore_dir_name = project_250m.onshore_dir_name
+
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name, basename_out=onshore_dir_name, use_cache=True, verbose=True)
+
+# creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name ,use_cache=True,verbose=True)
+
+# create onshore pts files
+print'create Geospatial data1 objects from topographies'
+G = Geospatial_data(file_name = onshore_dir_name + '.pts')
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print'clip combined geospatial object by bounding polygon'
+G_clipped = G.clip(project_250m.poly_all)
+
+print'export combined DEM file'
+if access(project_250m.topographies_dir,F_OK) == 0:
+    mkdir (project_250m.topographies_dir)
+G_clipped.export_points_file(project_250m.combined_dir_name + '.pts')
+#G_clipped.export_points_file(project_250m.combined_dir_name + '.txt') #Use for comparision in ARC
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,85 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\busselton_tsunami_scenario\\"
+output_dir="anuga\\outputs\\"
+
+time_dir1 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140747_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090327_152717_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_160646_run_final_0_27255_Bt_kvanputt'
+time_dir5 = '20090327_161520_run_final_0_68693_Bt_kvanputt'
+time_dir6 = '20090330_120458_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1] #1, time_dir2, time_dir3, time_dir4, time_dir5]
+   
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder = scenario_dir + output_dir + time_dir +'\\'
+    raster_gbd = folder + 'raster.gdb'
+    land = scenario_dir + "map_work\\Busselton.gdb\\Internal_polygons\\initial_conditions_extend"
+    ocean = scenario_dir + "map_work\\Busselton.gdb\\input_boundaries\\Ocean"
+
+    
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    print time_dir
+    
+    #replication dictionary
+    replicate = (('busselton', ''),('_', ''),('max','_M'),
+                 ('Busselton', 'Bus'),('Bunbury', 'Bun'),
+                 ('depth','_depth'),('speed', '_speed'),
+                 ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*elevation.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:12]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection' 
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+##        output_extract = output_DEM + '_E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/Arc_txt2feature_class.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/Arc_txt2feature_class.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/Arc_txt2feature_class.py	(revision 7411)
@@ -0,0 +1,51 @@
+# ---------------------------------------------------------------------------
+# txt2fc_field.py
+# Created on: Thu Nov 27 2008 01:48:26 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\busselton_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140747_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090327_152717_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_160646_run_final_0_27255_Bt_kvanputt'
+time_dir5 = '20090327_161520_run_final_0_68693_Bt_kvanputt'
+time_dir6 = '20090330_120458_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1, time_dir4] #, time_dir5] #4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'busselton_runup.csv'
+    input_name = os.path.basename(input_dir_name)
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+    feature_class_name = input_name[:-4]
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "x", "y", layer, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM"
+                                   "['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT"
+                                   "['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting'"
+                                   ",500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER"
+                                   "['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "busselton_runup", "", "area area true true false 255 Text 0 0 ,First,#,busselton_runup.csv_Features,area,-1,-1;q q true true false 8 Double 0 0 ,First,#,busselton_runup.csv_Features,q,-1,-1;x x true true false 8 Double 0 0 ,First,#,busselton_runup.csv_Features,x,-1,-1;y y true true false 8 Double 0 0 ,First,#,busselton_runup.csv_Features,y,-1,-1", "")
+
+
+  
Index: /anuga_work/production/wa/busselton/busselton_rerun/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/Arc_txt2feature_class_res.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/Arc_txt2feature_class_res.py	(revision 7411)
@@ -0,0 +1,67 @@
+# ---------------------------------------------------------------------------
+# txt2fc_res.py
+# Created on: Mon Dec 01 2008 11:36:17 AM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+from os.path import join
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\busselton_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140747_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090327_152717_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_160646_run_final_0_27255_Bt_kvanputt'
+time_dir5 = '20090327_161520_run_final_0_68693_Bt_kvanputt'
+time_dir6 = '20090330_120458_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir2, time_dir3, time_dir4, time_dir5, time_dir6] 
+
+def replace_in_file(filename, instr, repstr):
+    '''Replace one string with another in a file.'''
+    
+    # get the file contents
+    fd = open(filename, 'r')
+    lines = fd.readlines()
+    fd.close()
+
+    # convert list to one string
+    newlines = ''.join(lines)
+    
+    # replace 'instr' with 'repstr'
+    newlines = newlines.replace(instr, repstr)
+    
+    # write changed lines back to file
+    fd = open(filename, 'w')
+    fd.write(newlines)
+    fd.close()
+
+for time_dir in time_dirs:
+    print 'time_dir = ', time_dir
+    
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'busselton_res.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+
+    print 'replace _$ with nothing'
+    replace_in_file(input_dir_name, '_$', '')
+    
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "longitude", "latitude", layer, "GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "busselton_res", "", "OBJECTID OBJECTID true true false 4 Long 0 10 ,First,#,busselton_res.csv_Features,OBJECTID,-1,-1;LONGITUDE LONGITUDE true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,LONGITUDE,-1,-1;LATITUDE LATITUDE true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,LATITUDE,-1,-1;STRUCT_INUNDATED STRUCT_INUNDATED true true false 4 Long 0 10 ,First,#,busselton_res.csv_Features,STRUCT_INUNDATED,-1,-1;STRUCT_DAMAGE_fraction STRUCT_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,STRUCT_DAMAGE_fraction,-1,-1;COLLAPSE_CSV_INFO COLLAPSE_CSV_INFO true true false 255 Text 0 0 ,First,#,busselton_res.csv_Features,COLLAPSE_CSV_INFO,-1,-1;MAX_DEPTH_m MAX_DEPTH_m true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,MAX_DEPTH_m,-1,-1;STRUCT_COLLAPSED STRUCT_COLLAPSED true true false 255 Text 0 0 ,First,#,busselton_res.csv_Features,STRUCT_COLLAPSED,-1,-1;STRUCT_LOSS STRUCT_LOSS true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,STRUCT_LOSS,-1,-1;CONTENTS_DAMAGE_fraction CONTENTS_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,CONTENTS_DAMAGE_fraction,-1,-1;CONTENTS_LOSS CONTENTS_LOSS true true false 8 Double 0 0 ,First,#,busselton_res.csv_Features,CONTENTS_LOSS,-1,-1", "")
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/Busselton4distribution.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/Busselton4distribution.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/Busselton4distribution.py	(revision 7411)
@@ -0,0 +1,140 @@
+# ---------------------------------------------------------------------------
+# Carnarvon4distribution.py
+# Created on: Thu Apr 30 2009 03:51:03 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+community = 'Busselton'
+output_loc = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\FESA_outputs_Dec_08\\ARCgrids\\April_2009\\"
+input_scenario = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\busselton_tsunami_scenario\\"
+input_output = input_scenario + "\\anuga\\outputs\\"
+
+locations = ['Bunbury', 'Busselton']
+
+in_Tsunami_1_HAT = input_output + "20090327_152717_run_final_0.6_27283_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_1_MSL = input_output + "20090330_120458_run_final_0_27283_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_2_HAT = input_output + "20090324_134328_run_final_0.6_27255_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_2_MSL = input_output + "20090327_160646_run_final_0_27255_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_3_HAT = input_output + "20090324_140747_run_final_0.6_68693_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_3_MSL = input_output + "20090327_161520_run_final_0_68693_Bt_kvanputt\\raster.gdb\\"
+
+Tsunami_1_HAT = output_loc + "Tsunami1-Exmouth\\" + community + "_HAT.gdb\\"
+Tsunami_1_MSL = output_loc + "Tsunami1-Exmouth\\" + community + "_MSL.gdb\\"
+Tsunami_2_HAT = output_loc + "Tsunami2-Perth\\" + community + "_HAT.gdb\\"
+Tsunami_2_MSL = output_loc + "Tsunami2-Perth\\" + community + "_MSL.gdb\\"
+Tsunami_3_HAT = output_loc + "Tsunami3-1833\\" + community + "_HAT.gdb\\"
+Tsunami_3_MSL = output_loc + "Tsunami3-1833\\" + community + "_MSL.gdb\\"
+
+hr = community + '_runup'
+
+for location in locations:
+
+    # Local variables...
+    if location == 'Bunbury':
+        # polygon clip
+        extent = input_scenario + "map_work\\Busselton.gdb\\internal_polygons\\bunbury_1km"
+        # name of rasters
+        depth = 'Bun_depth_M_E'
+        speed = 'Bun_speed_M'
+    elif location == 'Busselton':
+        # polygon clip
+        extent = input_scenario + "map_work\\Busselton.gdb\\Internal_polygons\\busselton_1km"
+        # name of rasters
+        depth = 'Bus_depth_M_E'
+        speed = 'Bus_speed_M'
+    else:
+        print 'No recognisable location entered'
+
+    print 'location', location
+    print 'extent', extent
+
+    # Output locations
+    
+    hr_1_HAT = Tsunami_1_HAT +"highest_runup"
+    hr_1_MSL = Tsunami_1_MSL +"highest_runup"
+    hr_2_HAT = Tsunami_2_HAT +"highest_runup"
+    hr_2_MSL = Tsunami_2_MSL +"highest_runup"
+    hr_3_HAT = Tsunami_3_HAT +"highest_runup"
+    hr_3_MSL = Tsunami_3_MSL +"highest_runup"
+
+    depth_1_HAT = Tsunami_1_HAT + location + "_depth"
+    depth_1_MSL = Tsunami_1_MSL + location + "_depth"
+    depth_2_HAT = Tsunami_2_HAT + location + "_depth"
+    depth_2_MSL = Tsunami_2_MSL + location + "_depth"
+    depth_3_HAT = Tsunami_3_HAT + location + "_depth"
+    depth_3_MSL = Tsunami_3_MSL + location + "_depth"
+
+    speed_1_HAT = Tsunami_1_HAT + location + "_speed"
+    speed_1_MSL = Tsunami_1_MSL + location + "_speed"
+    speed_2_HAT = Tsunami_2_HAT + location + "_speed"
+    speed_2_MSL = Tsunami_2_MSL + location + "_speed"
+    speed_3_HAT = Tsunami_3_HAT + location + "_speed"
+    speed_3_MSL = Tsunami_3_MSL + location + "_speed"
+
+
+    # Input locations
+
+    in_depth_1_HAT = in_Tsunami_1_HAT + depth
+    in_depth_1_MSL = in_Tsunami_1_MSL + depth
+    in_depth_2_HAT = in_Tsunami_2_HAT + depth
+    in_depth_2_MSL = in_Tsunami_2_MSL + depth
+    in_depth_3_HAT = in_Tsunami_3_HAT + depth
+    in_depth_3_MSL = in_Tsunami_3_MSL + depth
+
+    in_speed_1_HAT = in_Tsunami_1_HAT + speed
+    in_speed_1_MSL = in_Tsunami_1_MSL + speed
+    in_speed_2_HAT = in_Tsunami_2_HAT + speed
+    in_speed_2_MSL = in_Tsunami_2_MSL + speed
+    in_speed_3_HAT = in_Tsunami_3_HAT + speed
+    in_speed_3_MSL = in_Tsunami_3_MSL + speed
+
+    in_hr_1_HAT = in_Tsunami_1_HAT + hr
+    in_hr_1_MSL = in_Tsunami_1_MSL + hr
+    in_hr_2_HAT = in_Tsunami_2_HAT + hr
+    in_hr_2_MSL = in_Tsunami_2_MSL + hr
+    in_hr_3_HAT = in_Tsunami_3_HAT + hr
+    in_hr_3_MSL = in_Tsunami_3_MSL + hr
+
+
+# Process: Extract by Mask
+    print 'Extract by mask for depth'
+    gp.ExtractByMask_sa(in_depth_1_HAT, extent, depth_1_HAT)
+    gp.ExtractByMask_sa(in_depth_1_MSL, extent, depth_1_MSL)
+    gp.ExtractByMask_sa(in_depth_2_HAT, extent, depth_2_HAT)
+    gp.ExtractByMask_sa(in_depth_2_MSL, extent, depth_2_MSL)
+    gp.ExtractByMask_sa(in_depth_3_HAT, extent, depth_3_HAT)
+    gp.ExtractByMask_sa(in_depth_3_MSL, extent, depth_3_MSL)
+
+    print 'Extract by mask for speed'
+    gp.ExtractByMask_sa(in_speed_1_HAT, extent, speed_1_HAT)
+    gp.ExtractByMask_sa(in_speed_1_MSL, extent, speed_1_MSL)
+    gp.ExtractByMask_sa(in_speed_2_HAT, extent, speed_2_HAT)
+    gp.ExtractByMask_sa(in_speed_2_MSL, extent, speed_2_MSL)
+    gp.ExtractByMask_sa(in_speed_3_HAT, extent, speed_3_HAT)
+    gp.ExtractByMask_sa(in_speed_3_MSL, extent, speed_3_MSL)
+
+
+# Process: Copy Features...
+
+print 'Copy Highest Runup'
+gp.CopyFeatures_management(in_hr_1_HAT, hr_1_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_1_MSL, hr_1_MSL, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_2_HAT, hr_2_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_2_MSL, hr_2_MSL, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_3_HAT, hr_3_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_3_MSL, hr_3_MSL, "", "0", "0", "0")
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/Inundation_polygon.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/Inundation_polygon.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/Inundation_polygon.py	(revision 7411)
@@ -0,0 +1,88 @@
+# ---------------------------------------------------------------------------
+# Inundation_line.py
+# Created on: Tue May 12 2009 01:50:45 PM
+#   (generated by ArcGIS/ModelBuilder)
+# Usage: Inundation_line <Bun_depth_M_E> <Bus_depth_M_E> <bunbury_1km> <busselton_1km> 
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+gp.overwriteoutput = 1
+
+# Set the necessary product code
+gp.SetProduct("ArcInfo")
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Analysis Tools.tbx")
+
+# Script arguments...
+time_dir1 = '20090327_152717_run_final_0.6_27283_Bt_kvanputt'
+time_dir2 = '20090330_120458_run_final_0_27283_Bt_kvanputt'
+time_dir3 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+time_dir4 = '20090327_160646_run_final_0_27255_Bt_kvanputt'
+time_dir5 = '20090324_140747_run_final_0.6_68693_Bt_kvanputt'
+time_dir6 = '20090327_161520_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6] 
+
+community = 'busselton'
+scenario = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\" + community +"_tsunami_scenario\\"
+output_folder = scenario + "anuga\\outputs\\"
+locations = ['bunbury', 'busselton']
+
+for time_dir in time_dirs:
+
+    raster = output_folder + time_dir + "\\raster.gdb\\"
+    
+    for location in locations:
+
+        # Local variables...
+        if location == 'bunbury':
+            # polygon clip
+            extent = scenario + "map_work\\Busselton.gdb\\internal_polygons\\bunbury_1km_clip"
+            # name of rasters
+            depth = raster + 'Bun_depth_M_E'
+            
+        elif location == 'busselton':
+            # polygon clip
+            extent = scenario + "map_work\\Busselton.gdb\\Internal_polygons\\busselton_1km_clip"
+            # name of rasters
+            depth = raster + 'Bus_depth_M_E'
+            
+        else:
+            print 'No recognisable location entered'
+
+        print 'location', location
+        print 'extent', extent
+
+        depth_raster = depth
+
+        # Local variables...
+        Output_raster = raster +"Temp_raster_"+ location
+        Output_polygon_features = raster +"Temp_polygon_"+ location
+        Output_Feature_Class = raster +"Temp_line_"+ location
+        Reclassification = "0 0.05 NODATA;0.05 4.5840001106262207 1"
+        Inundation = raster + "Inundation_" + location + "_polygon"
+        Inundation_line = raster + "Inundation_line"
+          
+        print 'Process: Reclassify'
+        gp.Reclassify_sa(depth, "Value", Reclassification, Output_raster, "DATA")
+        
+        print 'Process: Raster to Polygon'
+        gp.RasterToPolygon_conversion(Output_raster, Output_polygon_features, "SIMPLIFY", "VALUE")
+
+        print 'Process: Clip'
+        gp.Clip_analysis(Output_polygon_features, extent, Inundation, "")
+
+        print 'Process: Delete'
+        gp.Delete_management(Output_raster, "RasterDataset")
+        gp.Delete_management(Output_polygon_features, "FeatureClass")
Index: /anuga_work/production/wa/busselton/busselton_rerun/README.txt
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/README.txt	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/README.txt	(revision 7411)
@@ -0,0 +1,17 @@
+This area aims at collecting the best practices in setting up ANUGA models and
+show them as a running demo.
+
+The intent is to make setting up and running of models easier to do and more standardised (without compromising one bit of creativity, of course :-). One principle is that information should never have to be entered more than once.
+
+
+The ideas are:
+
+* Collect all elevation data files in lists for batch processing (as in Shark Bay 200&)
+
+* Roll all the urs2sts work into an ANUGA function (see ticket:317)
+ 
+* Get rid of kwargs and use project.* for all parameters and filenames.
+
+* Migrate towards unified anuga interface (as in the Patong scenario).
+
+*
Index: /anuga_work/production/wa/busselton/busselton_rerun/build_elevation.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/build_elevation.py	(revision 7411)
@@ -0,0 +1,100 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' # except', project.offshore_name5
+G = None
+for key in geospatial_data:
+    #if key == project.point_filenames[4] or key == project.ascii_filenames[1]:
+    #    # Skip these files for now
+    #    continue
+    
+    G += geospatial_data[key]
+        
+#print 'Clip combined geospatial data'
+##G_clip = G.clip_outside(project.poly_aoi1)
+##G_all = G_clip + geospatial_data[project.point_filenames[4]] 
+#G_clipped = G_all.clip(project.poly_all)
+#G_clip = G.clip(project.bounding_polygon)
+
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,167 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                zone=project.zone,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/export_results_max.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/export_results_max.py	(revision 7411)
@@ -0,0 +1,122 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+
+time_dir1 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140747_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090327_152717_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_160646_run_final_0_27255_Bt_kvanputt'
+time_dir5 = '20090327_161520_run_final_0_68693_Bt_kvanputt'
+time_dir6 = '20090330_120458_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1] #1,time_dir2, time_dir3, time_dir4, time_dir5]
+  
+
+##cellsize = 250
+cellsize = 20
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+area = ['Bunbury', 'Busselton']  # strings must match keys in var_equations below
+#area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            name2 = join(directory, time_dir, project.scenario_name)+'_time_35520_0'
+            name3 = join(directory, time_dir, project.scenario_name)+'_time_71040_0'
+
+            names = [name1] #, name2, name3]
+      
+            #asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/busselton/busselton_rerun/file_length.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/get_runup.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/get_runup.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/get_runup.py	(revision 7411)
@@ -0,0 +1,67 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from os.path import join
+from anuga.utilities.polygon import read_polygon
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+        
+# Application specific imports
+from setup_model import project  # Definition of file names and polygons
+import csv
+directory = project.output_folder
+
+time_dir1 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140747_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090327_152717_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_160646_run_final_0_27255_Bt_kvanputt'
+time_dir5 = '20090327_161520_run_final_0_68693_Bt_kvanputt'
+time_dir6 = '20090330_120458_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir6] #3, time_dir4, time_dir5]
+
+interior_region = []
+for region in project.interior_regions_data[:2]:
+    polygon = read_polygon(join(project.polygons_folder,
+                                region[0]))
+    interior_region.append(polygon)
+
+area_dictionary = {'Busselton': interior_region[0],
+                    'Bunbury' : interior_region[1]}
+
+area = ['Busselton', 'Bunbury'] 
+
+for time_dir in time_dirs:
+
+    basename = join(directory, time_dir, project.scenario_name)
+
+    out_file = basename+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+    print 'basename ',basename 
+
+    for which_area in area:
+        if which_area not in area_dictionary:
+            print 'Unrecognized variable name: %s' % which_area
+            break
+
+        polygon = area_dictionary[which_area]
+        
+        print 'Which area ',which_area
+
+        q, loc = get_maximum_inundation_data(basename+'.sww',
+                                             polygon=polygon, verbose=True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/busselton/busselton_rerun/get_runup_v2.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/get_runup_v2.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/get_runup_v2.py	(revision 7411)
@@ -0,0 +1,64 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from os.path import join
+from anuga.utilities.polygon import read_polygon
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+from anuga.shallow_water.data_manager import csv2polygons
+
+# Application specific imports
+from setup_model import project  # Definition of file names and polygons
+import csv
+directory = project.output_folder
+
+time_dir1 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140747_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090327_152717_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_160646_run_final_0_27255_Bt_kvanputt'
+time_dir5 = '20090327_161520_run_final_0_68693_Bt_kvanputt'
+time_dir6 = '20090330_120458_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1, time_dir4]
+
+
+# polygons is a dictionary of polygon data indexed by 'id'
+# values is a dictionary of polygon names indexed by 'id'
+polygons, values = csv2polygons(project.images)
+print 'Creating %d highest runup' % len(polygons)
+
+# create a dictionary {<polygon_name>: <polygon_data>, ...}
+area_dictionary = {}
+for id in polygons:
+    area_dictionary[values[id]] = polygons[id] 
+
+# for each time directory ...
+for time_dir in time_dirs:
+    print 'time_dir ',time_dir
+    basename = join(directory, time_dir, project.scenario_name)
+
+    out_file = basename+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+
+    # iterate over polygon names
+    for which_area in values.itervalues():
+        print 'which_area = %s' % which_area
+        polygon = area_dictionary[which_area]
+        
+        q, loc = get_maximum_inundation_data(basename+'.sww',
+                                             polygon=polygon, verbose=True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/busselton/busselton_rerun/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/get_timeseries.py	(revision 7411)
@@ -0,0 +1,34 @@
+"""
+Generate time series of nominated "gauges".
+Input: sww file from run_perth.py
+       gauges project.gauge_filename
+Output: csv files stage,speed,depth,elevation over time
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+Can run different sww files at the same time
+make sure if there is a second sww file that it is placed into a folder called sww2
+Can run different gauges at the same time - ie testing boundary index point
+"""
+
+from os import sep, rename, listdir, system
+from os.path import join
+from anuga.abstract_2d_finite_volumes.util import sww2csv_gauges,csv2timeseries_graphs
+import project
+
+directory = project.output_folder
+
+time_dir1 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+
+time_dirs = [time_dir1] #1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+print 'time directories', time_dirs
+
+for time_dir in time_dirs:
+    name = join(directory,time_dir,project.scenario_name)
+    gauge = project.gauges
+    sww2csv_gauges(name+'.sww',gauge,
+                   quantities = ['stage','speed','depth','elevation'],
+                   verbose=True)
+  
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/project.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/project.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/project.py	(revision 7411)
@@ -0,0 +1,262 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'busselton'
+scenario_folder = 'busselton_tsunami_scenario'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0.6              # difference between MSL and HAT in metres
+zone = 50               # specify zone of model
+event_number = 27255    # the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=80000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number, 'Bt']
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['busselton_v2',   # Topo
+                        'grid_250m_clip',
+                        'grid_250m_clip2'] # Busselton Topo
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['Busselton_Contour0.txt',    # Coastline
+                   'Busselton_BeachSurvey.txt', # Beach survey
+                   'Busselton_NavyFinal.txt',   # Bathymetry
+                   'Busselton_Chart.txt',       # Bathymetry Charts
+                   'Busselton_Digitised.txt',   # Digitised Fairsheet
+                   'Busselton_250m.txt',        # 250m
+                   'Bunbury_TIN.txt',           # Bunbury aoi TIN'd in ArcGIS
+                   'Busselton_TIN.txt',         # Busselton aoi TIN'd in ArcGIS
+                   'XYAHD_clip.txt']            # To extend boundary
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'bounding_polygon_new.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['busselton_1km.csv', 500],
+                         ['bunbury_1km.csv', 500],
+                         ['busselton_2km.csv', 10000],
+                         ['bunbury_2km.csv', 10000],
+                         ['island1.csv', 10000],
+                         ['island2.csv', 10000],
+                         ['coast_5km_d20m.csv', 40000]]
+
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing (no header)
+land_initial_conditions_filename = [['initial_condition_new.csv', 0],
+                                    ['initial_condition_marina.csv', 0]]
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = 'MH_gauges2.csv'
+
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = 'busselton_res_clip.csv' # from NEXIS
+
+# AREA OF IMAGES - Extent of each image to find out highest runup
+# Header - easting,northing,id,value
+# Used in get_runup.py
+images_filename = 'define_area_clip.csv'
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'thinned_boundary_ordering_extend.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_boundary_new.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+##mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+##multi_mux = False
+mux_input_filename = 'event.list'
+multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# ASCII export grid for Busselton
+xminBusselton = 340000
+xmaxBusselton = 352000
+yminBusselton = 6271500
+ymaxBusselton = 6280000
+
+# ASCII export grid for Bunbury
+xminBunbury = 369000
+xmaxBunbury = 381000
+yminBunbury = 6308000
+ymaxBunbury = 6316500
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# The absolute pathname for the image file
+# Used for get_runup.py
+if images_filename:
+    images = join(polygons_folder, images_filename)
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
Index: /anuga_work/production/wa/busselton/busselton_rerun/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,73 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from os.path import join
+from setup_model import project
+import csv
+
+directory = project.output_folder + sep
+
+time_dir1 = '20090324_134328_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140747_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090327_152717_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_160646_run_final_0_27255_Bt_kvanputt'
+time_dir5 = '20090327_161520_run_final_0_68693_Bt_kvanputt'
+time_dir6 = '20090330_120458_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir6] #, time_dir3, time_dir4, time_dir5, time_dir6]
+
+buildings = project.building_exposure
+
+for time_dir in time_dirs:
+    
+    time_dir_name = time_dir[-20:][:-12]
+    print time_dir_name
+       
+    building_marker = '_m_'+ time_dir_name
+    basename = join(directory, time_dir, project.scenario_name) #basename for the sww files 
+    
+    inundation_damage(basename, buildings, building_marker)
+    #add_depth_and_momentum2csv(name, buildings, building_marker)
+    
+    building_marker_dir_name = join(project.gauges_folder,
+                                    project.building_exposure_filename[:-4]) + building_marker + '.csv'
+    out_file = basename + '_res.csv'
+    print 'out file %s' %out_file
+    print 'building_marker_dir_name %s' %building_marker_dir_name
+    csv_fd = open(building_marker_dir_name, 'r')
+    output_file = open(out_file, 'w')
+
+    reader = csv.reader(csv_fd)
+    writer = csv.writer(output_file, lineterminator='\n')
+
+    for record in reader:
+       newline = record[-8:]
+       newline.insert(0,record[0])
+       newline.insert(1,record[1])
+       newline.insert(2,record[2])
+       writer.writerow(newline)
+       
+    print 'output file printed to: %s' %out_file
+    csv_fd.close()
+    output_file.close()
+     
+
+    
Index: /anuga_work/production/wa/busselton/busselton_rerun/run_model.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/run_model.py	(revision 7411)
@@ -0,0 +1,163 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/busselton/busselton_rerun/setup_model.py
===================================================================
--- /anuga_work/production/wa/busselton/busselton_rerun/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/busselton_rerun/setup_model.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+for filename, MSL in project.land_initial_conditions_filename:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.land_initial_conditions.append([polygon, MSL])
+
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/busselton/export_results.py
===================================================================
--- /anuga_work/production/wa/busselton/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/export_results.py	(revision 7411)
@@ -0,0 +1,83 @@
+import project, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+time_dir = '20080815_103708_run_final_0.6_polyline_newExtent_kvanputt'
+
+
+cellsize = 25
+#cellsize = 150
+#timestep = 0
+directory = project.output_dir
+name = directory+sep+time_dir+sep+project.scenario_name
+
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+
+
+is_parallel = False
+#is_parallel = True
+
+if is_parallel == True: nodes = 4
+print 'output dir:', name
+
+#var = [0,4] 
+#var = [2,3] # depth and Speed
+var = [2,3] # elevation, depth and Speed
+
+
+for which_var in var:
+    if which_var == 0:  # Stage
+        outname = name + '_stage'
+        quantityname = 'stage'
+
+    if which_var == 1:  # Absolute Momentum
+        outname = name + '_momentum'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+    if which_var == 2:  # Depth
+        outname = name + '_depth'
+        quantityname = 'stage-elevation'  
+
+    if which_var == 3:  # Speed
+        outname = name + '_speed'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+    if which_var == 4:  # Elevation
+        outname = name + '_elevation'
+        quantityname = 'elevation'  #Elevation
+
+    if is_parallel == True:
+    #    print 'is_parallel',is_parallel
+        for i in range(0,nodes):
+            namei = name + '_P%d_%d' %(i,nodes)
+            outnamei = outname + '_P%d_%d' %(i,nodes)
+            print 'start sww2dem for sww file %d' %(i)
+            sww2dem(namei, basename_out = outnamei,
+                        quantity = quantityname,
+                        #timestep = timestep,
+                        cellsize = cellsize,      
+                        easting_min = project_grad.e_min_area,
+                        easting_max = project_grad.e_max_area,
+                        northing_min = project_grad.n_min_area,
+                        northing_max = project_grad.n_max_area,        
+                        reduction = max, 
+                        verbose = True,
+                        format = 'asc')
+    else:
+        print 'start sww2dem'
+        sww2dem(name, basename_out = outname,
+                    quantity = quantityname,
+                    #timestep = timestep,
+                    cellsize = cellsize,
+                    number_of_decimal_places = 4,
+                    #easting_min = project_grad.e_min_area,
+                    #easting_max = project_grad.e_max_area,
+                    #northing_min = project_grad.n_min_area,
+                    #northing_max = project_grad.n_max_area,        
+                    reduction = max, 
+                    verbose = True,
+                    format = 'asc')
+
Index: /anuga_work/production/wa/busselton/export_results_max.py
===================================================================
--- /anuga_work/production/wa/busselton/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/export_results_max.py	(revision 7411)
@@ -0,0 +1,127 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_dir
+
+##time_dir1 = '20081217_101310_run_final_0_27283_250m_none_dt_kvanputt'
+##time_dir2 = '20081217_115336_run_final_0_27283_250m_none_dp_kvanputt'
+###time_dir1 = '20080924_123626_run_final_0_27283_250m_all_kvanputt' # This uses the 250m bathymetry with all interior polygons
+###time_dir2 = '20080912_154716_run_final_0_27283_alpha0.1_kvanputt' # This uses original bathyemetry data
+###time_dir3 = '20080924_123601_run_final_0_27283_250m_none_kvanputt' # This uses the 250m bathymetry without any interior polygons
+##time_dirs = [time_dir1, time_dir2]#, time_dir3]
+
+time_dir1 = '20081211_154006_run_final_0.6_27255_alpha0.1_kvanputt'
+##time_dir2 = '20081211_162311_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081211_162346_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081211_162433_run_final_0.6_68693_alpha0.1_kvanputt'
+##time_dir5 = '20081211_162656_run_final_0.6_27283_alpha0.1_kvanputt'
+##time_dir6 = '20081211_162744_run_final_0_27283_alpha0.1_kvanputt'
+##
+time_dirs = [time_dir1] #5, time_dir4]# , time_dir4, time_dir5, time_dir6]
+  
+
+##cellsize = 20
+cellsize = 5
+
+timestep = None    # None means no timestep!
+#timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+area = ['Bunbury']  # strings must match keys in var_equations below
+##area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['depth']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = directory+time_dir+sep+project.scenario_name
+            name2 = directory+time_dir+sep+project.scenario_name+'_time_39600_0'
+            name3 = directory+time_dir+sep+project.scenario_name+'_time_79200_0'
+
+            names = [name1, name2, name3]
+      
+            asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+                asc_name.append(outname + '.asc')
+    
+            maxasc_outname = directory+time_dir+sep+project.scenario_name+'_'+which_area+'_'+which_var+'_max.asc'
+
+            print 'max asc outname ', maxasc_outname
+            print 'asc_name ', str(asc_name)
+            
+            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/busselton/get_gauges.py
===================================================================
--- /anuga_work/production/wa/busselton/get_gauges.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/get_gauges.py	(revision 7411)
@@ -0,0 +1,58 @@
+import os
+from os import sep
+import project
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+from anuga.utilities.polygon import inside_polygon
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+        
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+        
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+        
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
Index: /anuga_work/production/wa/busselton/get_runup.py
===================================================================
--- /anuga_work/production/wa/busselton/get_runup.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/get_runup.py	(revision 7411)
@@ -0,0 +1,58 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+        
+# Application specific imports
+import project  # Definition of file names and polygons
+import csv
+directory = project.output_dir
+
+time_dir1 = '20081211_154006_run_final_0.6_27255_alpha0.1_kvanputt'
+##time_dir2 = '20081211_162311_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081211_162346_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081211_162433_run_final_0.6_68693_alpha0.1_kvanputt'
+##time_dir5 = '20081211_162656_run_final_0.6_27283_alpha0.1_kvanputt'
+##time_dir6 = '20081211_162744_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1] #4, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+
+area_dictionary = {'Busselton': project.poly_aoi1,
+                    'Bunbury' : project.poly_aoi2}
+
+area = ['Busselton', 'Bunbury'] 
+
+for time_dir in time_dirs:
+
+    name = directory+time_dir+sep+project.scenario_name
+
+    out_file = name+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+    print 'name ',name 
+
+    for which_area in area:
+        if which_area not in area_dictionary:
+            print 'Unrecognized variable name: %s' % which_area
+            break
+
+        polygon = area_dictionary[which_area]
+        
+        print 'Which area ',which_area
+
+        q, loc = get_maximum_inundation_data (name+'.sww', polygon = polygon, verbose= True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/busselton/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/busselton/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/get_timeseries.py	(revision 7411)
@@ -0,0 +1,41 @@
+"""
+Generate time series of nominated "gauges".
+Input: sww file from run_perth.py
+       gauges project.gauge_filename
+Output: csv files stage,speed,depth,elevation over time
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+Can run different sww files at the same time
+make sure if there is a second sww file that it is placed into a folder called sww2
+Can run different gauges at the same time - ie testing boundary index point
+"""
+
+from os import sep, rename, listdir, system
+from anuga.abstract_2d_finite_volumes.util import sww2csv_gauges,csv2timeseries_graphs
+import project
+
+directory = project.output_dir
+
+##time_dir1 = '20081009_184721_run_final_0.6_68693_alpha0.1_kvanputt'+sep+'gauge'
+##time_dir2 = '20081031_120316_run_final_0_68693_alpha0.1_kvanputt'+sep+'gauge'
+##time_dir3 = '20081031_120515_run_final_0_27255_alpha0.1_kvanputt'+sep+'gauge'
+##time_dir4 = '20081031_120642_run_final_0_27283_alpha0.1_kvanputt'+sep+'gauge'
+##time_dir5 = '20081031_120753_run_final_0.6_27283_alpha0.1_kvanputt'+sep+'gauge'
+##time_dir6 = '20081111_113832_run_final_0.6_27255_alpha0.1_kvanputt'+sep+'gauge'
+##
+##time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+##time_dir1 = '20081217_115336_run_final_0_27283_250m_none_dp_kvanputt'
+time_dir6 = '20081111_113832_run_final_0.6_27255_alpha0.1_kvanputt'
+
+time_dirs = [time_dir6]
+
+for time_dir in time_dirs:
+    name = directory+time_dir+sep+project.scenario_name 
+    gauge = project.gauges_dir_name
+    sww2csv_gauges(name+'.sww',gauge,
+                   quantities = ['stage','speed','depth','elevation'],
+                   verbose=True)
+  
+
Index: /anuga_work/production/wa/busselton/locate_indigeneous.py
===================================================================
--- /anuga_work/production/wa/busselton/locate_indigeneous.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/locate_indigeneous.py	(revision 7411)
@@ -0,0 +1,41 @@
+#
+# script to determine which communities are located in study region
+# 31 October 2006
+#
+
+def community_in_extent(filename,extent,zone,fid_out):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+
+    line1 = lines[0]
+    line11 = line1.split(',')
+    for i in range(len(line11)):
+        if line11[i].strip('\n').strip(' ') == 'LATITUDE': lat_index = i
+        if line11[i].strip('\n').strip(' ') == 'LONGITUDE': lon_index = i
+        if line11[i].strip('\n').strip(' ') == 'COMMUNITY': name_index = i
+
+    from anuga.coordinate_transforms.redfearn import convert_from_latlon_to_utm
+    from anuga.utilities.polygon import plot_polygons, is_inside_polygon
+    
+    for line in lines[1:]:
+        fields = line.split(',')
+        point, zone1 = convert_from_latlon_to_utm(latitudes=[fields[lat_index]],\
+                                                 longitudes=[fields[lon_index]])
+        if zone1 == zone:
+            v = is_inside_polygon(point,extent,verbose=False)
+            if v == True:
+                p = point[0]
+                s = '%s, %.2f, %.2f\n' %(fields[name_index], p[0], p[1])
+                fid_out.write(s)
+    return
+
+import project
+
+filename = project.community_filename
+filename_out = project.community_busselton
+fid_out = open(filename_out, 'w')
+extent = project.polyAll
+zone = 50
+
+community_in_extent(filename,extent,zone,fid_out)
Index: /anuga_work/production/wa/busselton/ph2_compare.py
===================================================================
--- /anuga_work/production/wa/busselton/ph2_compare.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/ph2_compare.py	(revision 7411)
@@ -0,0 +1,139 @@
+"""
+Read in event time series and determine max stage for Ph2 comparison
+Compare with Green's function (no focussing)
+Compare with ANUGA outputs (full model, 250m no polys, 250m all polys)
+Leharne Fountain and Jane Sexton, 2008
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid, figure
+from os import sep
+
+###################################################
+# Relevant definitions
+###################################################
+
+def get_max_boundary_data(filename):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[3]))
+    return mean(stage)
+
+def get_stage_data(filename,depth,no_models):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    mean_stages = zeros((len(depth),no_models), Float)
+    max_stages = zeros((len(depth),no_models), Float)
+    for i in range(no_models):
+        stage5 = []
+        stage10 = []
+        stage20 = []
+        stage50 = []
+        for line in lines[1:]:
+            fields = line.split(',')
+            x = float(fields[0])
+            # based on csv file output from ArcGIS: depth, x,y, no poly, all poly, and orig
+            y = float(fields[i+3]) 
+            if x == -depth[0]:
+                stage5.append(y)
+            if x == -depth[1]:
+                stage10.append(y)
+            if x == -depth[2]:
+                stage20.append(y)
+            if x == -depth[3]:
+                stage50.append(y)
+            
+        mean_stages[:,i] = [mean(stage5), mean(stage10), mean(stage20), mean(stage50)]
+        max_stages[:,i] = [max(stage5), max(stage10), max(stage20), max(stage50)]
+    return mean_stages, max_stages
+
+###################################################
+# Determine max stage at boundary points
+###################################################
+
+event_number = 27283
+boundary_mean = get_max_boundary_data(project.boundaries_dir+str(event_number)+sep+'max_sts_stage.csv')
+
+###################################################
+# Read in max data from all models
+###################################################
+
+from Numeric import zeros, Float
+directory = project.home+project.state+sep+project.scenario+sep+'map_work'
+depth = [5.0,10.,20.,50.]
+no_models = 3
+filename = directory + sep + 'Busselton_ph2_compare_v2.csv'
+mean_stages, max_stages = get_stage_data(filename, depth, no_models)
+
+###################################################
+# Compare with Green's function and plot
+###################################################
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 100.
+d2 = arange(d1,1,-0.1)
+h1 = boundary_mean
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+
+ion()
+figure(1)
+plot(depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Busselton')
+legend(['original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Busselton_mean_ORIG_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(2)
+plot(depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Busselton')
+legend(['250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Busselton_mean_250AP_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(3)
+plot(depth,mean_stages[:,0],'ob',depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Busselton')
+legend(['250m no poly','250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Busselton_mean_ALL_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(4)
+plot(depth,max_stages[:,0],'ob',depth,max_stages[:,1],'+r',depth,max_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (max stage) versus Green\'s approximation \n \
+for event 27283 at Busselton')
+legend(['250m no poly','250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Busselton_max_ALL_' + str(event_number) + '_mean'
+savefig(figname)
+close('all')
+
Index: /anuga_work/production/wa/busselton/ph2_compare_table.py
===================================================================
--- /anuga_work/production/wa/busselton/ph2_compare_table.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/ph2_compare_table.py	(revision 7411)
@@ -0,0 +1,206 @@
+"""
+Read in event time series and determine max stage for Ph2 comparison
+Compare with Green's function (no focussing)
+Compare with ANUGA outputs (full model, 250m no polys, 250m all polys)
+Leharne Fountain and Jane Sexton, 2008
+"""
+
+import project
+#from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid, figure
+from os import sep
+
+###################################################
+# Relevant definitions
+###################################################
+
+def get_max_boundary_data(filename):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[3]))
+    return mean(stage)
+
+def get_stage_data(filename,depth,no_models):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    mean_stages = zeros((len(depth),no_models), Float)
+    max_stages = zeros((len(depth),no_models), Float)
+    for i in range(no_models):
+        stage5 = []
+        stage10 = []
+        stage20 = []
+        stage50 = []
+        for line in lines[1:]:
+            fields = line.split(',')
+            x = float(fields[0])
+            # based on csv file output from ArcGIS: depth, x,y, no poly, all poly, and orig
+            y = float(fields[i+3]) 
+            if x == -depth[0]:
+                stage5.append(y)
+            if x == -depth[1]:
+                stage10.append(y)
+            if x == -depth[2]:
+                stage20.append(y)
+            if x == -depth[3]:
+                stage50.append(y)
+            
+        mean_stages[:,i] = [mean(stage5), mean(stage10), mean(stage20), mean(stage50)]
+        max_stages[:,i] = [max(stage5), max(stage10), max(stage20), max(stage50)]
+    return mean_stages, max_stages
+
+def calc_M(mean_stages,boundary_mean):
+    #M_value=zeros(no_models,Float)
+    M_value=mean_stages[1,:]/boundary_mean
+    return M_value
+
+def calc_errors(mean_stages,no_models):
+    abs_error = zeros(len(mean_stages[1,:]),Float)
+    rel_error = zeros(len(mean_stages[1,:]),Float)
+    for i in range(len(mean_stages[1,:])):
+        abs_error[i] = (mean_stages[1,i]-mean_stages[1,no_models-1])
+        rel_error[i]= (abs_error[i]/mean_stages[1,no_models-1])*100
+    return abs_error,rel_error
+
+###################################################
+# Determine max stage at boundary points
+###################################################
+
+event_number = 68693
+boundary_mean = get_max_boundary_data(project.boundaries_dir+str(event_number)+sep+'max_sts_stage.csv')
+
+###################################################
+# Read in max data from all models
+###################################################
+
+from Numeric import zeros, Float
+directory = project.home+project.state+sep+project.scenario+sep+'map_work'
+depth = [5.0,10.,20.,50.]
+no_models = 2
+#plot?
+plot_flag = False
+#Table??
+table_flag = True
+filename = directory + sep + 'Busselton_Ph2_compare_'+str(event_number)+'.csv'
+
+mean_stages, max_stages = get_stage_data(filename, depth, no_models)
+print mean_stages
+###################################################
+# Compare with Green's function and plot
+###################################################
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 100.
+d2 = arange(d1,1,-0.1)
+h1 = boundary_mean
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+
+###################################################
+#calculate M values (scaling of 100 m depth mean to 10 m)
+###################################################
+M_value = calc_M(mean_stages,boundary_mean)
+
+
+###################################################
+#calculate absolute and relative errors 
+###################################################
+abs_error,rel_error=calc_errors(mean_stages,no_models)
+
+
+##if plot_flag==True:
+##    ion()
+##    figure(1)
+##    plot(depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Busselton')
+##    legend(['original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Busselton_mean_ORIG_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(2)
+##    plot(depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Busselton')
+##    legend(['250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Busselton_mean_250AP_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(3)
+##    plot(depth,mean_stages[:,0],'ob',depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Busselton')
+##    legend(['250m no poly','250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Busselton_mean_ALL_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(4)
+##    plot(depth,max_stages[:,0],'ob',depth,max_stages[:,1],'+r',depth,max_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (max stage) versus Green\'s approximation \n \
+##    for event 27283 at Busselton')
+##    legend(['250m no poly','250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Busselton_max_ALL_' + str(event_number) + '_mean'
+##    savefig(figname)
+##    close('all')
+
+if table_flag==True:
+    import csv
+    csvfile = directory+sep+'ph2compare_Busselton_max_ALL_' + str(event_number) + '_mean.csv'
+    fid1 = open(csvfile,'w')
+    writer = csv.writer(fid1,delimiter=',',)
+
+    if no_models==1:
+        writer.writerow(('depth (m)','250m no poly'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0]))
+        writer.writerow(('100',boundary_mean,))
+        writer.writerow(('M-value',M_value[0]))
+        #writer.writerow(('Absolute Error', abs_error[0],abs_error[1]))
+        #writer.writerow(('Relative Error %', rel_error[0],rel_error[1]))
+
+    if no_models==2:
+        writer.writerow(('depth (m)','250m no poly','original'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0],mean_stages[i,1]))
+        writer.writerow(('100',boundary_mean,boundary_mean))
+        writer.writerow(('M-value',M_value[0],M_value[1]))
+        writer.writerow(('Absolute Error', abs_error[0],abs_error[1]))
+        writer.writerow(('Relative Error %', rel_error[0],rel_error[1]))
+        
+    if no_models==3:
+        writer.writerow(('depth (m)','250m no poly','250m poly','original'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0],mean_stages[i,1],mean_stages[i,2]))
+        writer.writerow(('100',boundary_mean,boundary_mean,boundary_mean))
+        writer.writerow(('M-value',M_value[0],M_value[1],M_value[2]))
+        writer.writerow(('Absolute Error', abs_error[0],abs_error[1],abs_error[2]))
+        writer.writerow(('Relative Error %', rel_error[0],rel_error[1],rel_error[2]))
+
+    fid1.close()
+    
+    
Index: /anuga_work/production/wa/busselton/project.py
===================================================================
--- /anuga_work/production/wa/busselton/project.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/project.py	(revision 7411)
@@ -0,0 +1,275 @@
+"""Common filenames and locations for elevation, meshes and outputs.
+This script is the heart of all scripts in the folder
+"""
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, is_inside_polygon, number_mesh_triangles
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+
+#------------------------------------------------------------------------------
+# Directory setup
+#------------------------------------------------------------------------------
+# Note: INUNDATIONHOME is the inundation directory, not the data directory.
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent diruser = get_user_name()
+muxhome = getenv('MUXHOME')
+user = get_user_name()
+host = get_host_name()
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S',localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S',gmtime()) 
+build_time = time+'_build'
+run_time = time+'_run'
+
+#------------------------------------------------------------------------------
+# Initial Conditions
+#------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'busselton'
+scenario = 'busselton_tsunami_scenario'
+
+# Model specific parameters. One or all can be changed each time the
+# run_scenario script is executed
+tide = 0              #0.6
+#event_number = 27255 # Java 9.3 worst case for Perth
+#event_number = 68693 # Sumatra 9.2
+event_number = 27283  # Java 9.3 original
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             
+finaltime=80000         # final time for simulation
+
+setup='final'  # Final can be replaced with trial or basic.
+               # Either will result in a coarser mesh that will allow a
+               # faster, but less accurate, simulation.
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=4
+    yieldstep=60
+
+#------------------------------------------------------------------------------
+# Revision numbers - for comparisons study
+#------------------------------------------------------------------------------
+rev_num = 'newExtent'
+#rev_num = '5449'
+#rev_num = '4695' # 2nd Sept 2007
+#rev_num = '4743' # 3nd Oct 2007
+#rev_num = '4777' # 1st Nov 2007
+#rev_num = '4874' # 3rd Dec 2007
+#rev_num = '4901' # 3rd Jan 2007
+#rev_num = '4990' # 5th Feb 2007
+#rev_num = '5103' # 3rd March 2007
+#rev_num = '5120' # 5th March 2007
+#rev_num = '5140' # 7th March 2007
+#rev_num = '5160' # 11th March 2007
+#rev_num = '5185' # 1st April 2007
+#rev_num = '5273' # 2nd May 2007
+
+
+#------------------------------------------------------------------------------
+# Output Filename
+#------------------------------------------------------------------------------
+# Important to distinguish each run - ensure str(user) is included!
+# Note, the user is free to include as many parameters as desired
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(event_number)+'_'+ 'alpha' +str(alpha)+'_'+str(user)
+
+#------------------------------------------------------------------------------
+# Input Data
+#------------------------------------------------------------------------------
+
+# elevation data used in build_busselton.py
+# onshore data: format ascii grid with accompanying projection file
+onshore_name = 'busselton_v2_gda94_mga50' 
+# coastline: format x,y,elevation (with title)
+coast_name = 'Busselton_Contour0.txt'
+coast_name1 = 'Busselton_BeachSurvey.txt'
+# bathymetry: format x,y,elevation (with title)
+offshore_name = 'Busselton_NavyFinal.txt'
+offshore_name1 = 'Busselton_Chart.txt'
+offshore_name2 = 'Busselton_Digitised.txt'
+offshore_name3 = 'Busselton_250m.txt' # for areas that were heading to zero - 2005 Bathymetry grid
+offshore_name4 = 'DPI.txt' # for area within Bunbury 500 mesh less than zero generated from TIN
+offshore_name5 = 'topo_20m_buss_1km' # for area within Busselton 500 mesh less than zero generated from TIN
+
+# gauges - used in get_timeseries.py
+#gauge_name = scenario_name+'.txt'
+#gauge_name = 'Gauges.csv'
+gauge_name = 'MH_gauges.csv'
+# buildings - used in run_building_inundation.py
+building = 'busselton_res_clip'
+
+
+# BOUNDING POLYGON - used in build_boundary.py and run_busselton.py respectively
+# NOTE: when files are put together the points must be in sequence - for ease go clockwise!
+# Check the run_busselton.py for boundary_tags
+# thinned ordering file from Hazard Map: format is index,latitude,longitude (with title)
+order_filename = 'thinned_boundary_ordering.csv'
+#landward bounding points
+landward = 'landward_bounding_polygon.csv'
+
+#------------------------------------------------------------------------------
+# Output Elevation Data
+#------------------------------------------------------------------------------
+# Output filename for elevation
+# this is a combination of all the data (utilisied in build_boundary)
+combined_name ='busselton_combined_elevation'
+combined_smaller_name = 'busselton_combined_elevation_smaller'
+
+#------------------------------------------------------------------------------
+# Directory Structure
+#------------------------------------------------------------------------------
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+boundaries_dir = anuga_dir+'boundaries'+ sep 
+output_dir = anuga_dir+'outputs'+sep
+gauges_dir = anuga_dir+'gauges'+sep
+meshes_dir = anuga_dir+'meshes'+sep
+
+#------------------------------------------------------------------------------
+# Location of input and output data
+#------------------------------------------------------------------------------
+# where the input data sits
+onshore_in_dir_name = topographies_in_dir + onshore_name #topo
+coast_in_dir_name = topographies_in_dir + coast_name #coastline
+coast_in_dir_name1 = topographies_in_dir + coast_name1 #beach survey
+offshore_in_dir_name = topographies_in_dir + offshore_name #bathymetry
+offshore_in_dir_name1 = topographies_in_dir + offshore_name1 #bathymetry Charts
+offshore_in_dir_name2 = topographies_in_dir + offshore_name2 #Digitised Fairsheet
+offshore_in_dir_name3 = topographies_in_dir + offshore_name3 #250m
+offshore_in_dir_name4 = topographies_in_dir + offshore_name4 #Bunbury DPI
+offshore_in_dir_name5 = topographies_in_dir + offshore_name5 #Busselton Topo
+
+# where the output data sits
+onshore_dir_name = topographies_dir + onshore_name
+
+coast_dir_name = topographies_dir + coast_name
+coast_dir_name1 = topographies_dir + coast_name1
+
+offshore_dir_name = topographies_dir + offshore_name
+offshore_dir_name1 = topographies_dir + offshore_name1
+offshore_dir_name2 = topographies_dir + offshore_name2
+offshore_dir_name3 = topographies_dir + offshore_name3
+offshore_dir_name4 = topographies_dir + offshore_name4
+offshore_dir_name5 = topographies_dir + offshore_name5
+
+# where the combined elevation file sits
+combined_dir_name = topographies_dir + combined_name
+combined_smaller_name_dir = topographies_dir + combined_smaller_name
+
+# where the mesh sits (this is created during the run_busselton.py)
+meshes_dir_name = meshes_dir + scenario_name+'.msh'
+
+# where the boundary ordering files sit (this is used within build_boundary.py)
+order_filename_dir = boundaries_dir + order_filename
+
+# where the landward points of boundary extent sit (this is used within run_busselton.py)
+landward_dir = boundaries_dir + landward
+
+# where the event sts files sits (this is created during the build_boundary.py)
+boundaries_dir_event = boundaries_dir + str(event_number) + sep
+boundaries_dir_mux = muxhome
+
+# where the directory of the output filename sits
+output_build_time_dir = output_dir+build_time+dir_comment+sep   #used for build_busselton.py
+output_run_time_dir = output_dir+run_time+dir_comment+sep       #used for run_busselton.py
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#w here the directory of the gauges sit
+gauges_dir_name = gauges_dir + gauge_name       #used for get_timeseries.py
+building_in_dir_name = gauges_dir + building + '.csv'    #used for run_building_inundation.py
+
+#------------------------------------------------------------------------------
+# Interior region definitions
+#------------------------------------------------------------------------------
+
+#Land, to set the initial stage/water to be offcoast only
+poly_mainland = read_polygon(polygons_dir+'initial_condition.csv')
+
+#Land, to set the initial stage/water to be offcoast only
+poly_marina = read_polygon(polygons_dir+'initial_condition_marina.csv')
+
+# Initial bounding polygon for data clipping 
+poly_all = read_polygon(polygons_dir+'poly_all_extend.csv')
+res_poly_all = 100000*res_factor
+
+# Area of Interest 1 (Busselton)
+poly_aoi1 = read_polygon(polygons_dir+'busselton_1km.csv')
+res_aoi1 = 500*res_factor
+
+# Area of Interest 2 (Bunbury)
+poly_aoi2 = read_polygon(polygons_dir+'bunbury_1km.csv')
+res_aoi2 = 500*res_factor
+
+# Area of Significance 1 (Busselton)
+poly_aos1 = read_polygon(polygons_dir+'busselton_2km.csv')
+res_aos1 = 10000*res_factor
+
+# Area of Significance 2 (Bunbury)
+poly_aos2 = read_polygon(polygons_dir+'busselton_2km.csv')
+res_aos2 = 10000*res_factor
+
+# Refined areas
+# Polygon designed to islands
+poly_aos3 = read_polygon(polygons_dir+'island1.csv')
+res_aos3 = 10000*res_factor
+poly_aos4 = read_polygon(polygons_dir+'island2.csv')
+res_aos4 = 10000*res_factor
+
+# Shallow water 1
+poly_sw1 = read_polygon(polygons_dir+'coast_5km_d20m.csv')
+res_sw1 = 40000*res_factor
+
+# Combined all regions, must check that all are included!
+interior_regions = [[poly_aoi1,res_aoi1],[poly_aoi2,res_aoi2]
+                     ,[poly_aos1,res_aos1],[poly_aos2,res_aos2]
+                     ,[poly_aos3,res_aos3],[poly_aos4,res_aos4]
+                     ,[poly_sw1,res_sw1]]
+
+    
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+print 'min estimated number of triangles', trigs_min
+   
+#------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#------------------------------------------------------------------------------
+
+# exporting asc grid for Busselton
+xminBusselton = 340000
+xmaxBusselton = 352000
+yminBusselton = 6271500
+ymaxBusselton = 6280000
+
+# exporting asc grid for Bunbury
+xminBunbury = 369000
+xmaxBunbury = 381000
+yminBunbury = 6308000
+ymaxBunbury = 6316500
+
Index: /anuga_work/production/wa/busselton/project_250m.py
===================================================================
--- /anuga_work/production/wa/busselton/project_250m.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/project_250m.py	(revision 7411)
@@ -0,0 +1,225 @@
+"""Common filenames and locations for elevation, meshes and outputs.
+This script is the heart of all scripts in the folder
+"""
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, is_inside_polygon, number_mesh_triangles
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+
+#------------------------------------------------------------------------------
+# Directory setup
+#------------------------------------------------------------------------------
+# Note: INUNDATIONHOME is the inundation directory, not the data directory.
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent diruser = get_user_name()
+muxhome = getenv('MUXHOME')
+user = get_user_name()
+host = get_host_name()
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S',localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S',gmtime()) 
+build_time = time+'_build'
+run_time = time+'_run'
+
+#------------------------------------------------------------------------------
+# Initial Conditions
+#------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'busselton'
+scenario = 'busselton_tsunami_scenario'
+
+# Model specific parameters. One or all can be changed each time the
+# run_scenario script is executed
+tide = 0                #0.6
+#event_number = 27255   # linked to hazard map
+event_number = 27283
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             
+finaltime=80000         # final time for simulation
+
+interior_mesh = 'none' # Can have 'all' or 'none' for Phase 2 study
+
+setup='final'  # Final can be replaced with trial or basic.
+               # Either will result in a coarser mesh that will allow a
+               # faster, but less accurate, simulation.
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=4
+    yieldstep=60
+
+#------------------------------------------------------------------------------
+# Output Filename
+#------------------------------------------------------------------------------
+# Important to distinguish each run - ensure str(user) is included!
+# Note, the user is free to include as many parameters as desired
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(event_number)+'_250m_' + str(interior_mesh) +'_dp_'+str(user)
+
+#------------------------------------------------------------------------------
+# Input Data
+#------------------------------------------------------------------------------
+
+# elevation data used in build_busselton.py
+# onshore data: format ascii grid with accompanying projection file
+onshore_name = 'grid_250m_2005' 
+
+# gauges - used in get_timeseries.py
+gauge_name = 'busselton.csv'
+gauge_name2 = 'thinned_MGA50.csv'
+
+# BOUNDING POLYGON - used in build_boundary.py and run_busselton.py respectively
+# NOTE: when files are put together the points must be in sequence - for ease go clockwise!
+# Check the run_busselton.py for boundary_tags
+# thinned ordering file from Hazard Map: format is index,latitude,longitude (with title)
+order_filename = 'thinned_boundary_ordering.csv'
+#landward bounding points
+landward = 'landward_bounding_polygon.csv'
+
+#------------------------------------------------------------------------------
+# Output Elevation Data
+#------------------------------------------------------------------------------
+# Output filename for elevation
+# this is a combination of all the data (utilisied in build_boundary)
+combined_name ='busselton_combined_elevation_250m'
+
+#------------------------------------------------------------------------------
+# Directory Structure
+#------------------------------------------------------------------------------
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+boundaries_dir = anuga_dir+'boundaries'+ sep 
+output_dir = anuga_dir+'outputs'+sep
+gauges_dir = anuga_dir+'gauges'+sep
+meshes_dir = anuga_dir+'meshes'+sep
+
+#------------------------------------------------------------------------------
+# Location of input and output data
+#------------------------------------------------------------------------------
+# where the input data sits
+onshore_in_dir_name = topographies_in_dir + onshore_name
+
+# where the output data sits
+onshore_dir_name = topographies_dir + onshore_name
+
+# where the combined elevation file sits
+combined_dir_name = topographies_dir + combined_name
+
+# where the mesh sits (this is created during the run_busselton.py)
+meshes_dir_name = meshes_dir + scenario_name+ interior_mesh +'.msh'
+
+# where the boundary ordering files sit (this is used within build_boundary.py)
+order_filename_dir = boundaries_dir + order_filename
+
+# where the landward points of boundary extent sit (this is used within run_busselton.py)
+landward_dir = boundaries_dir + landward
+
+# where the event sts files sits (this is created during the build_boundary.py)
+boundaries_dir_event = boundaries_dir + str(event_number) + sep
+boundaries_dir_mux = muxhome
+
+# where the directory of the output filename sits
+output_build_time_dir = output_dir+build_time+dir_comment+sep   #used for build_busselton.py
+output_run_time_dir = output_dir+run_time+dir_comment+sep       #used for run_busselton.py
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#w here the directory of the gauges sit
+gauges_dir_name = gauges_dir + gauge_name       #used for get_timeseries.py
+gauges_dir_name2 = gauges_dir + gauge_name2     #used for get_timeseries.py
+
+#------------------------------------------------------------------------------
+# Interior region definitions
+#------------------------------------------------------------------------------
+
+#Land, to set the initial stage/water to be offcoast only
+poly_mainland = read_polygon(polygons_dir+'initial_condition.csv')
+
+# Initial bounding polygon for data clipping 
+poly_all = read_polygon(polygons_dir+'poly_all_extend.csv')
+res_poly_all = 100000*res_factor
+
+# Area of Interest 1 (Busselton)
+poly_aoi1 = read_polygon(polygons_dir+'busselton_1km.csv')
+res_aoi1 = 500*res_factor
+
+# Area of Interest 2 (Bunbury)
+poly_aoi2 = read_polygon(polygons_dir+'bunbury_1km.csv')
+res_aoi2 = 500*res_factor
+
+# Area of Significance 1 (Busselton)
+poly_aos1 = read_polygon(polygons_dir+'busselton_2km.csv')
+res_aos1 = 10000*res_factor
+
+# Area of Significance 2 (Bunbury)
+poly_aos2 = read_polygon(polygons_dir+'busselton_2km.csv')
+res_aos2 = 10000*res_factor
+
+# Refined areas
+# Polygon designed to islands
+poly_aos3 = read_polygon(polygons_dir+'island1.csv')
+res_aos3 = 10000*res_factor
+poly_aos4 = read_polygon(polygons_dir+'island2.csv')
+res_aos4 = 10000*res_factor
+
+# Shallow water 1
+poly_sw1 = read_polygon(polygons_dir+'coast_5km_d20m.csv')
+res_sw1 = 40000*res_factor
+
+# Combined all regions, must check that all are included!
+
+if interior_mesh =='all':
+    print'Mesh = all'
+    interior_regions = [[poly_aoi1,res_aoi1],[poly_aoi2,res_aoi2]
+                     ,[poly_aos1,res_aos1],[poly_aos2,res_aos2]
+                     ,[poly_aos3,res_aos3],[poly_aos4,res_aos4]
+                     ,[poly_sw1,res_sw1]]
+if interior_mesh =='none': 
+    print'Mesh = none'
+    interior_regions = []
+     
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+print 'min estimated number of triangles', trigs_min
+   
+#------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#------------------------------------------------------------------------------
+
+# exporting asc grid for Busselton
+xminBusselton = 340000
+xmaxBusselton = 352000
+yminBusselton = 6271500
+ymaxBusselton = 6280000
+
+# exporting asc grid for Bunbury
+xminBunbury = 369000
+xmaxBunbury = 381000
+yminBunbury = 6308000
+ymaxBunbury = 6316500
+
Index: /anuga_work/production/wa/busselton/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/busselton/run_boundary_points.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/run_boundary_points.py	(revision 7411)
@@ -0,0 +1,47 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+
+# # Related major packages
+# from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import URS_points_needed_to_file, \
+     urs_ungridded2sww
+import project                 # Definition of file names and polygons
+
+#-----------------------------------------------------------------------------
+# run_boundary_points
+#-----------------------------------------------------------------------------
+  
+LL_LAT = -50.0          #ll_lat - lower left latitude, in decimal degrees
+LL_LONG = 80.0          #ll-long - lower left longitude, in decimal degrees
+GRID_SPACING = 2.0/60.0 #grid_spacing - in deciamal degrees
+LAT_AMOUNT = 4800       #lat_amount - number of latitudes 
+LONG_AMOUNT = 3600      #long_amount- number of longs
+ZONE = 50
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+poly = project.poly_all
+print "poly", poly
+print "project.boundaries_in_dir_name",project.boundaries_in_dir_name
+URS_points_needed_to_file(project.boundaries_in_dir_name,poly, ZONE,
+                          LL_LAT, LL_LONG,GRID_SPACING,LAT_AMOUNT, LONG_AMOUNT,export_csv=True)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True)
+#urs_ungridded2sww(project.boundaries_in_dir_name2, project.boundaries_dir_name5, mean_stage= project.tide,  verbose=True)
Index: /anuga_work/production/wa/busselton/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/busselton/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,70 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+import project
+import csv
+
+directory = project.output_dir
+
+time_dir1 = '20081211_154006_run_final_0.6_27255_alpha0.1_kvanputt'
+##time_dir2 = '20081211_162311_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081211_162346_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081211_162433_run_final_0.6_68693_alpha0.1_kvanputt'
+##time_dir5 = '20081211_162656_run_final_0.6_27283_alpha0.1_kvanputt'
+##time_dir6 = '20081211_162744_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1] #4, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+
+buildings = project.building_in_dir_name
+
+for time_dir in time_dirs:
+    
+    time_dir_name = time_dir[-25:][:-18]
+       
+    building_marker = '_m_'+ time_dir_name
+    name = directory+time_dir+sep+project.scenario_name #basename for the sww files 
+    
+    inundation_damage(name, buildings, building_marker)
+    #add_depth_and_momentum2csv(name, buildings, building_marker)
+    
+    building_marker_dir_name = project.gauges_dir + project.building + building_marker + '.csv'
+    out_file = directory+time_dir+ sep+'busselton_res.csv'
+    print 'out file %s' %out_file
+    print 'building_marker_dir_name %s' %building_marker_dir_name
+    csv_fd = open(building_marker_dir_name, 'r')
+    output_file = open(out_file, 'w')
+
+    reader = csv.reader(csv_fd)
+    writer = csv.writer(output_file, lineterminator='\n')
+
+    for record in reader:
+       newline = record[-8:]
+       newline.insert(0,record[0])
+       newline.insert(1,record[1])
+       newline.insert(2,record[2])
+       writer.writerow(newline)
+       
+    print 'output file printed to: %s' %out_file
+    csv_fd.close()
+    output_file.close()
+     
+
+    
Index: /anuga_work/production/wa/busselton/run_busselton.py
===================================================================
--- /anuga_work/production/wa/busselton/run_busselton.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/run_busselton.py	(revision 7411)
@@ -0,0 +1,245 @@
+"""Script for running a tsunami inundation scenario for busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data is compiled into a pts file through build_busselton.py
+and a simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_busselton.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.shallow_water_domain import Transmissive_stage_zero_momentum_boundary
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid, create_sts_boundary
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+from anuga.geospatial_data.geospatial_data import find_optimal_smoothing_parameter
+from polygon import Polygon_function
+    
+# Application specific imports
+import project  # Definition of file names and polygons
+numprocs = 1
+myid = 0
+
+def run_model(**kwargs):
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+    print "Processor Name:",get_processor_name()
+
+    #copy script must be before screen_catcher
+
+    print 'output_dir',kwargs['output_dir']
+    
+    copy_code_files(kwargs['output_dir'],__file__, 
+             dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+    store_parameters(**kwargs)
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print "Processor Name:",get_processor_name()
+    
+    #-----------------------------------------------------------------------
+    # Domain definitions
+    #-----------------------------------------------------------------------
+
+    # Read in boundary from ordered sts file
+    urs_bounding_polygon=create_sts_boundary(os.path.join(project.boundaries_dir_event,project.scenario_name))
+
+    # Reading the landward defined points, this incorporates the original clipping
+    # polygon minus the 100m contour
+    landward_bounding_polygon = read_polygon(project.landward_dir)
+
+    # Combine sts polyline with landward points
+    bounding_polygon = urs_bounding_polygon + landward_bounding_polygon
+    
+    # counting segments
+    N = len(urs_bounding_polygon)-1
+
+    # boundary tags refer to project.landward 4 points equals 5 segments start at N
+    boundary_tags={'back': [N+1,N+2,N+3,N+4, N+5, N+6, N+7], 'side': [N,N+8], 'ocean': range(N)}
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a tagged
+    # boundary and interior regions defined in project.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    # IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+        
+    print 'start create mesh from regions'
+
+    create_mesh_from_regions(bounding_polygon,
+                         boundary_tags=boundary_tags,
+                         maximum_triangle_area=project.res_poly_all,
+                         interior_regions=project.interior_regions,
+                         filename=project.meshes_dir_name,
+                         use_cache=False,
+                         verbose=False)
+   
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    domain = Domain(project.meshes_dir_name, use_cache=False, verbose=True)
+    print 'memory usage before del domain',mem_usage()
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    print 'Setup initial conditions'
+
+    # sets the initial stage in the offcoast region only
+    IC = Polygon_function( [(project.poly_mainland, 0),(project.poly_marina, 0)], default = kwargs['tide'],
+                             geo_reference = domain.geo_reference)
+    domain.set_quantity('stage', IC)
+    #domain.set_quantity('stage',kwargs['tide'] )
+    domain.set_quantity('friction', kwargs['friction']) 
+    
+    print 'Start Set quantity',kwargs['elevation_file']
+
+    domain.set_quantity('elevation', 
+                        filename = kwargs['elevation_file'],
+                        use_cache = False,
+                        verbose = True,
+                        alpha = kwargs['alpha'])
+    print 'Finished Set quantity'
+
+##   #------------------------------------------------------
+##    # Distribute domain to implement parallelism !!!
+##    #------------------------------------------------------
+##
+##    if numprocs > 1:
+##        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2)                 # Apply second order scheme
+    domain.set_minimum_storable_height(0.01)    # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.tight_slope_limiters = 1
+    print 'domain id', id(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+   
+    boundary_urs_out=project.boundaries_dir_event + sep + project.scenario_name
+
+    Br = Reflective_boundary(domain)
+    Bt = Transmissive_stage_zero_momentum_boundary(domain)
+    Bd = Dirichlet_boundary([kwargs['tide'],0,0])
+    
+    print 'Available boundary tags', domain.get_boundary_tags()
+    Bf = Field_boundary(boundary_urs_out+'.sts',  # Change from file_boundary
+                   domain, mean_stage= project.tide,
+                   time_thinning=1,
+                   default_boundary=Bd,
+                   use_cache=True,
+                   verbose = True,
+                   boundary_polygon=bounding_polygon)
+
+    domain.set_boundary({'back': Br,
+                         'side': Bt,
+                         'ocean': Bf}) 
+
+    kwargs['input_start_time']=domain.starttime
+
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #--------------------------------------------------------------------
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = project.yieldstep, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = False): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')
+
+    # these outputs should be checked with the resultant inundation map
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'Simulation took %.2f seconds' %(time.time()-t0)
+
+    #kwargs 'completed' must be added to write the final parameters to file
+    kwargs['completed']=str(time.time()-t0)
+     
+    store_parameters(**kwargs)
+     
+    print 'memory usage before del domain1',mem_usage()
+    
+    
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    
+    kwargs={}
+    kwargs['file_name']=project.dir_comment
+    kwargs['finaltime']=project.finaltime
+    kwargs['output_dir']=project.output_run_time_dir
+    kwargs['elevation_file']=project.combined_dir_name+'.pts'
+    kwargs['scenario_name']=project.scenario_name
+    kwargs['tide']=project.tide
+    kwargs['alpha'] = project.alpha
+    kwargs['friction']=project.friction
+    #kwargs['num_cpu']=numprocs
+    #kwargs['host']=project.host
+    #kwargs['starttime']=project.starttime
+    #kwargs['yieldstep']=project.yieldstep
+    #kwargs['user']=project.user
+    #kwargs['time_thinning'] = project.time_thinning
+      
+    run_model(**kwargs)
+      
+   
Index: /anuga_work/production/wa/busselton/run_busselton_250m.py
===================================================================
--- /anuga_work/production/wa/busselton/run_busselton_250m.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/run_busselton_250m.py	(revision 7411)
@@ -0,0 +1,240 @@
+"""Script for running a tsunami inundation scenario for busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project_250m.polygon,
+the elevation data is compiled into a pts file through build_busselton.py
+and a simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_busselton.py)
+       information from project file
+Outputs: sww file stored in project_250m.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.shallow_water_domain import Transmissive_stage_zero_momentum_boundary
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid, create_sts_boundary
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+from anuga.geospatial_data.geospatial_data import find_optimal_smoothing_parameter
+from polygon import Polygon_function
+    
+# Application specific imports
+import project_250m  # Definition of file names and polygons
+numprocs = 1
+myid = 0
+
+def run_model(**kwargs):
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+    print "Processor Name:",get_processor_name()
+
+    #copy script must be before screen_catcher
+
+    print 'output_dir',kwargs['output_dir']
+    
+    copy_code_files(kwargs['output_dir'],__file__, 
+             dirname(project_250m.__file__)+sep+ project_250m.__name__+'.py' )
+
+    store_parameters(**kwargs)
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print "Processor Name:",get_processor_name()
+    
+    #-----------------------------------------------------------------------
+    # Domain definitions
+    #-----------------------------------------------------------------------
+
+    # Read in boundary from ordered sts file
+    urs_bounding_polygon=create_sts_boundary(os.path.join(project_250m.boundaries_dir_event,project_250m.scenario_name))
+
+    # Reading the landward defined points, this incorporates the original clipping
+    # polygon minus the 100m contour
+    landward_bounding_polygon = read_polygon(project_250m.landward_dir)
+
+    # Combine sts polyline with landward points
+    bounding_polygon = urs_bounding_polygon + landward_bounding_polygon
+    
+    # counting segments
+    N = len(urs_bounding_polygon)-1
+
+    # boundary tags refer to project_250m.landward 4 points equals 5 segments start at N
+    boundary_tags={'back': [N+1,N+2,N+3,N+4, N+5], 'side': [N,N+6], 'ocean': range(N)}
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a tagged
+    # boundary and interior regions defined in project_250m.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    # IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+        
+    print 'start create mesh from regions'
+
+    create_mesh_from_regions(bounding_polygon,
+                         boundary_tags=boundary_tags,
+                         maximum_triangle_area=project_250m.res_poly_all,
+                         interior_regions=project_250m.interior_regions,
+                         filename=project_250m.meshes_dir_name,
+                         use_cache=True,
+                         verbose=True)
+   
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    domain = Domain(project_250m.meshes_dir_name, use_cache=False, verbose=True)
+    print 'memory usage before del domain',mem_usage()
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    print 'Setup initial conditions'
+
+    # sets the initial stage in the offcoast region only
+    IC = Polygon_function( [(project_250m.poly_mainland, 0)], default = kwargs['tide'],
+                             geo_reference = domain.geo_reference)
+    domain.set_quantity('stage', IC)
+    #domain.set_quantity('stage',kwargs['tide'] )
+    domain.set_quantity('friction', kwargs['friction']) 
+    
+    print 'Start Set quantity',kwargs['elevation_file']
+
+    domain.set_quantity('elevation', 
+                        filename = kwargs['elevation_file'],
+                        use_cache = False,
+                        verbose = True,
+                        alpha = kwargs['alpha'])
+    print 'Finished Set quantity'
+
+##   #------------------------------------------------------
+##    # Distribute domain to implement parallelism !!!
+##    #------------------------------------------------------
+##
+##    if numprocs > 1:
+##        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2)                 # Apply second order scheme
+    domain.set_minimum_storable_height(0.01)    # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.tight_slope_limiters = 1
+    print 'domain id', id(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+   
+    boundary_urs_out=project_250m.boundaries_dir_event + sep + project_250m.scenario_name
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([kwargs['tide'],0,0])
+    Bp = Dirichlet_boundary([kwargs['tide']-1,0,0])
+    Bt = Transmissive_stage_zero_momentum_boundary(domain)
+    
+    print 'Available boundary tags', domain.get_boundary_tags()
+    Bf = Field_boundary(boundary_urs_out+'.sts',  # Change from file_boundary
+                   domain, mean_stage= project_250m.tide,
+                   time_thinning=1,
+                   default_boundary=Bd,
+                   use_cache=True,
+                   verbose = True,
+                   boundary_polygon=bounding_polygon)
+
+    domain.set_boundary({'back': Br,
+                         'side': Bt,
+                         'ocean': Bf}) 
+
+    kwargs['input_start_time']=domain.starttime
+
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #--------------------------------------------------------------------
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = project_250m.yieldstep, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = False): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')
+
+    # these outputs should be checked with the resultant inundation map
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'Simulation took %.2f seconds' %(time.time()-t0)
+
+    #kwargs 'completed' must be added to write the final parameters to file
+    kwargs['completed']=str(time.time()-t0)
+     
+    store_parameters(**kwargs)
+     
+    print 'memory usage before del domain1',mem_usage()
+    
+    
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    
+    kwargs={}
+    kwargs['file_name']=project_250m.dir_comment
+    kwargs['finaltime']=project_250m.finaltime
+    kwargs['output_dir']=project_250m.output_run_time_dir
+    kwargs['elevation_file']=project_250m.combined_dir_name+'.pts'
+    kwargs['scenario_name']=project_250m.scenario_name
+    kwargs['tide']=project_250m.tide
+    kwargs['alpha'] = project_250m.alpha
+    kwargs['friction']=project_250m.friction
+     
+    run_model(**kwargs)
+      
+   
Index: /anuga_work/production/wa/busselton/standardised_version/README.txt
===================================================================
--- /anuga_work/production/wa/busselton/standardised_version/README.txt	(revision 7411)
+++ /anuga_work/production/wa/busselton/standardised_version/README.txt	(revision 7411)
@@ -0,0 +1,17 @@
+This area aims at collecting the best practices in setting up ANUGA models and
+show them as a running demo.
+
+The intent is to make setting up and running of models easier to do and more standardised (without compromising one bit of creativity, of course :-). One principle is that information should never have to be entered more than once.
+
+
+The ideas are:
+
+* Collect all elevation data files in lists for batch processing (as in Shark Bay 200&)
+
+* Roll all the urs2sts work into an ANUGA function (see ticket:317)
+ 
+* Get rid of kwargs and use project.* for all parameters and filenames.
+
+* Migrate towards unified anuga interface (as in the Patong scenario).
+
+*
Index: /anuga_work/production/wa/busselton/standardised_version/build_elevation.py
===================================================================
--- /anuga_work/production/wa/busselton/standardised_version/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/standardised_version/build_elevation.py	(revision 7411)
@@ -0,0 +1,100 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' # except', project.offshore_name5
+G = None
+for key in geospatial_data:
+    #if key == project.point_filenames[4] or key == project.ascii_filenames[1]:
+    #    # Skip these files for now
+    #    continue
+    
+    G += geospatial_data[key]
+        
+#print 'Clip combined geospatial data'
+##G_clip = G.clip_outside(project.poly_aoi1)
+##G_all = G_clip + geospatial_data[project.point_filenames[4]] 
+#G_clipped = G_all.clip(project.poly_all)
+#G_clip = G.clip(project.bounding_polygon)
+
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/busselton/standardised_version/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/busselton/standardised_version/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/standardised_version/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,169 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                zone=project.zone,
+                mean_stage=0.0,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                mean_stage=0.0,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/busselton/standardised_version/export_results_max.py
===================================================================
--- /anuga_work/production/wa/busselton/standardised_version/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/standardised_version/export_results_max.py	(revision 7411)
@@ -0,0 +1,128 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+##time_dir1 = '20081217_101310_run_final_0_27283_250m_none_dt_kvanputt'
+##time_dir2 = '20081217_115336_run_final_0_27283_250m_none_dp_kvanputt'
+###time_dir1 = '20080924_123626_run_final_0_27283_250m_all_kvanputt' # This uses the 250m bathymetry with all interior polygons
+###time_dir2 = '20080912_154716_run_final_0_27283_alpha0.1_kvanputt' # This uses original bathyemetry data
+###time_dir3 = '20080924_123601_run_final_0_27283_250m_none_kvanputt' # This uses the 250m bathymetry without any interior polygons
+##time_dirs = [time_dir1, time_dir2]#, time_dir3]
+
+time_dir1 = '20090130_165532_run_final_0.6_27255_extend_dt_kvanputt'
+##time_dir2 = '20081211_162311_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081211_162346_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081211_162433_run_final_0.6_68693_alpha0.1_kvanputt'
+##time_dir5 = '20081211_162656_run_final_0.6_27283_alpha0.1_kvanputt'
+##time_dir6 = '20081211_162744_run_final_0_27283_alpha0.1_kvanputt'
+##
+time_dirs = [time_dir1] #5, time_dir4]# , time_dir4, time_dir5, time_dir6]
+  
+
+cellsize = 250
+##cellsize = 5
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+#area = ['Bunbury', 'Busselton']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            #name2 = join(directory, time_dir, project.scenario_name)+'_time_39600_0'
+            #name3 = join(directory, time_dir, project.scenario_name)+'_time_79200_0'
+
+            names = [name1] #, name2]#, name3]
+      
+           # asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/busselton/standardised_version/file_length.py
===================================================================
--- /anuga_work/production/wa/busselton/standardised_version/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/standardised_version/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/busselton/standardised_version/project.py
===================================================================
--- /anuga_work/production/wa/busselton/standardised_version/project.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/standardised_version/project.py	(revision 7411)
@@ -0,0 +1,252 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'busselton'
+scenario_folder = 'busselton_tsunami_scenario'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0                # difference between MSL and HAT in metres
+zone = 50               # specify zone of model
+event_number = 27197    # the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=80000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number]
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['busselton_v2',   # Topo
+                        'grid_250m_clip'] # Busselton Topo
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['Busselton_Contour0.txt',    # Coastline
+                   'Busselton_BeachSurvey.txt', # Beach survey
+                   'Busselton_NavyFinal.txt',   # Bathymetry
+                   'Busselton_Chart.txt',       # Bathymetry Charts
+                   'Busselton_Digitised.txt',   # Digitised Fairsheet
+                   'Busselton_250m.txt',        # 250m
+                   'Bunbury_TIN.txt',           # Bunbury aoi TIN'd in ArcGIS
+                   'Busselton_TIN.txt',         # Busselton aoi TIN'd in ArcGIS
+                   'XYAHD_clip.txt']            # To extend boundary
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'bounding_polygon.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['busselton_1km.csv', 500],
+                         ['bunbury_1km.csv', 500],
+                         ['busselton_2km.csv', 10000],
+                         ['bunbury_2km.csv', 10000],
+                         ['island1.csv', 10000],
+                         ['island2.csv', 10000],
+                         ['coast_5km_d20m.csv', 40000]]
+
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing (no header)
+land_initial_conditions_filename = [['initial_condition_extend.csv', 0],
+                                    ['initial_condition_marina.csv', 0]]
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = 'gauges.csv'
+
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = 'busselton_res_clip.csv' # from NEXIS
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'thinned_boundary_ordering_extend.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_boundary_extend.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+##mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+##multi_mux = False
+mux_input_filename = 'event.list'
+multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# ASCII export grid for Busselton
+xminBusselton = 340000
+xmaxBusselton = 352000
+yminBusselton = 6271500
+ymaxBusselton = 6280000
+
+# ASCII export grid for Bunbury
+xminBunbury = 369000
+xmaxBunbury = 381000
+yminBunbury = 6308000
+ymaxBunbury = 6316500
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
Index: /anuga_work/production/wa/busselton/standardised_version/run_model.py
===================================================================
--- /anuga_work/production/wa/busselton/standardised_version/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/standardised_version/run_model.py	(revision 7411)
@@ -0,0 +1,163 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bd,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/busselton/standardised_version/setup_model.py
===================================================================
--- /anuga_work/production/wa/busselton/standardised_version/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/busselton/standardised_version/setup_model.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+for filename, MSL in project.land_initial_conditions_filename:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.land_initial_conditions.append([polygon, MSL])
+
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/carnarvon/Arc_asc2raster_GDA94z49.py
===================================================================
--- /anuga_work/production/wa/carnarvon/Arc_asc2raster_GDA94z49.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/Arc_asc2raster_GDA94z49.py	(revision 7411)
@@ -0,0 +1,92 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\carnarvon_tsunami_scenario\\"
+output_dir="anuga\\outputs\\"
+
+##time_dir1 = '20081209_155247_run_final_0_27255_250m_none_lfountai'
+##time_dir2 = '20081209_161626_run_final_0_68693_250m_none_lfountai'
+##time_dirs = [time_dir1, time_dir2]
+
+
+##time_dir1 = '20081202_084220_run_final_1_27283_alpha0.1_kvanputt'
+##time_dir2 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081202_084132_run_final_1_68693_alpha0.1_kvanputt'
+time_dir4 = '20081202_084025_run_final_0_68693_alpha0.1_kvanputt'
+time_dir5 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir6 = '20081201_103449_run_final_0_27283_alpha0.1_kvanputt'
+##
+time_dirs = [time_dir4, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder = scenario_dir + output_dir + time_dir + '\\'
+    raster_gbd = folder + 'raster.gdb'
+    land = scenario_dir + "map_work\\Carnarvon.gdb\\land_initial_condition_all"
+    ocean = scenario_dir + "map_work\\Carnarvon.gdb\\ocean_initial_condition"
+    
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    print time_dir
+    
+    #replication dictionary
+    replicate = (('carnarvon', ''),#('time_39900_0', 'b'), ('time_79800_0', 'c'),
+                 ('_', ''), ('max','_M'), ('depth','_dep_'),
+                 ('speed', '_speed_'), ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*stage_max.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+        print 'Output DEM ',output_DEM
+       
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection' 
+        gp.DefineProjection_management(output_DEM,"PROJCS['GDA_1994_MGA_Zone_49',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994'"
+                                       ",SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0]"
+                                       ",UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator']"
+                                       ",PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0]"
+                                       ",PARAMETER['Central_Meridian',111.0],PARAMETER['Scale_Factor',0.9996]"
+                                       ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+
+ 
+##        print 'Process: Extract by Mask'
+##        output_extract = output_DEM + '_E'
+##        print 'Output Extract ',output_extract
+##        gp.ExtractByMask_sa(output_DEM, ocean, output_extract)
+
+
Index: /anuga_work/production/wa/carnarvon/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/carnarvon/Arc_txt2feature_class_res.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/Arc_txt2feature_class_res.py	(revision 7411)
@@ -0,0 +1,45 @@
+# ---------------------------------------------------------------------------
+# txt2fc_res.py
+# Created on: Mon Dec 01 2008 11:36:17 AM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\carnarvon_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+##time_dir1 = '20081202_084220_run_final_1_27283_alpha0.1_kvanputt'
+##time_dir2 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081202_084132_run_final_1_68693_alpha0.1_kvanputt'
+time_dir4 = '20081202_084025_run_final_0_68693_alpha0.1_kvanputt'
+time_dir5 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+time_dir6 = '20081201_103449_run_final_0_27283_alpha0.1_kvanputt'
+
+
+time_dirs = [time_dir4, time_dir5, time_dir6]#, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'carnarvon_res.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+    
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "longitude", "latitude", layer, "GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "carnarvon_res", "", "OBJECTID OBJECTID true true false 4 Long 0 10 ,First,#,carnarvon_res.csv_Features,OBJECTID,-1,-1;LONGITUDE LONGITUDE true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,LONGITUDE,-1,-1;LATITUDE LATITUDE true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,LATITUDE,-1,-1;STRUCT_INUNDATED STRUCT_INUNDATED true true false 4 Long 0 10 ,First,#,carnarvon_res.csv_Features,STRUCT_INUNDATED,-1,-1;STRUCT_DAMAGE_fraction STRUCT_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,STRUCT_DAMAGE_fraction,-1,-1;COLLAPSE_CSV_INFO COLLAPSE_CSV_INFO true true false 255 Text 0 0 ,First,#,carnarvon_res.csv_Features,COLLAPSE_CSV_INFO,-1,-1;MAX_DEPTH_m MAX_DEPTH_m true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,MAX_DEPTH_m,-1,-1;STRUCT_COLLAPSED STRUCT_COLLAPSED true true false 255 Text 0 0 ,First,#,carnarvon_res.csv_Features,STRUCT_COLLAPSED,-1,-1;STRUCT_LOSS STRUCT_LOSS true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,STRUCT_LOSS,-1,-1;CONTENTS_DAMAGE_fraction CONTENTS_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,CONTENTS_DAMAGE_fraction,-1,-1;CONTENTS_LOSS CONTENTS_LOSS true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,CONTENTS_LOSS,-1,-1", "")
+
Index: /anuga_work/production/wa/carnarvon/Arc_txt2feature_class_runup.py
===================================================================
--- /anuga_work/production/wa/carnarvon/Arc_txt2feature_class_runup.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/Arc_txt2feature_class_runup.py	(revision 7411)
@@ -0,0 +1,53 @@
+# ---------------------------------------------------------------------------
+# txt2fc_field.py
+# Created on: Thu Nov 27 2008 01:48:26 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\carnarvon_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20081202_084220_run_final_1_27283_alpha0.1_kvanputt'
+time_dir2 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+time_dir3 = '20081202_084132_run_final_1_68693_alpha0.1_kvanputt'
+time_dir4 = '20081202_084025_run_final_0_68693_alpha0.1_kvanputt'
+time_dir5 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+time_dir6 = '20081201_103449_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'carnarvon_runup.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "x", "y", layer, "PROJCS['GDA_1994_MGA_Zone_49',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994'"
+                                       ",SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0]"
+                                       ",UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator']"
+                                       ",PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0]"
+                                       ",PARAMETER['Central_Meridian',111.0],PARAMETER['Scale_Factor',0.9996]"
+                                       ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "carnarvon_runup", "", "area area true true false 255 Text 0 0 ,First,#,carnarvon_runup.csv_Features,area,-1,-1;q q true true false 8 Double 0 0 ,First,#,carnarvon_runup.csv_Features,q,-1,-1;x x true true false 8 Double 0 0 ,First,#,carnarvon_runup.csv_Features,x,-1,-1;y y true true false 8 Double 0 0 ,First,#,carnarvon_runup.csv_Features,y,-1,-1", "")
+
+
+  
Index: /anuga_work/production/wa/carnarvon/build_boundary_27255.py
===================================================================
--- /anuga_work/production/wa/carnarvon/build_boundary_27255.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/build_boundary_27255.py	(revision 7411)
@@ -0,0 +1,150 @@
+"""
+Script for building boundary to run a tsunami inundation scenario for carnarvon,
+WA, Australia.  The boundary is sourced from the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_carnarvon.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+# location of mux files
+# Note, this may change when all mux files are on the GA network
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+# Note, this is specific to the event and will be supplied by David.
+# In time, this will become more automated.
+urs_filenames = [
+    os.path.join(dir,'Java-0017-z.grd'),  
+    os.path.join(dir,'Java-0018-z.grd'),
+    os.path.join(dir,'Java-0019-z.grd'),
+    os.path.join(dir,'Java-0022-z.grd'),  
+    os.path.join(dir,'Java-0023-z.grd'),  
+    os.path.join(dir,'Java-0024-z.grd'),  
+    os.path.join(dir,'Java-0027-z.grd'),  
+    os.path.join(dir,'Java-0028-z.grd'),  
+    os.path.join(dir,'Java-0031-z.grd'),  
+    os.path.join(dir,'Java-0032-z.grd')]  
+ 
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 10: #change per event
+
+    weight_factor = 30.84050 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #------------------------------------------------------------------------------
+    # Get maxium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+    #------------------------------------------------------------------------------
+    # Get minium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+    #------------------------------------------------------------------------------
+    # End of the get gauges
+    #------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/carnarvon/build_boundary_27283.py
===================================================================
--- /anuga_work/production/wa/carnarvon/build_boundary_27283.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/build_boundary_27283.py	(revision 7411)
@@ -0,0 +1,186 @@
+"""
+Script for building boundary to run tsunami inundation scenario for carnarvon,
+WA, Australia.  The boundary is based on the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_carnarvon.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+urs_filenames = [
+    os.path.join(dir,'Java-0000-z.grd'),
+    os.path.join(dir,'Java-0001-z.grd'),
+    os.path.join(dir,'Java-0002-z.grd'),
+    os.path.join(dir,'Java-0003-z.grd'),
+    os.path.join(dir,'Java-0005-z.grd'), 
+    os.path.join(dir,'Java-0006-z.grd'), 
+    os.path.join(dir,'Java-0007-z.grd'), 
+    os.path.join(dir,'Java-0008-z.grd'), 
+    os.path.join(dir,'Java-0010-z.grd'), 
+    os.path.join(dir,'Java-0011-z.grd'), 
+    os.path.join(dir,'Java-0012-z.grd'), 
+    os.path.join(dir,'Java-0013-z.grd'),  
+    os.path.join(dir,'Java-0015-z.grd'),  
+    os.path.join(dir,'Java-0016-z.grd'),  
+    os.path.join(dir,'Java-0017-z.grd'),  
+    os.path.join(dir,'Java-0018-z.grd'),  
+    os.path.join(dir,'Java-0020-z.grd'),  
+    os.path.join(dir,'Java-0021-z.grd'),  
+    os.path.join(dir,'Java-0022-z.grd'),  
+    os.path.join(dir,'Java-0023-z.grd'),  
+    os.path.join(dir,'Java-0025-z.grd'),  
+    os.path.join(dir,'Java-0026-z.grd'),  
+    os.path.join(dir,'Java-0027-z.grd'),  
+    os.path.join(dir,'Java-0028-z.grd'),  
+    os.path.join(dir,'Java-0029-z.grd'),  
+    os.path.join(dir,'Java-0030-z.grd'),  
+    os.path.join(dir,'Java-0031-z.grd'),  
+    os.path.join(dir,'Java-0032-z.grd'),  
+    os.path.join(dir,'Java-0033-z.grd'),  
+    os.path.join(dir,'Java-0034-z.grd'),  
+    os.path.join(dir,'Java-0035-z.grd'),  
+    os.path.join(dir,'Java-0036-z.grd'),  
+    os.path.join(dir,'Java-0037-z.grd'),  
+    os.path.join(dir,'Java-0038-z.grd'),  
+    os.path.join(dir,'Java-0039-z.grd'),  
+    os.path.join(dir,'Java-0040-z.grd'),  
+    os.path.join(dir,'Java-0041-z.grd'),  
+    os.path.join(dir,'Java-0042-z.grd'),  
+    os.path.join(dir,'Java-0043-z.grd'),  
+    os.path.join(dir,'Java-0044-z.grd'),  
+    os.path.join(dir,'Java-0045-z.grd'),  
+    os.path.join(dir,'Java-0046-z.grd'),  
+    os.path.join(dir,'Java-0047-z.grd'),
+    os.path.join(dir,'Java-0048-z.grd')]    
+ 
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 44: #change per event
+
+# AS per David Burbidge email on Friday 4th July the mag 9.3 event
+# has 1m worth of slip on each sub fault therefore mutliple each unit
+# source by the slip (10.4544) and sum the 44 time series together to
+# get the time series for this event at the points on your boundary. 
+
+    weight_factor = 10.4544 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+#------------------------------------------------------------------------------
+# Get Maxium wave height throughout timeseries at each index point
+#------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+#------------------------------------------------------------------------------
+# Get Minium wave height throughout timeseries at each index point
+#------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+#------------------------------------------------------------------------------
+# End of the get gauges
+#------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/carnarvon/build_boundary_68693.py
===================================================================
--- /anuga_work/production/wa/carnarvon/build_boundary_68693.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/build_boundary_68693.py	(revision 7411)
@@ -0,0 +1,152 @@
+"""
+Script for building boundary to run a tsunami inundation scenario for onslow,
+WA, Australia.  The boundary is sourced from the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_onslow.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+# location of mux files
+# Note, this may change when all mux files are on the GA network
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+# Note, this is specific to the event and will be supplied by David.
+# In time, this will become more automated.
+urs_filenames = [
+    os.path.join(dir,'Sumatra-0026-z.grd'),
+    os.path.join(dir,'Sumatra-0027-z.grd'),
+    os.path.join(dir,'Sumatra-0028-z.grd'),
+    os.path.join(dir,'Sumatra-0029-z.grd'),
+    os.path.join(dir,'Sumatra-0030-z.grd'),
+    os.path.join(dir,'Sumatra-0031-z.grd'),
+    os.path.join(dir,'Sumatra-0033-z.grd'),
+    os.path.join(dir,'Sumatra-0034-z.grd'),
+    os.path.join(dir,'Sumatra-0035-z.grd'),
+    os.path.join(dir,'Sumatra-0037-z.grd'),
+    os.path.join(dir,'Sumatra-0038-z.grd'),
+    os.path.join(dir,'Sumatra-0039-z.grd')]
+        
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 12: #change per event
+
+    weight_factor = 27.3603 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #------------------------------------------------------------------------------
+    # Get maxium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+    #------------------------------------------------------------------------------
+    # Get minium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+    #------------------------------------------------------------------------------
+    # End of the get gauges
+    #------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/carnarvon/build_carnarvon.py
===================================================================
--- /anuga_work/production/wa/carnarvon/build_carnarvon.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/build_carnarvon.py	(revision 7411)
@@ -0,0 +1,126 @@
+"""
+Script for building the elevation data to run a tsunami inundation scenario
+for geraldton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_geraldton.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.geospatial_data.geospatial_data import *
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files
+
+# Application specific imports
+import project   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project.output_build_time_dir,__file__, 
+               dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+start_screen_catcher(project.output_build_time_dir)
+
+print 'USER:    ', project.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print "project.poly_all", project.poly_all
+print "project.combined_dir_name", project.combined_dir_name
+
+# input elevation directory filenames
+onshore_in_dir_name = project.onshore_in_dir_name
+offshore_in_dir_name = project.offshore_in_dir_name
+offshore_in_dir_name1 = project.offshore_in_dir_name1
+offshore_in_dir_aoi = project.offshore_in_dir_aoi
+offshore_in_dir_aos = project.offshore_in_dir_aos
+
+# output elevation directory filenames
+onshore_dir_name = project.onshore_dir_name
+offshore_dir_name = project.offshore_dir_name
+offshore_dir_name1 = project.offshore_dir_name1
+offshore_dir_aoi = project.offshore_dir_aoi
+offshore_dir_aos = project.offshore_dir_aos
+
+
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name, basename_out=onshore_dir_name, use_cache=True, verbose=True)
+convert_dem_from_ascii2netcdf(offshore_in_dir_aoi, basename_out=offshore_dir_aoi, use_cache=True, verbose=True)
+convert_dem_from_ascii2netcdf(offshore_in_dir_aos, basename_out=offshore_dir_aos, use_cache=True, verbose=True)
+
+# creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name ,use_cache=True,verbose=True)
+dem2pts(offshore_dir_aoi ,use_cache=True,verbose=True)
+dem2pts(offshore_dir_aos ,use_cache=True,verbose=True)
+
+
+
+# create onshore pts files
+print'create Geospatial onshore objects from topographies'
+G1 = Geospatial_data(file_name = onshore_dir_name + '.pts')
+
+# create coastal and offshore txt files
+print'create Geospatial offshore objects from topographies'
+G_off1 = Geospatial_data(file_name = offshore_in_dir_name)
+print'create Geospatial makeup objects from topographies'
+G_off2 = Geospatial_data(file_name = offshore_in_dir_name1)
+print'create Geospatial aoi objects from topographies'
+G_offaoi = Geospatial_data(file_name = offshore_dir_aoi+ '.pts')
+print'create Geospatial aos objects from topographies'
+G_offaos = Geospatial_data(file_name = offshore_dir_aos+ '.pts')
+
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'add all bathymetry files'
+G_off = G_off1 + G_off2
+
+##print 'clipping data to coast'
+##G_ocean = G_off.clip(project.poly_ocean, verbose=True) #mainland
+##G_ocean_b = G_ocean.clip_outside(project.poly_island1, verbose=True) #bernier
+##G_ocean_bd = G_ocean_b.clip_outside(project.poly_island2, verbose=True) #dorne
+##
+##G1_clip_m = G1.clip(project.poly_mainland, verbose=True)
+##G1_clip_b = G1.clip(project.poly_island1, verbose=True)
+##G1_clip_d = G1.clip(project.poly_island2, verbose=True)
+##G1_clip = G1_clip_m + G1_clip_b + G1_clip_d
+
+print'add all geospatial objects'
+G_aos = G1 + G_off
+G_aosclip = G_aos.clip_outside(project.poly_aos_extract, verbose=True)
+G_aoi = G_aosclip.clip_outside(project.poly_aoi1, verbose=True)
+G = G_aoi +G_offaoi+G_offaos
+
+print'export combined DEM file'
+if access(project.topographies_dir,F_OK) == 0:
+    mkdir (project.topographies_dir)
+G.export_points_file(project.combined_dir_name + '.pts')
+G.export_points_file(project.combined_dir_name + '.txt') #Use for comparision in ARC
+
Index: /anuga_work/production/wa/carnarvon/build_carnarvon_250m.py
===================================================================
--- /anuga_work/production/wa/carnarvon/build_carnarvon_250m.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/build_carnarvon_250m.py	(revision 7411)
@@ -0,0 +1,81 @@
+"""
+Script for building the elevation data to run a tsunami inundation scenario
+for geraldton, WA, Australia.
+
+Input: elevation data from project_250m.py
+Output: pts file stored in project_250m.topographies_dir 
+The run_geraldton.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.geospatial_data.geospatial_data import *
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files
+
+# Application specific imports
+import project_250m   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project_250m.output_build_time_dir,__file__, 
+               dirname(project_250m.__file__)+sep+ project_250m.__name__+'.py' )
+
+start_screen_catcher(project_250m.output_build_time_dir)
+
+print 'USER:    ', project_250m.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print "project_250m.poly_all", project_250m.poly_all
+print "project_250m.combined_dir_name", project_250m.combined_dir_name
+
+# input elevation directory filenames
+onshore_in_dir_name = project_250m.onshore_in_dir_name
+
+# output elevation directory filenames
+onshore_dir_name = project_250m.onshore_dir_name
+
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name, basename_out=onshore_dir_name, use_cache=True, verbose=True)
+
+# creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name ,use_cache=True,verbose=True)
+
+# create onshore pts files
+print'create Geospatial data1 objects from topographies'
+G = Geospatial_data(file_name = onshore_dir_name + '.pts')
+
+#-------------------------------------------------------------------------------
+# export dataset 
+#-------------------------------------------------------------------------------
+
+print'export combined DEM file'
+if access(project_250m.topographies_dir,F_OK) == 0:
+    mkdir (project_250m.topographies_dir)
+G.export_points_file(project_250m.combined_dir_name + '.pts')
+G.export_points_file(project_250m.combined_dir_name + '.txt') #Use for comparision in ARC
+
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/Arc_asc2raster_GDA94z49.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/Arc_asc2raster_GDA94z49.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/Arc_asc2raster_GDA94z49.py	(revision 7411)
@@ -0,0 +1,87 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\carnarvon_tsunami_scenario\\"
+output_dir="anuga\\outputs\\"
+
+time_dir1 = '20090324_134442_run_final_1_27255_Bt_kvanputt'
+time_dir2 = '20090324_154738_run_final_1_27283_Bt_kvanputt'
+time_dir3 = '20090324_154824_run_final_1_68693_Bt_kvanputt'
+time_dir4 = '20090327_154730_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_154824_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_160753_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1] #, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]   
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder = scenario_dir + output_dir + time_dir + '\\'
+    raster_gbd = folder + 'raster.gdb'
+    land = scenario_dir + "map_work\\Carnarvon.gdb\\land_initial_condition_all"
+    ocean = scenario_dir + "map_work\\Carnarvon.gdb\\ocean_initial_condition"
+    
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    print time_dir
+    
+    #replication dictionary
+    replicate = (('carnarvon', ''),#('time_39900_0', 'b'), ('time_79800_0', 'c'),
+                 ('_', ''), ('max','_M'), ('depth','_dep_'),
+                 ('speed', '_speed_'), ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*elevation.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+        print 'Output DEM ',output_DEM
+       
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection' 
+        gp.DefineProjection_management(output_DEM,"PROJCS['GDA_1994_MGA_Zone_49',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994'"
+                                       ",SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0]"
+                                       ",UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator']"
+                                       ",PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0]"
+                                       ",PARAMETER['Central_Meridian',111.0],PARAMETER['Scale_Factor',0.9996]"
+                                       ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+
+ 
+##        print 'Process: Extract by Mask'
+##        output_extract = output_DEM + '_E'
+##        print 'Output Extract ',output_extract
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/Arc_txt2feature_class_runup.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/Arc_txt2feature_class_runup.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/Arc_txt2feature_class_runup.py	(revision 7411)
@@ -0,0 +1,53 @@
+# ---------------------------------------------------------------------------
+# txt2fc_field.py
+# Created on: Thu Nov 27 2008 01:48:26 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\carnarvon_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_134442_run_final_1_27255_Bt_kvanputt'
+time_dir2 = '20090324_154738_run_final_1_27283_Bt_kvanputt'
+time_dir3 = '20090324_154824_run_final_1_68693_Bt_kvanputt'
+time_dir4 = '20090327_154730_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_154824_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_160753_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'carnarvon_runup.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "x", "y", layer, "PROJCS['GDA_1994_MGA_Zone_49',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994'"
+                                       ",SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0]"
+                                       ",UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator']"
+                                       ",PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0]"
+                                       ",PARAMETER['Central_Meridian',111.0],PARAMETER['Scale_Factor',0.9996]"
+                                       ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "carnarvon_runup", "", "area area true true false 255 Text 0 0 ,First,#,carnarvon_runup.csv_Features,area,-1,-1;q q true true false 8 Double 0 0 ,First,#,carnarvon_runup.csv_Features,q,-1,-1;x x true true false 8 Double 0 0 ,First,#,carnarvon_runup.csv_Features,x,-1,-1;y y true true false 8 Double 0 0 ,First,#,carnarvon_runup.csv_Features,y,-1,-1", "")
+
+
+  
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/Carnarvon4distribution.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/Carnarvon4distribution.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/Carnarvon4distribution.py	(revision 7411)
@@ -0,0 +1,126 @@
+# ---------------------------------------------------------------------------
+# Carnarvon4distribution.py
+# Created on: Thu Apr 30 2009 03:51:03 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+
+output_loc = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\FESA_outputs_Dec_08\\ARCgrids\\April_2009\\"
+input_scenario = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\carnarvon_tsunami_scenario\\"
+input_output = input_scenario + "\\anuga\\outputs\\"
+community = 'Carnarvon'
+location = 'CBD'
+in_Tsunami_1_HAT = input_output + "20090324_154738_run_final_1_27283_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_1_MSL = input_output + "20090327_160753_run_final_0_27283_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_2_HAT = input_output + "20090324_134442_run_final_1_27255_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_2_MSL = input_output + "20090327_154824_run_final_0_27255_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_3_HAT = input_output + "20090324_154824_run_final_1_68693_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_3_MSL = input_output + "20090327_154730_run_final_0_68693_Bt_kvanputt\\raster.gdb\\"
+
+Tsunami_1_HAT = output_loc + "Tsunami1-Exmouth\\" + community + "_HAT.gdb\\"
+Tsunami_1_MSL = output_loc + "Tsunami1-Exmouth\\" + community + "_MSL.gdb\\"
+Tsunami_2_HAT = output_loc + "Tsunami2-Perth\\" + community + "_HAT.gdb\\"
+Tsunami_2_MSL = output_loc + "Tsunami2-Perth\\" + community + "_MSL.gdb\\"
+Tsunami_3_HAT = output_loc + "Tsunami3-1833\\" + community + "_HAT.gdb\\"
+Tsunami_3_MSL = output_loc + "Tsunami3-1833\\" + community + "_MSL.gdb\\"
+
+depth = 'CBD_dep__M_E'
+speed = 'CBD_speed_'
+hr = community + '_runup'
+
+# Local variables...
+# polygon clip
+if location == 'CBD':
+    extent = input_scenario + "map_work\\Carnarvon.gdb\\Polygon\\Carnarvon5m"
+
+# Output locations
+
+
+
+hr_1_HAT = Tsunami_1_HAT +"highest_runup"
+hr_1_MSL = Tsunami_1_MSL +"highest_runup"
+hr_2_HAT = Tsunami_2_HAT +"highest_runup"
+hr_2_MSL = Tsunami_2_MSL +"highest_runup"
+hr_3_HAT = Tsunami_3_HAT +"highest_runup"
+hr_3_MSL = Tsunami_3_MSL +"highest_runup"
+
+depth_1_HAT = Tsunami_1_HAT + location + "_depth"
+depth_1_MSL = Tsunami_1_MSL + location + "_depth"
+depth_2_HAT = Tsunami_2_HAT + location + "_depth"
+depth_2_MSL = Tsunami_2_MSL + location + "_depth"
+depth_3_HAT = Tsunami_3_HAT + location + "_depth"
+depth_3_MSL = Tsunami_3_MSL + location + "_depth"
+
+speed_1_HAT = Tsunami_1_HAT + location + "_speed"
+speed_1_MSL = Tsunami_1_MSL + location + "_speed"
+speed_2_HAT = Tsunami_2_HAT + location + "_speed"
+speed_2_MSL = Tsunami_2_MSL + location + "_speed"
+speed_3_HAT = Tsunami_3_HAT + location + "_speed"
+speed_3_MSL = Tsunami_3_MSL + location + "_speed"
+
+
+# Input locations
+
+in_depth_1_HAT = in_Tsunami_1_HAT + depth
+in_depth_1_MSL = in_Tsunami_1_MSL + depth
+in_depth_2_HAT = in_Tsunami_2_HAT + depth
+in_depth_2_MSL = in_Tsunami_2_MSL + depth
+in_depth_3_HAT = in_Tsunami_3_HAT + depth
+in_depth_3_MSL = in_Tsunami_3_MSL + depth
+
+in_speed_1_HAT = in_Tsunami_1_HAT + speed
+in_speed_1_MSL = in_Tsunami_1_MSL + speed
+in_speed_2_HAT = in_Tsunami_2_HAT + speed
+in_speed_2_MSL = in_Tsunami_2_MSL + speed
+in_speed_3_HAT = in_Tsunami_3_HAT + speed
+in_speed_3_MSL = in_Tsunami_3_MSL + speed
+
+in_hr_1_HAT = in_Tsunami_1_HAT + hr
+in_hr_1_MSL = in_Tsunami_1_MSL + hr
+in_hr_2_HAT = in_Tsunami_2_HAT + hr
+in_hr_2_MSL = in_Tsunami_2_MSL + hr
+in_hr_3_HAT = in_Tsunami_3_HAT + hr
+in_hr_3_MSL = in_Tsunami_3_MSL + hr
+
+
+# Process: Extract by Mask
+
+print 'Extract by mask for depth'
+gp.ExtractByMask_sa(in_depth_1_HAT, extent, depth_1_HAT)
+gp.ExtractByMask_sa(in_depth_1_MSL, extent, depth_1_MSL)
+gp.ExtractByMask_sa(in_depth_2_HAT, extent, depth_2_HAT)
+gp.ExtractByMask_sa(in_depth_2_MSL, extent, depth_2_MSL)
+gp.ExtractByMask_sa(in_depth_3_HAT, extent, depth_3_HAT)
+gp.ExtractByMask_sa(in_depth_3_MSL, extent, depth_3_MSL)
+
+print 'Extract by mask for speed'
+gp.ExtractByMask_sa(in_speed_1_HAT, extent, speed_1_HAT)
+gp.ExtractByMask_sa(in_speed_1_MSL, extent, speed_1_MSL)
+gp.ExtractByMask_sa(in_speed_2_HAT, extent, speed_2_HAT)
+gp.ExtractByMask_sa(in_speed_2_MSL, extent, speed_2_MSL)
+gp.ExtractByMask_sa(in_speed_3_HAT, extent, speed_3_HAT)
+gp.ExtractByMask_sa(in_speed_3_MSL, extent, speed_3_MSL)
+
+
+# Process: Copy Features...
+
+print 'Copy Highest Runup'
+gp.CopyFeatures_management(in_hr_1_HAT, hr_1_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_1_MSL, hr_1_MSL, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_2_HAT, hr_2_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_2_MSL, hr_2_MSL, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_3_HAT, hr_3_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_3_MSL, hr_3_MSL, "", "0", "0", "0")
+
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/Inundation_polygon.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/Inundation_polygon.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/Inundation_polygon.py	(revision 7411)
@@ -0,0 +1,69 @@
+# ---------------------------------------------------------------------------
+# Inundation_line.py
+# Created on: Tue May 12 2009 01:50:45 PM
+#   (generated by ArcGIS/ModelBuilder)
+# Usage: Inundation_line <Bun_depth_M_E> <Bus_depth_M_E> <bunbury_1km> <busselton_1km> 
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+gp.overwriteoutput = 1
+
+# Set the necessary product code
+gp.SetProduct("ArcInfo")
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Analysis Tools.tbx")
+
+# Script arguments...
+time_dir1 = '20090324_134442_run_final_1_27255_Bt_kvanputt'
+time_dir2 = '20090324_154738_run_final_1_27283_Bt_kvanputt'
+time_dir3 = '20090324_154824_run_final_1_68693_Bt_kvanputt'
+time_dir4 = '20090327_154730_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_154824_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_160753_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]   
+
+community = 'carnarvon'
+scenario = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\" + community +"_tsunami_scenario\\"
+output_folder = scenario + "anuga\\outputs\\"
+location = 'CBD'
+extent = scenario + "map_work\\Carnarvon.gdb\\Polygon\\Carnarvon5m_clip"
+depth = 'CBD_dep__M_E'
+
+for time_dir in time_dirs:
+
+    raster = output_folder + time_dir + "\\raster.gdb\\"
+    print 'location', location
+    print 'extent', extent
+
+    # Local variables...
+    Output_raster = raster +"Temp_raster_"+ location
+    Output_polygon_features = raster +"Temp_polygon_"+ location
+    Output_Feature_Class = raster +"Temp_line_"+ location
+    Reclassification = "0 0.05 NODATA;0.05 4.5840001106262207 1"
+    Inundation = raster + "Inundation_" + location + "_polygon"
+    depth_loc = raster + depth
+    
+    print 'Process: Reclassify'
+    gp.Reclassify_sa(depth_loc, "Value", Reclassification, Output_raster, "DATA")
+    
+    print 'Process: Raster to Polygon'
+    gp.RasterToPolygon_conversion(Output_raster, Output_polygon_features, "SIMPLIFY", "VALUE")
+
+    print 'Process: Clip'
+    gp.Clip_analysis(Output_polygon_features, extent, Inundation, "")
+
+    print 'Process: Delete'
+    gp.Delete_management(Output_raster, "RasterDataset")
+    gp.Delete_management(Output_polygon_features, "FeatureClass")
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/README.txt
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/README.txt	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/README.txt	(revision 7411)
@@ -0,0 +1,17 @@
+This area aims at collecting the best practices in setting up ANUGA models and
+show them as a running demo.
+
+The intent is to make setting up and running of models easier to do and more standardised (without compromising one bit of creativity, of course :-). One principle is that information should never have to be entered more than once.
+
+
+The ideas are:
+
+* Collect all elevation data files in lists for batch processing (as in Shark Bay 200&)
+
+* Roll all the urs2sts work into an ANUGA function (see ticket:317)
+ 
+* Get rid of kwargs and use project.* for all parameters and filenames.
+
+* Migrate towards unified anuga interface (as in the Patong scenario).
+
+*
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/build_elevation.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/build_elevation.py	(revision 7411)
@@ -0,0 +1,100 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+from anuga.utilities.polygon import read_polygon
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+extent_polygons = []
+for extent_polygon_filename in project.extent_polygon_filenames:
+    p = read_polygon(join(project.polygons_folder, extent_polygon_filename))
+    extent_polygons.append(p)
+    
+print 'Add geospatial objects' # except', project.offshore_name5
+G = None
+for key in geospatial_data:
+    if key == project.ascii_grid_filenames[1]or key == project.ascii_grid_filenames[2]:
+        G += geospatial_data[key]
+    elif key == project.ascii_grid_filenames[0] or key == project.point_filenames[0] or key == project.point_filenames[1]:
+        D = geospatial_data[key]
+        D = D.clip_outside(extent_polygons[0])
+        D = D.clip_outside(extent_polygons[1])
+        G += D
+    
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,167 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                zone=project.zone,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/export_results_max.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/export_results_max.py	(revision 7411)
@@ -0,0 +1,120 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+time_dir1 = '20090324_134442_run_final_1_27255_Bt_kvanputt'
+time_dir2 = '20090324_154738_run_final_1_27283_Bt_kvanputt'
+time_dir3 = '20090324_154824_run_final_1_68693_Bt_kvanputt'
+time_dir4 = '20090327_154730_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_154824_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_160753_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1] #5, time_dir6]   
+
+#cellsize = 250
+cellsize = 20
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+area = ['CBD']  # strings must match keys in var_equations below
+#area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            name2 = join(directory, time_dir, project.scenario_name)+'_time_39300_0'
+            name3 = join(directory, time_dir, project.scenario_name)+'_time_78600_0'
+
+            names = [name1] #, name2, name3]
+      
+            #asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+##
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/file_length.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/get_runup.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/get_runup.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/get_runup.py	(revision 7411)
@@ -0,0 +1,64 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from os.path import join
+from anuga.utilities.polygon import read_polygon
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+        
+# Application specific imports
+from setup_model import project  # Definition of file names and polygons
+import csv
+directory = project.output_folder
+
+time_dir1 = '20090324_134442_run_final_1_27255_Bt_kvanputt'
+time_dir2 = '20090324_154738_run_final_1_27283_Bt_kvanputt'
+time_dir3 = '20090324_154824_run_final_1_68693_Bt_kvanputt'
+time_dir4 = '20090327_154730_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_154824_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_160753_run_final_0_27283_Bt_kvanputt'
+
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+interior_region = project.interior_regions_data[0]
+polygon = read_polygon(join(project.polygons_folder, first_region))
+
+area_dictionary = {'Carnarvon': interior_region}
+
+area = ['Carnarvon'] 
+
+for time_dir in time_dirs:
+
+    basename = join(directory, time_dir, project.scenario_name)
+
+    out_file = basename+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+    print 'basename ',basename 
+
+    for which_area in area:
+        if which_area not in area_dictionary:
+            print 'Unrecognized variable name: %s' % which_area
+            break
+
+        polygon = area_dictionary[which_area]
+        
+        print 'Which area ',which_area
+
+        q, loc = get_maximum_inundation_data(basename+'.sww',
+                                             polygon=polygon, verbose=True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/get_timeseries.py	(revision 7411)
@@ -0,0 +1,34 @@
+"""
+Generate time series of nominated "gauges".
+Input: sww file from run_perth.py
+       gauges project.gauge_filename
+Output: csv files stage,speed,depth,elevation over time
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+Can run different sww files at the same time
+make sure if there is a second sww file that it is placed into a folder called sww2
+Can run different gauges at the same time - ie testing boundary index point
+"""
+
+from os import sep, rename, listdir, system
+from os.path import join
+from anuga.abstract_2d_finite_volumes.util import sww2csv_gauges,csv2timeseries_graphs
+import project
+
+directory = project.output_folder
+
+time_dir1 = '20090324_134442_run_final_1_27255_Bt_kvanputt'
+
+time_dirs = [time_dir1] #1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+print 'time directories', time_dirs
+
+for time_dir in time_dirs:
+    name = join(directory,time_dir,project.scenario_name)
+    gauge = project.gauges
+    sww2csv_gauges(name+'.sww',gauge,
+                   quantities = ['stage','speed','depth','elevation'],
+                   verbose=True)
+  
+
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/project.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/project.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/project.py	(revision 7411)
@@ -0,0 +1,243 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'carnarvon'
+scenario_folder = 'carnarvon_tsunami_scenario'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 1                # difference between MSL and HAT in metres
+zone = 49               # specify zone of model
+#event_number = 27255    # the event number or the mux file name
+event_number = 'wa04_val'
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=80000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number, 'Bt', 'yieldstep_5']
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['dem_onshore',   # 
+                        'topo_20m_aoi',
+                        'topo_50m_aos'] # 
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['carnarvon_data.txt',    # 
+                   'makeup.txt']            # 
+
+extent_polygon_filenames = ['extract_aos.csv',
+                            'Carnarvon5m.csv']
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'poly_all.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['Carnarvon5m.csv', 500],
+                         ['Carnarvon10m.csv', 1500],
+                         ['Carnarvon20m.csv', 25000],
+                         ['Island20m.csv', 50000]]
+
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing (no header)
+land_initial_conditions_filename = [['land_initial_condition.csv', 0],
+                                    ['land_initial_condition_bernier.csv', 0],
+                                    ['land_initial_condition_dorne.csv', 0]]
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = 'MH_gauges.csv' #'carnarvon.csv'
+gauges_filename2 = 'thinned_MGA50.csv'
+
+
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = 'carnarvon_res.csv' # from NEXIS
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'thinned_boundary_ordering.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_bounding_polygon.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+multi_mux = False
+##mux_input_filename = 'event.list'
+##multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# carnarvon CBD extract ascii grid
+xminCBD = 763000
+xmaxCBD = 775000
+yminCBD = 7239000
+ymaxCBD = 7251000
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,72 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from os.path import join
+from setup_model import project
+import csv
+
+directory = project.output_folder
+
+time_dir1 = '20090324_134442_run_final_1_27255_Bt_kvanputt'
+time_dir2 = '20090324_154738_run_final_1_27283_Bt_kvanputt'
+time_dir3 = '20090324_154824_run_final_1_68693_Bt_kvanputt'
+time_dir4 = '20090327_154730_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_154824_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_160753_run_final_0_27283_Bt_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3,time_dir4, time_dir5, time_dir6]   
+
+buildings = project.building_exposure
+
+for time_dir in time_dirs:
+    
+    time_dir_name = time_dir[-25:][:-11]
+       
+    building_marker = '_m_'+ time_dir_name
+    basename = join(directory, time_dir, project.scenario_name) #basename for the sww files 
+    
+    inundation_damage(basename, buildings, building_marker)
+    #add_depth_and_momentum2csv(name, buildings, building_marker)
+    
+    building_marker_dir_name = join(project.gauges_folder,
+                                    project.building_exposure_filename[:-4]) + building_marker + '.csv'
+    out_file = basename + '_res.csv'
+    print 'out file %s' %out_file
+    print 'building_marker_dir_name %s' %building_marker_dir_name
+    csv_fd = open(building_marker_dir_name, 'r')
+    output_file = open(out_file, 'w')
+
+    reader = csv.reader(csv_fd)
+    writer = csv.writer(output_file, lineterminator='\n')
+
+    for record in reader:
+       newline = record[-8:]
+       newline.insert(0,record[0])
+       newline.insert(1,record[1])
+       newline.insert(2,record[2])
+       writer.writerow(newline)
+       
+    print 'output file printed to: %s' %out_file
+    csv_fd.close()
+    output_file.close()
+     
+
+    
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/run_model.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/run_model.py	(revision 7411)
@@ -0,0 +1,164 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.geo_reference.zone = project.zone
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/carnarvon/carnarvon_rerun/setup_model.py
===================================================================
--- /anuga_work/production/wa/carnarvon/carnarvon_rerun/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/carnarvon_rerun/setup_model.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+for filename, MSL in project.land_initial_conditions_filename:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.land_initial_conditions.append([polygon, MSL])
+
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/carnarvon/export_results.py
===================================================================
--- /anuga_work/production/wa/carnarvon/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/export_results.py	(revision 7411)
@@ -0,0 +1,79 @@
+import project, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+
+
+#time_dir = '20080908_154507_run_final_0.0_polyline_alpha0.1_kvanputt'
+time_dir = '20080909_123144_run_final_0.0_polyline_alpha0.1_kvanputt'
+
+
+cellsize = 25
+#cellsize = 150
+timestep = 0
+directory = project.output_dir
+name = directory+sep+time_dir+sep+project.scenario_name
+
+is_parallel = False
+#is_parallel = True
+
+if is_parallel == True: nodes = 4
+print 'output dir:', name
+
+
+var = [0,4] 
+#var = [2,3] # depth and Speed
+#var = [2,3] # elevation, depth and Speed
+
+
+for which_var in var:
+    if which_var == 0:  # Stage
+        outname = name + '_stage'
+        quantityname = 'stage'
+
+    if which_var == 1:  # Absolute Momentum
+        outname = name + '_momentum'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+    if which_var == 2:  # Depth
+        outname = name + '_depth'
+        quantityname = 'stage-elevation'  
+
+    if which_var == 3:  # Speed
+        outname = name + '_speed'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+    if which_var == 4:  # Elevation
+        outname = name + '_elevation'
+        quantityname = 'elevation'  #Elevation
+
+    if is_parallel == True:
+    #    print 'is_parallel',is_parallel
+        for i in range(0,nodes):
+            namei = name + '_P%d_%d' %(i,nodes)
+            outnamei = outname + '_P%d_%d' %(i,nodes)
+            print 'start sww2dem for sww file %d' %(i)
+            sww2dem(namei, basename_out = outnamei,
+                        quantity = quantityname,
+                        #timestep = timestep,
+                        cellsize = cellsize,      
+                        easting_min = project_grad.e_min_area,
+                        easting_max = project_grad.e_max_area,
+                        northing_min = project_grad.n_min_area,
+                        northing_max = project_grad.n_max_area,        
+                        reduction = max, 
+                        verbose = True,
+                        format = 'asc')
+    else:
+        print 'start sww2dem'
+        sww2dem(name, basename_out = outname,
+                    quantity = quantityname,
+                    timestep = timestep,
+                    cellsize = cellsize,
+                    number_of_decimal_places = 4,
+                    reduction = max, 
+                    verbose = True,
+                    format = 'asc')
+
Index: /anuga_work/production/wa/carnarvon/export_results_all.py
===================================================================
--- /anuga_work/production/wa/carnarvon/export_results_all.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/export_results_all.py	(revision 7411)
@@ -0,0 +1,99 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_dir
+
+time_dir1 = '20081002_111053_run_final_0_27283_250m_none_kvanputt'
+time_dir2 = '20081002_111207_run_final_0_27283_250m_all_kvanputt'
+#time_dir3 = '20081007_081134_run_final_0_27283_alpha0.1_kvanputt'
+time_dir3 = '20081028_151417_run_final_0.0_27283_alpha0.1_lfountai'
+
+time_dirs = [time_dir1, time_dir2, time_dir3]
+
+#cellsize = 20
+cellsize = 250
+
+timestep = None    # None means no timestep!
+#timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+#area = ['Geordie', 'Sorrento', 'Fremantle', 'Rockingham']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['stage', 'elevation']
+
+######
+# Start running the various conversions we require.
+######
+for time_dir in time_dirs:
+    name1 = directory+time_dir+sep+project.scenario_name
+#    name2 = directory+time_dir+sep+'sww2'+sep+project.scenario_name+'_time_39900_0' #need to get assistance on how to make this into anything
+    names = [name1]
+    
+    for name in names:
+        for which_area in area:
+            if which_area == 'All':
+                easting_min = None
+                easting_max = None
+                northing_min = None
+                northing_max = None
+            else:
+                try:
+                    easting_min = eval('project.xmin%s' % which_area)
+                    easting_max = eval('project.xmax%s' % which_area)
+                    northing_min = eval('project.ymin%s' % which_area)
+                    northing_max = eval('project.ymax%s' % which_area)
+                except AttributeError:
+                    print 'Unrecognized area name: %s' % which_area
+                    break
+              
+            for which_var in var:
+                if which_var not in var_equations:
+                    print 'Unrecognized variable name: %s' % which_var
+                    break
+
+                outname = name + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
Index: /anuga_work/production/wa/carnarvon/export_results_max.py
===================================================================
--- /anuga_work/production/wa/carnarvon/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/export_results_max.py	(revision 7411)
@@ -0,0 +1,125 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+directory = project.output_dir
+
+##time_dir1 = '20081209_155247_run_final_0_27255_250m_none_lfountai'
+##time_dir2 = '20081209_161626_run_final_0_68693_250m_none_lfountai'
+##time_dirs = [time_dir1, time_dir2]
+
+##time_dir1 = '20081202_084220_run_final_1_27283_alpha0.1_kvanputt'
+##time_dir2 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081202_084132_run_final_1_68693_alpha0.1_kvanputt'
+time_dir4 = '20081202_084025_run_final_0_68693_alpha0.1_kvanputt'
+time_dir5 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir6 = '20081201_103449_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir4, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+ 
+
+#cellsize = 20
+cellsize = 250
+
+timestep = None    # None means no timestep!
+#timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+#area = ['CBD']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['stage']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = directory+time_dir+sep+project.scenario_name
+##            name2 = directory+time_dir+sep+project.scenario_name+'_time_77160_0'
+
+            name2 = directory+time_dir+sep+project.scenario_name+'_time_39300_0'
+            name3 = directory+time_dir+sep+project.scenario_name+'_time_78600_0'
+
+            names = [name1, name2, name3]
+      
+            asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+                asc_name.append(outname + '.asc')
+    
+            maxasc_outname = directory+time_dir+sep+project.scenario_name+'_'+which_area+'_'+which_var+'_max.asc'
+
+            print 'max asc outname ', maxasc_outname
+            print 'asc_name ', str(asc_name)
+            
+            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/carnarvon/export_results_max_multiple_timesteps.py
===================================================================
--- /anuga_work/production/wa/carnarvon/export_results_max_multiple_timesteps.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/export_results_max_multiple_timesteps.py	(revision 7411)
@@ -0,0 +1,124 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+directory = project.output_dir
+
+##time_dir1 = '20081209_155247_run_final_0_27255_250m_none_lfountai'
+##time_dir2 = '20081209_161626_run_final_0_68693_250m_none_lfountai'
+##time_dirs = [time_dir1, time_dir2]
+
+##time_dir1 = '20081202_084220_run_final_1_27283_alpha0.1_kvanputt'
+time_dir2 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081202_084132_run_final_1_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081202_084025_run_final_0_68693_alpha0.1_kvanputt'
+time_dir5 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir6 = '20081201_103449_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir2, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+ 
+
+#cellsize = 20
+cellsize = 250
+
+#timestep = None    # None means no timestep!
+timesteps = [39300,39360]
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+#area = ['CBD']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['stage','depth','elevation']
+
+######
+# Start running the various conversions we require.
+######
+for timestep in timesteps:
+    for which_var in var:
+        if which_var not in var_equations:
+            print 'Unrecognized variable name: %s' % which_var
+            break
+
+        for which_area in area:
+            if which_area == 'All':
+                easting_min = None
+                easting_max = None
+                northing_min = None
+                northing_max = None
+            else:
+                try:
+                    easting_min = eval('project.xmin%s' % which_area)
+                    easting_max = eval('project.xmax%s' % which_area)
+                    northing_min = eval('project.ymin%s' % which_area)
+                    northing_max = eval('project.ymax%s' % which_area)
+                except AttributeError:
+                    print 'Unrecognized area name: %s' % which_area
+                    break
+
+            for time_dir in time_dirs:
+
+                name1 = directory+time_dir+sep+project.scenario_name
+                name2 = directory+time_dir+sep+project.scenario_name+'_time_39300_0'
+                name3 = directory+time_dir+sep+project.scenario_name+'_time_78600_0'
+
+                names = [name2] #[name1, name2, name3]
+          
+##                asc_name = []   
+                   
+                for name in names:
+                             
+                    outname = name + '_' + which_area + '_' + which_var + '_' + str(timestep)
+                    quantityname = var_equations[which_var]
+
+                    print 'start sww2dem: time_dir=%s' % time_dir
+                    
+                    sww2dem(name, basename_out = outname,
+                                quantity = quantityname,
+                                timestep = timestep,
+                                cellsize = cellsize,      
+                                easting_min = easting_min,
+                                easting_max = easting_max,
+                                northing_min = northing_min,
+                                northing_max = northing_max,        
+                                reduction = max, 
+                                verbose = True,
+                                format = 'asc')
+
+##                    asc_name.append(outname + '.asc')
+##        
+##                maxasc_outname = directory+time_dir+sep+project.scenario_name+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##                print 'max asc outname ', maxasc_outname
+##                print 'asc_name ', str(asc_name)
+##                
+##                MaxAsc(maxasc_outname, asc_name)
+
Index: /anuga_work/production/wa/carnarvon/export_results_multiple_timesteps.py
===================================================================
--- /anuga_work/production/wa/carnarvon/export_results_multiple_timesteps.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/export_results_multiple_timesteps.py	(revision 7411)
@@ -0,0 +1,90 @@
+import project, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+
+
+#time_dir = '20080908_154507_run_final_0.0_polyline_alpha0.1_kvanputt'
+#time_dir = '20080909_123144_run_final_0.0_polyline_alpha0.1_kvanputt'
+
+time_dir1 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+time_dir2 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1,time_dir2]
+
+cellsize = 250
+#cellsize = 150
+timestep_list = range(53000,67000,1020)
+directory = project.output_dir
+
+is_parallel = False
+#is_parallel = True
+
+if is_parallel == True: nodes = 4
+
+
+
+var = [0,2,3] 
+#var = [2,3] # depth and Speed
+#var = [2,3] # elevation, depth and Speed
+
+for time_dir in time_dirs:
+    name = directory+sep+time_dir+sep+project.scenario_name+'_time_39300_0'
+    print 'output dir:', name
+    
+    for which_var in var:
+        if which_var == 0:  # Stage
+            outname = name + '_stage'
+            quantityname = 'stage'
+
+        if which_var == 1:  # Absolute Momentum
+            outname = name + '_momentum'
+            quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+        if which_var == 2:  # Depth
+            outname = name + '_depth'
+            quantityname = 'stage-elevation'  
+
+        if which_var == 3:  # Speed
+            outname = name + '_speed'
+            quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+        if which_var == 4:  # Elevation
+            outname = name + '_elevation'
+            quantityname = 'elevation'  #Elevation
+
+        for timestep in timestep_list:
+            outname_time = outname + '_' + str(timestep)
+            print 'output filename', outname_time
+            print 'time = ',timestep
+            if is_parallel == True:
+                print 'is_parallel',is_parallel
+    ##            for i in range(0,nodes):
+    ##                namei = name + '_P%d_%d' %(i,nodes)
+    ##                outnamei = outname + '_P%d_%d' %(i,nodes)
+    ##                print 'start sww2dem for sww file %d' %(i)
+    ##                sww2dem(namei, basename_out = outnamei,
+    ##                            quantity = quantityname,
+    ##                            #timestep = timestep,
+    ##                            cellsize = cellsize,      
+    ##                            easting_min = project_grad.e_min_area,
+    ##                            easting_max = project_grad.e_max_area,
+    ##                            northing_min = project_grad.n_min_area,
+    ##                            northing_max = project_grad.n_max_area,        
+    ##                            reduction = max, 
+    ##                            verbose = True,
+    ##                            format = 'asc')
+            else:
+                print 'start sww2dem'
+                sww2dem(name, basename_out = outname_time,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,
+                            number_of_decimal_places = 4,
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+
Index: /anuga_work/production/wa/carnarvon/get_gauges.py
===================================================================
--- /anuga_work/production/wa/carnarvon/get_gauges.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/get_gauges.py	(revision 7411)
@@ -0,0 +1,58 @@
+import os
+from os import sep
+import project
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+from anuga.utilities.polygon import inside_polygon
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+        
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+        
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+        
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
Index: /anuga_work/production/wa/carnarvon/get_runup.py
===================================================================
--- /anuga_work/production/wa/carnarvon/get_runup.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/get_runup.py	(revision 7411)
@@ -0,0 +1,57 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+        
+# Application specific imports
+import project  # Definition of file names and polygons
+import csv
+directory = project.output_dir
+
+time_dir1 = '20081202_084220_run_final_1_27283_alpha0.1_kvanputt'
+time_dir2 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+time_dir3 = '20081202_084132_run_final_1_68693_alpha0.1_kvanputt'
+time_dir4 = '20081202_084025_run_final_0_68693_alpha0.1_kvanputt'
+time_dir5 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+time_dir6 = '20081201_103449_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+area_dictionary = {'CBD': project.poly_aoi1}
+
+area = ['CBD'] 
+
+for time_dir in time_dirs:
+
+    name = directory+time_dir+sep+project.scenario_name
+
+    out_file = name+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+    print 'name ',name 
+
+    for which_area in area:
+        if which_area not in area_dictionary:
+            print 'Unrecognized variable name: %s' % which_area
+            break
+
+        polygon = area_dictionary[which_area]
+        
+        print 'Which area ',which_area
+
+        q, loc = get_maximum_inundation_data (name+'.sww', polygon = polygon, verbose= True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/carnarvon/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/carnarvon/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/get_timeseries.py	(revision 7411)
@@ -0,0 +1,38 @@
+"""
+Generate time series of nominated "gauges".
+Input: sww file from run_perth.py
+       gauges project.gauge_filename
+Output: csv files stage,speed,depth,elevation over time
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+Can run different sww files at the same time
+make sure if there is a second sww file that it is placed into a folder called sww2
+Can run different gauges at the same time - ie testing boundary index point
+"""
+
+from os import sep, rename, listdir, system
+from anuga.abstract_2d_finite_volumes.util import sww2csv_gauges,csv2timeseries_graphs
+import project
+
+directory = project.output_dir
+
+##time_dir1 = '20081202_084220_run_final_1_27283_alpha0.1_kvanputt'
+##time_dir2 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081202_084132_run_final_1_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081202_084025_run_final_0_68693_alpha0.1_kvanputt'
+time_dir5 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir6 = '20081201_103449_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir5] #1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+print 'time directories', time_dirs
+
+for time_dir in time_dirs:
+    name = directory+time_dir+sep+project.scenario_name 
+    gauge = project.gauges_dir_name
+    sww2csv_gauges(name+'.sww',gauge,
+                   quantities = ['stage','speed','depth','elevation'],
+                   verbose=True)
+  
+
Index: /anuga_work/production/wa/carnarvon/ph2_compare.py
===================================================================
--- /anuga_work/production/wa/carnarvon/ph2_compare.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/ph2_compare.py	(revision 7411)
@@ -0,0 +1,139 @@
+"""
+Read in event time series and determine max stage for Ph2 comparison
+Compare with Green's function (no focussing)
+Compare with ANUGA outputs (full model, 250m no polys, 250m all polys)
+Leharne Fountain and Jane Sexton, 2008
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid, figure
+from os import sep
+
+###################################################
+# Relevant definitions
+###################################################
+
+def get_max_boundary_data(filename):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[3]))
+    return mean(stage)
+
+def get_stage_data(filename,depth,no_models):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    mean_stages = zeros((len(depth),no_models), Float)
+    max_stages = zeros((len(depth),no_models), Float)
+    for i in range(no_models):
+        stage5 = []
+        stage10 = []
+        stage20 = []
+        stage50 = []
+        for line in lines[1:]:
+            fields = line.split(',')
+            x = float(fields[0])
+            # based on csv file output from ArcGIS: depth, x,y, no poly, all poly, and orig
+            y = float(fields[i+3]) 
+            if x == -depth[0]:
+                stage5.append(y)
+            if x == -depth[1]:
+                stage10.append(y)
+            if x == -depth[2]:
+                stage20.append(y)
+            if x == -depth[3]:
+                stage50.append(y)
+            
+        mean_stages[:,i] = [mean(stage5), mean(stage10), mean(stage20), mean(stage50)]
+        max_stages[:,i] = [max(stage5), max(stage10), max(stage20), max(stage50)]
+    return mean_stages, max_stages
+
+###################################################
+# Determine max stage at boundary points
+###################################################
+
+event_number = 27283
+boundary_mean = get_max_boundary_data(project.boundaries_dir+str(event_number)+sep+'max_sts_stage.csv')
+
+###################################################
+# Read in max data from all models
+###################################################
+
+from Numeric import zeros, Float
+directory = project.home+project.state+sep+project.scenario+sep+'map_work'
+depth = [5.0,10.,20.,50.]
+no_models = 3
+filename = directory + sep + 'Carnarvon_ph2_compare.csv'
+mean_stages, max_stages = get_stage_data(filename, depth, no_models)
+
+###################################################
+# Compare with Green's function and plot
+###################################################
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 100.
+d2 = arange(d1,1,-0.1)
+h1 = boundary_mean
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+
+ion()
+figure(1)
+plot(depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Carnarvon')
+legend(['original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Carnarvon_mean_ORIG_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(2)
+plot(depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Carnarvon')
+legend(['250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Carnarvon_mean_250AP_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(3)
+plot(depth,mean_stages[:,0],'ob',depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Carnarvon')
+legend(['250m no poly','250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Carnarvon_mean_ALL_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(4)
+plot(depth,max_stages[:,0],'ob',depth,max_stages[:,1],'+r',depth,max_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (max stage) versus Green\'s approximation \n \
+for event 27283 at Carnarvon')
+legend(['250m no poly','250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Carnarvon_max_ALL_' + str(event_number) + '_mean'
+savefig(figname)
+close('all')
+
Index: /anuga_work/production/wa/carnarvon/ph2_compare_table.py
===================================================================
--- /anuga_work/production/wa/carnarvon/ph2_compare_table.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/ph2_compare_table.py	(revision 7411)
@@ -0,0 +1,206 @@
+"""
+Read in event time series and determine max stage for Ph2 comparison
+Compare with Green's function (no focussing)
+Compare with ANUGA outputs (full model, 250m no polys, 250m all polys)
+Leharne Fountain and Jane Sexton, 2008
+"""
+
+import project
+#from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid, figure
+from os import sep
+
+###################################################
+# Relevant definitions
+###################################################
+
+def get_max_boundary_data(filename):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[3]))
+    return mean(stage)
+
+def get_stage_data(filename,depth,no_models):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    mean_stages = zeros((len(depth),no_models), Float)
+    max_stages = zeros((len(depth),no_models), Float)
+    for i in range(no_models):
+        stage5 = []
+        stage10 = []
+        stage20 = []
+        stage50 = []
+        for line in lines[1:]:
+            fields = line.split(',')
+            x = float(fields[0])
+            # based on csv file output from ArcGIS: depth, x,y, no poly, all poly, and orig
+            y = float(fields[i+3]) 
+            if x == -depth[0]:
+                stage5.append(y)
+            if x == -depth[1]:
+                stage10.append(y)
+            if x == -depth[2]:
+                stage20.append(y)
+            if x == -depth[3]:
+                stage50.append(y)
+            
+        mean_stages[:,i] = [mean(stage5), mean(stage10), mean(stage20), mean(stage50)]
+        max_stages[:,i] = [max(stage5), max(stage10), max(stage20), max(stage50)]
+    return mean_stages, max_stages
+
+def calc_M(mean_stages,boundary_mean):
+    #M_value=zeros(no_models,Float)
+    M_value=mean_stages[1,:]/boundary_mean
+    return M_value
+
+def calc_errors(mean_stages,no_models):
+    abs_error = zeros(len(mean_stages[1,:]),Float)
+    rel_error = zeros(len(mean_stages[1,:]),Float)
+    for i in range(len(mean_stages[1,:])):
+        abs_error[i] = (mean_stages[1,i]-mean_stages[1,no_models-1])
+        rel_error[i]= (abs_error[i]/mean_stages[1,no_models-1])*100
+    return abs_error,rel_error
+
+###################################################
+# Determine max stage at boundary points
+###################################################
+
+event_number = 27255
+boundary_mean = get_max_boundary_data(project.boundaries_dir+str(event_number)+sep+'max_sts_stage.csv')
+
+###################################################
+# Read in max data from all models
+###################################################
+
+from Numeric import zeros, Float
+directory = project.home+project.state+sep+project.scenario+sep+'map_work'
+depth = [5.0,10.,20.,50.]
+no_models = 2
+#plot?
+plot_flag = False
+#Table??
+table_flag = True
+filename = directory + sep + 'Carnarvon_Ph2_compare_'+str(event_number)+'.csv'
+
+mean_stages, max_stages = get_stage_data(filename, depth, no_models)
+print mean_stages
+###################################################
+# Compare with Green's function and plot
+###################################################
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 100.
+d2 = arange(d1,1,-0.1)
+h1 = boundary_mean
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+
+###################################################
+#calculate M values (scaling of 100 m depth mean to 10 m)
+###################################################
+M_value = calc_M(mean_stages,boundary_mean)
+
+
+###################################################
+#calculate absolute and relative errors 
+###################################################
+abs_error,rel_error=calc_errors(mean_stages,no_models)
+
+
+##if plot_flag==True:
+##    ion()
+##    figure(1)
+##    plot(depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Carnarvon')
+##    legend(['original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Carnarvon_mean_ORIG_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(2)
+##    plot(depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Carnarvon')
+##    legend(['250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Carnarvon_mean_250AP_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(3)
+##    plot(depth,mean_stages[:,0],'ob',depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Carnarvon')
+##    legend(['250m no poly','250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Carnarvon_mean_ALL_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(4)
+##    plot(depth,max_stages[:,0],'ob',depth,max_stages[:,1],'+r',depth,max_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (max stage) versus Green\'s approximation \n \
+##    for event 27283 at Carnarvon')
+##    legend(['250m no poly','250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Carnarvon_max_ALL_' + str(event_number) + '_mean'
+##    savefig(figname)
+##    close('all')
+
+if table_flag==True:
+    import csv
+    csvfile = directory+sep+'ph2compare_Carnarvon_max_ALL_' + str(event_number) + '_mean.csv'
+    fid1 = open(csvfile,'w')
+    writer = csv.writer(fid1,delimiter=',',)
+
+    if no_models==1:
+        writer.writerow(('depth (m)','250m no poly'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0]))
+        writer.writerow(('100',boundary_mean,))
+        writer.writerow(('M-value',M_value[0]))
+        #writer.writerow(('Absolute Error', abs_error[0],abs_error[1]))
+        #writer.writerow(('Relative Error %', rel_error[0],rel_error[1]))
+
+    if no_models==2:
+        writer.writerow(('depth (m)','250m no poly','original'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0],mean_stages[i,1]))
+        writer.writerow(('100',boundary_mean,boundary_mean))
+        writer.writerow(('M-value',M_value[0],M_value[1]))
+        writer.writerow(('Absolute Error', abs_error[0],abs_error[1]))
+        writer.writerow(('Relative Error %', rel_error[0],rel_error[1]))
+        
+    if no_models==3:
+        writer.writerow(('depth (m)','250m no poly','250m poly','original'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0],mean_stages[i,1],mean_stages[i,2]))
+        writer.writerow(('100',boundary_mean,boundary_mean,boundary_mean))
+        writer.writerow(('M-value',M_value[0],M_value[1],M_value[2]))
+        writer.writerow(('Absolute Error', abs_error[0],abs_error[1],abs_error[2]))
+        writer.writerow(('Relative Error %', rel_error[0],rel_error[1],rel_error[2]))
+
+    fid1.close()
+    
+    
Index: /anuga_work/production/wa/carnarvon/project.py
===================================================================
--- /anuga_work/production/wa/carnarvon/project.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/project.py	(revision 7411)
@@ -0,0 +1,222 @@
+"""Common filenames and locations for elevation, meshes and outputs.
+This script is the heart of all scripts in the folder
+"""
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, is_inside_polygon, number_mesh_triangles
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+
+#------------------------------------------------------------------------------
+# Directory setup
+#------------------------------------------------------------------------------
+# Note: INUNDATIONHOME is the inundation directory, not the data directory.
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent diruser = get_user_name()
+muxhome = getenv('MUXHOME')
+user = get_user_name()
+host = get_host_name()
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S',localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S',gmtime()) 
+build_time = time+'_build'
+run_time = time+'_run'
+
+#------------------------------------------------------------------------------
+# Initial Conditions
+#------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'carnarvon'
+scenario = 'carnarvon_tsunami_scenario'
+
+# Model specific parameters. One or all can be changed each time the
+# run_scenario script is executed
+tide = 1                #1.0
+#event_number = 27255 # Java 9.3 worst case for Perth
+#event_number = 68693 # Sumatra 9.2
+event_number = 27283  # Java 9.3 original
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             
+finaltime=80000         # final time for simulation
+
+setup='final'  # Final can be replaced with trial or basic.
+               # Either will result in a coarser mesh that will allow a
+               # faster, but less accurate, simulation.
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=4
+    yieldstep=60
+
+#------------------------------------------------------------------------------
+# Output Filename
+#------------------------------------------------------------------------------
+# Important to distinguish each run - ensure str(user) is included!
+# Note, the user is free to include as many parameters as desired
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(event_number)+'_'+ 'alpha' +str(alpha)+'_'+str(user)
+
+#------------------------------------------------------------------------------
+# Input Data
+#------------------------------------------------------------------------------
+
+# elevation data used in build_carnarvon.py
+# onshore data: format ascii grid with accompanying projection file
+onshore_name = 'dem_onshore' 
+# bathymetry: format x,y,elevation (with title)
+offshore_name = 'carnarvon_data.txt'
+offshore_name1 = 'makeup.txt'
+#grids made for aoi and aos as anuga interpretation was bad
+topo_aoi = 'topo_20m_aoi'
+topo_aos = 'topo_50m_aos'
+
+# gauges - used in get_timeseries.py
+gauge_name = 'MH_gauges_deep.csv' #'carnarvon.csv'
+gauge_name2 = 'thinned_MGA50.csv'
+#buildings - used in run_building_inundation.py
+building = 'carnarvon_res'
+
+# BOUNDING POLYGON - used in build_boundary.py and run_carnarvon.py respectively
+# NOTE: when files are put together the points must be in sequence - for ease go clockwise!
+# Check the run_carnarvon.py for boundary_tags
+# thinned ordering file from Hazard Map: format is index,latitude,longitude (with title)
+order_filename = 'thinned_boundary_ordering.csv'
+#landward bounding points
+landward = 'landward_bounding_polygon.csv'
+
+#------------------------------------------------------------------------------
+# Output Elevation Data
+#------------------------------------------------------------------------------
+# Output filename for elevation
+# this is a combination of all the data (utilisied in build_boundary)
+combined_name ='carnarvon_combined_elevation_quick'
+combined_smaller_name = 'carnarvon_combined_elevation_smaller'
+
+#------------------------------------------------------------------------------
+# Directory Structure
+#------------------------------------------------------------------------------
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+boundaries_dir = anuga_dir+'boundaries'+ sep 
+output_dir = anuga_dir+'outputs'+sep
+gauges_dir = anuga_dir+'gauges'+sep
+meshes_dir = anuga_dir+'meshes'+sep
+
+#------------------------------------------------------------------------------
+# Location of input and output data
+#------------------------------------------------------------------------------
+# where the input data sits
+onshore_in_dir_name = topographies_in_dir + onshore_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+offshore_in_dir_name1 = topographies_in_dir + offshore_name1
+offshore_in_dir_aoi = topographies_in_dir + topo_aoi
+offshore_in_dir_aos = topographies_in_dir + topo_aos
+
+# where the output data sits
+onshore_dir_name = topographies_dir + onshore_name
+offshore_dir_name = topographies_dir + offshore_name
+offshore_dir_name1 = topographies_dir + offshore_name1
+offshore_dir_aoi = topographies_dir + topo_aoi
+offshore_dir_aos = topographies_dir + topo_aos
+
+# where the combined elevation file sits
+combined_dir_name = topographies_dir + combined_name
+combined_smaller_name_dir = topographies_dir + combined_smaller_name
+
+# where the mesh sits (this is created during the run_carnarvon.py)
+meshes_dir_name = meshes_dir + scenario_name+'.msh'
+
+# where the boundary ordering files sit (this is used within build_boundary.py)
+order_filename_dir = boundaries_dir + order_filename
+
+# where the landward points of boundary extent sit (this is used within run_carnarvon.py)
+landward_dir = boundaries_dir + landward
+
+# where the event sts files sits (this is created during the build_boundary.py)
+boundaries_dir_event = boundaries_dir + str(event_number) + sep
+boundaries_dir_mux = muxhome
+
+# where the directory of the output filename sits
+output_build_time_dir = output_dir+build_time+dir_comment+sep   #used for build_carnarvon.py
+output_run_time_dir = output_dir+run_time+dir_comment+sep       #used for run_carnarvon.py
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#w here the directory of the gauges sit
+gauges_dir_name = gauges_dir + gauge_name       #used for get_timeseries.py
+gauges_dir_name2 = gauges_dir + gauge_name2     #used for get_timeseries.py
+building_in_dir_name = gauges_dir + building + '.csv' 
+#------------------------------------------------------------------------------
+# Interior region definitions
+#------------------------------------------------------------------------------
+
+#Land, to set the initial stage/water to be offcoast only
+#Land and Ocean to clip data
+poly_mainland=read_polygon(polygons_dir +'land_initial_condition.csv')
+poly_island1=read_polygon(polygons_dir +'land_initial_condition_bernier.csv')
+poly_island2=read_polygon(polygons_dir +'land_initial_condition_dorne.csv')
+poly_ocean=read_polygon(polygons_dir +'ocean_initial_condition.csv')
+poly_aos_extract = read_polygon(polygons_dir+'extract_aos.csv')
+
+# Initial bounding polygon for data clipping 
+poly_all = read_polygon(polygons_dir+'poly_all.csv')
+res_poly_all = 100000*res_factor
+
+# Area of Interest 1 (carnarvon)
+poly_aoi1 = read_polygon(polygons_dir+'Carnarvon5m.csv')
+res_aoi1 = 500*res_factor
+
+# Area of Significance 1 (carnarvon)
+poly_aos1 = read_polygon(polygons_dir+'Carnarvon10m.csv')
+res_aos1 = 1500*res_factor
+
+# Shallow water 1
+poly_sw1 = read_polygon(polygons_dir+'Carnarvon20m.csv')
+res_sw1 = 25000*res_factor
+
+# Shallow water 2
+poly_sw2 = read_polygon(polygons_dir+'Island20m.csv')
+res_sw2 = 50000*res_factor
+
+# Combined all regions, must check that all are included!
+interior_regions = [[poly_aoi1,res_aoi1],[poly_aos1,res_aos1]
+                     ,[poly_sw1,res_sw1],[poly_sw2,res_sw2]]
+
+    
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+print 'min estimated number of triangles', trigs_min
+   
+#------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#------------------------------------------------------------------------------
+
+# carnarvon CBD extract ascii grid
+xminCBD = 763000
+xmaxCBD = 775000
+yminCBD = 7239000
+ymaxCBD = 7251000
Index: /anuga_work/production/wa/carnarvon/project_250m.py
===================================================================
--- /anuga_work/production/wa/carnarvon/project_250m.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/project_250m.py	(revision 7411)
@@ -0,0 +1,210 @@
+"""Common filenames and locations for elevation, meshes and outputs.
+This script is the heart of all scripts in the folder
+"""
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, is_inside_polygon, number_mesh_triangles
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+
+#------------------------------------------------------------------------------
+# Directory setup
+#------------------------------------------------------------------------------
+# Note: INUNDATIONHOME is the inundation directory, not the data directory.
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent diruser = get_user_name()
+muxhome = getenv('MUXHOME')
+user = get_user_name()
+host = get_host_name()
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S',localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S',gmtime()) 
+build_time = time+'_build'
+run_time = time+'_run'
+
+#------------------------------------------------------------------------------
+# Initial Conditions
+#------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'carnarvon'
+scenario = 'carnarvon_tsunami_scenario'
+
+# Model specific parameters. One or all can be changed each time the
+# run_scenario script is executed
+tide = 0                #0.6
+event_number = 27255   # linked to hazard map
+#event_number = 27283
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             
+finaltime=80000         # final time for simulation
+
+interior_mesh = 'none' # Can have 'all' or 'none' for Phase 2 study
+
+setup='trial'  # Final can be replaced with trial or basic.
+               # Either will result in a coarser mesh that will allow a
+               # faster, but less accurate, simulation.
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=4
+    yieldstep=60
+
+#------------------------------------------------------------------------------
+# Output Filename
+#------------------------------------------------------------------------------
+# Important to distinguish each run - ensure str(user) is included!
+# Note, the user is free to include as many parameters as desired
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(event_number)+'_250m_' + str(interior_mesh) +'_'+str(user)
+
+#------------------------------------------------------------------------------
+# Input Data
+#------------------------------------------------------------------------------
+
+# elevation data used in build_carnarvon.py
+# onshore data: format ascii grid with accompanying projection file
+onshore_name = 'grid_250m_2005' 
+
+# gauges - used in get_timeseries.py
+gauge_name = 'carnarvon.csv'
+gauge_name2 = 'thinned_MGA50.csv'
+
+# BOUNDING POLYGON - used in build_boundary.py and run_carnarvon.py respectively
+# NOTE: when files are put together the points must be in sequence - for ease go clockwise!
+# Check the run_carnarvon.py for boundary_tags
+# thinned ordering file from Hazard Map: format is index,latitude,longitude (with title)
+order_filename = 'thinned_boundary_ordering.csv'
+#landward bounding points
+landward = 'landward_bounding_polygon.csv'
+
+#------------------------------------------------------------------------------
+# Output Elevation Data
+#------------------------------------------------------------------------------
+# Output filename for elevation
+# this is a combination of all the data (utilisied in build_boundary)
+combined_name ='carnarvon_combined_elevation_250m'
+
+#------------------------------------------------------------------------------
+# Directory Structure
+#------------------------------------------------------------------------------
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+boundaries_dir = anuga_dir+'boundaries'+ sep 
+output_dir = anuga_dir+'outputs'+sep
+gauges_dir = anuga_dir+'gauges'+sep
+meshes_dir = anuga_dir+'meshes'+sep
+
+#------------------------------------------------------------------------------
+# Location of input and output data
+#------------------------------------------------------------------------------
+# where the input data sits
+onshore_in_dir_name = topographies_in_dir + onshore_name
+
+# where the output data sits
+onshore_dir_name = topographies_dir + onshore_name
+
+# where the combined elevation file sits
+combined_dir_name = topographies_dir + combined_name
+
+# where the mesh sits (this is created during the run_carnarvon.py)
+meshes_dir_name = meshes_dir + scenario_name+ interior_mesh +'.msh'
+
+# where the boundary ordering files sit (this is used within build_boundary.py)
+order_filename_dir = boundaries_dir + order_filename
+
+# where the landward points of boundary extent sit (this is used within run_carnarvon.py)
+landward_dir = boundaries_dir + landward
+
+# where the event sts files sits (this is created during the build_boundary.py)
+boundaries_dir_event = boundaries_dir + str(event_number) + sep
+boundaries_dir_mux = muxhome
+
+# where the directory of the output filename sits
+output_build_time_dir = output_dir+build_time+dir_comment+sep   #used for build_carnarvon.py
+output_run_time_dir = output_dir+run_time+dir_comment+sep       #used for run_carnarvon.py
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#w here the directory of the gauges sit
+gauges_dir_name = gauges_dir + gauge_name       #used for get_timeseries.py
+gauges_dir_name2 = gauges_dir + gauge_name2     #used for get_timeseries.py
+
+#------------------------------------------------------------------------------
+# Interior region definitions
+#------------------------------------------------------------------------------
+
+#Land, to set the initial stage/water to be offcoast only
+#Land and Ocean to clip data
+poly_mainland=read_polygon(polygons_dir +'land_initial_condition.csv')
+poly_island1=read_polygon(polygons_dir +'land_initial_condition_bernier.csv')
+poly_island2=read_polygon(polygons_dir +'land_initial_condition_dorne.csv')
+poly_ocean=read_polygon(polygons_dir +'ocean_initial_condition.csv')
+
+# Initial bounding polygon for data clipping 
+poly_all = read_polygon(polygons_dir+'poly_all.csv')
+res_poly_all = 100000*res_factor
+
+# Area of Interest 1 (carnarvon)
+poly_aoi1 = read_polygon(polygons_dir+'Carnarvon5m.csv')
+res_aoi1 = 500*res_factor
+
+# Area of Significance 1 (carnarvon)
+poly_aos1 = read_polygon(polygons_dir+'Carnarvon10m.csv')
+res_aos1 = 1500*res_factor
+
+# Shallow water 1
+poly_sw1 = read_polygon(polygons_dir+'Carnarvon20m.csv')
+res_sw1 = 25000*res_factor
+
+# Shallow water 2
+poly_sw2 = read_polygon(polygons_dir+'Island20m.csv')
+res_sw2 = 50000*res_factor
+
+
+# Combined all regions, must check that all are included!
+
+if interior_mesh =='all':
+    print'Mesh = all'
+    interior_regions = [[poly_aoi1,res_aoi1],[poly_aos1,res_aos1]
+                     ,[poly_sw1,res_sw1],[poly_sw2,res_sw2]]
+if interior_mesh =='none': 
+    print'Mesh = none'
+    interior_regions = []
+     
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+print 'min estimated number of triangles', trigs_min
+   
+#------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#------------------------------------------------------------------------------
+
+# carnarvon CBD extract ascii grid
+##xminCBD = 
+##xmaxCBD = 
+##yminCBD = 
+##ymaxCBD = 
Index: /anuga_work/production/wa/carnarvon/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/carnarvon/run_boundary_points.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/run_boundary_points.py	(revision 7411)
@@ -0,0 +1,77 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+
+# # Related major packages
+# from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import URS_points_needed_to_file, \
+     urs_ungridded2sww
+#import project                 # Definition of file names and polygons
+
+#-----------------------------------------------------------------------------
+# With no project file
+#-----------------------------------------------------------------------------
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+from os import sep, environ, getenv, getcwd ,umask
+from anuga.utilities.system_tools import get_user_name, get_host_name
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent dir   
+user = get_user_name()
+host = get_host_name()
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'carnarvon'
+scenario = 'carnarvon_tsunami_scenario'
+
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+polygons_dir = anuga_dir+'polygons'+sep
+
+#boundaries locations
+boundaries_in_dir = anuga_dir + sep + 'boundaries' + sep + scenario_name
+boundaries_dir = anuga_dir+'boundaries'+sep
+boundaries_dir_name = boundaries_dir + scenario_name
+
+# bounding polygon for study area
+poly_all = read_polygon(polygons_dir+'poly_all.csv')
+
+
+
+#-----------------------------------------------------------------------------
+# run_boundary_points
+#-----------------------------------------------------------------------------
+  
+LL_LAT = -50.0          #ll_lat - lower left latitude, in decimal degrees
+LL_LONG = 80.0          #ll-long - lower left longitude, in decimal degrees
+GRID_SPACING = 2.0/60.0 #grid_spacing - in deciamal degrees
+LAT_AMOUNT = 4800       #lat_amount - number of latitudes 
+LONG_AMOUNT = 3600      #long_amount- number of longs
+ZONE = 49
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+poly = poly_all
+print "poly", poly
+print "project.boundaries_in_dir",boundaries_in_dir
+URS_points_needed_to_file(boundaries_in_dir,poly, ZONE,
+                          LL_LAT, LL_LONG,GRID_SPACING,LAT_AMOUNT, LONG_AMOUNT,export_csv=True)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True)
+#urs_ungridded2sww(project.boundaries_in_dir_name2, project.boundaries_dir_name5, mean_stage= project.tide,  verbose=True)
Index: /anuga_work/production/wa/carnarvon/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/carnarvon/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,69 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+import project
+import csv
+
+directory = project.output_dir
+
+##time_dir1 = '20081202_084220_run_final_1_27283_alpha0.1_kvanputt'
+##time_dir2 = '20081202_084202_run_final_1_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081202_084132_run_final_1_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081202_084025_run_final_0_68693_alpha0.1_kvanputt'
+time_dir5 = '20081202_083932_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir6 = '20081201_103449_run_final_0_27283_alpha0.1_kvanputt'
+
+time_dirs = [time_dir5] #, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+buildings = project.building_in_dir_name
+
+for time_dir in time_dirs:
+    time_dir_name = time_dir[-25:][:-18]
+    building_marker = '_m_'+ time_dir_name
+   
+    name = directory+time_dir+sep+project.scenario_name #basename for the sww files 
+    
+    inundation_damage(name, buildings, building_marker)
+    #add_depth_and_momentum2csv(name, buildings, building_marker)
+    
+    building_marker_dir_name = project.gauges_dir + project.building + building_marker + '.csv'
+    out_file = directory+time_dir+ sep+'carnarvon_res.csv'
+    print 'out file %s' %out_file
+    print 'building_marker_dir_name %s' %building_marker_dir_name
+    csv_fd = open(building_marker_dir_name, 'r')
+    output_file = open(out_file, 'w')
+
+    reader = csv.reader(csv_fd)
+    writer = csv.writer(output_file, lineterminator='\n')
+
+    for record in reader:
+       newline = record[-8:]
+       newline.insert(0,record[0])
+       newline.insert(1,record[1])
+       newline.insert(2,record[2])
+       writer.writerow(newline)
+       
+    print 'output file printed to: %s' %out_file
+    csv_fd.close()
+    output_file.close()
+     
+
+    
Index: /anuga_work/production/wa/carnarvon/run_carnarvon.py
===================================================================
--- /anuga_work/production/wa/carnarvon/run_carnarvon.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/run_carnarvon.py	(revision 7411)
@@ -0,0 +1,244 @@
+"""Script for running a tsunami inundation scenario for carnarvon, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data is compiled into a pts file through build_carnarvon.py
+and a simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_carnarvon.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid, create_sts_boundary
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+from anuga.geospatial_data.geospatial_data import find_optimal_smoothing_parameter
+from polygon import Polygon_function
+    
+# Application specific imports
+import project  # Definition of file names and polygons
+numprocs = 1
+myid = 0
+
+def run_model(**kwargs):
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+    print "Processor Name:",get_processor_name()
+
+    #copy script must be before screen_catcher
+
+    print 'output_dir',kwargs['output_dir']
+    
+    copy_code_files(kwargs['output_dir'],__file__, 
+             dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+    store_parameters(**kwargs)
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print "Processor Name:",get_processor_name()
+    
+    #-----------------------------------------------------------------------
+    # Domain definitions
+    #-----------------------------------------------------------------------
+
+    # Read in boundary from ordered sts file
+    urs_bounding_polygon=create_sts_boundary(os.path.join(project.boundaries_dir_event,project.scenario_name))
+
+    # Reading the landward defined points, this incorporates the original clipping
+    # polygon minus the 100m contour
+    landward_bounding_polygon = read_polygon(project.landward_dir)
+
+    # Combine sts polyline with landward points
+    bounding_polygon = urs_bounding_polygon + landward_bounding_polygon
+    
+    # counting segments
+    N = len(urs_bounding_polygon)-1
+
+    # boundary tags refer to project.landward 4 points equals 5 segments start at N
+    boundary_tags={'back': [N+1,N+2,N+3], 'side': [N,N+4], 'ocean': range(N)}
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a tagged
+    # boundary and interior regions defined in project.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    # IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+        
+    print 'start create mesh from regions'
+
+    create_mesh_from_regions(bounding_polygon,
+                         boundary_tags=boundary_tags,
+                         maximum_triangle_area=project.res_poly_all,
+                         interior_regions=project.interior_regions,
+                         filename=project.meshes_dir_name,
+                         use_cache=True,
+                         verbose=True)
+   
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    domain = Domain(project.meshes_dir_name, use_cache=False, verbose=True)
+    print 'memory usage before del domain',mem_usage()
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    print 'Setup initial conditions'
+
+    # sets the initial stage in the offcoast region only
+    IC = Polygon_function( [(project.poly_mainland, 0),(project.poly_island1, 0)
+                            ,(project.poly_island2, 0)], default = kwargs['tide'],
+                             geo_reference = domain.geo_reference)
+    domain.set_quantity('stage', IC)
+    #domain.set_quantity('stage',kwargs['tide'] )
+    domain.set_quantity('friction', kwargs['friction']) 
+    
+    print 'Start Set quantity',kwargs['elevation_file']
+
+    domain.set_quantity('elevation', 
+                        filename = kwargs['elevation_file'],
+                        use_cache = False,
+                        verbose = True,
+                        alpha = kwargs['alpha'])
+    print 'Finished Set quantity'
+
+##   #------------------------------------------------------
+##    # Distribute domain to implement parallelism !!!
+##    #------------------------------------------------------
+##
+##    if numprocs > 1:
+##        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2)                 # Apply second order scheme
+    domain.set_minimum_storable_height(0.01)    # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.tight_slope_limiters = 1
+    print 'domain id', id(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+   
+    boundary_urs_out=project.boundaries_dir_event + sep + project.scenario_name
+
+    Br = Reflective_boundary(domain)
+    Bs = Dirichlet_boundary([kwargs['tide'],0,0])
+    
+    print 'Available boundary tags', domain.get_boundary_tags()
+    Bf = Field_boundary(boundary_urs_out+'.sts',  # Change from file_boundary
+                   domain, mean_stage=project.tide,
+                   time_thinning=1,
+                   default_boundary=Dirichlet_boundary(0,0,0]),
+                   use_cache=True,
+                   verbose=True,
+                   boundary_polygon=bounding_polygon)
+
+    domain.set_boundary({'back': Br,
+                         'side': Bs,
+                         'ocean': Bf}) 
+
+    kwargs['input_start_time']=domain.starttime
+
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #--------------------------------------------------------------------
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = project.yieldstep, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = False): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')
+
+    # these outputs should be checked with the resultant inundation map
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'Simulation took %.2f seconds' %(time.time()-t0)
+
+    #kwargs 'completed' must be added to write the final parameters to file
+    kwargs['completed']=str(time.time()-t0)
+     
+    store_parameters(**kwargs)
+     
+    print 'memory usage before del domain1',mem_usage()
+    
+    
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    
+    kwargs={}
+    kwargs['file_name']=project.dir_comment
+    kwargs['finaltime']=project.finaltime
+    kwargs['output_dir']=project.output_run_time_dir
+    kwargs['elevation_file']=project.combined_dir_name+'.pts'
+    kwargs['scenario_name']=project.scenario_name
+    kwargs['tide']=project.tide
+    kwargs['alpha'] = project.alpha
+    kwargs['friction']=project.friction
+    #kwargs['num_cpu']=numprocs
+    #kwargs['host']=project.host
+    #kwargs['starttime']=project.starttime
+    #kwargs['yieldstep']=project.yieldstep
+    #kwargs['user']=project.user
+    #kwargs['time_thinning'] = project.time_thinning
+      
+    run_model(**kwargs)
+      
+   
Index: /anuga_work/production/wa/carnarvon/run_carnarvon_250m.py
===================================================================
--- /anuga_work/production/wa/carnarvon/run_carnarvon_250m.py	(revision 7411)
+++ /anuga_work/production/wa/carnarvon/run_carnarvon_250m.py	(revision 7411)
@@ -0,0 +1,239 @@
+"""Script for running a tsunami inundation scenario for carnarvon, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project_250m.polygon,
+the elevation data is compiled into a pts file through build_carnarvon.py
+and a simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_carnarvon.py)
+       information from project file
+Outputs: sww file stored in project_250m.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid, create_sts_boundary
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+from anuga.geospatial_data.geospatial_data import find_optimal_smoothing_parameter
+from polygon import Polygon_function
+    
+# Application specific imports
+import project_250m  # Definition of file names and polygons
+numprocs = 1
+myid = 0
+
+def run_model(**kwargs):
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+    print "Processor Name:",get_processor_name()
+
+    #copy script must be before screen_catcher
+
+    print 'output_dir',kwargs['output_dir']
+    
+    copy_code_files(kwargs['output_dir'],__file__, 
+             dirname(project_250m.__file__)+sep+ project_250m.__name__+'.py' )
+
+    store_parameters(**kwargs)
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print "Processor Name:",get_processor_name()
+    
+    #-----------------------------------------------------------------------
+    # Domain definitions
+    #-----------------------------------------------------------------------
+
+    # Read in boundary from ordered sts file
+    urs_bounding_polygon=create_sts_boundary(os.path.join(project_250m.boundaries_dir_event,project_250m.scenario_name))
+
+    # Reading the landward defined points, this incorporates the original clipping
+    # polygon minus the 100m contour
+    landward_bounding_polygon = read_polygon(project_250m.landward_dir)
+
+    # Combine sts polyline with landward points
+    bounding_polygon = urs_bounding_polygon + landward_bounding_polygon
+    
+    # counting segments
+    N = len(urs_bounding_polygon)-1
+
+    # boundary tags refer to project_250m.landward 4 points equals 5 segments start at N
+    boundary_tags={'back': [N+1,N+2,N+3], 'side': [N,N+4], 'ocean': range(N)}
+
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a tagged
+    # boundary and interior regions defined in project_250m.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    # IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+        
+    print 'start create mesh from regions'
+
+    create_mesh_from_regions(bounding_polygon,
+                         boundary_tags=boundary_tags,
+                         maximum_triangle_area=project_250m.res_poly_all,
+                         interior_regions=project_250m.interior_regions,
+                         filename=project_250m.meshes_dir_name,
+                         use_cache=True,
+                         verbose=True)
+   
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    domain = Domain(project_250m.meshes_dir_name, use_cache=False, verbose=True)
+    print 'memory usage before del domain',mem_usage()
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    print 'Setup initial conditions'
+
+    # sets the initial stage in the offcoast region only
+    IC = Polygon_function( [(project_250m.poly_mainland, 0),(project_250m.poly_island1, 0)
+                            ,(project_250m.poly_island2, 0)], default = kwargs['tide'],
+                             geo_reference = domain.geo_reference)
+    domain.set_quantity('stage', IC)
+    #domain.set_quantity('stage',kwargs['tide'] )
+    domain.set_quantity('friction', kwargs['friction']) 
+    
+    print 'Start Set quantity',kwargs['elevation_file']
+
+    domain.set_quantity('elevation', 
+                        filename = kwargs['elevation_file'],
+                        use_cache = False,
+                        verbose = True,
+                        alpha = kwargs['alpha'])
+    print 'Finished Set quantity'
+
+##   #------------------------------------------------------
+##    # Distribute domain to implement parallelism !!!
+##    #------------------------------------------------------
+##
+##    if numprocs > 1:
+##        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2)                 # Apply second order scheme
+    domain.set_minimum_storable_height(0.01)    # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.tight_slope_limiters = 1
+    print 'domain id', id(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+   
+    boundary_urs_out=project_250m.boundaries_dir_event + sep + project_250m.scenario_name
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([kwargs['tide'],0,0])
+    
+    print 'Available boundary tags', domain.get_boundary_tags()
+    Bf = Field_boundary(boundary_urs_out+'.sts',  # Change from file_boundary
+                   domain, mean_stage= project_250m.tide,
+                   time_thinning=1,
+                   default_boundary=Bd,
+                   use_cache=True,
+                   verbose = True,
+                   boundary_polygon=bounding_polygon)
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf}) 
+
+    kwargs['input_start_time']=domain.starttime
+
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #--------------------------------------------------------------------
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = project_250m.yieldstep, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = False): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')
+
+    # these outputs should be checked with the resultant inundation map
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'Simulation took %.2f seconds' %(time.time()-t0)
+
+    #kwargs 'completed' must be added to write the final parameters to file
+    kwargs['completed']=str(time.time()-t0)
+     
+    store_parameters(**kwargs)
+     
+    print 'memory usage before del domain1',mem_usage()
+    
+    
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    
+    kwargs={}
+    kwargs['file_name']=project.dir_comment
+    kwargs['finaltime']=project_250m.finaltime
+    kwargs['output_dir']=project_250m.output_run_time_dir
+    kwargs['elevation_file']=project_250m.combined_dir_name+'.pts'
+    kwargs['scenario_name']=project_250m.scenario_name
+    kwargs['tide']=project_250m.tide
+    kwargs['alpha'] = project_250m.alpha
+    kwargs['friction']=project_250m.friction
+     
+    run_model(**kwargs)
+      
+   
Index: /anuga_work/production/wa/dampier_2006/build_dampier.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/build_dampier.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/build_dampier.py	(revision 7411)
@@ -0,0 +1,186 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.geospatial_data.geospatial_data import *
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, copy_code_files
+from anuga_parallel.parallel_abstraction import get_processor_name
+
+# Application specific imports
+import project_urs   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project_urs.output_build_time_dir,__file__, 
+               dirname(project_urs.__file__)+sep+ project_urs.__name__+'.py' )
+
+start_screen_catcher(project_urs.output_build_time_dir)
+print "Processor Name:",get_processor_name()
+
+print 'USER:    ', project_urs.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print"project_urs.combined_dir_name",project_urs.combined_dir_name
+
+# topography directory filenames
+onshore_in_dir_name = project_urs.onshore_in_dir_name
+coast_in_dir_name = project_urs.coast_in_dir_name
+offshore_in_dir_name = project_urs.offshore_in_dir_name
+offshore1_in_dir_name = project_urs.offshore1_in_dir_name
+offshore2_in_dir_name = project_urs.offshore2_in_dir_name
+
+onshore_dir_name = project_urs.onshore_dir_name
+coast_dir_name = project_urs.coast_dir_name
+offshore_dir_name = project_urs.offshore_dir_name
+offshore1_dir_name = project_urs.offshore1_dir_name
+offshore2_dir_name = project_urs.offshore2_dir_name
+'''
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name,
+                              basename_out=onshore_dir_name,
+                              use_cache=True, verbose=True)
+
+convert_dem_from_ascii2netcdf(offshore1_in_dir_name,
+                              basename_out=offshore1_dir_name,
+                              use_cache=True, verbose=True)
+convert_dem_from_ascii2netcdf(offshore2_in_dir_name,
+                              basename_out=offshore2_dir_name,
+                              use_cache=True, verbose=True)
+
+#creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name, use_cache=True, verbose=True)
+
+#creates pts file for clipped DEMs
+dem2pts(offshore1_dir_name,
+        basename_out=offshore1_dir_name,
+        use_cache=True, verbose=True)
+dem2pts(offshore2_dir_name,
+        basename_out=offshore2_dir_name,
+        use_cache=True, verbose=True)
+
+print'create Geospatial onshore objects from topographies'
+#print'create Geospatial coastal objects from topographies'
+#print'create Geospatial nickel bay objects from topographies'
+#print'create Geospatial clipped TIN offshore objects from topographies'
+#print'create Geospatial offshore objects from topographies'
+G = Geospatial_data(file_name = onshore_dir_name + '.pts') +\
+    Geospatial_data(file_name = coast_in_dir_name + '.txt') +\
+    Geospatial_data(file_name = offshore_in_dir_name + '.txt') +\
+    Geospatial_data(file_name = offshore1_dir_name + '.pts') +\
+    Geospatial_data(file_name = offshore2_dir_name + '.pts')
+     
+
+print'add all geospatial objects'
+#G = G1 + G2 + G3 + G4 + G_off
+
+print'clip combined geospatial object by bounding polygon'
+G_clipped = G.clip(project_urs.poly_all)
+#FIXME: add a clip function to pts
+#print'shape of clipped data', G_clipped.get_data_points().shape
+
+print'export combined DEM file'
+if access(project_urs.topographies_dir,F_OK) == 0:
+    mkdir (project_urs.topographies_dir)
+G_clipped.export_points_file(project_urs.combined_dir_name + '.pts')
+#G_clipped.export_points_file(project_urs.combined_dir_name + '.txt')
+
+print'split combined data set'
+G_small, G_other = G_clipped.split(0.1, True)
+
+print'export split DEM file'
+G_small.export_points_file(project_urs.combined_dir_name + '_small' + '.pts')
+G_other.export_points_file(project_urs.combined_dir_name + '_other' + '.pts')
+
+print 'start reading:',project_urs.combined_smaller_dir_name + '.txt'
+G = Geospatial_data(file_name = project_urs.combined_smaller_dir_name + '.txt')
+print 'start split'
+G_smallest, G_other = G.split(0.1,True)
+
+print 'start export',project_urs.combined_smallest_dir_name + '.txt'
+#G.export_points_file(project_urs.combined_smaller_dir_name + '.txt')
+#G_smallest.export_points_file(project_urs.combined_smallest_dir_name + '.txt')
+'''
+#-------------------------------------------------------------------------
+# Convert URS to SWW file for boundary conditions 
+#-------------------------------------------------------------------------
+'''
+print 'starting to create boundary conditions'
+boundaries_in_dir_name = project_urs.boundaries_in_dir_name
+
+from anuga.shallow_water.data_manager import urs2sww
+
+print 'minlat=project_urs.north_boundary, maxlat=project_urs.south_boundary',project_urs.north_boundary, project_urs.south_boundary
+print 'minlon= project_urs.west_boundary, maxlon=project_urs.east_boundary',project_urs.west_boundary, project_urs.east_boundary
+
+#import sys; sys.exit()
+
+#if access(project_urs.boundaries_dir,F_OK) == 0:
+#    mkdir (project_urs.boundaries_dir)
+
+from caching import cache
+cache(urs2sww,
+      (boundaries_in_dir_name,
+       project_urs.boundaries_dir_name+'a'),
+      {'verbose': True,
+       'minlat': project_urs.south_boundary,
+       'maxlat': project_urs.north_boundary,
+       'minlon': project_urs.west_boundary,
+       'maxlon': project_urs.east_boundary,
+       'mint': 5000, 'maxt': 35000,
+#       'origin': domain.geo_reference.get_origin(),
+#       'mean_stage': project_urs.tide,
+       'zscale': 1,                 #Enhance tsunami
+       'fail_on_NaN': False},
+       verbose = True,
+       )
+#       dependencies = source_dir + project_urs.boundary_basename + '.sww')
+'''
+print 'starting to create boundary conditions'
+from anuga.shallow_water.data_manager import urs2sww, urs_ungridded2sww
+
+print 'boundaries_in_dir_name',project_urs.boundaries_in_dir_name
+
+urs_ungridded2sww(project_urs.boundaries_in_dir_name, project_urs.boundaries_in_dir_name,
+                  verbose=True, mint=4000, maxt=35000, zscale=1)
+
+
+
+
Index: /anuga_work/production/wa/dampier_2006/check_data.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/check_data.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/check_data.py	(revision 7411)
@@ -0,0 +1,60 @@
+
+
+from os import sep, getcwd, access, F_OK, mkdir, getenv
+from anuga.abstract_2d_finite_volumes.util import get_data_from_file
+import os
+from Numeric import zeros, array, allclose
+
+#makes the csv files from the evolved model
+
+home = getenv('INUNDATIONHOME') #Sandpit's parent dir   
+#user = get_user_name()
+data = 'data'
+state = 'western_australia'
+scenario_name = 'dampier'
+scenario = 'dampier_tsunami_scenario_2006'
+#scenario = 'test_dampier'
+an = 'anuga'
+bo = 'boundaries'
+
+#run_time = '20070305_055256_run'
+#run_time = '20070305_134855_run'
+run_time = '20070321_164505_run'
+
+topo = 'topographies'
+out = 'outputs'
+urs = 'urs'
+gridded = '1_10000'
+
+gauge_boundary_filename = 'gauges_time_series_first.csv'
+gauge_evolved_filename = 'gauges_time_series_first.csv'
+
+boundary_dir_filename = os.path.join(home,data,state,scenario,an,bo,gauge_boundary_filename)
+
+evolved_dir_filename= os.path.join(home,data,state,scenario,an,out,run_time,gauge_evolved_filename)
+
+
+print'evolved_dir_filename',evolved_dir_filename
+e_time, e_stage, e_momentum, e_speed, e_elevation = get_data_from_file(evolved_dir_filename)
+
+print'boundary_dir_filename',boundary_dir_filename
+b_time, b_stage, b_momentum, b_speed, b_elevation = get_data_from_file(boundary_dir_filename)
+
+ 
+# compares the 2 models
+j=0
+b_sample = []
+for i in range(len(b_time)):
+    if j<(len(e_time)) and b_time[i] == e_time[j]:
+        b_sample.append(float(b_stage[i]))
+        print 'time e equal b:', b_time[i], b_stage[i],i, j, b_sample[j], e_stage[j],(len(e_time)-1)
+        j = j +1
+
+
+assert allclose (b_sample, e_stage, 2, 0.1) 
+print "test successful" 
+
+
+
+
+                             
Index: /anuga_work/production/wa/dampier_2006/convert2latlon.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/convert2latlon.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/convert2latlon.py	(revision 7411)
@@ -0,0 +1,47 @@
+"""
+Convert Easting Northing to lon/lat for ultimately get kml file
+"""
+
+def alter_file(filename,filenameout):
+
+    from anuga.coordinate_transforms.lat_long_UTM_conversion import UTMtoLL
+    
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    fid_out = open(filenameout, 'w')
+    s = '%s,%s,%s\n' %('lon','lat','stage')
+    fid_out.write(s)
+    for line in lines[1:]:
+       fields = line.split(',')
+       easting = float(fields[0])
+       northing = float(fields[1])
+       stage = float(fields[3])
+       lat, lon = UTMtoLL(northing,easting, 50)
+       s = '%f,%f,%f\n' %(lon,lat,stage)
+       fid_out.write(s)
+
+    fid_out.close() 
+
+    return
+
+import project
+from os import sep
+
+# Dampier
+#timedir = '20070618_063824_run_final_2.4_onslow_nbartzis'
+timedir = '20070620_044413_run_final_2.4_exmouth_nbartzis'
+#timedir = '20070419_065050_run_final_2.4_dampier_nbartzi
+
+# Karratha
+
+filename = project.outputdir + timedir + sep + 'stage0_interp.csv'
+#filename = project.outputdir + timedir + sep + 'stage5_interp.csv'
+#filename = project.outputdir+ timedir + sep + 'stage20_interp.csv'
+#filename = project.outputdir+  timedir + sep + 'stage80_interp.csv'
+filename_out = project.outputdir + timedir + sep + 'stage0_convert.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage5_convert.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage20_convert.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage80_convert.csv'
+alter_file(filename,filename_out)
Index: /anuga_work/production/wa/dampier_2006/export_results.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/export_results.py	(revision 7411)
@@ -0,0 +1,81 @@
+import project, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+#time_dir = '20070426_045818_run' # HAT 1 in Dampier 10000 yr - CIPMA scenario
+#time_dir = '20070419_065050_run_final_2.4_dampier_nbartzis' # HAT 1 in Dampier 10000 yr
+#time_dir = '20070419_065018_run_final_0.0_dampier_nbartzis' # MSL 1 in Dampier 10000 yr
+#time_dir = '20070618_063824_run_final_2.4_onslow_nbartzis' # HAT 1 in Onslow 10000 yr
+#time_dir = '20070618_050232_run_final_0.0_onslow_nbartzis' # MSL 1 in Onslow 10000 yr
+#time_dir = '20070620_044413_run_final_2.4_exmouth_nbartzis' # HAT 1 in Exmouth 10000 yr
+time_dir = '20070620_044352_run_final_0.0_exmouth_nbartzis' # MSL 1 in Exmouth 10000 yr
+#time_dir = '20070618_063824_run_final_2.4_onslow_nbartzis' # HAT onslow
+#time_dir = '20070618_050232_run_final_0.0_onslow_nbartzis' # MSL onslow
+cellsize = 25
+timestep = None
+directory = project.output_dir
+#name = directory + time_dir + sep + project.scenario_name
+name = directory+time_dir+sep+project.scenario_name
+
+is_parallel = False
+if is_parallel == True: nodes = 4
+print 'output dir:', name
+
+#var = [2,3] # depth and speed
+var = [0,2,3]
+
+for which_var in var:
+    if which_var == 0:  # Stage
+        outname = name + '_stage_dampier'
+        quantityname = 'stage'
+
+    if which_var == 1:  # Absolute Momentum
+        outname = name + '_momentum_i1'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+    if which_var == 2:  # Depth
+        outname = name + '_depth_dampier'
+        quantityname = 'stage-elevation'  
+
+    if which_var == 3:  # Speed
+        outname = name + '_speed_dampier'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+    if which_var == 4:  # Elevation
+        outname = name + '_elevation_dampier'
+        quantityname = 'elevation'  #Elevation
+
+    if is_parallel == True:
+    #    print 'is_parallel',is_parallel
+        for i in range(0,nodes):
+            # this naming structure is defined in
+            # parallel_shallow_water
+            namei = name + '_P%d_%d' %(i,nodes)
+            outnamei = outname + '_P%d_%d' %(i,nodes)
+            print 'start sww2dem for sww file %d' %(i)
+            sww2dem(namei, basename_out = outnamei,
+                        quantity = quantityname,
+                        timestep = timestep,
+                        cellsize = cellsize,      
+                        #easting_min = project.e_min_area,
+                        #easting_max = project.e_max_area,
+                        #northing_min = project.n_min_area,
+                        #northing_max = project.n_max_area,        
+                        reduction = max, 
+                        verbose = True,
+                        format = 'asc')
+    else:
+        print 'start sww2dem'
+        sww2dem(name, basename_out = outname,
+                    quantity = quantityname,
+                    timestep = timestep,
+                    cellsize = cellsize,      
+                    easting_min = project.e_min_area_d,
+                    easting_max = project.e_max_area_d,
+                    northing_min = project.n_min_area_d,
+                    northing_max = project.n_max_area_d,        
+                    reduction = max, 
+                    verbose = True,
+                    format = 'asc')
Index: /anuga_work/production/wa/dampier_2006/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/get_timeseries.py	(revision 7411)
@@ -0,0 +1,102 @@
+"""
+Generate images of "gauges" for production run
+
+Inputs:
+
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+Outputs:
+
+* figures used for report stored in the report_figure directory
+
+"""
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries
+
+# Create report directory
+reportdir = getcwd()+sep+'report'+sep
+if access(reportdir,F_OK) == 0:
+    mkdir (reportdir)
+    
+# sww file created from URS boundary
+production_dirs = {#'boundaries': '10000 yr wave height'
+                   '20070418_035124_run': 'URS boundary normal'
+                   }
+
+    
+is_parallel = False
+if is_parallel == True:
+    nodes = 8
+    
+# Generate figures
+swwfiles = {}
+
+#J:\inundation\data\western_australia\onslow_tsunami_scenario_2006\anuga\boundaries SU-AU_high_res1.sww
+
+#boundary_dir_filename= os.path.join(home,data,state,'onslow_tsunami_scenario_2006',an,bo,'SU-AU_high_res1.sww')
+#gauges_dir_name_simple = 
+if is_parallel is True:
+    
+    for i in range(nodes):
+        print 'Sending node %d of %d' %(i,nodes)
+        swwfiles = {}
+        #reportname = report_name + '_%s' %(i)
+        for label_id in production_dirs.keys():
+            if label_id == 'boundaries':
+#                file_loc = project.boundaries_in_dir
+                swwfile = best_boundary_sww
+                print 'hi'
+            else:
+                file_loc = project.output_dir + label_id + sep
+                sww_extra = '_P%s_%s' %(i,nodes)
+                swwfile = file_loc + project.scenario_name + sww_extra + '.sww'
+                print 'swwfile',swwfile
+            swwfiles[swwfile] = label_id
+
+        texname, elev_output = sww2timeseries(swwfiles,
+                                              project.gauges_dir_name_simple,
+                                              production_dirs,
+                                              report = False,
+                                              #reportname = reportname,
+                                              plot_quantity = ['stage', 'momentum'],
+                                              generate_fig = False,
+                                              surface = False,
+                                              time_min = None,
+                                              time_max = None,
+                                              title_on = False,
+                                              verbose = True)
+            
+            #latex_output.append(texname)
+   
+
+else:
+    
+    for label_id in production_dirs.keys():
+        
+        if label_id == 'boundaries':
+                print 'boundaries'
+                file_loc = project.boundaries_in_dir
+                swwfile = project.boundaries_dir_name3 + '.sww'
+#                swwfile = boundary_dir_filename
+        else:
+            file_loc = project.output_dir + label_id + sep
+            swwfile = file_loc + project.scenario_name + '.sww'
+        swwfiles[swwfile] = label_id
+        
+    texname, elev_output = sww2timeseries(swwfiles,
+                                          project.gauges_dir_name,
+#                                          project.gauges_dir_name_simple,
+                                          production_dirs,
+                                          report = False,
+                                          #reportname = report_name,
+#                                          plot_quantity = ['stage', 'momentum'],
+                                          plot_quantity = ['stage', 'xmomentum', 'ymomentum'],
+                                          surface = False,
+                                          time_min = None,
+                                          time_max = None,
+                                          title_on = False,
+                                          verbose = True)
+                                          
Index: /anuga_work/production/wa/dampier_2006/get_timeseries_and.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/get_timeseries_and.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/get_timeseries_and.py	(revision 7411)
@@ -0,0 +1,178 @@
+"""
+Generate images of "gauges" for production run
+
+Inputs:
+
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+Outputs:
+
+* figures used for report stored in the report_figure directory
+
+"""
+
+from os import sep, getcwd, access, F_OK, mkdir, getenv
+#from anuga.abstract_2d_finite_volumes.util import get_data_from_file
+import os
+from Numeric import zeros, array, allclose
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, sww2timeseries, get_data_from_file
+
+#makes the csv files from the evolved model
+
+
+home = getenv('INUNDATIONHOME') #Sandpit's parent dir   
+#user = get_user_name()
+data = 'data'
+state = 'western_australia'
+scenario_name = 'dampier.sww'
+scenario = 'dampier_tsunami_scenario_2006'
+#scenario = 'test_dampier'
+an = 'anuga'
+bo = 'boundaries'
+
+run_time = '20070311_225041_run'
+production_dirs = {run_time: 'URS evolved data'#,
+                   #'boundaries': 'URS boundary condition'
+                   }
+
+topo = 'topographies'
+out = 'outputs'
+urs = 'urs'
+gridded = '1_10000'
+
+#gauge_filename = os.path.join(home,data,state,scenario,an,out,scenario_name,'.sww')
+#sww_filename ={}
+#swwfiles = {}
+
+#sww_filename[os.path.join(home,data,state,scenario,an,out,run_time,scenario_name)] = run_time
+
+gauge_boundary_filename = 'gauges_time_series_near_top.csv'
+gauge_evolved_filename = 'gauges_time_series_near_top.csv'
+#gauge_boundary_filename = 'gauges_time_series_middle.csv'
+#gauge_evolved_filename = 'gauges_time_series_middle.csv'
+
+#gauge_boundary_filename = 'gauges_time_series_first.csv'
+#gauge_evolved_filename = 'gauges_time_series_first.csv'
+
+boundary_dir_filename = os.path.join(home,data,state,scenario,an,bo,gauge_boundary_filename)
+print'boundary_dir_filename',boundary_dir_filename
+out_dir=os.path.join(home,data,state,scenario,an,out,run_time)
+out_dir_name= out_dir+sep
+
+evolved_dir_filename= os.path.join(home,data,state,scenario,an,out,run_time,gauge_evolved_filename)
+
+#start_screen_catcher(out_dir_name, print_to_screen=True)
+start_screen_catcher(out_dir_name, extra_info='get_time', print_to_screen=True)
+print'boundary_dir_filename',boundary_dir_filename
+print'evolved_dir_filename',evolved_dir_filename
+
+#file_loc = project.output_dir + label_id + sep
+#swwfile = file_loc + project.scenario_name + '.sww'
+#swwfiles[swwfile] = label_id
+print "hella what the!"
+'''
+#get the timeseries for the evolved sww file
+texname, elev_output = sww2timeseries(sww_filename,
+                                      project.gauges_dir_name_simple,
+                                      production_dirs,
+                                      report = False,
+                                      #reportname = report_name,
+                                      plot_quantity = ['stage', 'momentum'],
+                                      surface = False,
+                                      time_min = None,
+                                      time_max = None,
+                                      title_on = False,
+                                      verbose = True)
+                                      
+'''                                      
+swwfiles = {}
+                                      
+for label_id in production_dirs.keys():
+        
+    if label_id == 'boundaries':
+        print 'boundaries'
+#        file_loc = project.boundaries_in_dir
+        swwfile = project.boundaries_dir_name3 + '.sww'
+#        swwfile = project.boundaries_dir_name6+'.sww'
+    else:
+#        file_loc = project.output_dir + label_id + sep
+        file_loc = out_dir_name
+        swwfile = file_loc + project.scenario_name + '.sww'
+    swwfiles[swwfile] = label_id
+    print"swwfiles",swwfiles
+        
+texname, elev_output = sww2timeseries(swwfiles,
+                                      project.gauges_dir_name_simple,
+                                      production_dirs,
+                                      report = False,
+                                      #reportname = report_name,
+                                      plot_quantity = ['stage', 'xmomentum', 'ymomentum'],
+#                                      plot_quantity = ['stage', 'momentum'],
+                                      surface = False,
+                                      time_min = None,
+                                      time_max = None,
+                                      title_on = False,
+#                                      use_cache = True,
+                                      verbose = True)
+
+#makes the csv files from the evolved model
+
+
+
+e_header, e_data = get_data_from_file(evolved_dir_filename)
+
+e_time = e_data[:,0]
+e_stage = e_data[:,1]
+e_momentum = e_data[:,2]
+e_speed = e_data[:,3]
+e_elevation = e_data[:,4]
+
+print'boundary_dir_filename',boundary_dir_filename
+b_header, b_data = get_data_from_file(boundary_dir_filename)
+
+b_time = b_data[:,0]
+b_stage = b_data[:,1]
+b_momentum = b_data[:,2]
+b_speed = b_data[:,3]
+b_elevation = b_data[:,4]
+
+
+# compares the 2 models
+j=0
+k=2
+b_sample = []
+e_sample = []
+for i in range(len(b_time)):
+#    if j<(len(e_time)) and b_time[i] == e_time[j]:
+    if j<(len(e_time)) and k<(len(e_time)) and b_time[i] == e_time[j]:
+        b_sample.append(float(b_stage[i]))
+        e_sample.append(float(e_stage[k]))
+#        print 'out:', b_time[i], b_stage[i],i, j, b_sample[j],e_stage[j]
+        if k <len(e_time): print 'time e equal b:', b_time[i], b_stage[i],i, j, b_sample[j],e_stage[j], e_stage[k],(len(e_time)-1)
+        j = j +1
+        k = k +1
+
+
+print len(b_sample), len(e_stage),e_stage,type(e_stage)
+e_stage = e_stage.tolist()
+e_stage.pop()
+#e_stage = e_stage.tolist().pop()
+e_stage.pop()
+#e_stage.pop()
+ 
+print len(b_sample), len(e_stage),e_stage
+#assert allclose (b_sample, e_sample, 0.5, 0.5)
+
+assert allclose (b_sample, e_stage, 0.2, 0.2) 
+print "test successful" 
+
+
+
+
+                             
+                             
+                                          
Index: /anuga_work/production/wa/dampier_2006/get_timeseries_bf.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/get_timeseries_bf.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/get_timeseries_bf.py	(revision 7411)
@@ -0,0 +1,159 @@
+"""
+Generate images of "gauges" for production run
+
+Inputs:
+
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+Outputs:
+
+* figures used for report stored in the report_figure directory
+
+"""
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries
+from anuga.shallow_water import Domain
+from anuga.pmesh.mesh_interface import create_mesh_from_regions 
+from anuga.shallow_water import File_boundary
+#from anuga.fit_interpolate import Interpolation_function
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher
+
+
+start_screen_catcher(project.temp_dir_name, print_to_screen=True)
+
+# Create report directory
+reportdir = getcwd()+sep+'report'+sep
+if access(reportdir,F_OK) == 0:
+    mkdir (reportdir)
+    
+# sww file created from URS boundary
+production_dirs = {#'20070206_005106_run': '10000 yr wave height'}
+                   'boundaries': 'URS boundary condition'}
+                   
+meshes_dir_name = project.meshes_dir_name+'.msh'
+print 'create mesh' 
+create_mesh_from_regions(project.poly_all,
+                             boundary_tags=None,
+                             maximum_triangle_area=500000,
+                             interior_regions=None,
+                             filename=meshes_dir_name,
+                             use_cache=False,
+                             verbose=True)
+                             
+domain = Domain(meshes_dir_name, use_cache=True, verbose=True)
+#print"domain id", id(domain)
+
+print domain.statistics()
+boundaries_dir_name=project.boundaries_dir_name
+
+domain.set_quantity('stage', 2.4)
+print 'Reading Boundary file', boundaries_dir_name
+Bf = File_boundary(project.boundaries_dir_name3 + '.sww',
+                  domain, time_thinning=1, use_cache=True, verbose=True)
+#print "domain id", id(domain)
+print "Bf id", id(Bf)
+
+print "dir,bf", dir(Bf)
+#print 'finished reading boundary file', Bf.get_midpoint_coords()
+print 'finished reading boundary file', Bf.midpoint_coordinates.shape[0],Bf.midpoint_coordinates[0]
+
+# interpolation_points[0]
+
+#number_of_points = Bf.midpoint_coordinates.shape[0]
+number_of_points = (50,200,324)
+
+#number_of_points = Bf.interpolation_points.shape[0]
+print "number_of_points", number_of_points
+dir(Bf.F)
+#for id in range(number_of_points)[10:]:
+for id in number_of_points:
+    print "id", id
+    x,y=Bf.midpoint_coordinates[id]
+#    x,y=Bf.interpolation_points[id]
+    print"x,y",x,y
+    t_boundary = Bf.F.precomputed_values["stage"][:,id]
+    print "t_boundary", t_boundary
+
+#t_file = 
+
+
+import sys   
+sys.exit()
+
+
+
+is_parallel = False
+if is_parallel == True:
+    nodes = 2
+    
+# Generate figures
+swwfiles = {}
+
+if is_parallel == True:
+
+    for i in range(nodes):
+        print 'Sending node %d of %d' %(i,nodes)
+        swwfiles = {}
+        #reportname = report_name + '_%s' %(i)
+        for label_id in production_dirs.keys():
+            if label_id == 'boundaries':
+                file_loc = project.boundaries_in_dir
+                swwfile = file_loc + sep + '20061102_221245_build' + sep + 'dampier.sww'
+                print 'hi'
+            #else:
+            #file_loc = project.output_dir + label_id + sep
+            #sww_extra = '_P%s_%s' %(i,nodes)
+            #swwfile = file_loc + project.scenario_name + sww_extra + '.sww'
+            swwfiles[swwfile] = label_id
+
+        texname, elev_output = sww2timeseries(swwfiles,
+                                              project.gauges_dir_name,
+                                              production_dirs,
+                                              report = False,
+                                              #reportname = reportname,
+                                              plot_quantity = ['stage', 'momentum'],
+                                              generate_fig = False,
+                                              surface = False,
+                                              time_min = None,
+                                              time_max = None,
+                                              title_on = False,
+                                              verbose = True)
+            
+            #latex_output.append(texname)
+    
+else:
+    
+    for label_id in production_dirs.keys():
+        
+        if label_id == 'boundaries':
+                file_loc = project.boundaries_in_dir
+                swwfile = project.boundaries_dir_name3 + '.sww'
+        else:
+            file_loc = project.output_dir + label_id + sep
+            swwfile = file_loc + project.scenario_name + '.sww'
+        swwfiles[swwfile] = label_id
+        
+    texname, elev_output = sww2timeseries(swwfiles,
+                                          project.gauges_dir_name_test,
+                                          production_dirs,
+                                          report = False,
+                                          #reportname = report_name,
+                                          plot_quantity = ['stage', 'momentum'],
+                                          surface = False,
+                                          time_min = None,
+                                          time_max = None,
+                                          title_on = False,
+                                          verbose = True)
+
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    polygon = []
+    for line in lines:
+        fields = line.split(split)
+        polygon.append( [float(fields[0]), float(fields[1])] )
+
+
Index: /anuga_work/production/wa/dampier_2006/get_timeseries_redone.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/get_timeseries_redone.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/get_timeseries_redone.py	(revision 7411)
@@ -0,0 +1,28 @@
+"""
+Generate images of "gauges" for production run
+
+Inputs:
+
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+Outputs:
+
+* figures used for report stored in the report_figure directory
+
+"""
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.shallow_water.data_manager import get_timeseries
+
+# Create report directory
+reportdir = getcwd()+sep+'report'+sep
+if access(reportdir,F_OK) == 0:
+    mkdir (reportdir)
+    
+    
+production_dirs = { 'dsg': 'URS boundary normal'  }
+plot_quantity = ['stage', 'momentum']
+get_timeseries(production_dirs, project.output_dir, project.scenario_name,
+               project.gauges_dir_name, plot_quantity)
Index: /anuga_work/production/wa/dampier_2006/locate_indigeneous.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/locate_indigeneous.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/locate_indigeneous.py	(revision 7411)
@@ -0,0 +1,41 @@
+#
+# script to determine which communities are located in study region
+# 31 October 2006
+#
+
+def community_in_extent(filename,extent,zone,fid_out):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+
+    line1 = lines[0]
+    line11 = line1.split(',')
+    for i in range(len(line11)):
+        if line11[i].strip('\n').strip(' ') == 'LATITUDE': lat_index = i
+        if line11[i].strip('\n').strip(' ') == 'LONGITUDE': lon_index = i
+        if line11[i].strip('\n').strip(' ') == 'COMMUNITY': name_index = i
+
+    from anuga.coordinate_transforms.redfearn import convert_from_latlon_to_utm
+    from anuga.utilities.polygon import plot_polygons, is_inside_polygon
+    
+    for line in lines[1:]:
+        fields = line.split(',')
+        point, zone1 = convert_from_latlon_to_utm(latitudes=[fields[lat_index]],\
+                                                 longitudes=[fields[lon_index]])
+        if zone1 == zone:
+            v = is_inside_polygon(point,extent,verbose=False)
+            if v == True:
+                p = point[0]
+                s = '%s, %.2f, %.2f\n' %(fields[name_index], p[0], p[1])
+                fid_out.write(s)
+    return
+
+import project
+
+filename = project.community_filename
+filename_out = project.community_KD
+fid_out = open(filename_out, 'w')
+extent = project.poly_all
+zone = 50
+
+community_in_extent(filename,extent,zone,fid_out)
Index: /anuga_work/production/wa/dampier_2006/make_report.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/make_report.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/make_report.py	(revision 7411)
@@ -0,0 +1,363 @@
+"""
+Generate report for production run
+
+NOTE - this will only work on Windows system (as pylab not installed on unix).
+
+Inputs:
+
+report_title:    title to be included in tex file
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+
+Outputs:
+
+* Report generated to scenario_report.tex where the scenario relates
+the name of the production directory this script is being run from.
+* figures used for report stored in the report_figure directory
+NOTE, this directory will need to be committed, as well as
+the latex files.
+
+The report structure is
+
+* Executive Summary
+* Introduction
+* Modelling Methodology
+* Tsunami scenario
+* Data sources
+* Inundation modelling results
+* Impact modelling
+* Summary
+* Acknowledgements
+* References
+* Appendix: Metadata
+* Appendix: Inundation model metadata
+* Appendix: Time series outputs
+
+Other files included in document which require manual intervention:
+
+* an abstract must be written in abstract.tex
+* an introduction must be written in introduction.tex; a basic outline and
+  some of the core inputs are already in place
+* the tsunami-genic event should be discussed in tsunami_scenario.tex
+* a discussion of the ANUGA model is required in anuga.tex
+* a computational_setup.tex file needs to be written for the particular scenario
+* the interpretation of the results needs to be written to interpretation.tex
+* maximum inundation map names need to be included in HAT_map and LAT_map etc.
+* damage modelling map names need to be included in HAT_damage and LAT_damage etc.
+* a summary must be written into summary.tex
+* metadata for the scenario data to be included in metadata.tex
+
+May, June 2006                    
+"""
+
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries, get_gauges_from_file
+
+# Derive scenario name
+p = getcwd().split(sep)
+scenario = p[-1] # Last element of absolute CWD path
+scenario_name = scenario.split('_2006')[0] # Strip any text past `_2006`
+test = scenario_name.split('_')
+if len(test) <> 1:
+    scenario_name = '%s %s' %(test[0], test[1])
+
+# Create report directory
+reportdir = getcwd()+sep+'report07'+sep
+if access(reportdir,F_OK) == 0:
+    mkdir (reportdir)
+    
+# User defined inputs
+report_title = 'Tsunami impact modelling for %s' %scenario_name.title()
+
+is_parallel = True
+if is_parallel == True:
+    nodes = 8
+    
+return_periods = [1000, 100000]
+
+# output directories
+production_dirs_1000 = {'20061116_055135_run': 'Mw 9.0'} # RP 1000 years
+production_dirs_100000 = {'20061116_055135': 'Mw 8.0'} # RP 100000 years
+
+all_prod_dirs = [production_dirs_1000, production_dirs_100000]
+                          
+max_maps_1000 = {'Mw 6.0': 'mw6_map'}
+max_maps_100000 = {'Mw 9.0': 'mw9_map'}
+
+all_maps = [max_maps_1000, max_maps_100000]
+
+# gauge map names
+gauge_map1 = 'dampier_gauges_1.jpg'
+gauge_map2 = 'dampier_gauges_2.jpg'
+
+# Create sections and graphs for each designated production directory
+latex_output = []
+report_name = 'latexoutput'
+
+if is_parallel == True:
+    
+    for j, production_dirs in enumerate(all_prod_dirs):
+        
+        for i in range(nodes):
+            print 'Sending node %d of %d' %(i,nodes)
+            reportname = report_name + '%s' + 'rp%s' %(i,j)
+            swwfiles = {}
+            
+            for label_id in production_dirs.keys():
+                file_loc = project.output_dir + label_id + sep
+                sww_extra = '_P%s_%s' %(i,nodes)
+                swwfile = file_loc + project.scenario_name + sww_extra + '.sww'
+                swwfiles[swwfile] = label_id
+
+                texname, elev_output = sww2timeseries(swwfiles,
+                                                      project.gauge_filename,
+                                                      production_dirs,
+                                                      report = True,
+                                                      reportname = reportname,
+                                                      plot_quantity = ['stage', 'speed'],
+                                                      generate_fig = True,
+                                                      surface = False,
+                                                      time_min = None,
+                                                      time_max = None,
+                                                      time_unit = 'hours',
+                                                      title_on = False,
+                                                      use_cache = True,
+                                                      verbose = True)
+                
+                latex_output.append(texname)
+    
+else:
+
+    for i, production_dirs in enumerate(all_prod_dirs):
+
+        swwfiles = {}
+        reportname = report_name + 'rp%s' %(i)
+        
+        for label_id in production_dirs.keys():
+
+            file_loc = project.output_dir + label_id + sep
+            swwfile = file_loc + project.scenario_name + '.sww'
+            swwfiles[swwfile] = label_id
+            
+        texname, elev_output = sww2timeseries(swwfiles,
+                                              project.gauge_filename,
+                                              production_dirs,
+                                              report = True,
+                                              reportname = reportname,
+                                              plot_quantity = ['stage', 'speed'],
+                                              generate_fig = True,
+                                              surface = False,
+                                              time_min = None,
+                                              time_max = None,
+                                              time_unit ='hours',
+                                              title_on = False,
+                                              use_cache = True,
+                                              verbose = True)
+        latex_output.append(texname)
+
+# Start report generation
+# Future: generate_report(reportdir, scenario, report_title, 
+# project.gauge_filename, max_maps, damage_maps, production_dirs, latex_output)
+report_name = reportdir + scenario + '_report.tex'
+fid = open(report_name, 'w')
+
+s = """
+% This is based on an automatically generated file (by make_report.py).
+%
+% Manual parts are:
+% * an abstract must be written in abstract.tex
+% * an introduction must be written in introduction.tex; a basic outline and
+%   some of the core inputs are already in place
+% * outline of the modelling methodology provided in modelling_methodology.tex
+% * the tsunami-genic event should be discussed in tsunami_scenario.tex
+% * an computational_setup.tex file needs to be written for the particular scenario
+% * the interpretation of the results needs to be written to interpretation.tex
+% * maximum inundation maps need to be included in HAT_map.tex and LAT_map.tex etc.
+% * damage modelling maps need to be included in HAT_damage and LAT_damage etc.
+% * a summary must be written into summary.tex
+% * metadata for the scenario data to be included in metadata.tex
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\usepackage{pdfpages}
+\include{appendix}
+\setstretch{1.25}
+\\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\\textwidth \paperwidth
+\\advance\\textwidth -2in
+
+"""
+fid.write(s)
+
+s = """
+\date{\\today}
+%\\author{Geoscience Australia}
+
+\\begin{document}
+\\title{
+\\begin{figure}[hbt]
+  \centerline{ \includegraphics[scale=0.4]{../report_figures/GAlogo.jpg}}
+\end{figure}
+"""
+fid.write(s)
+s = '%s} '%report_title
+fid.write(s)
+
+s = """
+  \maketitle
+
+    \section{Executive Summary}
+    \label{sec:execsum}
+  \input{execsum}
+
+\clearpage
+
+  \\tableofcontents
+  
+  \section{Introduction}
+    \label{sec:intro}
+  \input{introduction}
+
+   \section{Modelling methodology}
+    \label{sec:methodology}
+    \input{modelling_methodology}
+    
+  \section{Tsunami scenarios}
+    \label{sec:tsunamiscenario}
+    \input{tsunami_scenario}
+
+  \section{Data sources}
+    \label{sec:data}
+    \input{data}
+        
+  \section{Inundation modelling results}
+     \label{sec:results}
+         
+"""
+fid.write(s)
+    
+s = '\input{interpretation} \n'
+fid.write(s)
+
+# Assign titles to each production section 
+# Must specify one name per section
+for i, max_maps in enumerate(all_maps):
+
+    s = '\subsection{Return Period: %s years} \n \n' %return_periods[i]      
+    fid.write(s)
+
+    production_dirs = all_prod_dirs[i]
+    for name in enumerate(production_dirs.keys()):
+        s = '\input{%s} \n \clearpage \n \n' %max_maps[production_dirs[name]]
+        fid.write(s)
+
+# Generate latex output for location points
+s = '\\begin{table} \\begin{center} \n'
+fid.write(s)
+s = '\caption{Defined point locations for %s study area.}' %scenario_name.title()
+fid.write(s)
+s = """
+\label{table:locations}
+\\begin{tabular}{|l|l|l|l|}\hline
+\\bf{Point Name} & \\bf{Easting} & \\bf{Northing} & \\bf{Elevation (m)}\\\\ \hline
+"""
+fid.write(s)
+
+gauges, locations, elevation = get_gauges_from_file(project.gauge_filename)
+
+for name, gauges, elev in zip(locations, gauges, elevation):
+    east = gauges[0]
+    north = gauges[1]
+    s = '%s & %.2f & %.2f & %.2f \\\\ \hline \n' %(name.replace('_',' '), east, north, elev)
+    fid.write(s)
+
+s = '\\end{tabular} \n  \end{center} \n \end{table} \n \n'
+fid.write(s)
+
+#s = '\\begin{figure}[h] \n \centerline{ \includegraphics[width=\paperwidth]{../report_figures/%s}}' %gauge_map
+s = '\\begin{figure}[h] \n \centerline{ \includegraphics[scale=0.7]{../report_figures/%s}}' %gauge_map
+fid.write(s)
+
+s  = """
+\caption{Point locations used for Dampier study.}  
+\label{fig:points}
+\end{figure}
+
+\clearpage
+"""
+fid.write(s)
+
+# Closing
+
+s = """
+   \section{Impact modelling}
+    \label{sec:impact}
+     \input{damage}
+"""
+fid.write(s)
+
+s = """
+     \section{Summary}
+     \label{sec:summary}
+     \input{summary}
+
+     \section{Acknowledgements}
+     \input{acknowledgements}
+     
+    \input{references}
+
+\clearpage
+
+    \\appendix
+
+    \section{ANUGA modelling parameters}
+    \label{sec:anugasetup}
+    \input{anuga_setup}
+
+\clearpage
+
+   \section{Metadata}
+     \label{sec:metadata}
+     \input{metadata}
+
+\clearpage
+
+   \section{Time series}
+     \label{sec:timeseries}
+     \input{timeseriesdiscussion}
+     \clearpage
+"""
+fid.write(s)
+
+for i in range(len(latex_output)):
+    if latex_output[i] <> '':
+        s = '\subsection{Return Period: %s years} \n' %return_periods[i]
+        fid.write(s)
+        s = '\input{%s} \n \clearpage \n \n' %latex_output[i]   
+        fid.write(s)
+
+s="""
+     \section{Damage modelling inputs}
+     \label{sec:damageinputs}
+     \input{damage_inputs}
+     
+\end{document}
+"""
+fid.write(s)
Index: /anuga_work/production/wa/dampier_2006/make_report_cipma.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/make_report_cipma.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/make_report_cipma.py	(revision 7411)
@@ -0,0 +1,336 @@
+"""
+Generate report for production run
+
+NOTE - this will only work on Windows system (as pylab not installed on unix).
+
+Inputs:
+
+report_title:    title to be included in tex file
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+
+Outputs:
+
+* Report generated to scenario_report.tex where the scenario relates
+the name of the production directory this script is being run from.
+* figures used for report stored in the report_figure directory
+NOTE, this directory will need to be committed, as well as
+the latex files.
+
+The report structure is
+
+* Executive Summary
+* Introduction
+* Modelling Methodology
+* Tsunami scenario
+* Data sources
+* Inundation modelling results
+* Impact modelling
+* Summary
+* Acknowledgements
+* References
+* Appendix: Metadata
+* Appendix: Inundation model metadata
+* Appendix: Time series outputs
+
+Other files included in document which require manual intervention:
+
+* an abstract must be written in abstract.tex
+* an introduction must be written in introduction.tex; a basic outline and
+  some of the core inputs are already in place
+* the tsunami-genic event should be discussed in tsunami_scenario.tex
+* a discussion of the ANUGA model is required in anuga.tex
+* a computational_setup.tex file needs to be written for the particular scenario
+* the interpretation of the results needs to be written to interpretation.tex
+* maximum inundation map names need to be included in HAT_map and LAT_map etc.
+* damage modelling map names need to be included in HAT_damage and LAT_damage etc.
+* a summary must be written into summary.tex
+* metadata for the scenario data to be included in metadata.tex
+
+May, June 2006                    
+"""
+
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries, get_gauges_from_file
+
+# Derive scenario name
+p = getcwd().split(sep)
+scenario = p[-1] # Last element of absolute CWD path
+scenario_name = scenario.split('_2006')[0] # Strip any text past `_2006`
+test = scenario_name.split('_')
+if len(test) <> 1:
+    scenario_name = '%s %s' %(test[0], test[1])
+
+# Create report directory
+reportdir = getcwd()+sep+'report'+sep
+if access(reportdir,F_OK) == 0:
+    mkdir (reportdir)
+    
+# User defined inputs
+report_title = 'Tsunami impact modelling for %s' %scenario_name.title()
+
+# WA DLI data
+production_dirs = {#'20061101_053132_run': 'big event'} # parallel
+                    #'20061101_054432_run': 'big event'} # sequential
+                    #'20061107_070805_run': 'Mw 9.0',
+                    #'20061116_055135_run': 'Mw 9.0'} # multiple interior regions
+                    #'20061116_062924_run': 'Mw 9.0'} # one interior region
+                    '20070426_045818_run': '1 in 10000 wave height'} # revised run with water flowing in the correct direction!
+
+is_parallel = False
+if is_parallel == True:
+    nodes = 8
+
+max_maps = {'1 in 10000 wave height': 'mw9_map'}
+
+gauge_map1 = 'dampier_gauges_1.jpg'
+gauge_map2 = 'dampier_gauges_2.jpg'
+
+# Create sections and graphs for each designated production directory
+latex_output = []
+report_name = 'latexoutput_cipma'
+
+if is_parallel == True:
+
+    for i in range(nodes):
+        print 'Sending node %d of %d' %(i,nodes)
+        swwfiles = {}
+        reportname = report_name + '_%s' %(i)
+        for label_id in production_dirs.keys():
+            file_loc = project.output_dir + label_id + sep
+            sww_extra = '_P%s_%s' %(i,nodes)
+            swwfile = file_loc + project.scenario_name + sww_extra + '.sww'
+            swwfiles[swwfile] = label_id
+
+            texname, elev_output = sww2timeseries(swwfiles,
+                                                  project.gauges_dir_name,
+                                                  production_dirs,
+                                                  report = True,
+                                                  reportname = reportname,
+                                                  plot_quantity = ['stage', 'speed'],
+                                                  generate_fig = True,
+                                                  surface = False,
+                                                  time_min = None,
+                                                  time_max = None,
+                                                  time_unit = 'hours',
+                                                  title_on = False,
+                                                  use_cache = True,
+                                                  verbose = True)
+            
+            latex_output.append(texname)
+    
+else:
+    swwfiles = {}
+    for label_id in production_dirs.keys():
+
+        file_loc = project.output_dir + label_id + sep
+        swwfile = file_loc + project.scenario_name + '.sww'
+        swwfiles[swwfile] = label_id
+        
+    texname, elev_output = sww2timeseries(swwfiles,
+                                          project.gauges_dir_name,
+                                          production_dirs,
+                                          report = True,
+                                          reportname = report_name,
+                                          plot_quantity = ['stage', 'speed'],
+                                          generate_fig = True,
+                                          surface = False,
+                                          time_min = None,
+                                          time_max = None,
+                                          time_unit = 'hours',
+                                          title_on = False,
+                                          use_cache = True,
+                                          verbose = True)
+    latex_output.append(texname)
+
+# Start report generation
+# Future: generate_report(reportdir, scenario, report_title, 
+# project.gauge_filename, max_maps, damage_maps, production_dirs, latex_output)
+report_name = reportdir + scenario + '_report_CIPMA.tex'
+fid = open(report_name, 'w')
+
+s = """
+% This is based on an automatically generated file (by make_report.py).
+%
+% Manual parts are:
+% * an abstract must be written in abstract.tex
+% * an introduction must be written in introduction.tex; a basic outline and
+%   some of the core inputs are already in place
+% * outline of the modelling methodology provided in modelling_methodology.tex
+% * the tsunami-genic event should be discussed in tsunami_scenario.tex
+% * an computational_setup.tex file needs to be written for the particular scenario
+% * the interpretation of the results needs to be written to interpretation.tex
+% * maximum inundation maps need to be included in HAT_map.tex and LAT_map.tex etc.
+% * damage modelling maps need to be included in HAT_damage and LAT_damage etc.
+% * a summary must be written into summary.tex
+% * metadata for the scenario data to be included in metadata.tex
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\usepackage{pdfpages}
+\include{appendix}
+\setstretch{1.25}
+\\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\\textwidth \paperwidth
+\\advance\\textwidth -2in
+
+"""
+fid.write(s)
+
+s = """
+\date{\\today}
+%\\author{Geoscience Australia}
+
+\\begin{document}
+\\title{
+\\begin{figure}[hbt]
+  \centerline{ \includegraphics[scale=0.4]{../report_figures/GAlogo.jpg}}
+\end{figure}
+"""
+fid.write(s)
+s = '%s} '%report_title
+fid.write(s)
+s = """
+  \maketitle
+
+    \section{Executive Summary}
+    \label{sec:execsum}
+  \input{execsum}
+
+  \\tableofcontents
+  
+   \section{Modelling methodology}
+    \label{sec:methodology}
+    \input{modelling_methodology}
+
+  \section{Data sources}
+    \label{sec:data}
+    \input{data}
+    
+   %\section{Inundation model}
+   % \label{sec:anuga}
+   % \input{anuga}
+   % \input{computational_setup}
+        
+  \section{Inundation modelling results}
+     \label{sec:results}
+         
+"""
+fid.write(s)
+
+# Generate latex output for location points
+##s = '\\begin{table} \\begin{center} \n'
+##fid.write(s)
+##s = '\caption{Defined point locations for %s study area.}' %scenario_name
+##fid.write(s)
+##s = """
+##\label{table:locations}
+##\\begin{tabular}{|l|l|l|l|}\hline
+##\\bf{Point Name} & \\bf{Easting} & \\bf{Northing} & \\bf{Elevation (m)}\\\\ \hline
+##"""
+##fid.write(s)
+##
+##gauges, locations, elevation = get_gauges_from_file(project.gauge_filename)
+##
+##for name, gauges, elev in zip(locations, gauges, elevation):
+##    east = gauges[0]
+##    north = gauges[1]
+##    s = '%s & %.2f & %.2f & %.2f \\\\ \hline \n' %(name.replace('_',' '), east, north, elev)
+##    fid.write(s)
+##
+##s = '\\end{tabular} \n  \end{center} \n \end{table} \n \n'
+##fid.write(s)
+##
+
+s = '\\begin{figure}[hbt] \centerline{\includegraphics[scale = 0.5]{../report_figures/%s}}' %gauge_map2
+fid.write(s)
+s  = """
+\caption{Point locations used for Dampier study; surrounding the facility.
+See Appendix \\ref{sec:timeseries} for stage and momentum results.
+}  
+\label{fig:points2}
+\end{figure}
+"""
+fid.write(s)
+s = '\\begin{figure}[hbt] \centerline{\includegraphics[scale=0.5]{../report_figures/%s}}' %gauge_map1
+fid.write(s)
+s  = """
+\caption{Point locations used for Dampier study; section
+of the pipeline towards the boundary of the region and other boundary gauges.
+See Appendix \\ref{sec:timeseries} for stage and momentum results.}  
+\label{fig:points3}
+\end{figure}
+"""
+fid.write(s)
+    
+#s = '\input{interpretation} \n'
+#fid.write(s)
+
+# Assign titles to each production section 
+# Must specify one name per section
+for i, name in enumerate(production_dirs.keys()):
+
+    s = '\input{%s} \n \clearpage \n \n' %max_maps[production_dirs[name]]
+    fid.write(s)
+
+# Closing
+
+
+s = """
+
+     \section{Summary}
+     \label{sec:summary}
+     \input{summary}
+
+     %\section{Acknowledgements}
+     %\input{acknowledgements}
+     
+    \input{references}
+
+    \\appendix
+
+   \section{ANUGA modelling parameters}
+\label{sec:anugasetup}
+\input{anuga_setup}
+
+   \section{Metadata}
+     \label{sec:metadata}
+     \input{metadata}
+     
+\section{ANUGA modelling parameters}
+\label{sec:anugasetup}
+\input{anuga_setup}
+
+\clearpage
+
+   \section{Time series}
+     \label{sec:timeseries}
+"""
+fid.write(s)
+
+for i in range(len(latex_output)):
+    if latex_output[i] <> '':
+        s = '\input{%s} \n \clearpage \n \n' %latex_output[i]   
+        fid.write(s)
+
+s="""
+\end{document}
+"""
+fid.write(s)
Index: /anuga_work/production/wa/dampier_2006/plot_contour_data.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/plot_contour_data.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/plot_contour_data.py	(revision 7411)
@@ -0,0 +1,78 @@
+"""Read in contour data file and plot max and min
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid
+from os import sep
+ 
+directory = project.outputdir
+
+#timedir = '20070618_063824_run_final_2.4_onslow_nbartzis'
+timedir = '20070620_044413_run_final_2.4_exmouth_nbartzis'
+#timedir = '20070419_065050_run_final_2.4_dampier_nbartzis'
+
+def get_data(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[2]))
+    return max(stage), min(stage)
+
+# Dampier
+files = ['stage0_convert_d.csv','stage5_convert_d.csv','stage20_convert_d.csv','stage80_convert_d.csv']
+depth = [0,5,20,80]
+# Karratha
+#files = ['stage0_convert_k.csv','stage5_convert_k.csv','stage20_convert_k.csv','stage80_convert_k.csv']
+
+stage_max = []
+stage_min = []
+
+for thefile in files:
+
+    filename = directory + timedir + sep + thefile
+    max_stage, min_stage = get_data(filename)
+    stage_max.append(max_stage)
+    stage_min.append(min_stage)
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 80.
+d2 = arange(d1,0.15,-0.1)
+h1 = max_stage
+#h1 = 4.0
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+    
+ion()
+plot(depth,stage_max,'ob',d2,green,'-g',depth,stage_max,'-b')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+# Dampier
+title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+Magnitude 9.3 event (Java) at Dampier')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.1 event (Sumba) at Dampier')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.0 event (Sumba) at Dampier')
+# Karratha
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.3 event (Java) at Karratha')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.1 event (Sumba) at Karratha')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.0 event (Sumba) at Karratha')
+
+legend(['ANUGA','Green\'s law'])
+axis([-5,85,min(stage_max)*0.9,max(stage_max)*1.1])
+grid(True)
+#savefig('stratification_onslow_gun')
+savefig('stratification_exmouth_gun')
+#savefig('stratification_dampier_gun')
+
+close('all')
+
Index: /anuga_work/production/wa/dampier_2006/plot_for_map.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/plot_for_map.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/plot_for_map.py	(revision 7411)
@@ -0,0 +1,85 @@
+"""Read in csv files and plot time series
+
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, hold, axis, close, figure
+from os import sep
+ 
+time_dir1 = '20070419_065050_run'# HAT dampier
+directory = project.output_dir
+filenames = [directory + time_dir1 + sep + 'gauges_time_series_p12.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_p13.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_p14.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_p15.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_p20.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_p21.csv',
+             directory + time_dir1 + sep + 'gauges_time_series_p22.csv',
+             directory + time_dir1 + sep + 'gauges_time_series_p23.csv']
+
+def get_time_series_from_file(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    t = []
+    stage = []
+    depth = []
+    speed = []
+    momentum = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        t.append((float(fields[0])/3600.0+4000./3600.)) # 4000 for Dampier run
+        stage.append(float(fields[1]))
+        depth.append(float(fields[1])-float(fields[4]))
+        speed.append(float(fields[3]))
+        momentum.append(float(fields[2]))        
+    return t, stage, depth, speed, momentum
+
+max_st = 0.
+max_sp = 0.
+max_mom = 0.
+min_st = 0.
+min_sp = 0.
+min_mom = 0.
+max_t = 0.0
+
+for filename in filenames:
+    t, stage, depth, speed, momentum = get_time_series_from_file(filename)
+    if max(t) > max_t: max_t = max(t)
+    if max(stage) > max_st: max_st = max(stage)
+    if max(speed) > max_sp: max_sp = max(speed)
+    if max(momentum) > max_mom: max_mom = max(momentum)
+    if min(stage) < min_st: min_st = min(stage)
+    if min(speed) < min_sp: min_sp = min(speed)
+    if min(momentum) < min_mom: min_mom = min(momentum)
+
+#stage_axis = ([5000./3600.,max_t, min_st, max_st])
+#speed_axis = ([5000/3600.,max_t, min_sp, max_sp])
+#mom_axis = ([5000/3600.,max_t, min_mom, max_mom])
+
+stage_axis = ([5000./3600.,max_t, -2.5,6.5])
+    
+ion()
+
+hold(False)
+
+for i, filename in enumerate(filenames):
+    t, stage, depth, speed, momentum = get_time_series_from_file(filename)
+
+    i1 = filename.rfind('gauges')
+    i2 = filename.rfind('csv')
+    name = filename[i1:i2-1]
+
+    community = 'dampier'
+    figure(1)
+    plot(t, stage, '-b', linewidth=1)
+    xlabel('time (hour)')
+    ylabel('wave height (m)')
+    axis(stage_axis)
+    figname = 'stage_%s_%s.png' %(name,community)
+    savefig(figname)
+
+
+close('all')
+
Index: /anuga_work/production/wa/dampier_2006/project.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/project.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/project.py	(revision 7411)
@@ -0,0 +1,289 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+"""
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon, number_mesh_triangles
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees, convert_from_latlon_to_utm
+from anuga.utilities.system_tools import get_user_name
+
+# file and system info
+#---------------------------------
+codename = 'project.py'
+
+home = getenv('INUNDATIONHOME') #Sandpit's parent dir   
+user = get_user_name()
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+home += sep +'data'
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+#time = strftime('%Y%m%d_%H%M%S',localtime()) #gets time for new dir
+gtime = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+temp_time = time+'_temp'
+print 'gtime: ', gtime
+
+#tide = -2.5
+#tide = 0.0
+#tide = 2.4
+tide = 200.0
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'dampier'
+scenario = 'dampier_tsunami_scenario_2006'
+
+# onshore data provided by WA DLI
+onshore_name = 'DLI_DTED_raster_clipped' # original
+
+# AHO + DPI data + colin French coastline
+coast_name = 'coastline_edited_w_DEM'
+offshore_name = 'clipped_bathy'
+offshore1_name = 'elev_501'
+offshore2_name = 'inferrec_e'
+
+#final topo name
+combined_name ='dampier_combined_elevation'
+combined_smaller_name = 'dampier_combined_elevation_small'
+combined_smallest_name = 'dampier_combined_elevation_smallest'
+
+topographies_in_dir = home+sep+state+sep+scenario+sep+'elevation_final'+sep+'070112'+sep+'points'+sep
+topographies_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'topographies'+sep
+topographies_time_dir = topographies_dir+build_time+sep
+
+temp_dir = home+sep+state+sep+scenario+sep+'anuga'+sep
+temp_dir_name = temp_dir + temp_time+sep
+
+# input topo file location
+onshore_in_dir_name = topographies_in_dir + onshore_name
+coast_in_dir_name = topographies_in_dir + coast_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+offshore1_in_dir_name = topographies_in_dir + offshore1_name
+offshore2_in_dir_name = topographies_in_dir + offshore2_name
+
+onshore_dir_name = topographies_dir + onshore_name
+coast_dir_name = topographies_dir + coast_name
+offshore_dir_name = topographies_dir + offshore_name
+offshore1_dir_name = topographies_dir + offshore1_name
+offshore2_dir_name = topographies_dir + offshore2_name
+
+#final topo files
+combined_dir_name = topographies_dir + combined_name
+combined_time_dir_name = topographies_time_dir + combined_name
+combined_smaller_dir_name = topographies_dir + combined_smaller_name
+combined_smallest_dir_name = topographies_dir + combined_smallest_name
+#combined_time_dir_final_name = topographies_time_dir + combined_final_name
+
+meshes_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'meshes'+sep
+meshes_dir_name = meshes_dir + scenario_name
+
+polygons_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'polygons'+sep+'2007polys'+sep
+tide_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'tide_data'+sep
+
+boundaries_source = ''
+boundaries_name = 'o'
+boundaries_name1 = 'o_new1'
+boundaries_name2 = 'o_test'
+
+#boundaries locations
+#boundaries_in_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'boundaries'+sep
+boundaries_in_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'boundaries'+sep+'urs'+sep+'1_10000'+sep
+boundaries_in_dir_name = boundaries_in_dir + boundaries_name
+boundaries_in_dir2 = home+sep+state+sep+scenario+sep+'anuga'+sep+'boundaries'+sep+'urs'+sep+'ungridded'+sep
+boundaries_in_dir_name2 = boundaries_in_dir2 + boundaries_name
+boundaries_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'boundaries'+sep
+boundaries_dir_name = boundaries_dir + boundaries_name
+boundaries_dir_namea = boundaries_dir + boundaries_name+'_5000_35000'
+boundaries_dir_name1 = boundaries_dir + boundaries_name1
+boundaries_dir_name2 = boundaries_dir + boundaries_name2
+boundaries_dir_name3 = boundaries_dir + boundaries_name+'_test_8500_12000'
+boundaries_dir_name4 = boundaries_dir + boundaries_name+'_8500_12000_no_zone'
+boundaries_dir_name5 = boundaries_dir + '20061026_173920_build'+sep+'dampier'
+boundaries_dir_name6 = boundaries_dir + 'SU-AU'
+
+#boundaries_time_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'boundaries'+sep+build_time+sep
+#boundaries_time_dir_name = boundaries_time_dir + boundaries_name  #Used by post processing
+
+#output locations
+output_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'outputs'+sep
+output_build_time_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'outputs'+sep+build_time+sep
+output_run_time_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'outputs'+sep+run_time+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+gauge_name = 'dampier_gauges_up2.csv' #'dampier.csv'
+
+gauge_name_simple = 'dampier_gauges_simple.csv' 
+gauge_name_test = 'dampier_gauges_up_test.csv' #'dampier.csv'
+gauges_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'gauges'+sep
+gauges_dir_name = gauges_dir + gauge_name
+gauges_dir_name_simple = gauges_dir + gauge_name_simple
+gauges_dir_name_test = gauges_dir + gauge_name_test
+beach_gauges = gauges_dir + 'beach_gauges.csv'
+
+community_filename = gauges_dir + 'CHINS_v2.csv'
+community_KD = gauges_dir + 'community_KD.csv'
+
+buildings_filename = gauges_dir + 'Dampier_res_Project.csv'
+buildings_filename_out = 'Dampier_res_Project_modified.csv'
+###############################
+# Domain definitions
+###############################
+
+refzone = 50 
+south_boundary = degminsec2decimal_degrees(-20,58,0)
+#north_boundary = degminsec2decimal_degrees(-20,13,0)
+north_boundary = degminsec2decimal_degrees(-19,30,0)
+west_boundary = degminsec2decimal_degrees(116,15,0)
+east_boundary = degminsec2decimal_degrees(117,11,0)
+##
+##p0 = [south, degminsec2decimal_degrees(116,32,0)]
+##p1 = [south, west]
+##p2 = [degminsec2decimal_degrees(-20,23,0), west]
+##p3 = [north, degminsec2decimal_degrees(116,45,0)]
+##p4 = [north, degminsec2decimal_degrees(117,0,0)]
+##p5 = [p2[0], degminsec2decimal_degrees(117,8,0)]
+##p6 = [degminsec2decimal_degrees(-20,30,0), east]
+##p7 = [degminsec2decimal_degrees(-20,38,0), east]
+##p8 = [south, east]
+##
+##poly_all, zone = convert_from_latlon_to_utm([p0, p1, p2, p3, p4, p5, p6, p7, p8])
+##refzone = zone
+poly_all = read_polygon(polygons_dir+'extent.csv')
+print 'Area of bounding polygon', polygon_area(poly_all)/1000000.0
+
+res_factor = 2
+res_poly_all = 150000*res_factor
+#res_poly_all = 150000
+
+poly_pipeline = read_polygon(polygons_dir+'pipeline2.csv')
+res_pipeline = 2000
+
+###############################
+# Interior region definitions
+###############################
+
+poly_region = read_polygon(polygons_dir+'region.csv')
+res_region = 50000*res_factor
+
+poly_dampier = read_polygon(polygons_dir+'dampier_town.csv')
+res_dampier = 500*res_factor
+
+poly_karratha = read_polygon(polygons_dir+'karrathav2.csv')
+res_karratha = 15000*res_factor
+
+poly_karratha_town = read_polygon(polygons_dir+'karratha_townv2.csv')
+res_karratha_town = 500*res_factor
+
+poly_facility = read_polygon(polygons_dir+'facility.csv')
+res_facility = 1000*res_factor
+
+poly_delambre = read_polygon(polygons_dir+'delambre.csv')
+res_delambre = 1000*res_factor
+
+poly_coast = read_polygon(polygons_dir+'coastpoly.csv')
+res_coast = 5000*res_factor
+
+poly_NWislands = read_polygon(polygons_dir+'nw_islands_area.csv')
+res_NWislands = 50000*res_factor
+
+poly_island0 = read_polygon(polygons_dir+'island0.csv')
+res_island0 = res_poly_all
+
+poly_island1 = read_polygon(polygons_dir+'island1.csv')
+res_island0 = res_poly_all
+
+poly_island2 = read_polygon(polygons_dir+'island2.csv')
+res_island0 = res_poly_all
+
+poly_island3 = read_polygon(polygons_dir+'island3.csv')
+res_island0 = res_poly_all
+
+res_islands = 5000*res_factor
+
+poly_ref_nw4 = read_polygon(polygons_dir+'ref_nw4.csv')
+res_ref_nw4 = res_islands
+
+poly_island4 = read_polygon(polygons_dir+'island4.csv')
+res_island0 = res_poly_all
+
+poly_ref_nw5 = read_polygon(polygons_dir+'ref_nw5.csv')
+res_ref_nw5 = res_islands
+
+poly_island5 = read_polygon(polygons_dir+'island5.csv')
+res_island0 = res_poly_all
+
+poly_ref_nw6 = read_polygon(polygons_dir+'ref_nw6.csv')
+res_ref_nw6 = res_islands
+
+poly_island6 = read_polygon(polygons_dir+'island6.csv')
+res_island0 = res_poly_all
+
+poly_ref_nw7 = read_polygon(polygons_dir+'ref_nw7.csv')
+res_ref_nw7 = res_islands
+
+poly_island7 = read_polygon(polygons_dir+'island7.csv')
+res_island0 = res_poly_all
+
+poly_ref_nw8 = read_polygon(polygons_dir+'ref_nw8.csv')
+res_ref_nw8 = res_islands
+
+poly_island8 = read_polygon(polygons_dir+'island8.csv')
+res_island0 = res_poly_all
+
+
+#plot_polygons([poly_dampier,poly_karratha,poly_karratha_town,poly_delambre,
+#                poly_coast,poly_NWislands,poly_island0,poly_island1,poly_island2,
+#                poly_island3,poly_island4,poly_island5,poly_island6,
+#                poly_island7,poly_island8,poly_ref_nw4,poly_ref_nw5,
+#                poly_ref_nw6,poly_ref_nw7,poly_ref_nw8,poly_all],figname='poly_pic')
+
+interior_regions = [[poly_dampier,res_dampier], 
+                    [poly_karratha,res_karratha],[poly_karratha_town,res_karratha_town],
+                    [poly_delambre,res_delambre],[poly_coast,res_coast],
+                    [poly_facility,res_facility],
+                    #[poly_NWislands,res_NWislands],
+                    [poly_island0,res_island0],[poly_island1,res_island0],
+                    [poly_island2,res_island0],[poly_island3,res_island0],
+                    [poly_island4,res_island0],[poly_island5,res_island0],
+                    [poly_island6,res_island0],[poly_island7,res_island0],
+                    [poly_island8,res_island0],[poly_ref_nw4,res_ref_nw4],
+                    [poly_ref_nw5,res_ref_nw5],[poly_ref_nw6,res_ref_nw6],
+                    [poly_ref_nw7,res_ref_nw7],[poly_ref_nw8,res_ref_nw8]
+#                    ,[poly_pipeline,res_pipeline]
+                    ]
+
+interior_regions_test = [[poly_dampier,res_dampier], 
+                    [poly_karratha,res_karratha],[poly_karratha_town,res_karratha_town]]
+
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+
+print 'min number triangles', trigs_min
+
+###################################################################
+# Clipping regions for export to asc and regions for clipping data
+###################################################################
+
+poly_mainland = read_polygon(polygons_dir+'mainland_only.csv')
+
+# exporting asc grid - Dampier gas facility
+e_min_area = 474000
+e_max_area = 480000
+n_min_area = 7719000
+n_max_area = 7725000
+
+# residential Dampier
+e_min_area_d = 468450
+e_max_area_d = 470820
+n_min_area_d = 7714050
+n_max_area_d = 7716625
+
+# residential Karratha
+e_min_area_k = 474690
+e_max_area_k = 489900
+n_min_area_k = 7704760
+n_max_area_k = 7712600
Index: /anuga_work/production/wa/dampier_2006/project_new.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/project_new.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/project_new.py	(revision 7411)
@@ -0,0 +1,277 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+"""
+
+import sys
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser, basename
+
+from anuga.coordinate_transforms.redfearn import\
+     degminsec2decimal_degrees,\
+     convert_from_latlon_to_utm
+
+from time import localtime, strftime
+from anuga.geospatial_data.geospatial_data import *
+
+# file and system info
+#---------------------------------
+codename = 'project.py'
+
+home = getenv('INUNDATIONHOME') #Sandpit's parent dir   
+
+if sys.platform == 'win32':
+    user = getenv('USERPROFILE')
+else:
+    user = getenv('LOGNAME')
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+home += sep +'data'
+#----------------------------------
+# Location and naming of scenario data
+#----------------------------------
+state = 'western_australia'
+scenario_name = 'dampier_tsunami'
+scenario_datas_name = 'dampier_tsunami_scenario_2006'  #name of the directory where the data is stored
+#scenario_datas_name = 'karratha_tsunami_scenario_2005' # Tmp location
+
+mesh_name = 'elevation50m'
+boundary_name = 'dampier'
+
+# topography file names
+onshore_name = 'dli_no_islands.asc'
+coast_name = 'DTED_05_Contour.xya'
+islands_name = 'dted_islands.asc'
+offshore_name = 'XY100003902.xya'
+offshore_name1 = 'XY100003903.xya'
+offshore_name2 = 'XY100003951.xya'
+offshore_name3 = 'XY100006321.xya'
+offshore_name4 = 'XY100011756.xya'
+offshore_name5 = 'XY100014243.xya'
+offshore_name6 = 'XY100014244.xya'
+offshore_name7 = 'XY100021081.xya'
+offshore_name8 = 'XY100021082.xya'
+offshore_name9 = 'XY100021083.xya'
+offshore_name10 = 'XY100021085.xya'
+offshore_name11 = 'XY100021086.xya'
+offshore_name12 = 'XY100026309.xya'
+offshore_name13 = 'XY100026338.xya'
+offshore_name14 = 'XYDM83.xya'
+
+combined_name ='dampier_combined_elevation'
+
+
+
+#Derive subdirectories and filenames
+
+meshes_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'meshes'+sep
+topographies_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'topographies'+sep
+gauges_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'gauges'+sep
+polygons_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'polygons'+sep
+boundaries_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'boundaries'+sep+'urs'+sep+'test'+sep
+#outputdir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'output'+sep
+tide_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'tide_data'+sep
+
+time = strftime('%Y%m%d_%H%M%S',localtime()) #gets time for new dir
+
+output_time_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'output'+sep+time+sep
+topographies_time_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'topographies'+sep+time+sep
+boundaries_time_dir = home+sep+state+sep+scenario_datas_name+sep+'anuga'+sep+'boundaries'+sep+time+sep
+
+
+
+#gauge_filename = gaugedir + 'gauge_location_broome.csv'
+
+onshore_dir_name = topographies_dir + onshore_name
+coast_dir_name = topographies_dir + coast_name
+islands_dir_name = topographies_dir + islands_name
+offshore_dir_name = topographies_dir + offshore_name
+
+combined_dir_name = topographies_dir + combined_name
+
+mesh_dir_name = mesh_dir + scenario_name
+output_dir_name = output_time_dir + scenario_name  #Used by post processing
+boundary_dir_name = boundary_dir + boundary_name  #Used by post processing
+
+
+
+
+# Regions
+
+refzone = 50 
+south = degminsec2decimal_degrees(-20,55,0)
+north = degminsec2decimal_degrees(-19,15,0)
+west = degminsec2decimal_degrees(116,17,0)
+east = degminsec2decimal_degrees(117,10,0)
+
+p0 = [south, degminsec2decimal_degrees(116,32,0)]
+p1 = [south, west]
+p2 = [degminsec2decimal_degrees(-20,23,0), west]
+p3 = [north, degminsec2decimal_degrees(116,45,0)]
+p4 = [north, degminsec2decimal_degrees(117,0,0)]
+p5 = [p2[0], degminsec2decimal_degrees(117,8,0)]
+p6 = [degminsec2decimal_degrees(-20,30,0), east]
+p7 = [degminsec2decimal_degrees(-20,38,0), east]
+p8 = [south, east]
+
+
+bounding_polygon, zone =\
+                  convert_from_latlon_to_utm([p0, p1, p2, p3, p4,
+                                              p5, p6, p7, p8])
+refzone = zone
+
+
+#Interior regions
+
+# CIPMA point of interest
+cipma_latitude = -20.588456
+cipma_longitude = 116.771527
+
+
+k0 = [cipma_latitude-0.02, cipma_longitude-0.02]
+k1 = [cipma_latitude-0.02, cipma_longitude+0.02]
+k2 = [cipma_latitude+0.02, cipma_longitude+0.02]
+k3 = [cipma_latitude+0.02, cipma_longitude-0.02]
+
+cipma_polygon, zone = convert_from_latlon_to_utm([k0, k1, k2, k3])
+assert zone == refzone
+
+e_min_area = 474000
+e_max_area = 480000
+n_min_area = 7719000
+n_max_area = 7725000
+
+#Interior regions
+karratha_south = degminsec2decimal_degrees(-20,44,0)
+karratha_north = degminsec2decimal_degrees(-20,42,0)
+karratha_west = degminsec2decimal_degrees(116,48,0)
+karratha_east = degminsec2decimal_degrees(116,53,30)
+
+k0 = [karratha_south, karratha_west]
+k1 = [karratha_south, karratha_east]
+k2 = [karratha_north, karratha_east]
+k3 = [karratha_north, karratha_west]    
+
+karratha_polygon, zone = convert_from_latlon_to_utm([k0, k1, k2, k3])
+assert zone == refzone
+
+
+#Interior regions
+dampier_south = degminsec2decimal_degrees(-20,40,0)
+dampier_north = degminsec2decimal_degrees(-20,38,10)
+dampier_west = degminsec2decimal_degrees(116,43,0)
+dampier_east = degminsec2decimal_degrees(116,45,0)
+
+d0 = [dampier_south, dampier_west]
+d1 = [dampier_south, dampier_east]
+d2 = [dampier_north, dampier_east]
+d3 = [dampier_north, dampier_west]    
+
+dampier_polygon, zone = convert_from_latlon_to_utm([d0, d1, d2, d3])
+assert zone == refzone
+
+
+#Interior regions
+refinery_south = degminsec2decimal_degrees(-20,37,50)
+refinery_north = degminsec2decimal_degrees(-20,36,0)
+refinery_west = degminsec2decimal_degrees(116,44,0)
+refinery_east = degminsec2decimal_degrees(116,46,10)
+
+d0 = [refinery_south, refinery_west]
+d1 = [refinery_south, refinery_east]
+d2 = [refinery_north, refinery_east]
+d3 = [refinery_north, refinery_west]    
+
+refinery_polygon, zone = convert_from_latlon_to_utm([d0, d1, d2, d3])
+assert zone == refzone
+
+
+#Interior region around 468899, 7715177:
+#lat (-20, 39, 44.93753), lon (116, 42, 5.09106)
+
+point_south = degminsec2decimal_degrees(-20,39,46)
+point_north = degminsec2decimal_degrees(-20,39,42)
+point_west = degminsec2decimal_degrees(116,42,0)
+point_east = degminsec2decimal_degrees(116,42,10)
+
+d0 = [point_south, point_west]
+d1 = [point_south, point_east]
+d2 = [point_north, point_east]
+d3 = [point_north, point_west]    
+
+point_polygon, zone = convert_from_latlon_to_utm([d0, d1, d2, d3])
+assert zone == refzone
+
+
+#Neils areas around interesting points
+neil1_point1 = [degminsec2decimal_degrees(-20,35,34),
+                degminsec2decimal_degrees(116,45,18)]
+neil1_point2 = [degminsec2decimal_degrees(-20,36,15),
+                degminsec2decimal_degrees(116,46,18)]
+neil1_point3 = [degminsec2decimal_degrees(-20,35,9),
+                degminsec2decimal_degrees(116,47,17)]
+neil1_point4 = [degminsec2decimal_degrees(-20,34,26),
+                degminsec2decimal_degrees(116,46,17)]
+
+neil1_polygon, zone = convert_from_latlon_to_utm([neil1_point1,
+                                                  neil1_point2,
+                                                  neil1_point3,
+                                                  neil1_point4])
+assert zone == refzone
+
+
+
+
+neil2_point1 = [degminsec2decimal_degrees(-20,39,36),
+                degminsec2decimal_degrees(116,41,33)]
+neil2_point2 = [degminsec2decimal_degrees(-20,40,10),
+                degminsec2decimal_degrees(116,42,13)]
+neil2_point3 = [degminsec2decimal_degrees(-20,38,39),
+                degminsec2decimal_degrees(116,43,49)]
+neil2_point4 = [degminsec2decimal_degrees(-20,38,5),
+                degminsec2decimal_degrees(116,43,9)]
+
+neil2_polygon, zone = convert_from_latlon_to_utm([neil2_point1,
+                                                  neil2_point2,
+                                                  neil2_point3,
+                                                  neil2_point4])
+assert zone == refzone
+
+
+
+
+
+#Withnell bay
+wb_point1 = [degminsec2decimal_degrees(-20,35,34),
+                degminsec2decimal_degrees(116,45,18)]
+wb_point2 = [degminsec2decimal_degrees(-20,36,15),
+                degminsec2decimal_degrees(116,46,18)]
+wb_point3 = [degminsec2decimal_degrees(-20,35,9),
+                degminsec2decimal_degrees(116,47,17)]
+wb_point4 = [degminsec2decimal_degrees(-20,34,26),
+                degminsec2decimal_degrees(116,46,17)]
+
+wb_polygon, zone = convert_from_latlon_to_utm([wb_point1, wb_point2,
+                                               wb_point3, wb_point4])
+assert zone == refzone
+
+
+
+
+
+#Larger Withnell bay
+lwb_point1 = [degminsec2decimal_degrees(-20,35,59),
+                degminsec2decimal_degrees(116,42,00)]
+lwb_point2 = [degminsec2decimal_degrees(-20,36,50),
+                degminsec2decimal_degrees(116,46,50)]
+lwb_point3 = [degminsec2decimal_degrees(-20,34,00),
+                degminsec2decimal_degrees(116,47,39)]
+lwb_point4 = [degminsec2decimal_degrees(-20,33,00),
+                degminsec2decimal_degrees(116,42,50)]
+
+lwb_polygon, zone = convert_from_latlon_to_utm([lwb_point1, lwb_point2,
+                                                lwb_point3, lwb_point4])
+                                                      
+assert zone == refzone
+
+
+
+
Index: /anuga_work/production/wa/dampier_2006/project_original.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/project_original.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/project_original.py	(revision 7411)
@@ -0,0 +1,239 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+"""
+
+import sys
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser, basename
+
+from anuga.coordinate_transforms.redfearn import\
+     degminsec2decimal_degrees,\
+     convert_from_latlon_to_utm
+
+from time import localtime, strftime
+from anuga.geospatial_data.geospatial_data import *
+
+# Location and naming of scenario data
+state = 'western_australia'
+scenario_dir_name = 'dampier_tsunami_scenario_2006'
+#scenario_dir_name = 'karratha_tsunami_scenario_2005' # Tmp location
+
+basename = 'elevation50m'
+boundary_basename = 'dampier'
+
+
+# Data output
+codename = 'project.py'
+
+home = getenv('INUNDATIONHOME') #Sandpit's parent dir   
+
+if sys.platform == 'win32':
+    user = getenv('USERPROFILE')
+else:
+    user = getenv('LOGNAME')
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+home += sep +'data'
+
+#Derive subdirectories and filenames
+print 'home',home
+time = strftime('%Y%m%d_%H%M%S',localtime()) #gets time for new dir
+outputtimedir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'outputs'+sep+time+sep
+
+meshdir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'meshes'+sep
+datadir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'topographies'+sep
+gaugedir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'gauges'+sep
+polygondir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'polygons'+sep
+boundarydir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'boundaries'+sep+'urs'+sep+'test'+sep
+outputdir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'outputs'+sep
+tidedir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'tide_data'+sep
+
+#gauge_filename = gaugedir + 'gauge_location_broome.csv'
+
+meshname = meshdir + basename
+outputname = outputtimedir + basename  #Used by post processing
+boundaryname = boundarydir + boundary_basename  #Used by post processing
+
+
+
+
+# Regions
+
+refzone = 50 
+south = degminsec2decimal_degrees(-20,55,0)
+north = degminsec2decimal_degrees(-20,15,0)
+west = degminsec2decimal_degrees(116,17,0)
+east = degminsec2decimal_degrees(117,10,0)
+
+p0 = [south, degminsec2decimal_degrees(116,32,0)]
+p1 = [south, west]
+p2 = [degminsec2decimal_degrees(-20,23,0), west]
+p3 = [north, degminsec2decimal_degrees(116,45,0)]
+p4 = [north, degminsec2decimal_degrees(117,0,0)]
+p5 = [p2[0], degminsec2decimal_degrees(117,8,0)]
+p6 = [degminsec2decimal_degrees(-20,30,0), east]
+p7 = [degminsec2decimal_degrees(-20,38,0), east]
+p8 = [south, east]
+
+
+bounding_polygon, zone =\
+                  convert_from_latlon_to_utm([p0, p1, p2, p3, p4,
+                                              p5, p6, p7, p8])
+refzone = zone
+
+
+#Interior regions
+
+# CIPMA point of interest
+cipma_latitude = -20.588456
+cipma_longitude = 116.771527
+
+
+k0 = [cipma_latitude-0.02, cipma_longitude-0.02]
+k1 = [cipma_latitude-0.02, cipma_longitude+0.02]
+k2 = [cipma_latitude+0.02, cipma_longitude+0.02]
+k3 = [cipma_latitude+0.02, cipma_longitude-0.02]
+
+cipma_polygon, zone = convert_from_latlon_to_utm([k0, k1, k2, k3])
+assert zone == refzone
+
+e_min_area = 474000
+e_max_area = 480000
+n_min_area = 7719000
+n_max_area = 7725000
+
+#Interior regions
+karratha_south = degminsec2decimal_degrees(-20,44,0)
+karratha_north = degminsec2decimal_degrees(-20,42,0)
+karratha_west = degminsec2decimal_degrees(116,48,0)
+karratha_east = degminsec2decimal_degrees(116,53,30)
+
+k0 = [karratha_south, karratha_west]
+k1 = [karratha_south, karratha_east]
+k2 = [karratha_north, karratha_east]
+k3 = [karratha_north, karratha_west]    
+
+karratha_polygon, zone = convert_from_latlon_to_utm([k0, k1, k2, k3])
+assert zone == refzone
+
+
+#Interior regions
+dampier_south = degminsec2decimal_degrees(-20,40,0)
+dampier_north = degminsec2decimal_degrees(-20,38,10)
+dampier_west = degminsec2decimal_degrees(116,43,0)
+dampier_east = degminsec2decimal_degrees(116,45,0)
+
+d0 = [dampier_south, dampier_west]
+d1 = [dampier_south, dampier_east]
+d2 = [dampier_north, dampier_east]
+d3 = [dampier_north, dampier_west]    
+
+dampier_polygon, zone = convert_from_latlon_to_utm([d0, d1, d2, d3])
+assert zone == refzone
+
+
+#Interior regions
+refinery_south = degminsec2decimal_degrees(-20,37,50)
+refinery_north = degminsec2decimal_degrees(-20,36,0)
+refinery_west = degminsec2decimal_degrees(116,44,0)
+refinery_east = degminsec2decimal_degrees(116,46,10)
+
+d0 = [refinery_south, refinery_west]
+d1 = [refinery_south, refinery_east]
+d2 = [refinery_north, refinery_east]
+d3 = [refinery_north, refinery_west]    
+
+refinery_polygon, zone = convert_from_latlon_to_utm([d0, d1, d2, d3])
+assert zone == refzone
+
+
+#Interior region around 468899, 7715177:
+#lat (-20, 39, 44.93753), lon (116, 42, 5.09106)
+
+point_south = degminsec2decimal_degrees(-20,39,46)
+point_north = degminsec2decimal_degrees(-20,39,42)
+point_west = degminsec2decimal_degrees(116,42,0)
+point_east = degminsec2decimal_degrees(116,42,10)
+
+d0 = [point_south, point_west]
+d1 = [point_south, point_east]
+d2 = [point_north, point_east]
+d3 = [point_north, point_west]    
+
+point_polygon, zone = convert_from_latlon_to_utm([d0, d1, d2, d3])
+assert zone == refzone
+
+
+#Neils areas around interesting points
+neil1_point1 = [degminsec2decimal_degrees(-20,35,34),
+                degminsec2decimal_degrees(116,45,18)]
+neil1_point2 = [degminsec2decimal_degrees(-20,36,15),
+                degminsec2decimal_degrees(116,46,18)]
+neil1_point3 = [degminsec2decimal_degrees(-20,35,9),
+                degminsec2decimal_degrees(116,47,17)]
+neil1_point4 = [degminsec2decimal_degrees(-20,34,26),
+                degminsec2decimal_degrees(116,46,17)]
+
+neil1_polygon, zone = convert_from_latlon_to_utm([neil1_point1,
+                                                  neil1_point2,
+                                                  neil1_point3,
+                                                  neil1_point4])
+assert zone == refzone
+
+
+
+
+neil2_point1 = [degminsec2decimal_degrees(-20,39,36),
+                degminsec2decimal_degrees(116,41,33)]
+neil2_point2 = [degminsec2decimal_degrees(-20,40,10),
+                degminsec2decimal_degrees(116,42,13)]
+neil2_point3 = [degminsec2decimal_degrees(-20,38,39),
+                degminsec2decimal_degrees(116,43,49)]
+neil2_point4 = [degminsec2decimal_degrees(-20,38,5),
+                degminsec2decimal_degrees(116,43,9)]
+
+neil2_polygon, zone = convert_from_latlon_to_utm([neil2_point1,
+                                                  neil2_point2,
+                                                  neil2_point3,
+                                                  neil2_point4])
+assert zone == refzone
+
+
+
+
+
+#Withnell bay
+wb_point1 = [degminsec2decimal_degrees(-20,35,34),
+                degminsec2decimal_degrees(116,45,18)]
+wb_point2 = [degminsec2decimal_degrees(-20,36,15),
+                degminsec2decimal_degrees(116,46,18)]
+wb_point3 = [degminsec2decimal_degrees(-20,35,9),
+                degminsec2decimal_degrees(116,47,17)]
+wb_point4 = [degminsec2decimal_degrees(-20,34,26),
+                degminsec2decimal_degrees(116,46,17)]
+
+wb_polygon, zone = convert_from_latlon_to_utm([wb_point1, wb_point2,
+                                               wb_point3, wb_point4])
+assert zone == refzone
+
+
+
+
+
+#Larger Withnell bay
+lwb_point1 = [degminsec2decimal_degrees(-20,35,59),
+                degminsec2decimal_degrees(116,42,00)]
+lwb_point2 = [degminsec2decimal_degrees(-20,36,50),
+                degminsec2decimal_degrees(116,46,50)]
+lwb_point3 = [degminsec2decimal_degrees(-20,34,00),
+                degminsec2decimal_degrees(116,47,39)]
+lwb_point4 = [degminsec2decimal_degrees(-20,33,00),
+                degminsec2decimal_degrees(116,42,50)]
+
+lwb_polygon, zone = convert_from_latlon_to_utm([lwb_point1, lwb_point2,
+                                                lwb_point3, lwb_point4])
+                                                      
+assert zone == refzone
+
+
+
+
Index: /anuga_work/production/wa/dampier_2006/project_urs.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/project_urs.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/project_urs.py	(revision 7411)
@@ -0,0 +1,295 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+"""
+
+from os import sep, environ, getenv, getcwd,umask
+from os.path import expanduser, basename
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon, number_mesh_triangles
+import sys
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+from time import localtime, strftime, gmtime
+from anuga.utilities.system_tools import get_user_name, get_host_name
+
+# file and system info
+#---------------------------------
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent dir   
+user = get_user_name()
+host = get_host_name()
+#needed when running using mpirun, mpirun doesn't inherit umask from .bashrc
+umask(002)
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+
+#tide = -2.5
+#tide = 0.0
+tide = 2.4
+
+#Maybe will try to make project a class to allow these parameters to be passed in.
+alpha = 0.1
+friction=0.01
+starttime=3600
+finaltime=25000
+setup='final'
+source='exmouth'
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=1
+    yieldstep=60
+if setup =='store':
+    print'store'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240    
+
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(source)+'_'+str(user)
+
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'dampier'
+scenario = 'dampier_tsunami_scenario_2006'
+
+# onshore data provided by WA DLI
+onshore_name = 'DLI_DTED_raster_clipped' # original
+
+# AHO + DPI data + colin French coastline
+coast_name = 'coastline_edited_w_DEM'
+offshore_name = 'clipped_bathy'
+offshore1_name = 'elev_501'
+offshore2_name = 'inferrec_e'
+
+#final topo name
+combined_name ='dampier_combined_elevation'
+combined_smaller_name = 'dampier_combined_elevation_small'
+combined_smallest_name = 'dampier_combined_elevation_smallest'
+
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+
+topographies_in_dir = home+sep+state+sep+scenario+sep+'elevation_final'+sep+'070112'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+topographies_time_dir = topographies_dir+build_time+sep
+
+
+# input topo file location
+onshore_in_dir_name = topographies_in_dir + onshore_name
+coast_in_dir_name = topographies_in_dir + coast_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+offshore1_in_dir_name = topographies_in_dir + offshore1_name
+offshore2_in_dir_name = topographies_in_dir + offshore2_name
+
+onshore_dir_name = topographies_dir + onshore_name
+coast_dir_name = topographies_dir + coast_name
+offshore_dir_name = topographies_dir + offshore_name
+offshore1_dir_name = topographies_dir + offshore1_name
+offshore2_dir_name = topographies_dir + offshore2_name
+
+#final topo files
+combined_dir_name = topographies_dir + combined_name
+combined_time_dir_name = topographies_time_dir + combined_name
+combined_smaller_dir_name = topographies_dir + combined_smaller_name
+combined_smallest_dir_name = topographies_dir + combined_smallest_name
+#combined_time_dir_final_name = topographies_time_dir + combined_final_name
+
+meshes_dir = anuga_dir+'meshes'+sep
+meshes_dir_name = meshes_dir + scenario_name
+
+polygons_dir = anuga_dir+'polygons'+sep+'2007polys'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+
+if source =='dampier':
+    boundaries_name = 'dampier' #Dampier gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'dampier'+sep+'1_10000'+sep
+
+if source=='onslow':
+    boundaries_name = 'dampier_3859_16052007' #onslow_hedland_broome gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'onslow_hedland_broome'+sep+'1_10000'+sep
+    
+if source=='exmouth':
+    boundaries_name = 'dampier_3103_18052007' #exmouth gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'exmouth'+sep+'1_10000'+sep
+
+#boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'1_10000'+sep
+boundaries_in_dir_name = boundaries_in_dir + boundaries_name
+boundaries_dir = anuga_dir+'boundaries'+sep
+boundaries_dir_name = boundaries_dir + boundaries_name
+
+#output locations
+output_dir = anuga_dir+'outputs'+sep
+output_build_time_dir = output_dir+build_time+'_'+source+sep
+output_run_time_dir = output_dir +run_time+dir_comment+sep
+#output_run_time_dir = output_dir +'20070618_050232_run_final_0.0_onslow_nbartzis'+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+gauge_name = 'dampier_gauges_up2.csv' #'dampier.csv'
+gauge_name_simple = 'dampier_gauges_simple.csv' 
+gauge_name_test = 'dampier_gauges_up_test.csv' #'dampier.csv'
+gauges_dir = anuga_dir+'gauges'+sep
+gauges_dir_name = gauges_dir + gauge_name
+gauges_dir_name_simple = gauges_dir + gauge_name_simple
+gauges_dir_name_test = gauges_dir + gauge_name_test
+
+community_filename = gauges_dir + 'CHINS_v2.csv'
+community_KD = gauges_dir + 'community_KD.csv'
+
+buildings_filename = gauges_dir + 'Dampier_res_Project.csv'
+buildings_filename_out = 'Dampier_res_Project_modified.csv'
+###############################
+# Domain definitions
+###############################
+
+#refzone = 50 
+south_boundary = degminsec2decimal_degrees(-20,58,0)
+#north_boundary = degminsec2decimal_degrees(-20,13,0)
+north_boundary = degminsec2decimal_degrees(-19,30,0)
+west_boundary = degminsec2decimal_degrees(116,15,0)
+east_boundary = degminsec2decimal_degrees(117,11,0)
+
+poly_all = read_polygon(polygons_dir+'extent.csv')
+print 'Area of bounding polygon', polygon_area(poly_all)/1000000.0
+
+res_poly_all = 150000*res_factor
+#res_poly_all = 150000
+
+poly_pipeline = read_polygon(polygons_dir+'pipeline2.csv')
+res_pipeline = 2000
+
+###############################
+# Interior region definitions
+###############################
+
+poly_region = read_polygon(polygons_dir+'region.csv')
+res_region = 50000*res_factor
+
+poly_dampier = read_polygon(polygons_dir+'dampier_town.csv')
+res_dampier = 500*res_factor
+
+poly_karratha = read_polygon(polygons_dir+'karrathav2.csv')
+res_karratha = 15000*res_factor
+
+poly_karratha_town = read_polygon(polygons_dir+'karratha_townv2.csv')
+res_karratha_town = 500*res_factor
+
+poly_facility = read_polygon(polygons_dir+'facility.csv')
+res_facility = 1000*res_factor
+
+poly_delambre = read_polygon(polygons_dir+'delambre.csv')
+res_delambre = 1000*res_factor
+
+poly_coast = read_polygon(polygons_dir+'coastpoly.csv')
+res_coast = 5000*res_factor
+
+poly_NWislands = read_polygon(polygons_dir+'nw_islands_area.csv')
+res_NWislands = 50000*res_factor
+
+poly_island0 = read_polygon(polygons_dir+'island0.csv')
+res_island0 = res_poly_all
+
+poly_island1 = read_polygon(polygons_dir+'island1.csv')
+res_island0 = res_poly_all
+
+poly_island2 = read_polygon(polygons_dir+'island2.csv')
+res_island0 = res_poly_all
+
+poly_island3 = read_polygon(polygons_dir+'island3.csv')
+res_island0 = res_poly_all
+
+res_islands = 5000*res_factor
+
+poly_ref_nw4 = read_polygon(polygons_dir+'ref_nw4.csv')
+res_ref_nw4 = res_islands
+
+poly_island4 = read_polygon(polygons_dir+'island4.csv')
+res_island0 = res_poly_all
+
+poly_ref_nw5 = read_polygon(polygons_dir+'ref_nw5.csv')
+res_ref_nw5 = res_islands
+
+poly_island5 = read_polygon(polygons_dir+'island5.csv')
+res_island0 = res_poly_all
+
+poly_ref_nw6 = read_polygon(polygons_dir+'ref_nw6.csv')
+res_ref_nw6 = res_islands
+
+poly_island6 = read_polygon(polygons_dir+'island6.csv')
+res_island0 = res_poly_all
+
+poly_ref_nw7 = read_polygon(polygons_dir+'ref_nw7.csv')
+res_ref_nw7 = res_islands
+
+poly_island7 = read_polygon(polygons_dir+'island7.csv')
+res_island0 = res_poly_all
+
+poly_ref_nw8 = read_polygon(polygons_dir+'ref_nw8.csv')
+res_ref_nw8 = res_islands
+
+poly_island8 = read_polygon(polygons_dir+'island8.csv')
+res_island0 = res_poly_all
+
+
+#plot_polygons([poly_dampier,poly_karratha,poly_karratha_town,poly_delambre,
+#                poly_coast,poly_NWislands,poly_island0,poly_island1,poly_island2,
+#                poly_island3,poly_island4,poly_island5,poly_island6,
+#                poly_island7,poly_island8,poly_ref_nw4,poly_ref_nw5,
+#                poly_ref_nw6,poly_ref_nw7,poly_ref_nw8,poly_all],figname='poly_pic')
+
+interior_regions = [[poly_dampier,res_dampier], 
+                    [poly_karratha,res_karratha],[poly_karratha_town,res_karratha_town],
+                    [poly_delambre,res_delambre],[poly_coast,res_coast],
+                    [poly_facility,res_facility],
+                    #[poly_NWislands,res_NWislands],
+                    [poly_island0,res_island0],[poly_island1,res_island0],
+                    [poly_island2,res_island0],[poly_island3,res_island0],
+                    [poly_island4,res_island0],[poly_island5,res_island0],
+                    [poly_island6,res_island0],[poly_island7,res_island0],
+                    [poly_island8,res_island0],[poly_ref_nw4,res_ref_nw4],
+                    [poly_ref_nw5,res_ref_nw5],[poly_ref_nw6,res_ref_nw6],
+                    [poly_ref_nw7,res_ref_nw7],[poly_ref_nw8,res_ref_nw8]
+#                    ,[poly_pipeline,res_pipeline]
+                    ]
+
+interior_regions_test = [[poly_dampier,res_dampier], 
+                    [poly_karratha,res_karratha],[poly_karratha_town,res_karratha_town]]
+
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+
+print 'min number triangles', trigs_min
+
+###################################################################
+# Clipping regions for export to asc and regions for clipping data
+###################################################################
+
+poly_mainland = read_polygon(polygons_dir+'mainland_only.csv')
+#
+## exporting asc grid - Dampier gas facility
+#e_min_area = 474000
+#e_max_area = 480000
+#n_min_area = 7719000
+#n_max_area = 7725000
+#
+## residential Dampier
+#e_min_area_d = 468450
+#e_max_area_d = 470820
+#n_min_area_d = 7714050
+#n_max_area_d = 7716625
+
+# residential Karratha
+eastingmin = 474690
+eastingmax = 489900
+northingmin = 7704760
+northingmax = 7712600
Index: /anuga_work/production/wa/dampier_2006/report/anuga_setup.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/anuga_setup.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/anuga_setup.tex	(revision 7411)
@@ -0,0 +1,89 @@
+The following information is required to undertake the 
+inundation modelling;
+
+\begin{itemize}
+\item onshore and offshore elevation data (topographic and bathymetric data, 
+see Section \ref{sec:data}),
+\item initial conditions, such as initial water levels (e.g. determined by tides),
+\item boundary conditions (the tsunami source as described in 
+Section \ref{sec:methodology}), and
+\item computational requirements relating to the mesh construction.
+\end{itemize}
+ 
+Here, we choose HAT as the only initial condition for this study 
+as we expect a greater impact to occur. HAT is
+defined in Section \ref{sec:data}.
+The dynamics of
+tidal effects (that is, the changes in water height over time for
+the entire study area) are not currently modelled.
+
+To set up a model for the tsunami scenario, a study area is first 
+determined. Here, we define the study area to 
+extend offshore to around the 70m depth contour with the onshore data covering the
+area of interest to CIPMA. The study area is around 6250 km$^2$.
+
+The finite volume technique relies on the construction of a triangular mesh which covers the study region. 
+This mesh can be altered to suit the needs of the scenario in question. The mesh can be refined in areas of 
+interest, particularly in the coastal region where complex behaviour is likely to occur. For the purpose
+of this study for CIPMA, we will refine the mesh around the major onshore gas facility and the gas pipelines.
+In setting up the model, the user defines the area of the triangular cells in each region of interest\footnote{Note that the cell 
+area will be the maximum cell area within the defined region and that each 
+cell in the region does not necessarily have the same area.}.
+Figure \ref{fig:dampier_area} shows the study area with regions of difference cell areas. The total number
+of cells is 177 191. 
+Lateral accuracy refers to the distance at which we are confident in stating a region is inundated. 
+Figure \ref{fig:dampier_area} shows the maximum triangular cell area and lateral accuracy for each region. 
+Therefore we can only be confident in the calculated inundation extent surrounding the onshore
+gas infrastructure to within 30 m.
+
+
+\begin{figure}[h]
+
+  %\centerline{ \includegraphics[scale=0.5]{../report_figures/dampier_model.jpg}}
+  \centerline{ \includegraphics[scale=0.3]{../report_figures/model.jpg}}
+  
+  \caption{Study area for Dampier scenario highlighting four regions of increased refinement.
+Region 1: Surrounds onshore gas infrastructure at Dampier with a cell area of 500 m$^2$ (lateral accuracy 30 m). 
+Region 2: Surrounds the gas pipelines with a cell area of 2000 m$^2$ (lateral accuracy 100 m).
+Region 3: Surrounds the coastal regions with a cell area of 10000 m$^2$ (lateral accuracy  m).
+Region 4: The remaining area is given a cell area of 100000 m$^2$ (lateral accuracy 450 m).
+}
+  \label{fig:dampier_area}
+\end{figure}
+
+
+The final item to be addressed to complete the model setup is the 
+definition of the boundary condition. As 
+discussed in Section \ref{sec:methodology}, a Mw 9 event provides
+the tsunami source. The resultant tsunami wave is made up of a series
+of waves with different amplitudes which is affected by the energy
+and style of the event as well as the bathymetry whilst it travels
+from its source to Dampier. The amplitude and velocity of each of these
+waves are then provided to ANUGA as boundary conditions and propagated
+inshore.
+
+Sea floor friction will generally provide resistance to the water flow
+and thus reduce the impact somewhat. However, limited
+research has been carried out to determine 
+the friction coefficients, and 
+thus it has not been incorporated
+in the scenario. The 
+results are therefore likely to be over estimates.
+
+%The following table summarises the modelling parameters;
+%
+%\begin{table}
+%\begin{center}
+%\caption{Parameters used in ANUGA for the Dampier scenario.}
+%\begin{tabular}{|l|l|l|}\hline
+%Mesh & & \\ \hline
+%& resolution in Region 1 & 500 m$^2$  \\ \hline
+%& resolution in Region 2 & 2000 m$^2$ \\ \hline
+%& resolution in Region 3 & 2000 m$^2$ \\ \hline
+%& remaining resolution & 100 000 m$^2$ \\ \hline
+%Model parameters & & \\ \hline
+%& friction & 0 \\ \hline
+%& minimum stored height & 0.1 m \\ \hline
+%\end{tabular}
+%\end{center}
+%\end{table}
Index: /anuga_work/production/wa/dampier_2006/report/dampier_2006_report_CIPMA.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/dampier_2006_report_CIPMA.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/dampier_2006_report_CIPMA.tex	(revision 7411)
@@ -0,0 +1,120 @@
+
+% This is based on an automatically generated file (by make_report.py).
+%
+% Manual parts are:
+% * an abstract must be written in abstract.tex
+% * an introduction must be written in introduction.tex; a basic outline and
+%   some of the core inputs are already in place
+% * outline of the modelling methodology provided in modelling_methodology.tex
+% * the tsunami-genic event should be discussed in tsunami_scenario.tex
+% * an computational_setup.tex file needs to be written for the particular scenario
+% * the interpretation of the results needs to be written to interpretation.tex
+% * maximum inundation maps need to be included in HAT_map.tex and LAT_map.tex etc.
+% * damage modelling maps need to be included in HAT_damage and LAT_damage etc.
+% * a summary must be written into summary.tex
+% * metadata for the scenario data to be included in metadata.tex
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\usepackage{pdfpages}
+\include{appendix}
+\setstretch{1.25}
+\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\textwidth \paperwidth
+\advance\textwidth -2in
+
+
+\date{\today}
+%\author{Geoscience Australia}
+
+\begin{document}
+\title{
+\begin{figure}[hbt]
+  \centerline{ \includegraphics[scale=0.4]{../report_figures/GAlogo.jpg}}
+\end{figure}
+Tsunami impact modelling for Dampier} 
+  \maketitle
+
+    \section{Executive Summary}
+    \label{sec:execsum}
+  \input{execsum}
+
+  \tableofcontents
+  
+   \section{Modelling methodology}
+    \label{sec:methodology}
+    \input{modelling_methodology}
+
+  \section{Data sources}
+    \label{sec:data}
+    \input{data}
+    
+   %\section{Inundation model}
+   % \label{sec:anuga}
+   % \input{anuga}
+   % \input{computational_setup}
+        
+  \section{Inundation modelling results}
+     \label{sec:results}
+         
+\begin{figure}[hbt] \centerline{\includegraphics[scale = 0.5]{../report_figures/dampier_gauges_2.jpg}}
+\caption{Point locations used for Dampier study; surrounding the facility.
+See Appendix \ref{sec:timeseries} for stage and momentum results.
+}  
+\label{fig:points2}
+\end{figure}
+\begin{figure}[hbt] \centerline{\includegraphics[scale=0.5]{../report_figures/dampier_gauges_1.jpg}}
+\caption{Point locations used for Dampier study; section
+of the pipeline towards the boundary of the region and other boundary gauges.
+See Appendix \ref{sec:timeseries} for stage and momentum results.}  
+\label{fig:points3}
+\end{figure}
+\input{mw9_map} 
+ \clearpage 
+ 
+
+
+     \section{Summary}
+     \label{sec:summary}
+     \input{summary}
+
+     %\section{Acknowledgements}
+     %\input{acknowledgements}
+     
+    \input{references}
+
+    \appendix
+
+   \section{ANUGA modelling parameters}
+\label{sec:anugasetup}
+\input{anuga_setup}
+
+\clearpage
+
+   \section{Metadata}
+     \label{sec:metadata}
+     \input{metadata}
+
+\clearpage
+
+   \section{Time series}
+     \label{sec:timeseries}
+\input{latexoutput_cipma20070426045818run} 
+ \clearpage 
+ 
+
+\end{document}
Index: /anuga_work/production/wa/dampier_2006/report/data.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/data.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/data.tex	(revision 7411)
@@ -0,0 +1,76 @@
+The calculated run-up height and resulting inundation ashore is controlled by
+the input topographic and bathymetric elevation, the
+initial and boundary conditions, as well as the cell area of the computational
+mesh. 
+Ideally, the topographic and bathymetric data
+should adequately capture all complex features
+of the underlying bathymetry and topography. Any limitations
+in the resolution and accuracy of the data will introduce 
+errors to the inundation maps, in addition to the range of approximations
+made within the model.
+
+In this study, we used the Australian Height Datum (AHD)
+as the vertical datum. Mean Sea Level (MSL) is approximately equal to
+0m AHD with the Highest Astronomical Tide (HAT) 
+defined as 2.4m AHD for Dampier \cite{antt:06}. 
+
+Data for this study have been sourced from a number of agencies. With
+respect to the onshore data, the Defence Imagery and Geospatial
+Organisation (DIGO) supplied the Digital Terrain Elevation
+Data Level 2 (DTED) which has been authorised for Australian Tsunami
+Warning System use only. The resolution of this data is 1 second
+(about 30 metres), and has been produced from 1:50 000 contours, elevations and
+drainage. In addition, the Department of Land Information (DLI) has provided a
+20m Digital Elevation Model (DEM) and orthophotography 
+covering the NW Shelf. The DTED Level 2 data is ``bare earth'' while the 
+DLI data is distorted by vegetation and buildings. Due to data accuracies, we 
+use the DLI data everywhere apart from the islands, where the DTED data is used.
+
+With respect to the offshore data, the Department of Planning and
+Infrastructure (DPI) have provided state digital fairsheet data around
+Dampier. This data covers a very small geographic area. 
+The Australian Hydrographic Office (AHO) has supplied extensive
+fairsheet data which has also been utilised. In contrast to the onshore data, 
+the offshore data is a series of survey points which is typically 
+not supplied on a fixed grid. In addition, offshore data typically 
+does not have the coverage of the onshore data, and often the 
+offshore data will have gaps where surveys have not been conducted.
+The coastline has been generated by using the aerial photography as
+the WA DLI data surrounding the coast are error prone. Therefore the WA DLI data has been clipped 
+at the derived coastline. 
+
+%Figure \ref{fig:contours_compare} shows the contour lines for
+%HAT, MSL and LAT for Dampier using the combined DLI and DTED data.
+
+%\begin{figure}[p]
+%\center{(a)}
+  %\centerline{ \includegraphics[width=150mm, height=100mm]{../report_figures/dampier_contour.jpg}}
+
+%  \caption{Dampier region showing the -m AHD (LAT), 0m AHD (MSL) 
+%and 2.4m AHD (HAT) contour lines using the combined DTED Level 2 data and
+%the WA DLI data.}
+ %\label{fig:contours_compare}
+%\end{figure}
+
+
+Appendix \ref{sec:metadata} provides more details and the supporting metadata 
+for this study, including images of the data extent.
+Table \ref{table:data} summarises the available data. 
+
+\begin{table}
+\caption{Available data for the North West shelf tsunami inundation studies.}
+\label{table:data}
+\begin{center}
+\begin{tabular}{|l|l|}\hline
+Data & Specifications \\ \hline 
+DIGO DTED Level 2  & Onshore, 1 second $\approx$ 30m \\ \hline 
+DLI & Onshore, 20m DEM and orthophotography \\ \hline
+DPI & Offshore, fairsheet data around Dampier \\ \hline
+AHO & Offshore, fairsheet data for North West Shelf region \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+
+\pagebreak
+
Index: /anuga_work/production/wa/dampier_2006/report/execsum.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/execsum.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/execsum.tex	(revision 7411)
@@ -0,0 +1,15 @@
+This report is being provided to the Critical Infrastructure
+and Protection Modelling and Analysis (CIPMA) Project by the 
+Risk Assessment Methods Project (RAMP). The purpose of this
+study is to determine the potential tsunami inundation extent and 
+particle speed as the tsunami
+impacts the major gas facilities and infrastructure in Dampier.
+
+This report describes the modelling methodology (Section \ref{sec:methodology}),
+data inputs (Section \ref{sec:data})
+and results (Section \ref{sec:results})
+for a specific tsunami-genic event as it impacts the Dampier gas facilities and infrastructure.
+In particular, maximum inundation as well as depth and velocity time series are shown 
+for the event occurring at highest astronomical tide. 
+Impact assessments will be conducted by CIPMA and are not discussed here.
+
Index: /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_420061107070805run.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_420061107070805run.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_420061107070805run.tex	(revision 7411)
@@ -0,0 +1,40 @@
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline3stage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline3speed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at pipeline3 location (elevation -15.68m)} 
+ \label{fig:20061107070805rungaugepipeline3} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline4stage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline4speed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at pipeline4 location (elevation -3.24m)} 
+ \label{fig:20061107070805rungaugepipeline4} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeboundaryNEstage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeboundaryNEspeed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at boundaryNE location (elevation -41.45m)} 
+ \label{fig:20061107070805rungaugeboundaryNE} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeinternalstage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeinternalspeed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at internal location (elevation -22.40m)} 
+ \label{fig:20061107070805rungaugeinternal} 
+ \end{figure} 
+ 
Index: /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_620061107070805run.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_620061107070805run.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_620061107070805run.tex	(revision 7411)
@@ -0,0 +1,30 @@
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline1stage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline1speed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at pipeline1 location (elevation -9.82m)} 
+ \label{fig:20061107070805rungaugepipeline1} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline5stage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline5speed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at pipeline5 location (elevation -42.58m)} 
+ \label{fig:20061107070805rungaugepipeline5} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline6stage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline6speed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at pipeline6 location (elevation -40.60m)} 
+ \label{fig:20061107070805rungaugepipeline6} 
+ \end{figure} 
+ 
Index: /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_720061107070805run.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_720061107070805run.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/latexoutput_cipma_720061107070805run.tex	(revision 7411)
@@ -0,0 +1,20 @@
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugefacilitystage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugefacilityspeed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at facility location (elevation 13.46m)} 
+ \label{fig:20061107070805rungaugefacility} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline2stage20061107070805run.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugepipeline2speed20061107070805run.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at pipeline2 location (elevation -8.64m)} 
+ \label{fig:20061107070805rungaugepipeline2} 
+ \end{figure} 
+ 
Index: /anuga_work/production/wa/dampier_2006/report/metadata.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/metadata.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/metadata.tex	(revision 7411)
@@ -0,0 +1,1 @@
+\includepdf[pages={1-6}]{MetadataforATWSDampierScenario}
Index: /anuga_work/production/wa/dampier_2006/report/modelling_methodology.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/modelling_methodology.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/modelling_methodology.tex	(revision 7411)
@@ -0,0 +1,81 @@
+
+The Risk Research Group aims to define the economic and social threat posed to urban communities 
+by a range of rapid onset natural hazards. Through the integration of natural hazard research, defining national exposure and 
+estimating socio-economic vulnerabilities, predictions of the likely impacts of events can be made. 
+By modelling the likely impacts on urban communities as accurately as possible and
+building these estimates into land use planning and emergency
+management, communities will be better prepared to respond to
+natural disasters when they occur.
+
+
+%GA bases its risk modelling on the process of understanding the hazard and a community's 
+%vulnerability in order to determine the impact of a particular hazard event. 
+%The resultant risk relies on an assessment of the likelihood of the event. 
+%An overall risk assessment for a particular hazard would then rely on scaling 
+%each event's impact by its likelihood.
+
+To develop a tsunami risk assessment, 
+the tsunami hazard itself must first be understood. These events are generally modelled by converting
+the energy released by a subduction earthquake into a vertical displacement of the ocean surface. 
+%Tsunami hazard models have been available for some time. 
+The resulting wave is
+then propagated across a sometimes vast stretch of ocean towards the
+area of interest. 
+%using a relatively coarse model 
+%based on bathymetries with a typical resolution of two arc minutes.
+Initial hazard assessments have been based on reporting the maximum wave height at a fixed contour line near the coastline, 
+(e.g. 50m). This is how the preliminary tsunami hazard assessment was reported by GA 
+to FESA in September 2005 \cite{BC:FESA} for a suite of Mw 9 earthquakes
+evenly spaced along the Sunda Arc subduction zone. 
+The assessment used the Method of Splitting Tsunamis (MOST)
+\cite{VT:MOST} model. Subsequent hazard assessments are been developed in a 
+probabilistic manner which are being derived from the URS Corporation's
+Probabilistic Tsunami Hazard Analysis model \cite{somerville:urs}. 
+%The maximal wave height at a fixed contour line near the coastline
+%(e.g. 50m) is then reported as the hazard to communities ashore. 
+%Models such as Method of Splitting Tsunamis (MOST) \cite{VT:MOST} and the 
+%URS Corporation's
+%Probabilistic Tsunami Hazard Analysis  
+%\cite{somerville:urs} follow this paradigm.
+
+While MOST and URS are suitable for generating and propagating the tsunami wave from its source, it is not adequate to
+model the wave's impact on communities ashore.  
+To capture the \emph{impact} of a tsunami to a coastal community, 
+the model must be capable of capturing more detail about the wave, 
+particularly how it is affected by the local bathymetry, as well as the 
+local topography as the wave moves onshore. 
+%the details of how waves are reflected and otherwise 
+%shaped by the local bathymetries as well as the dynamics of the 
+%runup process onto the topography in question.
+It is well known that local bathymetric and topographic effects are 
+critical in determining the severity of a hydrological disaster 
+\cite{matsuyama:1999}. To model the impact of the tsunami wave on the 
+coastal community, we use ANUGA \cite{ON:modsim}. In order to capture the 
+details of the wave and its interactions, a much finer resolution is 
+required than that of the hazard model. As a result, ANUGA simulations concentrate 
+on specific coastal communities. MOST and URS by contrast use a 
+coarser resolution and covers often vast areas. To develop the impact 
+from an earthquake event from a distant source, we adopt a hybrid approach of 
+modelling the event itself with the URS model and modelling the impact with ANUGA. 
+In this way, the output from URS serves as an input to ANUGA. 
+In modelling terms, the URS output is a boundary condition for ANUGA. Further details
+regarding the modelling requirements for this study can be found in 
+Appendix \ref{sec:anugasetup}.
+
+The event chosen for this study has been determined from the probabilistic
+hazard modelling being undertaken by the Earthquake and Hazards Project.
+The low probability, high potential impact Mw 9.0 event has been chosen
+for this study.
+
+%\begin{figure}[h]
+
+  %\centerline{ \includegraphics[width=140mm, height=100mm]
+%{../report_figures/mw9.jpg}}
+
+%  \caption{Maximum wave height (in cms) for a Mw 9.0 event off the 
+%coast of Java}
+%  \label{fig:mw9}
+%\end{figure}
+
+
+ 
Index: /anuga_work/production/wa/dampier_2006/report/mw9_map.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/mw9_map.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/mw9_map.tex	(revision 7411)
@@ -0,0 +1,7 @@
+\begin{sidewaysfigure}
+%\begin{figure}
+\centerline{ \includegraphics[scale=0.4]{../report_figures/max_inundation_high_tide_v3.jpg}} 
+\caption{Maximum inundation map for the HAT scenario for Dampier region. Data: WA DLI, DPI and AHO.}  
+\label{fig:HAT_max_inundation}
+\end{sidewaysfigure}
+%\end{figure}
Index: /anuga_work/production/wa/dampier_2006/report/references.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/references.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/references.tex	(revision 7411)
@@ -0,0 +1,48 @@
+\begin{thebibliography}{99}
+
+\bibitem{CB:ausgeo} Cummins, P. and Burbidge, D. (2004) 
+Small threat, but warning sounded for tsunami research. AusGeo News 75, 4-7.
+
+\bibitem{BC:FESA} Burbidge, D. and Cummins, P. (2005) Preliminary Tsuanmi 
+Hazard Assesment of Western Australia. Report 
+to the Fire and Emergency Services Authority of Western Australia.
+
+\bibitem{VT:MOST} Titov, V.V., and F.I. Gonzalez (1997)
+Implementation and testing of the Method of Splitting 
+Tsunami (MOST) model, NOAA Technical Memorandum ERL PMEL-112.
+
+\bibitem{somerville:urs} Somerville, P., Thio, H.K. and Ichinose, G. (2005)
+Probabilistic Tsunami Hazard Analysis. Report delivered to Geoscience
+Australia 2005.
+
+\bibitem{matsuyama:1999}
+Matsuyama, M., Walsh, J.P. and Yeh, H. (1999) 
+The effect of bathymetry on tsunami characteristics at 
+Sisano Lagoon, Papua New Guinea. 
+Geophysical Research Letters, 26, 23, 3513-3516.
+
+\bibitem{ON:modsim} Nielsen, O., Roberts, Gray, D., McPherson, A. and 
+Hitchman, A (2005) 
+Hydrodynamic modelling of coastal inundation, MODSIM 2005 International 
+Congress on Modelling and Simulation.
+Modelling and Simulation Society of Australian and New Zealand, 518-523,
+URL: http://www.mssanz.org.au/modsim05/papers/nielsen.pdf
+
+\bibitem{antt:06} Australian National Tide Tables 2006:
+Australia, Papua New Guinea, Solomon Islands and Antarctica and East Timor.
+Australian Hydrographic Publication 11, Australian Hydrographic Service.
+
+\bibitem{papathoma:vulnerability} 
+Papathoma, M. and Dominey-Howes, D. (2003) 
+Tsunami vulnerability assessment and its implications for coastal hazard 
+analysis and disaster management planning, Gulf of Corinth, Greece, 
+Natural Hazards and Earth System Sciences, 3, 733-747.
+
+\bibitem{cooper:2005}
+Cooper, D. (2005) Risk Research Group Personal Communication at NSW Tsunami 
+Workshop 12th and 13th April, Masonic Centre, Goulburn St, Sydney.
+
+\bibitem{NIBS:2003} National Institute of Building Sciences (2003) 
+HAZUS-MH User Manual, Washington DC, USA.
+
+\end{thebibliography}
Index: /anuga_work/production/wa/dampier_2006/report/summary.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report/summary.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report/summary.tex	(revision 7411)
@@ -0,0 +1,8 @@
+This report has described the tsunami inundation occurring at the gas
+facility at Dampier from a tsunami
+generated by a Mw 9 earthquake on the Sunda Arc subduction zone 
+occurring at Highest Astronomical Tide. 
+Velocity data has also been provided at the locations of interest surrounding the gas pipeline.
+The results described must be tempered with the modelling assumptions 
+and the accuracy and coverage of the underlying elevation data.
+
Index: /anuga_work/production/wa/dampier_2006/report07/anuga_setup.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/anuga_setup.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/anuga_setup.tex	(revision 7411)
@@ -0,0 +1,103 @@
+The following information is required to undertake the 
+inundation modelling;
+
+\begin{itemize}
+\item onshore and offshore elevation data (topographic and bathymetric data, 
+see Section \ref{sec:data}),
+\item initial conditions, such as initial water levels (e.g. determined by tides),
+\item boundary conditions (the tsunami source as described in 
+Section \ref{sec:methodology}), and
+\item computational requirements relating to the mesh construction.
+\end{itemize}
+ 
+he initial conditions used for this scenario are MSL, HAT and LAT which were
+defined in Section \ref{sec:data}. Figure \ref{fig:IC} shows the MSL, HAT and 
+LAT contours to illustrate the water level for each of these inial conditions.
+The dynamics of
+tidal effects (that is, the changes in water height over time for
+the entire study area) are not currently modelled.
+
+\begin{figure}[h]
+
+  %\centerline{\includegraphics[width=\paperwidth]{../report_figures/kd_ic_contour.jpg}}
+
+  \caption{Karratha/Dampier region showing the initial conditions used for the study; 
+  -2.5m AHD (LAT), 0m AHD (MSL) and 2.4m AHD (HAT) contour lines.}
+  \label{fig:IC}
+\end{figure}
+
+To set up a model for the tsunami scenario, a study area is first 
+determined. Here, we define the study area to 
+extend offshore to around the 70m depth contour with the onshore data covering the 
+residential areas of Karratha and Dampier. The study area is around 6250 km$^2$.
+
+The finite volume technique relies on the construction of a triangular mesh which covers the study region. 
+This mesh can be altered to suit the needs of the scenario in question. The mesh can be refined in areas of 
+interest, particularly in the coastal region where complex behaviour is likely to occur. For the purpose
+of this study for CIPMA, we will refine the mesh around the major onshore gas facility and the gas pipelines.
+In setting up the model, the user defines the area of the triangular cells in each region of interest\footnote{Note that the cell 
+area will be the maximum cell area within the defined region and that each 
+cell in the region does not necessarily have the same area.}.
+\Figure \ref{fig:dampier_area} shows the study area with regions of difference cell areas. The total number
+of cells is 177 191. 
+Lateral accuracy refers to the distance at which we are confident in stating a region is inundated. 
+Figure \ref{fig:dampier_area} shows the maximum triangular cell area and lateral accuracy for each region. 
+Therefore we can only be confident in the calculated inundation extent surrounding the onshore
+gas infrastructure to within 30 m.
+
+
+\begin{figure}[hbt]
+
+  \centerline{ \includegraphics[scale=0.5]{../report_figures/dampier_model_fesa.jpg}}
+
+  \caption{Study area for Karratha/Dampier scenario highlighting four regions of increased refinement.
+Region 1: Surrounds onshore gas infrastructure at Dampier with a cell area of 500 m$^2$ (lateral accuracy 30 m) - not shown here.
+Region 2: Surrounds the gas pipelines with a cell area of 2000 m$^2$ (lateral accuracy 100 m).
+Region 3: Surrounds the coastal regions with a cell area of 10000 m$^2$ (lateral accuracy  m).
+Region 4: The remaining area is given a cell area of 100000 m$^2$ (lateral accuracy 450 m).
+}
+  \label{fig:dampier_area}
+\end{figure}
+
+
+The final item to be addressed to complete the model setup is the 
+definition of the boundary condition. As 
+discussed in Section \ref{sec:methodology}, a series of events corresponding
+to a range of return periods are selected as the tsunami sources.
+The resultant tsunami wave is made up of a series
+of waves with different amplitudes which is affected by the energy
+and style of the event as well as the bathymetry whilst it travels
+from its source to Dampier. The amplitude and velocity of each of these
+waves are then provided to ANUGA as boundary conditions and propagated
+inshore.
+
+The tsunami generation and propagation modelling uses the URS paradigm.
+The URS output is saved every 2.5 seconds and with a spatial resolution
+of two arc minutes.
+
+Sea floor friction will generally provide resistance to the water flow
+and thus reduce the impact somewhat. However, limited
+research has been carried out to determine 
+the friction coefficients, and 
+thus it has not been incorporated
+in the scenario. The 
+results are therefore likely to be over estimates.
+
+The following table summarises the modelling parameters;
+
+
+\begin{table}
+\begin{center}
+\caption{Parameters used in ANUGA for the Karratha/Dampier scenario.}
+\begin{tabular}{|l|l|l|}\hline
+Mesh & & \hline
+& resolution in Region 1 & 500 m$^2$ \hline
+& resolution in Region 2 & 2000 m$^2$ \hline
+& resolution in Region 3 & 2000 m$^2$ \hline
+& remaining resolution & 100 000 m$^2$ \hline
+Model parameters & & \hline
+& friction & 0
+& minimum stored height & 0.1 m \hline
+\end{tabular}
+\end{center}
+\end{table}
Index: /anuga_work/production/wa/dampier_2006/report07/damage.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/damage.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/damage.tex	(revision 7411)
@@ -0,0 +1,108 @@
+In this report, impact modelling refers to casualties and
+damage to residential buildings as a result
+of the inundation described in Section \ref{sec:results}. It is assumed
+that the event occurs at night. 
+Exposure data are sourced from the National Building Exposure Database (NBED), 
+developed by GA\footnote{http://www.ga.gov.au/urban/projects/ramp/NBED.jsp}. 
+It contains information about residential buildings, people and the
+cost of replacing buildings and contents.
+
+To develop building damage and casuality estimates, 
+residential collapse vulnerability models and casualty models were developed.
+The vulnerability models have been developed for 
+framed residential construction based on limited data found in the literature
+as well as observations from the Indian Ocean tsunami event. 
+The models predict the collapse 
+probability for an exposed population and incorporates the following 
+parameters thought to influence building damage \cite{papathoma:vulnerability},
+
+\begin{itemize}
+\item	inundation depth at building	
+\item	distance from the coast	
+\item	building material (residential framed construction)	
+\item	inundation depth in house above floor level
+\end{itemize}	
+
+The collapse vulnerability models used are presented in Table \ref{table:collapse}. 
+%In applying the model, all structures in the inundation zone were 
+%spatially located and the local water depth and building row 
+%number from the exposed edge of the suburb were determined for each %structure.
+
+Casualty models were based on the
+storm surge models used for the Cairns Cyclone Scenario and 
+through consultation with Dr David Cooper of NSW Health, \cite{cooper:2005}. 
+The injury probabilities for exposed populations were determined 
+based on the nocturnal nature of the event, the collapse outcome 
+for the structure, the water depth with respect to 
+sleeping height (1.0 m) and the limited warning noise for people 
+in the first three city blocks (six house rows) that could potentially 
+awaken them. The three injury categories correspond with the 
+categories presented in HAZUS-MH \cite{NIBS:2003} for earthquake 
+related injury. The casualty model used is presented in Table
+\ref{table:casualty} 
+and the injury categories are presented in Table \ref{table:injury}. 
+Input data comprised of resident population data at census
+district level derived from the ABS 2001 Census. Given the exposure database is
+based on residential structures, we assume that the
+population are at home and sleeping when the event occurs and that there is no
+warning. Therefore, the casualty estimates would be significantly different
+if the event were to occur during the day when people are at work, travelling
+in a vehicle, spending time on the beach, for example, or if the event occurred
+during a major holiday season.
+
+There are an estimated
+325 residential structures and a population of approximately 770
+in Onslow\footnote{Population is determined by census data and the 1999
+ABS housing survey}. 
+The damage to the residential structures in the Onslow community
+is summarised in Table \ref{table:damageoutput}. As expected, the
+greatest impact is found for the high tide scenario. The percentage
+of repair cost to structural value shown is based on the total structural value
+of \$71M. Likewise, the percentage of contents loss shown is
+based on the total contents value of \$101M for
+the Onslow region\footnote{These values are based on 2003 figures.}. 
+The injuries sustained is summarised in Table \ref{table:injuries}. 
+The HAT scenario is the only scenario to cause damage 
+to Onslow with around 15-20\% of the population affected. 
+
+\begin{table}[h]
+\begin{center}
+\caption{Residential damage sustained for the MSL, HAT and LAT scenarios.}
+\label{table:damageoutput}
+\begin{tabular}{|l|l|l|l|l|l|l|}\hline
+&Houses  & Houses  & Structural & Repair Cost \% & Contents & Contents Loss \% \\ 
+&Inundated & Collapsed & Repair Cost 
+& of Total Value & Losses & of Total Value \\ \hline
+HAT & 100 &2&\$8M & 11\%&\$16M & 16 \% \\ \hline
+MSL & 0 & 0 & \$0 &   & \$0 &  \\ \hline
+LAT & 0 & 0 & \$0 &   & \$0 & \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+\begin{table}[h]
+\begin{center}
+\caption{Injuries sustained for the MSL, HAT and LAT scenarios.}
+\label{table:injuries}
+\begin{tabular}{|l|l|l|l|l|l|}\hline
+&Minor & Moderate & Serious & Fatal \\ \hline
+HAT & 10's & 10's & 10's & 10's \\ \hline
+MSL & 0& 0 & 0 &0 \\ \hline
+LAT & 0&0 & 0& 0\\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+Tsunami impact on indigeneous communities should be considered
+in the future as a number of communities exist in coastal regions of north west WA.
+These communities are typically not included in national residential databases 
+and would be therefore overlooked in damage model estimates
+We can confirm that Bindi Bindi is not contained in the NBED.
+There is one indigeneous community located in this study area as seen
+in Figure \ref{fig:points}. 
+The population of the Bindibindi community is 140 
+(18 \% of the Onslow population)
+and is situated close to the coast as seen in Figure \ref{fig:points}.
+During the HAT scenario, over 1 m of water will inundate parts of the community (Figure 
+\ref{fig:gaugeBindiBindiCommunity}) which would cause 
+significant impact.
Index: /anuga_work/production/wa/dampier_2006/report07/damage_inputs.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/damage_inputs.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/damage_inputs.tex	(revision 7411)
@@ -0,0 +1,64 @@
+\begin{table}[h]
+\begin{center}
+\caption{Framed residential building collapse probability. $h$ is the
+inundation height (m) above ground where the ground floor height of 0.3m is
+assumed.}
+\label{table:collapse}
+\begin{tabular}{|l|l|l|l|l|l|}\hline
+Distance from coast ($d[m]$) & 
+$h$<1.0 &1.0<$h$<2.0&	2.0<$h$<3.0	&3.0<$h$<5.0	&$h$>5.0 \\ \hline
+$d < 125$	 &0.05	&0.6	&0.8	&0.95	&0.99 \\ \hline
+$125 < d < 200$ &0.02	&0.3	&0.4	&0.7	&0.9 \\ \hline
+$200 < d < 250$	&0.01	&0.1	&0.25	&0.5	&0.65 \\ \hline
+$200 < d$	&0.0	&0.05	&0.15	&0.3	&0.45 \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+\begin{table}[h]
+\begin{center}
+\caption{Mortality and injury state probability}
+\label{table:casualty} 
+\begin{tabular}{|l|l|l|l|l|l|l|}\hline
+Hazard Exposure	& depth above floor & Unharmed	&Minor
+	&Moderate 	&Serious	&Death \\ \hline
+Collapse	&<1.0	&0.3	&0.28	&0.08	&0.04	&0.30 \\ \hline
+	&>1.0	&0.01	&0.028	&0.008	&0.004	&0.95 \\ \hline
+No Collapse - $d < 250$	&<1.0	&0.35	&0.40	&0.1	&0.05	&0.10 
+\\ \hline
+	&>1.0	&0.1	&0.28	&0.08	&0.04	&0.50 \\ \hline
+No Collapse - $250 < d$	&<1.0	&0.4	&0.4	&0.1	&0.05	&0.05 \\ \hline
+	&>1.0	&0.12	&0.33	&0.1	&0.05	&0.40 \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+\begin{table}[h]
+\begin{center}
+\caption{Injury level classificationse. Floor height is assumed to be 30cm}
+\label{table:injury}
+\begin{tabular*}{\textwidth}{|l|p{.695\textwidth}|}\hline
+Injury Severity Level	&Injury Description \\ \hline
+Minor Injury
+Severity 1	&Injuries requiring basic medical aid without requiring 
+hospitalisation.
+These types of injuries would require bandages or observation. 
+Some examples are: a sprain, a severe cut requiring stitches, 
+a  bump on the head without loss of consciousness. \\ \hline
+Moderate Injury
+Severity 2	&Injuries requiring a greater degree of 
+medical care and use of medical technology such as x-rays or surgery, 
+but not expected to progress to a life threatening status.
+Some examples are: a bump on the head that causes loss of consciousness, 
+fractured bone, dehydration or exposure. \\ \hline
+Severe Injury
+Severity 3	&Injuries that pose an immediate life threatening 
+condition if not treated adequately and expeditiously. Some examples are: 
+uncontrolled bleeding, punctured organ, other internal injuries, 
+spinal column injuries, or crush syndrome. \\ \hline
+Fatal
+Severity 4	&Instantaneously killed or mortally injured. \\ \hline
+\end{tabular*}
+\end{center}
+\end{table}
+\clearpage
Index: /anuga_work/production/wa/dampier_2006/report07/data.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/data.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/data.tex	(revision 7411)
@@ -0,0 +1,76 @@
+The calculated run-up height and resulting inundation ashore is controlled by
+the input topographic and bathymetric elevation, the
+initial and boundary conditions, as well as the cell area of the computational
+mesh. 
+Ideally, the topographic and bathymetric data
+should adequately capture all complex features
+of the underlying bathymetry and topography. Any limitations
+in the resolution and accuracy of the data will introduce 
+errors to the inundation maps, in addition to the range of approximations
+made within the model.
+
+In this study, we used the Australian Height Datum (AHD)
+as the vertical datum. Mean Sea Level (MSL) is approximately equal to
+0m AHD with the Highest Astronomical Tide (HAT) 
+defined as 2.4m AHD for Dampier \cite{antt:06}. 
+
+Data for this study have been sourced from a number of agencies. With
+respect to the onshore data, the Defence Imagery and Geospatial
+Organisation (DIGO) supplied the Digital Terrain Elevation
+Data Level 2 (DTED) which has been authorised for Australian Tsunami
+Warning System use only. The resolution of this data is 1 second
+(about 30 metres), and has been produced from 1:50 000 contours, elevations and
+drainage. In addition, the Department of Land Information (DLI) has provided a
+10m Digital Elevation Model (DEM) and orthophotography 
+covering the NW Shelf. The DTED Level 2 data is ``bare earth'' while the 
+DLI data is distorted by vegetation and buildings. Due to data accuracies, we 
+use the DLI data everywhere apart from the islands, where the DTED data is used.
+
+With respect to the offshore data, the Department of Planning and
+Infrastructure (DPI) have provided state digital fairsheet data around
+Dampier. This data covers a very small geographic area. 
+The Australian Hydrographic Office (AHO) has supplied extensive
+fairsheet data which has also been utilised. In contrast to the onshore data, 
+the offshore data is a series of survey points which is typically 
+not supplied on a fixed grid. In addition, offshore data typically 
+does not have the coverage of the onshore data, and often the 
+offshore data will have gaps where surveys have not been conducted.
+The coastline has been generated by using the aerial photography as
+the WA DLI data surrounding the coast are error prone. Therefore the WA DLI data has been clipped 
+at the derived coastline. 
+
+%Figure \ref{fig:contours_compare} shows the contour lines for
+%HAT, MSL and LAT for Dampier using the combined DLI and DTED data.
+
+%\begin{figure}[p]
+%\center{(a)}
+  %\centerline{ \includegraphics[width=150mm, height=100mm]{../report_figures/dampier_contour.jpg}}
+
+%  \caption{Dampier region showing the -m AHD (LAT), 0m AHD (MSL) 
+%and 2.4m AHD (HAT) contour lines using the combined DTED Level 2 data and
+%the WA DLI data.}
+ %\label{fig:contours_compare}
+%\end{figure}
+
+
+Appendix \ref{sec:metadata} provides more details and the supporting metadata 
+for this study, including images of the data extent.
+Table \ref{table:data} summarises the available data. 
+
+\begin{table}
+\caption{Available data for the North West shelf tsunami inundation studies.}
+\label{table:data}
+\begin{center}
+\begin{tabular}{|l|l|}\hline
+Data & Specifications \\ \hline 
+DIGO DTED Level 2  & Onshore, 1 second $\approx$ 30m \\ \hline 
+DLI & Onshore, 10m DEM and orthophotography \\ \hline
+DPI & Offshore, fairsheet data around Dampier \\ \hline
+AHO & Offshore, fairsheet data for North West Shelf region \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+
+\pagebreak
+
Index: /anuga_work/production/wa/dampier_2006/report07/execsum.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/execsum.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/execsum.tex	(revision 7411)
@@ -0,0 +1,29 @@
+This report is being provided to the Fire and Emergency Services Authority
+(FESA) as part of the Collaborative Research Agreement (CRA) 
+with Geoscience Australia (GA), Tsunami Impact Modelling for WA.
+FESA has recognised the potential vulnerability of the Western Australia
+coastline to tsunami originating from earthquakes on
+the Sunda Arc subduction zone. 
+There is historic evidence of tsunami affecting the 
+Western Australia coastline, \cite{CB:ausgeo}, 
+and FESA has sought to assess
+the relative risk of its urban and regional communities to the tsunami
+threat and develop detailed response plans for a range of plausible events.
+
+This report describes the modelling methodology and results
+for a number of tsunami-genic events with varied return periods
+as they impact the Karratha and Dampier region. This will al
+In particular, maximum inundation maps are shown
+and discussed 
+for the event occurring at mean sea level as well as 
+highest and lowest astronomical tide. The inundation results allow
+estimation of the number of houses inundated and collapsed, as well as
+the numbers of persons affected. The Karratha \backslash Dampier township has approximately
+residential structures and a population of around .
+
+The results of this study will allow an assessment of the relative tsunami risk 
+to communities along the NW Shelf of WA. 
+This report and the decision support tool are the 
+June 2007 deliverables of the Collaborative Research Agreement
+between FESA and GA.
+
Index: /anuga_work/production/wa/dampier_2006/report07/interpretation.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/interpretation.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/interpretation.tex	(revision 7411)
@@ -0,0 +1,65 @@
+The inundation extent calculated at Onslow will be described in this section with
+impact assessments following in Section \ref{sec:impact}.
+% there will need to be something in here for when doing a range of events for each return period.
+Figures \ref{fig:HAT_max_inundation}, \ref{fig:MSL_max_inundation} and 
+\ref{fig:LAT_max_inundation} illustrate the maximum inundation extent
+for the Mw 9 event occurring at HAT, MSL and LAT respectively. 
+As expected, there is greater inundation at HAT with increased
+extent. The major road
+into Onslow, the Onslow Mount Stuart Rd, remains free of inundation for
+all tidal scenarios with a small amount of inundation evident at HAT at
+the intersection with Beadon Creek Rd. Beadon Creek Rd services the wharf in the
+creek which becomes increasingly inundated as the tide height
+increases. The only road sufficiently inundated at LAT is Beadon
+Creek Rd near the entry to the wharf. This road during the HAT 
+scenario would be impassable as the water depths are consistently
+over 1 m with a maximum water depth of around 2 m found close to 
+the wharf. 
+
+There is significant inundation of at
+least 2 m on the foreshore of Onslow for MSL and HAT.
+The inundation extends further as the tidal heights increase.  
+At HAT, the inundation reaches the southern boundaries of 
+the road infrastructure in the Onslow town centre.  
+The airport remains
+free of inundation for each tidal scenario. Section \ref{sec:impact}
+details the impact estimates to the residential infrastructure.
+
+The geography of the Onslow area has played a role in offering
+some protection to the Onslow community. The tsunami wave is 
+travelling from the north west of the area. Most of
+the inundation along the coast is that which is open to this
+direction.  
+The sand dunes west of Onslow 
+appear to have halted this tsunami wave
+(see Figure \ref{fig:MSL_max_inundation}) with limited
+inundation found on the town's side of the dunes.
+The inundation within the community has occurred due to the
+wave reflecting from the beach area west of the creek and
+returning towards the Onslow town itself.  
+There are also sand dunes east of the creek which have also
+halted inundation beyond them. 
+Currently, we do not model changes 
+to the bathymetry or topography due to effects of the water flow. 
+Therefore, we do not know whether these sand dunes would withstand the
+transmitted energy of the tsunami wave. 
+Water features such as rivers, creeks and estuaries also play a role
+in the inundation extent.
+The tsunami wave penetrates the creek east of Onslow, however it
+is evident that the inundation is essentailly maintained in the
+large tidal flat region surrounding the southern parts of the creek.
+
+In addition to describing the maximum inundation extent,
+we have
+chosen a number of locations to illustrate the features
+of the tsunami as it approaches and impacts Onslow.
+These locations have been chosen as we believe they would 
+either be critical
+in an emergency situation, (e.g. the hospital and power station) or
+effect recovery efforts, (e.g. the airport and docks). These locations
+are described in Table \ref{table:locations} and shown in 
+Figure \ref{fig:points}. The water's stage and speed 
+at each of these locations are shown
+as a function of time in the series of graphs shown in
+Appendix \ref{sec:timeseries}. Discussion of the main features of the
+tsunami wave is also described in Appendix \ref{sec:timeseries}.
Index: /anuga_work/production/wa/dampier_2006/report07/introduction.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/introduction.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/introduction.tex	(revision 7411)
@@ -0,0 +1,52 @@
+The Fire and Emergency Services Authority (FESA) of Western Australia  and 
+associated volunteers respond to a wide range of emergencies 
+as well as undertaking search and rescue operations on land and 
+water\footnote{http://www.fesa.wa.gov.au/internet/}. 
+FESA helps the West Australian 
+community prepare, prevent (where possible) and respond safely to disasters.
+FESA also aims to reduce injury, loss of life and destruction of property in 
+Western Australian communities through proactive measures. 
+These measures involve understanding the relative risk
+of the disaster so that resources can be directed to appropriate areas
+and corresponding evacuation plans put in place.  
+
+The key role of the Risk Research Group at Geoscience Australian 
+is to develop knowledge on the risk from natural and 
+human-caused hazards for input to policy and operational decision making on 
+the mitigation of risk to Australian communities. The Group achieves 
+this through the development of computational methods, models and decision 
+support tools that assess the hazard, vulnerability and risk posed by hazard
+events. To develop an understanding of the tsunami risk, GA has developed
+decision support tools, consisting of inundation
+maps overlaid on aerial photography of the region 
+detailing critical infrastructure as well as damage modelling estimates. 
+
+This report details the impact assessments for a range of tsunami events.
+These events are based on the probabilistic hazard assessment conducted
+for the Western Australian coastline. A number of events are selected for
+return periods of 500, 1000 and 2000 years, see Section \ref{sec:tsunamiscenario}.
+%This report is the first in a series of tsunami assessments 
+%of the North West Shelf. The scenario used for this study has
+%an unknown return period, but is considered a plausible event (see
+%Section \ref{sec:methodology}). 
+%Subsequent assessments will use refined hazard models with
+%associate return periods. A suite of assessments will be
+%made for Onslow and other localities, as advised by FESA.
+
+Onslow has a population of around 800 and
+is part of the Shire of Ashburton in the Pilbara region of 
+Western Autralia\footnote{http://www.pdc.wa.gov.au/region/political.htm}. 
+Onslow supports
+a variety of industries, including oil, gas, mining, cattle, 
+fishing and tourism.
+
+The modelling technique to simulate the 
+impact ashore is discussed in Section \ref{sec:methodology} with 
+event and data inputs
+discussed in Sections \ref{sec:tsunamiscenario} and \ref{sec:data} respectively. 
+The inundation results are presented and discussed in Section \ref{sec:results} 
+and the impact modelling results outlined in Section \ref{sec:impact}.
+A summary of the results detailing issues
+regarding underlying data and further model development, are discussed 
+in Section \ref{sec:summary}.
+
Index: /anuga_work/production/wa/dampier_2006/report07/metadata.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/metadata.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/metadata.tex	(revision 7411)
@@ -0,0 +1,1 @@
+\includepdf[pages={1-6}]{MetadataforATWSDampierScenario}
Index: /anuga_work/production/wa/dampier_2006/report07/modelling_methodology.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/modelling_methodology.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/modelling_methodology.tex	(revision 7411)
@@ -0,0 +1,81 @@
+
+The Risk Research Group aims to define the economic and social threat posed to urban communities 
+by a range of rapid onset natural hazards. Through the integration of natural hazard research, defining national exposure and 
+estimating socio-economic vulnerabilities, predictions of the likely impacts of events can be made. 
+By modelling the likely impacts on urban communities as accurately as possible and
+building these estimates into land use planning and emergency
+management, communities will be better prepared to respond to
+natural disasters when they occur.
+
+
+%GA bases its risk modelling on the process of understanding the hazard and a community's 
+%vulnerability in order to determine the impact of a particular hazard event. 
+%The resultant risk relies on an assessment of the likelihood of the event. 
+%An overall risk assessment for a particular hazard would then rely on scaling 
+%each event's impact by its likelihood.
+
+To develop a tsunami risk assessment, 
+the tsunami hazard itself must first be understood. These events are generally modelled by converting
+the energy released by a subduction earthquake into a vertical displacement of the ocean surface. 
+%Tsunami hazard models have been available for some time. 
+The resulting wave is
+then propagated across a sometimes vast stretch of ocean towards the
+area of interest. 
+%using a relatively coarse model 
+%based on bathymetries with a typical resolution of two arc minutes.
+Initial hazard assessments have been based on reporting the maximum wave height at a fixed contour line near the coastline, 
+(e.g. 50m). This is how the preliminary tsunami hazard assessment was reported by GA 
+to FESA in September 2005 \cite{BC:FESA} for a suite of Mw 9 earthquakes
+evenly spaced along the Sunda Arc subduction zone. 
+The assessment used the Method of Splitting Tsunamis (MOST)
+\cite{VT:MOST} model. Subsequent hazard assessments are been developed in a 
+probabilistic manner which are being derived from the URS Corporation's
+Probabilistic Tsunami Hazard Analysis model \cite{somerville:urs}. 
+%The maximal wave height at a fixed contour line near the coastline
+%(e.g. 50m) is then reported as the hazard to communities ashore. 
+%Models such as Method of Splitting Tsunamis (MOST) \cite{VT:MOST} and the 
+%URS Corporation's
+%Probabilistic Tsunami Hazard Analysis  
+%\cite{somerville:urs} follow this paradigm.
+
+While MOST and URS are suitable for generating and propagating the tsunami wave from its source, it is not adequate to
+model the wave's impact on communities ashore.  
+To capture the \emph{impact} of a tsunami to a coastal community, 
+the model must be capable of capturing more detail about the wave, 
+particularly how it is affected by the local bathymetry, as well as the 
+local topography as the wave moves onshore. 
+%the details of how waves are reflected and otherwise 
+%shaped by the local bathymetries as well as the dynamics of the 
+%runup process onto the topography in question.
+It is well known that local bathymetric and topographic effects are 
+critical in determining the severity of a hydrological disaster 
+\cite{matsuyama:1999}. To model the impact of the tsunami wave on the 
+coastal community, we use ANUGA \cite{ON:modsim}. In order to capture the 
+details of the wave and its interactions, a much finer resolution is 
+required than that of the hazard model. As a result, ANUGA simulations concentrate 
+on specific coastal communities. MOST and URS by contrast use a 
+coarser resolution and covers often vast areas. To develop the impact 
+from an earthquake event from a distant source, we adopt a hybrid approach of 
+modelling the event itself with the URS model and modelling the impact with ANUGA. 
+In this way, the output from URS serves as an input to ANUGA. 
+In modelling terms, the URS output is a boundary condition for ANUGA. Further details
+regarding the modelling requirements for this study can be found in 
+Appendix \ref{sec:anugasetup}.
+
+The event chosen for this study has been determined from the probabilistic
+hazard modelling being undertaken by the Earthquake and Hazards Project.
+The low probability, high potential impact Mw 9.0 event has been chosen
+for this study.
+
+%\begin{figure}[h]
+
+  %\centerline{ \includegraphics[width=140mm, height=100mm]
+%{../report_figures/mw9.jpg}}
+
+%  \caption{Maximum wave height (in cms) for a Mw 9.0 event off the 
+%coast of Java}
+%  \label{fig:mw9}
+%\end{figure}
+
+
+ 
Index: /anuga_work/production/wa/dampier_2006/report07/mw9_map.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/mw9_map.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/mw9_map.tex	(revision 7411)
@@ -0,0 +1,8 @@
+%\begin{sidewaysfigure}
+
+\begin{figure}
+\centerline{ \includegraphics[scale=0.6]{../report_figures/max_inundation_high_tide.jpg}} 
+\caption{Maximum inundation map for the HAT scenario for Dampier region. Data: WA DLI, DPI and AHO.}  
+\label{fig:HAT_max_inundation}
+%\end{sidewaysfigure}
+\end{figure}
Index: /anuga_work/production/wa/dampier_2006/report07/references.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/references.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/references.tex	(revision 7411)
@@ -0,0 +1,54 @@
+\begin{thebibliography}{99}
+
+\bibitem{CB:ausgeo} Cummins, P. and Burbidge, D. (2004) 
+Small threat, but warning sounded for tsunami research. AusGeo News 75, 4-7.
+
+\bibitem{BC:FESA} Burbidge, D. and Cummins, P. (2005) Preliminary Tsuanmi 
+Hazard Assesment of Western Australia. Report 
+to the Fire and Emergency Services Authority of Western Australia.
+
+\bibitem{VT:MOST} Titov, V.V., and F.I. Gonzalez (1997)
+Implementation and testing of the Method of Splitting 
+Tsunami (MOST) model, NOAA Technical Memorandum ERL PMEL-112.
+
+\bibitem{prob:fesa} Burbidge, D. and Cummins, P. (2006) Probabilistic
+Tsunami Hazard Assessment of Western Australia. Report to the 
+Fire and Emergency Services Authority of Western Australia.
+
+\bibitem{somerville:urs} Somerville, P., Thio, H.K. and Ichinose, G. (2005)
+Probabilistic Tsunami Hazard Analysis. Report delivered to Geoscience
+Australia 2005.
+
+\bibitem{matsuyama:1999}
+Matsuyama, M., Walsh, J.P. and Yeh, H. (1999) 
+The effect of bathymetry on tsunami characteristics at 
+Sisano Lagoon, Papua New Guinea. 
+Geophysical Research Letters, 26, 23, 3513-3516.
+
+\bibitem{ON:modsim} Nielsen, O., Roberts, Gray, D., McPherson, A. and 
+Hitchman, A (2005) 
+Hydrodynamic modelling of coastal inundation, MODSIM 2005 International 
+Congress on Modelling and Simulation.
+Modelling and Simulation Society of Australian and New Zealand, 518-523,
+URL: http://www.mssanz.org.au/modsim05/papers/nielsen.pdf
+
+\bibitem{antt:06} Australian National Tide Tables 2006:
+Australia, Papua New Guinea, Solomon Islands and Antarctica and East Timor.
+Australian Hydrographic Publication 11, Australian Hydrographic Service.
+
+\bibitem{papathoma:vulnerability} 
+Papathoma, M. and Dominey-Howes, D. (2003) 
+Tsunami vulnerability assessment and its implications for coastal hazard 
+analysis and disaster management planning, Gulf of Corinth, Greece, 
+Natural Hazards and Earth System Sciences, 3, 733-747.
+
+\bibitem{cooper:2005}
+Cooper, D. (2005) Risk Research Group Personal Communication at NSW Tsunami 
+Workshop 12th and 13th April, Masonic Centre, Goulburn St, Sydney.
+
+\bibitem{NIBS:2003} National Institute of Building Sciences (2003) 
+HAZUS-MH User Manual, Washington DC, USA.
+
+\bibitem{uq:friction} Duncan - do you have a reference for this?
+
+\end{thebibliography}
Index: /anuga_work/production/wa/dampier_2006/report07/summary.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/summary.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/summary.tex	(revision 7411)
@@ -0,0 +1,8 @@
+This report has described the tsunami inundation occurring at the gas
+facility at Dampier from a tsunami
+generated by a Mw 9 earthquake on the Sunda Arc subduction zone 
+occurring at Highest Astronomical Tide. 
+Velocity data has also been provided at the locations of interest surrounding the gas pipeline.
+The results described must be tempered with the modelling assumptions 
+and the accuracy and coverage of the underlying elevation data.
+
Index: /anuga_work/production/wa/dampier_2006/report07/timeseriesdiscussion.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/timeseriesdiscussion.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/timeseriesdiscussion.tex	(revision 7411)
@@ -0,0 +1,97 @@
+It is assumed that the earthquake is
+generated at the beginning of the simulation, i.e. time = 0 minutes.
+Stage is defined as the absolute
+water level (in metres) relative to AHD 
+\footnote{For an offshore location such as Beadon Bay West,
+the initial water level will be that of the tidal scenario. In the 
+case of MSL, this water level will be 0. As the tsunami wave moves
+through this point, the water height may grow and thus the stage will 
+represent the amplitude of the wave.} For an onshore location such as the 
+Light Tower, the actual water depth will be shown rather than the stage. 
+Both stage and speed 
+(in metres/second) for
+each scenario (HAT, MSL and LAT) are shown
+on consistent scales to allow comparison between point locations.
+As a useful benchmark, Table \ref{table:speedexamples}
+describes typical examples for a range of speeds found in the 
+simulations. 
+
+\begin{table}[h]
+\label{table:speedexamples}
+\caption{Examples of a range of velocities.}
+\begin{center}
+\begin{tabular}{|l|l|}\hline
+{\bf Velocity (m/s)} & {\bf Example} \\ \hline
+1 & leisurely stroll pace\\ \hline
+1.5 & average walking pace \\ \hline
+%2 & 100m Olympic male freestyle \\ \hline
+%3 & mackeral \\ \hline
+4 & average person can maintain running for 1000m \\ \hline
+%5 & blue whale \\ \hline
+10 & 100m Olympic male sprinter \\ \hline
+16 & car travelling in urban zones (60 km/hr) \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+A tsunami wave typically has a small amplitude and typically travels at 100's of kilometres per hour. 
+The low amplitude complicates the ability to detect
+the wave. As the water depth decreases, 
+the speed of the wave 
+decreases and the amplitude grows. Another important feature of tsunamis 
+is drawdown. This means that the water is seen to retreat from the beaches
+before a tsunami wave 
+impacts that location. Other features 
+include reflections (where the wave is redirected due to the 
+influence 
+of the coast) and shoaling (where the wave's amplitude is amplified
+close to the coast due to wave interactions).
+These features are seen in these scenarios, and are consistent
+for HAT, MSL and LAT. 
+There is a small wave, followed
+by a large drawdown and then a large secondary wave. 
+
+These 
+features are illustrated in Figure \ref{fig:gaugeBeadonBayeast}
+where a small wave can be seen at around 200 mins. For the HAT
+case (shown in blue), the amplitude
+of the wave at this location is around 0.8 m\footnote{In this
+scenario, the initial water level is 1.5 m, which means that
+the actual amplitude is the difference between the stage value
+and the initial water level; 2.3 - 1.5}.
+The drawdown of 4.05 m (i.e. 2.3 - -1.75) then occurs at around 230 mins
+(i.e. 3.8 hours after the event has been generated), before
+the second wave arrives 
+with an amplitude of around 3.6 m (i.e. 4.1 - 1.5). A further wave
+is then evident a short time later (around 255 mins) 
+which further increases the amplitude to around 5 m (i.e. 6.6 - 1.5).
+These features are replicated at each of the offshore points (those
+points with negative elevation as shown in Table \ref{table:locations}).
+
+The wave amplitude is typically greater
+for those locations which are in the shallowest water. For example,
+the maximum wave amplitude at the Beadon Bay East location 
+(Figure \ref{fig:gaugeBeadonBayeast}) is over
+4.5m where the water depth would normally be 3.56 m. In the 
+Beadon Bay West location (Figure \ref{fig:gaugeBeadonBaywest})
+where the water depth would normally be 4.62 m, 
+the maximum wave amplitude is much less (around 3 m). The wave amplitude
+at the West of Groyne location (Figure \ref{fig:gaugeWestofGroyne})
+is not greater than that seen
+at the Beadon Bay East location, even though the water depth is 
+much less, at 2.11m. This is probably due to its proximity
+to the groyne\footnote{A groyne is a man made structure to combat
+coastal erosion.}
+which has impeded the tsunami wave to some degree. However, the 
+maximum speed found amongst the locations is at the West of Groyne
+point which is in the shallowest water.
+
+The speed of the tsunami sharply increases as it moves onshore. There
+is minimal inundation found at the locations chosen, with the Bindi Bindi
+community receiving the greatest inundation for all tidal scenarios.
+At HAT, the community would receive over 1 m of inundation with 
+the water moving through the community at approximately 16 m/s. Referring
+to Table \ref{table:speedexamples}, a person in this location could
+not outrun this water movement. A small amount of water is found
+at the hospital (10 cm). Whilst this seems minimal, the water is moving 
+at around 6 m/s which could dislodge some items if the water was able to enter the hospital.
Index: /anuga_work/production/wa/dampier_2006/report07/tsunami_scenario.tex
===================================================================
--- /anuga_work/production/wa/dampier_2006/report07/tsunami_scenario.tex	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/report07/tsunami_scenario.tex	(revision 7411)
@@ -0,0 +1,1 @@
+
Index: /anuga_work/production/wa/dampier_2006/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/run_boundary_points.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/run_boundary_points.py	(revision 7411)
@@ -0,0 +1,35 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+
+# # Related major packages
+# from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import URS_points_needed_to_file, \
+     urs_ungridded2sww
+import project                 # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+poly = project.poly_all
+print "poly", poly
+print "project.boundaries_dir_name5",project.boundaries_dir_name5
+URS_points_needed_to_file('i',poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True)
+#urs_ungridded2sww(project.boundaries_in_dir_name2, project.boundaries_dir_name5, mean_stage= project.tide,  verbose=True)
Index: /anuga_work/production/wa/dampier_2006/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,40 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+import project
+
+# Inputs
+#timestampdir = '20070419_065050_run' # HAT 1 in 10000 yr Dampier event
+#timestampdir = '20070419_065018_run' # MSL 1 in 10000 yr Dampier event
+#timestampdir = '20070618_063824_run_final_2.4_onslow_nbartzis' # HAT onslow
+#timestampdir = '20070618_050232_run_final_0.0_onslow_nbartzis' # MSL onslow
+#timestampdir = '20070620_044352_run_final_0.0_exmouth_nbartzis' # MSL exmouth
+timestampdir = '20070620_044413_run_final_2.4_exmouth_nbartzis' # HAT exmouth
+file_loc = project.output_dir + timestampdir + sep 
+swwfilebasename = file_loc + project.scenario_name #+ '.sww'
+buildings_filename = project.buildings_filename
+buildings_filename_out = file_loc + project.buildings_filename_out
+print 'hello', swwfilebasename
+add_depth_and_momentum2csv(swwfilebasename, buildings_filename, buildings_filename_out)
+inundation_damage(swwfilebasename, buildings_filename, buildings_filename_out)
+
+print '\n Augmented building file written to %s \n' \
+      %buildings_filename_out
Index: /anuga_work/production/wa/dampier_2006/run_dampier.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/run_dampier.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/run_dampier.py	(revision 7411)
@@ -0,0 +1,220 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, copy_code_files
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+#copy script must be before screen_catcher
+if myid == 0:
+    copy_code_files(project.output_run_time_dir,__file__, 
+                 dirname(project.__file__)+sep+ project.__name__+'.py' )
+barrier()
+
+start_screen_catcher(project.output_run_time_dir, myid, numprocs)
+
+print "Processor Name:",get_processor_name()
+barrier()
+
+# filenames
+#boundaries_name = project.boundaries_name
+meshes_dir_name = project.meshes_dir_name+'.msh'
+#boundaries_dir_name = project.boundaries_dir_name
+
+tide = project.tide
+
+# creates copy of code in output dir
+
+
+print 'USER: ', project.user
+print 'min triangles', project.trigs_min,
+print 'Note: This is generally about 20% less than the final amount'
+
+#--------------------------------------------------------------------------
+# Create the triangular mesh based on overall clipping polygon with a
+# tagged
+# boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#--------------------------------------------------------------------------
+
+if myid == 0:
+    
+    print 'start create mesh from regions'
+
+    create_mesh_from_regions(project.poly_all,
+                             boundary_tags={'back': [2,3], 'side': [0, 1, 4],
+                                            'ocean': [5]},
+                             maximum_triangle_area=project.res_poly_all,
+                             interior_regions=project.interior_regions,
+                             filename=meshes_dir_name,
+                             use_cache=False,
+                             verbose=True)
+
+# to sync all processors are ready 
+barrier()
+
+#-------------------------------------------------------------------------
+# Setup computational domain
+#-------------------------------------------------------------------------
+print 'Setup computational domain'
+#from caching import cache
+
+#domain = cache(Domain, (meshes_dir_name), {'use_cache':True, 'verbose':True}, verbose=True)
+#above don't work
+domain = Domain(meshes_dir_name, use_cache=False, verbose=True)
+print 'domain id', id(domain) 
+print 'myhash', myhash(domain)      
+       
+print domain.statistics()
+
+#boundaries_dir_name=project.boundaries_dir_name
+
+#print 'starting to create boundary conditions'
+
+#from anuga.shallow_water.data_manager import urs2sww
+
+
+#-------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------
+if myid == 0:
+
+    print 'Setup initial conditions'
+
+    from polygon import *
+    #following sets the stage/water to be offcoast only
+    IC = Polygon_function( [(project.poly_mainland, 0.)], default = tide)
+#    IC = Polygon_function( [(project.poly_mainland, 0.)], default = 200)
+    domain.set_quantity('stage', IC)
+    domain.set_quantity('friction', 0.01) 
+    print 'Start Set quantity'
+
+    domain.set_quantity('elevation', 
+#                    filename = project.combined_dir_name + '.pts',
+# MUST USE TXT FILES FOR CACHING TO WORK!
+                    filename = project.combined_dir_name + '.txt',
+#                    filename = project.combined_smallest_dir_name + '.txt',
+                    use_cache = True,
+                    verbose = True,
+                    alpha = 0.1)
+    print 'Finished Set quantity'
+barrier()
+
+
+#------------------------------------------------------
+# Distribute domain to implement parallelism !!!
+#------------------------------------------------------
+
+if numprocs > 1:
+    domain=distribute(domain)
+
+#------------------------------------------------------
+# Set domain parameters
+#------------------------------------------------------
+print 'domain id', id(domain)
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run_time_dir)
+domain.set_default_order(2) # Apply second order scheme
+domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+domain.set_store_vertices_uniquely(False)
+domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+print 'domain id', id(domain)
+
+#-------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------
+print 'Available boundary tags', domain.get_boundary_tags()
+print 'domain id', id(domain)
+#print 'Reading Boundary file',project.boundaries_dir_namea + '.sww'
+
+Bf = Field_boundary(project.boundaries_dir_namea + '.sww',
+                    domain, time_thinning=12, mean_stage=tide, 
+                    use_cache=True, verbose=True)
+
+print 'finished reading boundary file'
+
+Br = Reflective_boundary(domain)
+Bd = Dirichlet_boundary([tide,0,0])
+
+print'set_boundary'
+##domain.set_boundary({'back': Br,
+##                     'side': Bf,
+##                     'ocean': Bf})
+domain.set_boundary({'back': Br,
+                     'side': Bd,
+                     'ocean': Bf}) 
+print'finish set boundary'
+
+#----------------------------------------------------------------------------
+# Evolve system through time
+#----------------------------------------------------------------------------
+
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = 60, finaltime = 29950):
+    domain.write_time()
+#    domain.write_time(track_speeds=True)
+    domain.write_boundary_statistics(tags = 'ocean')
+    
+#    domain.write_time(track_speeds=True)
+
+#for t in domain.evolve(yieldstep = 120, finaltime = 9000):
+#    domain.write_time()
+#    domain.write_boundary_statistics(tags = 'ocean')
+'''     
+for t in domain.evolve(yieldstep = 60, finaltime = 28800
+                       ,skip_initial_step = True):
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'ocean')    
+
+for t in domain.evolve(yieldstep = 120, finaltime = 34800
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'ocean')    
+'''
+x, y = domain.get_maximum_inundation_location()
+q = domain.get_maximum_inundation_elevation()
+
+print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+print 'That took %.2f seconds' %(time.time()-t0)
+
Index: /anuga_work/production/wa/dampier_2006/run_dampier_parallel.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/run_dampier_parallel.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/run_dampier_parallel.py	(revision 7411)
@@ -0,0 +1,190 @@
+"""Script for running tsunami inundation scenario for Karratha, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.outputtimedir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+# FIXME - parallel library not yet ready (16/10/2006)
+
+
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+
+from anuga.geospatial_data.geospatial_data import *
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+from anuga_parallel.parallel_api import distribute, myid, numprocs
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+# filenames
+meshname = project.meshname+'.msh'
+source_dir = project.boundarydir
+
+if myid == 0:
+    # creates copy of code in output dir if dir doesn't exist
+    if access(project.outputtimedir,F_OK) == 0:
+        mkdir (project.outputtimedir)
+    copy (dirname(project.__file__) +sep+ project.__name__+'.py',
+          project.outputtimedir + project.__name__+'.py')
+    copy (__file__, project.outputtimedir + basename(__file__))
+    print 'project.outputtimedir',project.outputtimedir
+
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+
+    print 'start create mesh from regions'
+    from caching import cache
+    meshname = project.meshname + '_%d.msh' %myid
+    _ = cache(create_mesh_from_regions,
+              project.bounding_polygon,
+              {'boundary_tags': {'back': [7, 8], 'side': [0, 6],
+                                 'ocean': [1, 2, 3, 4, 5]},
+               'maximum_triangle_area': 200000,
+               'filename': meshname},
+              verbose = True,
+              evaluate = False)
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    domain = Domain(meshname, use_cache = True, verbose = True)
+    print domain.statistics()
+    domain.set_name(project.basename)
+    domain.set_datadir(project.outputtimedir)
+
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    tide = 0.
+    domain.set_quantity('stage', tide)
+    domain.set_quantity('friction', 0.0) 
+    domain.set_quantity('elevation', 
+                        filename = project.datadir + project.basename + '.pts',
+                        use_cache = False,
+                        verbose = True,
+                        alpha = 0.1)
+    
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+
+    print 'Available boundary tags', domain.get_boundary_tags()
+    #Bf = File_boundary(source_dir + project.boundary_basename + '.sww', 
+    #                   domain, verbose = True)
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([tide,0,0])
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': None}) # Bind this one later
+else:
+    domain = None
+
+
+#--------------------------------------------------------------------------
+# Create the parallel domain
+#--------------------------------------------------------------------------
+if numprocs > 1:
+    domain = distribute(domain, verbose=True)
+
+# Set those boundaries that can't be communicated automatically
+# FIXME: There is a problem with the parallel domain.
+# It seems that boundaries are outside coverage.
+#
+# We get
+#
+#------------------------------------------------
+#Interpolation_function (spatio-temporal) statistics:
+#  Extent:
+#    x in [-60494.651593, 149593.652382], len(x) == 56
+#    y in [-74198.017534, 184623.446077], len(y) == 56
+#    t in [0.000000, 28610.000000], len(t) == 145
+#  Quantities:
+#    stage in [-1.797799, 1.644574]
+#    xmomentum in [-33.219473, 21.571094]
+#    ymomentum in [-32.775090, 73.761256]
+#  Interpolation points (xi, eta): number of points == 411
+#    xi in [-420467.297166, -368252.119852]
+#    eta in [-7652664.149808, -7605199.504709]
+#  Interpolated quantities (over all timesteps):
+#    stage at interpolation points in [inf, inf]
+#    xmomentum at interpolation points in [inf, inf]
+#    ymomentum at interpolation points in [inf, inf]
+#------------------------------------------------
+#
+#Instead of
+#
+#------------------------------------------------
+#Interpolation_function (spatio-temporal) statistics:
+#  Extent:
+#    x in [-60494.651593, 149593.652382], len(x) == 56
+#    y in [-74198.017534, 184623.446077], len(y) == 56
+#    t in [0.000000, 28610.000000], len(t) == 145
+#  Quantities:
+#    stage in [-1.797799, 1.644574]
+#    xmomentum in [-33.219473, 21.571094]
+#    ymomentum in [-32.775090, 73.761256]
+#  Interpolation points (xi, eta): number of points == 503
+#    xi in [4747.280215, 96909.729282]
+#    eta in [9240.613414, 83183.465791]
+#  Interpolated quantities (over all timesteps):
+#    stage at interpolation points in [-0.909515, 1.331521]
+#    xmomentum at interpolation points in [-17.054914, 17.110528]
+#    ymomentum at interpolation points in [-24.691402, 16.625063]
+#------------------------------------------------
+
+
+Bf = File_boundary(source_dir + project.boundary_basename + '.sww',
+                   domain, verbose = True)
+domain.set_boundary({'ocean': Bf})
+
+
+#----------------------------------------------------------------------------
+# Evolve system through time
+#----------------------------------------------------------------------------
+import time
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = 60, finaltime = 28600):
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'ocean')     
+    
+print 'That took %.2f seconds' %(time.time()-t0)
+
Index: /anuga_work/production/wa/dampier_2006/run_dampier_simple.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/run_dampier_simple.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/run_dampier_simple.py	(revision 7411)
@@ -0,0 +1,293 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename,
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from Numeric import allclose
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, copy_code_files
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+start_screen_catcher(project.output_run_time_dir, myid, numprocs)
+print "Processor Name:",get_processor_name()
+
+# filenames
+#boundaries_name = project.boundaries_name
+meshes_dir_name = 'small.tsh' # this will be local
+#meshes_dir_name = project.meshes_dir_name+'.msh'
+#boundaries_dir_name = project.boundaries_dir_name
+
+tide = project.tide
+
+# creates copy of code in output dir
+if myid == 0:
+    copy_code_files(project.output_run_time_dir,__file__, 
+                 dirname(project.__file__)+sep+ project.__name__+'.py' )
+barrier()
+
+print 'USER: ', project.user
+print 'min triangles', project.trigs_min,
+print 'Note: This is generally about 20% less than the final amount'
+
+#--------------------------------------------------------------------------
+# Create the triangular mesh based on overall clipping polygon with a
+# tagged
+# boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#--------------------------------------------------------------------------
+'''
+poly = [[0,0],[0,100],[100,100],[100,0]]
+
+create_mesh_from_regions(poly,
+                             boundary_tags={'back': [0], 'side': [1,3],
+                                            'ocean': [2]},
+                             maximum_triangle_area=1,
+                             interior_regions=None,
+                             filename=meshes_dir_name,
+                             use_cache=True,
+                             verbose=True)
+
+sys.exit()
+
+if myid == 0:
+    
+    print 'start create mesh from regions'
+#    print 'project.res_poly_all',project.res_poly_all
+#    print 'project.interior_regions_test',project.interior_regions_test
+#    print 'meshes_dir_name',meshes_dir_name
+    create_mesh_from_regions(project.poly_all,
+                             boundary_tags={'back': [2,3], 'side': [0, 1, 4],
+                                            'ocean': [5]},
+                             maximum_triangle_area=project.res_poly_all,
+                             interior_regions=project.interior_regions_test,
+                             filename=meshes_dir_name,
+                             use_cache=True,
+                             verbose=True)
+
+# to sync all processors are ready 
+barrier()
+
+#all= [[517303.61,7760858.88],[517477.06,7733020.49],[425462.92,7733020.49],[425462.92,7760338.54]]
+#all= [[500000,7760800],[500000,7733000],[450000,7733000],[450000,7760800]]
+#all= [[469000,7760800],[490000,7750000],[459000,7750000]]
+all= [[479000,7760800],[469000,7750000],[459000,7760800]] #swapped edge of triangle
+#all= [[469000,7760800],[490000,7750000],[459000,7750000]]
+create_mesh_from_regions(all,
+                             boundary_tags={'ocean': [ 2],'side': [0, 1]},
+#                             boundary_tags={'back': [2,3], 'side': [0, 1, 4],'ocean': [5]},
+                             maximum_triangle_area=50000,
+#                             interior_regions=project.interior_regions_test,
+                             filename=meshes_dir_name,
+                             use_cache=False,
+                             verbose=True)
+'''                            
+#all = [[469000,7760000],[470000,7758000],[468000,7758000]]
+all = [[470000,7760000],[469000,7758000],[468000,7760000]]
+create_mesh_from_regions(all,
+                             boundary_tags={'ocean': [0,1,2]},
+#                             boundary_tags={'ocean': [ 2],'side': [0, 1]},
+                             maximum_triangle_area=50000,
+                             filename=meshes_dir_name,
+                             use_cache=False,
+                             verbose=True)
+
+#-------------------------------------------------------------------------
+# Setup computational domain
+#-------------------------------------------------------------------------
+print 'Setup computational domain'
+domain = Domain( meshes_dir_name, verbose=True)
+'''
+from caching import cache
+domain = cache(Domain, (meshes_dir_name), {'use_cache':True, 'verbose':True}, verbose=True)
+print 'domain id', id(domain) 
+print 'myhash', myhash(domain)      
+'''       
+print domain.statistics()
+
+boundaries_dir_name=project.boundaries_dir_name
+
+print 'starting to create boundary conditions'
+
+from anuga.shallow_water.data_manager import urs2sww
+'''
+# put above distribute
+print 'boundary file is: ',project.boundaries_dir_name
+from caching import cache
+if myid == 0:
+    cache(urs2sww,
+          (project.boundaries_in_dir_name,
+           project.boundaries_dir_name), 
+          {'verbose': True,
+           'minlat': project.south_boundary,
+           'maxlat': project.north_boundary,
+           'minlon': project.west_boundary,
+           'maxlon': project.east_boundary,
+           'mint': 0, 'maxt': 35100,
+           'origin': domain.geo_reference.get_origin(),
+           'mean_stage': project.tide,
+#           'zscale': 1,                 #Enhance tsunami
+           'fail_on_NaN': False},
+           verbose = True,
+           )
+barrier()
+'''
+
+#-------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------
+'''
+
+if myid == 0:
+
+    print 'Setup initial conditions'
+
+    from polygon import *
+    #following sets the stage/water to be offcoast only
+    IC = Polygon_function( [(project.poly_bathy, 0.)], default = tide)
+    domain.set_quantity('stage', IC)
+    domain.set_quantity('friction', 0.01) 
+    print 'Start Set quantity'
+
+    domain.set_quantity('elevation', 
+#                    filename = project.combined_dir_name + '.pts',
+# MUST USE TXT FILES FOR CACHING TO WORK!
+                    filename = project.combined_smallest_dir_name + '.txt',
+                    use_cache = True,
+                    verbose = True,
+                    alpha = 0.1)
+    print 'Finished Set quantity'
+barrier()
+'''
+print 'Start Set quantity'
+
+#domain.set_quantity('elevation', 
+#                    filename = project.combined_dir_name + '.pts',
+# MUST USE TXT FILES FOR CACHING TO WORK!
+#                    filename = project.combined_smallest_dir_name + '.txt',
+#                    use_cache = True,
+#                    verbose = True,
+#                    alpha = 0.1)
+domain.set_quantity('elevation', -42.3)
+
+print 'Finished Set quantity'
+
+#------------------------------------------------------
+# Distribute domain to implement parallelism !!!
+#------------------------------------------------------
+'''
+if numprocs > 1:
+    domain=distribute(domain)
+'''
+#------------------------------------------------------
+# Set domain parameters
+#------------------------------------------------------
+
+domain.set_quantity('stage', 2.4)
+domain.set_quantity('friction', 0.01)
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run_time_dir)
+
+print 'domain id', id(domain)
+'''
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run_time_dir)
+domain.set_default_order(2) # Apply second order scheme
+domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+domain.set_store_vertices_uniquely(False)
+domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+print 'domain id', id(domain)
+'''
+#-------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------
+print 'Available boundary tags', domain.get_boundary_tags()
+print 'domain id', id(domain)
+print 'Reading Boundary file',project.boundaries_dir_name4 + '.sww'
+#Bf = File_boundary(boundaries_dir_name + '.sww',
+Bf = File_boundary(project.boundaries_dir_name4 + '.sww',
+                  domain, time_thinning=24, use_cache=False, verbose=True)
+
+print 'finished reading boundary file'
+
+Br = Reflective_boundary(domain)
+Bd = Dirichlet_boundary([tide,0,0])
+
+print'set_boundary'
+##domain.set_boundary({'back': Br,
+##                     'side': Bf,
+##                     'ocean': Bf})
+domain.set_boundary({#'back': Br,
+                     'side': Bd,
+                    'ocean': Bf
+                    })
+print'finish set boundary'
+
+#----------------------------------------------------------------------------
+# Evolve system through time
+#----------------------------------------------------------------------------
+
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = 60, finaltime = 3400):
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'ocean')
+
+#for t in domain.evolve(yieldstep = 120, finaltime = 9000):
+#    domain.write_time()
+#    domain.write_boundary_statistics(tags = 'ocean')
+'''     
+for t in domain.evolve(yieldstep = 60, finaltime = 28800
+                       ,skip_initial_step = True):
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'ocean')    
+
+for t in domain.evolve(yieldstep = 120, finaltime = 34800
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'ocean')    
+'''
+x, y = domain.get_maximum_inundation_location()
+q = domain.get_maximum_inundation_elevation()
+
+print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+print 'That took %.2f seconds' %(time.time()-t0)
+
+
+
+
Index: /anuga_work/production/wa/dampier_2006/run_dampier_urs.py
===================================================================
--- /anuga_work/production/wa/dampier_2006/run_dampier_urs.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2006/run_dampier_urs.py	(revision 7411)
@@ -0,0 +1,265 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project_urs.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep,umask
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+# Application specific imports
+import project_urs                 # Definition of file names and polygons
+
+def run_model(**kwargs):
+    
+    tide = kwargs['tide']
+    alpha = kwargs['alpha']
+    friction = kwargs['friction']
+    time_thinning = kwargs['time_thinning']
+    scenario_name = kwargs['aa_scenario_name']
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+
+    #copy script must be before screen_catcher
+    print 'tide',tide
+    kwargs['est_num_trigs']=project_urs.trigs_min
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project_urs.host
+    kwargs['res_factor']=project_urs.res_factor
+    kwargs['starttime']=project_urs.starttime
+    kwargs['yieldstep']=project_urs.yieldstep
+    kwargs['finaltime']=project_urs.finaltime
+    
+    kwargs['output_dir']=project_urs.output_run_time_dir
+    kwargs['bathy_file']=project_urs.combined_dir_name + '.txt'
+#    kwargs['bathy_file']=project_urs.combined_small_dir_name + '.pts'
+    kwargs['boundary_file']=project_urs.boundaries_in_dir_name + '.sww'
+#    kwargs['Completed']=''
+    
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print 'output_dir',kwargs['output_dir']
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                 dirname(project_urs.__file__)+sep+ project_urs.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+
+    print "Processor Name:",get_processor_name()
+
+    # creates copy of code in output dir
+    print 'min triangles', project_urs.trigs_min,
+    print 'Note: This is generally about 20% less than the final amount'
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project_urs.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    #IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+    if myid == 0:
+    
+        print 'start create mesh from regions'
+
+        create_mesh_from_regions(project_urs.poly_all,
+                             boundary_tags={'back': [2,3], 'side': [0, 1, 4],
+                                            'ocean': [5]},
+                             maximum_triangle_area=project_urs.res_poly_all,
+                             interior_regions=project_urs.interior_regions,
+                             filename=project_urs.meshes_dir_name+'.msh',
+                             use_cache=False,
+                             verbose=True)
+    barrier()
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    #domain = cache(Domain, (meshes_dir_name), {'use_cache':True, 'verbose':True}, verbose=True)
+    #above don't work
+    domain = Domain(project_urs.meshes_dir_name+'.msh', use_cache=False, verbose=True)
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    if myid == 0:
+
+        print 'Setup initial conditions'
+
+        from polygon import Polygon_function
+        #following sets the stage/water to be offcoast only
+        IC = Polygon_function( [(project_urs.poly_mainland, -1.0)], default = tide,
+                                 geo_reference = domain.geo_reference)
+        domain.set_quantity('stage', IC)
+        domain.set_quantity('friction', friction) 
+        
+        print 'Start Set quantity'
+
+        domain.set_quantity('elevation', 
+                            filename = kwargs['bathy_file'],
+                            use_cache = True,
+                            verbose = True,
+                            alpha = alpha)
+        print 'Finished Set quantity'
+    barrier()
+
+    #------------------------------------------------------
+    # Distribute domain to implement parallelism !!!
+    #------------------------------------------------------
+
+    if numprocs > 1:
+        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(scenario_name)
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2) # Apply second order scheme
+    domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+    print 'domain id', id(domain)
+
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+    #print 'Reading Boundary file',project_urs.boundaries_dir_namea + '.sww'
+
+    Bf = Field_boundary(kwargs['boundary_file'],
+                    domain, time_thinning=time_thinning, mean_stage=tide, 
+                    use_cache=True, verbose=True)
+                    
+    kwargs['input_start_time']=domain.starttime
+
+    print 'finished reading boundary file'
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([tide,0,0])
+
+    print'set_boundary'
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf}) 
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #----------------------------------------------------------------------------
+
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['starttime']): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+
+    for t in domain.evolve(yieldstep = kwargs['yieldstep'], finaltime = 21600
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+    
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')   
+
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'That took %.2f seconds' %(time.time()-t0)
+    
+    kwargs['completed']=str(time.time()-t0)
+     
+    if myid == 0:
+ #       store_parameters(**kwargs)
+        
+        print 'memory usage before del domain',mem_usage()
+#        del domain
+        print 'memory usage after del domain',mem_usage()
+
+        swwfile = kwargs['output_dir']+kwargs['aa_scenario_name']
+        export_grid(swwfile, extra_name_out = 'town',
+                quantities = ['elevation','depth','stage','speed'], # '(xmomentum**2 + ymomentum**2)**0.5' defaults to elevation
+                timestep = None,
+                reduction = max,
+                cellsize = 25,
+                NODATA_value = -9999,
+                easting_min = project_urs.eastingmin,
+                easting_max = project_urs.eastingmax,
+                northing_min = project_urs.northingmin,
+                northing_max = project_urs.northingmax,
+                verbose = True,
+                origin = None,
+                datum = 'WGS84',
+                format = 'asc')
+    
+        buildings_filename = project_urs.buildings_filename
+        buildings_filename_out = project_urs.buildings_filename_out
+                
+        inundation_damage(swwfile+'.sww', buildings_filename, buildings_filename_out)
+        print '\n Augmented building file written to %s \n' %buildings_filename_out
+    
+    barrier()
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+    run_model(file_name=project_urs.home+'detail.csv', aa_scenario_name=project_urs.scenario_name,
+              ab_time=project_urs.time, res_factor= project_urs.res_factor, tide=project_urs.tide, user=project_urs.user,
+              alpha = project_urs.alpha, friction=project_urs.friction,
+              time_thinning = project_urs.time_thinning,
+              dir_comment=project_urs.dir_comment)
+
+
Index: /anuga_work/production/wa/dampier_2009/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/dampier_2009/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2009/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,78 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\dampier_tsunami_scenario_2009\\"
+output_dir="anuga\\outputs\\"
+
+time_dir1 = '20090817_150959_run_final_0.0_70408_kvanputt'
+
+time_dirs = [time_dir1]
+
+for time_dir in time_dirs:
+    # Local variables...
+    folder = scenario_dir + output_dir +  time_dir +'\\'
+    raster_gbd = folder + 'raster.gdb'
+##    land = scenario_dir + "map_work\\\port_hedland.gdb\\outlines\\initial_condition"
+##    ocean = scenario_dir + "map_work\\\port_hedland.gdb\\outlines\\initial_conditions_ocean"
+
+    print 'Process: Create File GDB'
+    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    print gp.Workspace
+    
+    #replication dictionary
+    replicate = (('dampier', ''),('_', ''),('max','_M'),
+                 ('CBD', 'CDB'),('Dampier', 'Damp'),('Karratha', 'Karr')
+                 ('depth','_depth'),('speed', '_speed'),
+                 ('elevation', '_ele'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection'
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+##        output_extract = output_DEM + 'E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+
Index: /anuga_work/production/wa/dampier_2009/build_elevation.py
===================================================================
--- /anuga_work/production/wa/dampier_2009/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2009/build_elevation.py	(revision 7411)
@@ -0,0 +1,100 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' # except', project.offshore_name5
+G = None
+for key in geospatial_data:
+    #if key == project.point_filenames[4] or key == project.ascii_filenames[1]:
+    #    # Skip these files for now
+    #    continue
+    
+    G += geospatial_data[key]
+        
+#print 'Clip combined geospatial data'
+##G_clip = G.clip_outside(project.poly_aoi1)
+##G_all = G_clip + geospatial_data[project.point_filenames[4]] 
+#G_clipped = G_all.clip(project.poly_all)
+#G_clip = G.clip(project.bounding_polygon)
+
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/dampier_2009/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/dampier_2009/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2009/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                central_meridian=project.central_meridian,
+                zone=project.zone,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                central_meridian=project.central_meridian,
+                zone=project.zone,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/dampier_2009/export_results.py
===================================================================
--- /anuga_work/production/wa/dampier_2009/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2009/export_results.py	(revision 7411)
@@ -0,0 +1,121 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+time_dir1 = '20090624_145617_run_final_0.0_27283_mhingee'
+##time_dir2 = ''
+##time_dir3 = ''
+##time_dir4 = ''
+##time_dir5 = ''
+##time_dir6 = ''
+##
+time_dirs = [time_dir1]#, time_dir2]# , time_dir4, time_dir5, time_dir6]
+  
+
+cellsize = 250
+##cellsize = 5
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+#area = ['Exmouth']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation','stage']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            #name2 = join(directory, time_dir, project.scenario_name)+'_time_39600_0'
+            #name3 = join(directory, time_dir, project.scenario_name)+'_time_79200_0'
+
+            names = [name1] #, name2]#, name3]
+      
+           # asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/dampier_2009/file_length.py
===================================================================
--- /anuga_work/production/wa/dampier_2009/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2009/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/dampier_2009/project.py
===================================================================
--- /anuga_work/production/wa/dampier_2009/project.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2009/project.py	(revision 7411)
@@ -0,0 +1,259 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+from anuga.lib.add_csv_header.add_csv_header import add_csv_header
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'dampier'
+scenario_folder = 'dampier_tsunami_scenario_2009'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0.0              # 3.6 difference between MSL and HAT in metres
+zone = 50               # specify UTM zone of model
+central_meridian = None 
+event_number = 70408    # 27255,27283 the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=1000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number]
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['topo_to_raster_0_30', 'land_final_240107']
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['Hydro_fair_chart.txt', 'coast_line.txt']
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'bounding_polygon.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['dampier_aoi.csv', 500],
+                         ['karratha_aoi.csv', 500]]
+
+PriorityArea_filename = 'aos.csv'
+    
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing,id,value
+land_initial_conditions_filename = 'initial_conditions_simple.csv'
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = ''
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = '' # from NEXIS
+
+# AREA OF IMAGES - Extent of each image to find out highest runup
+# Header - easting,northing,id,value
+# Used in get_runup.py
+images_filename = ''
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'thinned_boundary_ordering.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_boundary.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+##mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+##multi_mux = False
+mux_input_filename = 'event.list'
+multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# ASCII export grid for Dampier
+xminDampier = 465000
+xmaxDampier = 471000
+yminDampier = 7713000
+ymaxDampier = 7719000
+
+# ASCII export grid for Karratha
+xminKarratha = 475700
+xmaxKarratha = 489600
+yminKarratha = 7707000
+ymaxKarratha = 7718000
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# The absolute pathname for the image file
+# Used for get_runup.py
+if images_filename:
+    images = join(polygons_folder, images_filename)
+
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
+#Multiple polygons in one CSV file to make internal polygons
+if not PriorityArea_filename == None:
+    PriorityAreas = join(polygons_folder, PriorityArea_filename)
+
+
Index: /anuga_work/production/wa/dampier_2009/run_model.py
===================================================================
--- /anuga_work/production/wa/dampier_2009/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2009/run_model.py	(revision 7411)
@@ -0,0 +1,163 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/dampier_2009/setup_model.py
===================================================================
--- /anuga_work/production/wa/dampier_2009/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/dampier_2009/setup_model.py	(revision 7411)
@@ -0,0 +1,180 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+from anuga.shallow_water.data_manager import csv2polygons
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+# if it's a list, then it's a list of land condition filenames
+# else it's a string - a single file, multiple land conditions
+if isinstance(project.land_initial_conditions_filename, list):
+    for filename, MSL in project.land_initial_conditions_filename:
+        polygon = read_polygon(join(project.polygons_folder, filename))
+        project.land_initial_conditions.append([polygon, MSL])
+elif isinstance(project.land_initial_conditions_filename, basestring):
+    polygons, MSL = csv2polygons(join(project.polygons_folder,
+                                      project.land_initial_conditions_filename))
+    for i, key in enumerate(polygons):
+        if i%100==0: print i
+        poly = polygons[key]
+        land = float(MSL[key])
+        project.land_initial_conditions.append([poly, land])
+else:
+    msg = ('project.land_initial_conditions_filename must be a list or '
+           'string, got %s'
+           % type(project.land_initial_conditions_filename))
+    raise Exception, msg
+
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+
+if project.PriorityArea_filename is not None:
+    polygons, maxareas = csv2polygons(project.PriorityAreas)
+    print 'Creating %d internal polygons' % len(polygons)
+    #def create_polygon_function(polygons, geo_reference=None):
+    project.interior_regions = []
+    for i, key in enumerate(polygons):
+        if i%100==0: print i
+        poly = polygons[key]
+        maxarea = float(maxareas[key])
+        project.interior_regions.append([poly,
+                                         maxarea*project.scale_factor])
+
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/exmouth_2006/build_exmouth.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/build_exmouth.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/build_exmouth.py	(revision 7411)
@@ -0,0 +1,145 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.geospatial_data.geospatial_data import *
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files
+from anuga_parallel.parallel_abstraction import get_processor_name
+
+# Application specific imports
+import project   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project.output_build_time_dir,__file__, 
+               dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+start_screen_catcher(project.output_build_time_dir)
+
+print "Processor Name:",get_processor_name()
+print 'USER:    ', project.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print"project.combined_dir_name",project.combined_dir_name
+
+# topography directory filenames
+onshore_in_dir_name = project.onshore_in_dir_name
+onshore1_in_dir_name = project.onshore1_in_dir_name
+coast_in_dir_name = project.coast_in_dir_name
+#island_in_dir_name = project.island_in_dir_name
+offshore_in_dir_name = project.offshore_in_dir_name
+#offshore_in_dir_name1 = project.offshore_in_dir_name1
+#offshore_in_dir_name2 = project.offshore_in_dir_name2
+
+onshore_dir_name = project.onshore_dir_name
+onshore1_dir_name = project.onshore1_dir_name
+coast_dir_name = project.coast_dir_name
+#island_dir_name = project.island_dir_name
+offshore_dir_name = project.offshore_dir_name
+#offshore_dir_name1 = project.offshore_dir_name1
+#offshore_dir_name2 = project.offshore_dir_name2
+'''
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name, basename_out=onshore_dir_name, use_cache=True, verbose=True)
+convert_dem_from_ascii2netcdf(onshore1_in_dir_name, basename_out=onshore1_dir_name, use_cache=True, verbose=True)
+
+#creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name, use_cache=True, verbose=True)
+dem2pts(onshore1_dir_name, use_cache=True, verbose=True)
+
+print'create Geospatial data1 objects from topographies',onshore_dir_name + '.pts'
+G1 = Geospatial_data(file_name = onshore_dir_name + '.pts',verbose=True)
+print'create Geospatial data2 objects from topographies',onshore1_dir_name + '.pts'
+G2 = Geospatial_data(file_name = onshore1_dir_name + '.pts',verbose=True)
+print'create Geospatial data3 objects from coast', coast_in_dir_name + '.txt'
+G3 = Geospatial_data(file_name = coast_in_dir_name + '.txt',verbose=True)
+print'create Geospatial data3 objects from offshore',offshore_in_dir_name + '.txt'
+G_off = Geospatial_data(file_name = offshore_in_dir_name + '.txt',verbose=True)
+
+print'add all geospatial objects'
+G = G2 + G3 + G_off 
+
+print'add DLI data'
+G = G + G1
+
+print'export combined DEM file'
+if access(project.topographies_dir,F_OK) == 0:
+    mkdir (project.topographies_dir)
+print'export',project.combined_dir_name+'_unclipped' + '.txt'
+#G.export_points_file(project.combined_dir_name+ '.txt')
+
+print'create Geospatial data1 objects from topographies',onshore_dir_name + '.pts'
+#G = Geospatial_data(file_name = project.combined_dir_name+ '.txt',verbose=True)
+
+print'split'
+G_small, G_other = G.split(.10,verbose=True)
+
+print 'export', project.combined_small_dir_name + '.txt'
+G_small.export_points_file(project.combined_small_dir_name + '.txt')
+#G_clipped.export_points_file(project.combined_dir_name + '.xya')
+
+
+
+print'project.combined_dir_name + 1.xya',project.combined_dir_name + '1.xya'
+G_all=Geospatial_data(file_name = project.combined_dir_name + '1.xya')
+print'split'
+G_all_1, G_all_2 = G_all.split(.10)
+print'export 1'
+G_all_1.export_points_file(project.combined_dir_name+'_small1' + '.xya')
+print'export 2'
+G_all_2.export_points_file(project.combined_dir_name+'_other1' + '.xya')
+'''
+
+#-------------------------------------------------------------------------
+# Convert URS to SWW file for boundary conditions 
+#-------------------------------------------------------------------------
+print 'starting to create boundary conditions'
+boundaries_in_dir_name = project.boundaries_in_dir_name
+
+from anuga.shallow_water.data_manager import urs2sww, urs_ungridded2sww
+
+print 'boundaries_in_dir_name',boundaries_in_dir_name
+print 'project.boundaries_dir_name',project.boundaries_dir_name
+
+urs_ungridded2sww(boundaries_in_dir_name, boundaries_in_dir_name,
+                  verbose=True, mint=4000, maxt=35000, zscale=1)
+
+
+
+
+
+
Index: /anuga_work/production/wa/exmouth_2006/convert2latlon.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/convert2latlon.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/convert2latlon.py	(revision 7411)
@@ -0,0 +1,46 @@
+"""
+Convert Easting Northing to lon/lat for ultimately get kml file
+"""
+
+def alter_file(filename,filenameout):
+
+    from anuga.coordinate_transforms.lat_long_UTM_conversion import UTMtoLL
+    
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    fid_out = open(filenameout, 'w')
+    s = '%s,%s,%s\n' %('lon','lat','stage')
+    fid_out.write(s)
+    for line in lines[1:]:
+       fields = line.split(',')
+       easting = float(fields[0])
+       northing = float(fields[1])
+       stage = float(fields[3])
+       lat, lon = UTMtoLL(northing,easting, 50)
+       s = '%f,%f,%f\n' %(lon,lat,stage)
+       fid_out.write(s)
+
+    fid_out.close() 
+
+    return
+
+import project
+from os import sep
+
+#timedir = '20070618_035101_run_final_1.4_dampier_nbartzis' # HAT 1 in Dampier 10000 yr
+#timedir = '20070619_042043_run_final_1.4_onslow_nbartzis' # HAT 1 in Onslow 10000 yr
+timedir = '20070619_042542_run_final_1.4_exmouth_nbartzis' # HAT 1 in Exmouth 10000 yr
+
+filename = project.output_dir + timedir + sep + 'stage0_interp.csv'
+#filename = project.output_dir + timedir + sep + 'stage5_interp.csv'
+#filename = project.output_dir+ timedir + sep + 'stage20_interp.csv'
+#filename = project.output_dir+ timedir + sep + 'stage50_interp.csv'
+#filename = project.output_dir+  timedir + sep + 'stage80_interp.csv'
+filename_out = project.output_dir + timedir + sep + 'stage0_convert.csv'
+#filename_out = project.output_dir + timedir + sep + 'stage5_convert.csv'
+#filename_out = project.output_dir + timedir + sep + 'stage20_convert.csv'
+#filename_out = project.output_dir + timedir + sep + 'stage50_convert.csv'
+#filename_out = project.output_dir + timedir + sep + 'stage80_convert.csv'
+alter_file(filename,filename_out)
Index: /anuga_work/production/wa/exmouth_2006/export_results.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/export_results.py	(revision 7411)
@@ -0,0 +1,78 @@
+import project, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+#time_dir = '20070618_035101_run_final_1.4_dampier_nbartzis' # HAT 1 in Dampier 10000 yr
+#time_dir = '20070618_035114_run_final_0_dampier_nbartzis' # MSL 1 in Dampier 10000 yr
+#time_dir = '20070619_042043_run_final_1.4_onslow_nbartzis' # HAT 1 in Onslow 10000 yr
+#time_dir = '20070619_042140_run_final_0_onslow_nbartzis' # MSL 1 in Onslow 10000 yr
+#time_dir = '20070619_042542_run_final_1.4_exmouth_nbartzis' # HAT 1 in Exmouth 10000 yr
+#time_dir = '20070619_042417_run_final_0_exmouth_nbartzis' # MSL 1 in Exmouth 10000 yr
+#time_dir = '20080610_041607_run_final_1.4_exmouth_kvanputt' # HAT 1 in Exmouth 10000 yr
+time_dir = '20080613_055032_run_final_1.4_exmouth_kvanputt' # HAT 1 in Exmouth 10000 yr slope 1
+
+cellsize = 25
+timestep = None
+directory = project.output_dir
+
+name = directory+time_dir+sep+project.scenario_name
+
+is_parallel = False
+if is_parallel == True: nodes = 4
+print 'output dir:', name
+
+var = [2,3, 4] # depth and speed
+
+for which_var in var:
+    if which_var == 0:  # Stage
+        outname = name + '_stage'
+        quantityname = 'stage'
+
+    if which_var == 1:  # Absolute Momentum
+        outname = name + '_momentum_i1'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+    if which_var == 2:  # Depth
+        outname = name + '_depth'
+        quantityname = 'stage-elevation'  
+
+    if which_var == 3:  # Speed
+        outname = name + '_speed'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+    if which_var == 4:  # Elevation
+        outname = name + '_elevation'
+        quantityname = 'elevation'  #Elevation
+
+    if is_parallel == True:
+    #    print 'is_parallel',is_parallel
+        for i in range(0,nodes):
+            namei = name + '_P%d_%d' %(i,nodes)
+            outnamei = outname + '_P%d_%d' %(i,nodes)
+            print 'start sww2dem for sww file %d' %(i)
+            sww2dem(namei, basename_out = outnamei,
+                        quantity = quantityname,
+                        timestep = timestep,
+                        cellsize = cellsize,      
+                        easting_min = project.e_min_area,
+                        easting_max = project.e_max_area,
+                        northing_min = project.n_min_area,
+                        northing_max = project.n_max_area,        
+                        reduction = max, 
+                        verbose = True,
+                        format = 'asc')
+    else:
+        print 'start sww2dem'
+        sww2dem(name, basename_out = outname,
+                    quantity = quantityname,
+                    timestep = timestep,
+                    cellsize = cellsize,      
+                    easting_min = project.eastingmin,
+                    easting_max = project.eastingmax,
+                    northing_min = project.northingmin,
+                    northing_max = project.northingmax,        
+                    reduction = max, 
+                    verbose = True,
+                    format = 'asc')
Index: /anuga_work/production/wa/exmouth_2006/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/get_timeseries.py	(revision 7411)
@@ -0,0 +1,80 @@
+"""
+Generate images of "gauges" for production run
+
+Inputs:
+
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+Outputs:
+
+* figures used for report stored in the report_figure directory
+
+"""
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries
+
+# bulli event
+production_dirs = {'20070619_042043_run_final_1.4_onslow_nbartzis': ''}
+# 20070618_035101_run_final_1.4_dampier_nbartzis # HAT dampier
+# 20070618_035114_run_final_0_dampier_nbartzis # MSL dampier
+# 20070619_042542_run_final_1.4_exmouth_nbartzis # HAT exmouth parallel 4
+# 20070619_042417_run_final_0_exmouth_nbartzis # MSL exmouth parallel 4
+# 20070619_042043_run_final_1.4_onslow_nbartzis # HAT onslow
+# 20070619_042140_run_final_0_onslow_nbartzis # MSL onslow parallel 2
+
+is_parallel = True
+
+if is_parallel is True:
+    no_nodes = 4
+    
+if is_parallel is False:
+    
+    swwfiles = {}    
+    for label_id in production_dirs.keys():
+        
+        file_loc = project.output_dir + label_id + sep
+        swwfile = file_loc + project.scenario_name + '.sww'
+        swwfiles[swwfile] = label_id
+            
+        texname, elev_output = sww2timeseries(swwfiles,
+                                              project.beach_gauges,
+                                              production_dirs,
+                                              report = False,
+                                              plot_quantity = ['stage', 'speed'],
+                                              generate_fig = False,
+                                              surface = False,
+                                              time_min = None,
+                                              time_max = None,
+                                              time_unit = 'hours',
+                                              title_on = False,
+                                              use_cache = True,
+                                              verbose = True)
+
+if is_parallel is True:                                      
+
+    for count in range(no_nodes):
+        swwfiles = {} 
+        for label_id in production_dirs.keys():
+
+            file_loc = project.output_dir + label_id + sep
+            extra = '_P%i_%i' %(count,no_nodes)
+            swwfile = file_loc + project.scenario_name + extra + '.sww'
+            swwfiles[swwfile] = label_id
+
+            texname, elev_output = sww2timeseries(swwfiles,
+                                                  project.beach_gauges,
+                                                  production_dirs,
+                                                  report = False,
+                                                  plot_quantity = ['stage', 'speed'],
+                                                  generate_fig = False,
+                                                  surface = False,
+                                                  time_min = None,
+                                                  time_max = None,
+                                                  time_unit = 'hours',
+                                                  title_on = False,
+                                                  use_cache = True,
+                                                  verbose = True)
+                                      
Index: /anuga_work/production/wa/exmouth_2006/locate_indigeneous.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/locate_indigeneous.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/locate_indigeneous.py	(revision 7411)
@@ -0,0 +1,41 @@
+#
+# script to determine which communities are located in study region
+# 31 October 2006
+#
+
+def community_in_extent(filename,extent,zone,fid_out):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+
+    line1 = lines[0]
+    line11 = line1.split(',')
+    for i in range(len(line11)):
+        if line11[i].strip('\n').strip(' ') == 'LATITUDE': lat_index = i
+        if line11[i].strip('\n').strip(' ') == 'LONGITUDE': lon_index = i
+        if line11[i].strip('\n').strip(' ') == 'COMMUNITY': name_index = i
+
+    from anuga.coordinate_transforms.redfearn import convert_from_latlon_to_utm
+    from anuga.utilities.polygon import plot_polygons, is_inside_polygon
+    
+    for line in lines[1:]:
+        fields = line.split(',')
+        point, zone1 = convert_from_latlon_to_utm(latitudes=[fields[lat_index]],\
+                                                 longitudes=[fields[lon_index]])
+        if zone1 == zone:
+            v = is_inside_polygon(point,extent,verbose=False)
+            if v == True:
+                p = point[0]
+                s = '%s, %.2f, %.2f\n' %(fields[name_index], p[0], p[1])
+                fid_out.write(s)
+    return
+
+import project
+
+filename = project.community_filename
+filename_out = project.community_exmouth
+fid_out = open(filename_out, 'w')
+extent = project.poly_all
+zone = 50 # or is it 49?
+
+community_in_extent(filename,extent,zone,fid_out)
Index: /anuga_work/production/wa/exmouth_2006/plot_contour_data.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/plot_contour_data.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/plot_contour_data.py	(revision 7411)
@@ -0,0 +1,78 @@
+"""Read in contour data file and plot max and min
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid, figure
+from os import sep
+ 
+directory = project.output_dir
+
+#timedir = '20070618_035101_run_final_1.4_dampier_nbartzis' # HAT 1 in Dampier 10000 yr
+#timedir = '20070619_042043_run_final_1.4_onslow_nbartzis' # HAT 1 in Onslow 10000 yr
+timedir = '20070619_042542_run_final_1.4_exmouth_nbartzis' # HAT 1 in Exmouth 10000 yr
+
+def get_data(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[2]))
+    return max(stage), min(stage)
+
+files = ['stage0_convert.csv','stage5_convert.csv','stage20_convert.csv','stage50_convert.csv','stage80_convert.csv']
+depth = [0,5,20,50,80]
+stage_max = []
+stage_min = []
+
+for thefile in files:
+
+    filename = directory + timedir + sep + thefile
+    max_stage, min_stage = get_data(filename)
+    stage_max.append(max_stage)
+    stage_min.append(min_stage)
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 80.
+d2 = arange(d1,0.15,-0.1)
+h1 = max_stage
+#h1 = 4.0
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+    
+ion()
+plot(depth,stage_max,'ob',d2,green,'-g',depth,stage_max,'-b')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+Magnitude 9.3 event (Java) at Exmouth')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.1 event (Sumba) at Exmouth')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.0 event (Sumba) at Exmouth')
+legend(['ANUGA','Green\'s law'])
+#axis([-5,85,min(stage_max)*0.9,max(stage_max)*1.1])
+axis([-5,85,3.5,max(stage_max)*1.1])
+grid(True)
+#savefig('stratification_onslow_gun')
+savefig('stratification_exmouth_gun')
+#savefig('stratification_dampier_gun')
+
+depthv2 = [0,5,20,80]
+datav2 = [8.2,6,4,h1]
+figure(2)
+plot(d2,green,'g-',depthv2,datav2,'bo-')
+xlabel('depth (m)')
+ylabel('stage (m)')
+title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+Magnitude 9.3 event (Java) at Exmouth')
+legend(['ANUGA','Green\'s law'])
+axis([-5,85,3.5,max(stage_max)*1.1])
+grid(True)
+savefig('strat_exmouth_gun_v2')
+close('all')
+
Index: /anuga_work/production/wa/exmouth_2006/project.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/project.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/project.py	(revision 7411)
@@ -0,0 +1,234 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+Also includes origin for slump scenario.
+"""
+
+from os import sep, environ, getenv, getcwd,umask
+from os.path import expanduser, basename
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon, number_mesh_triangles
+import sys
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+from time import localtime, strftime, gmtime
+from anuga.utilities.system_tools import get_user_name, get_host_name
+
+#codename = 'project.py'
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent dir   
+user = get_user_name()
+host = get_host_name()
+#needed when running using mpirun, mpirun doesn't inherit umask from .bashrc
+umask(002)
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'exmouth'
+scenario = 'exmouth_tsunami_scenario'
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+
+#tide = -1.4
+#tide = 0
+tide = 1.4
+
+#Maybe will try to make project a class to allow these parameters to be passed in.
+alpha = 0.1
+friction=0.01
+starttime=3600
+finaltime=25000
+setup='final'
+#source='onslow'
+#source='dampier'
+source='exmouth'
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=4
+    yieldstep=60
+if setup =='store':
+    print'store'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240    
+
+
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(source)+'_'+str(user)
+
+onshore_name = 'DLI' 
+onshore_name1 = 'DTED' 
+# offshore
+offshore_name = 'Exmouth_bathymetry'
+#offshore_name1 = 'inferred_north'
+#offshore_name2 = 'inferred_south'
+coast_name = 'Exmouth_coastline'
+
+#final topo name
+combined_name ='exmouth_combined_elevation'
+#combined_name1 ='exmouth_combined_elevation1'
+#combined_name_unclipped1 ='exmouth_combined_elevation_unclipped1'
+combined_small_name = 'exmouth_combined_elevation_small'
+
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+
+# input topo file location
+onshore_in_dir_name = topographies_in_dir + onshore_name
+onshore1_in_dir_name = topographies_in_dir + onshore_name1
+coast_in_dir_name = topographies_in_dir + coast_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+#offshore_in_dir_name1 = topographies_in_dir + offshore_name1
+#offshore_in_dir_name2 = topographies_in_dir + offshore_name2
+
+onshore_dir_name = topographies_dir + onshore_name
+onshore1_dir_name = topographies_dir + onshore_name1
+coast_dir_name = topographies_dir + coast_name
+offshore_dir_name = topographies_dir + offshore_name
+#offshore_dir_name1 = topographies_dir + offshore_name1
+#offshore_dir_name2 = topographies_dir + offshore_name2
+
+#final topo files
+combined_dir_name = topographies_dir + combined_name
+#combined_dir_name_unclipped1 = topographies_dir + combined_name_unclipped1
+#combined_dir_name1 = topographies_dir + combined_name1
+combined_small_dir_name = topographies_dir + combined_small_name
+
+meshes_dir = anuga_dir+'meshes'+sep
+meshes_dir_name = meshes_dir + scenario_name
+
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+
+if source =='dampier':
+    boundaries_name = 'exmouth_3854_17042007' #Dampier gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'dampier'+sep+'1_10000'+sep
+
+if source=='onslow':
+    boundaries_name = 'exmouth_3859_16052007' #onslow_hedland_broome gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'onslow_hedland_broome'+sep+'1_10000'+sep
+    
+if source=='exmouth':
+    boundaries_name = 'exmouth_3103_18052007' #exmouth gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'exmouth'+sep+'1_10000'+sep
+
+#boundaries locations
+boundaries_source = ''
+#boundaries_in_dir = anuga_dir+'boundaries'+sep
+boundaries_in_dir_name = boundaries_in_dir + boundaries_name
+
+#output locations
+output_dir = anuga_dir+'outputs'+sep
+output_build_time_dir = output_dir+build_time+sep
+output_run_time_dir = output_dir +run_time+dir_comment+sep
+#output_run_time_dir = output_dir +'20070619_042140_run_final_0_onslow_nbartzis'+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+beach_gauges = 'beach_gauges.csv'
+gauge_name = 'exmouth_gauges.csv'
+
+gauges_dir = home+sep+state+sep+scenario+sep+'anuga'+sep+'gauges'+sep
+beach_gauges = gauges_dir + 'beach_gauges.csv'
+gauges_dir_name = gauges_dir + gauge_name
+
+community_filename = gauges_dir + 'CHINS_v2.csv'
+community_exmouth = gauges_dir + 'community_exmouth.csv'
+
+buildings_filename = gauges_dir +'Exmouth_res_Project.csv'
+buildings_filename_out = output_run_time_dir +'Exmouth_res_Project_modified.csv'
+
+###############################
+# Domain definitions
+###############################
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+
+poly_all = read_polygon(polygons_dir+'extent_more_points.csv')
+
+print 'Area of bounding polygon', polygon_area(poly_all)/1000000.0
+
+res_poly_all = 150000*res_factor
+
+###############################
+# Interior region definitions
+###############################
+
+
+poly_coast = read_polygon(polygons_dir+'coast_new_pts.csv')
+#poly_coast = read_polygon(polygons_dir+'pts_coast.csv')
+res_coast = 10000*res_factor
+
+#poly_coast1 = read_polygon(polygons_dir+'pts_coast1.csv')
+#res_0 = 20000*res_factor
+
+poly_coast2 = read_polygon(polygons_dir+'coast2_new_pts.csv')
+#poly_coast2 = read_polygon(polygons_dir+'pts_coast2.csv')
+#res_0 = 20000*res_factor
+
+poly_coast3 = read_polygon(polygons_dir+'pts_coast3.csv')
+#res_0 = 20000*res_factor
+
+poly_exmouth = read_polygon(polygons_dir+'exmouth_new_pts.csv')
+#poly_exmouth = read_polygon(polygons_dir+'pts_exmouth.csv')
+res_exmouth = 500*res_factor
+
+poly_exmouth_south = read_polygon(polygons_dir+'exmouth_south_pts.csv')
+#res_exmouth = 500*res_factor
+
+poly_carpark1 = read_polygon(polygons_dir+'carpark1_pts.csv')
+#res_exmouth = 500*res_factor
+
+poly_carpark2 = read_polygon(polygons_dir+'carpark2_pts.csv')
+#res_exmouth = 500*res_factor
+
+poly_carpark3 = read_polygon(polygons_dir+'carpark3_pts.csv')
+#res_exmouth = 500*res_factor
+
+poly_nth_defence = read_polygon(polygons_dir+'pts_nth_defence.csv')
+res_nth_defence = 5000*res_factor
+
+poly_middle = read_polygon(polygons_dir+'middle_new_pts.csv')
+#poly_middle = read_polygon(polygons_dir+'pts_middle.csv')
+res_middle = 30000*res_factor
+
+poly_airport = read_polygon(polygons_dir+'pts_airport.csv')
+res_airport = 5000*res_factor
+
+interior_regions = [[poly_coast,res_coast],[poly_coast2,res_coast]
+                   ,[poly_coast3,res_coast],[poly_middle,res_middle],[poly_exmouth,res_exmouth]
+                   ,[poly_exmouth_south,res_exmouth],[poly_carpark1,res_exmouth],[poly_carpark2,res_exmouth]
+                   ,[poly_carpark3,res_exmouth],[poly_nth_defence,res_nth_defence],[poly_airport,res_airport]]
+
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+
+print 'min number triangles', trigs_min
+
+poly_mainland = read_polygon(polygons_dir+'Initial_Condition.csv')
+
+###################################################################
+# Clipping regions for export to asc and regions for clipping data
+###################################################################
+
+# exporting asc grid - Exmouth town area
+eastingmin = 200663
+eastingmax = 207500
+northingmax = 7574000
+northingmin = 7564500
+
+# exporting asc grid - carparks etc on NW peninsula
+e_min_area = 192700
+e_max_area = 203755
+n_max_area = 7587330
+n_min_area = 7579460
Index: /anuga_work/production/wa/exmouth_2006/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/run_boundary_points.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/run_boundary_points.py	(revision 7411)
@@ -0,0 +1,35 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+
+# # Related major packages
+# from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import URS_points_needed_to_file, \
+     urs_ungridded2sww
+import project                 # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+poly = project.poly_all
+print "poly", poly
+print "project.boundaries",project.boundarydir
+URS_points_needed_to_file(project.boundarydir,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True)
+#urs_ungridded2sww(project.boundaries_in_dir_name2, project.boundaries_dir_name5, mean_stage= project.tide,  verbose=True)
Index: /anuga_work/production/wa/exmouth_2006/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,41 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+import project
+
+# Inputs
+#timestamp_dir = '20070615_024233_run_final_1.4_dampier_nbartzis' # HAT dampier
+#timestamp_dir = '20070615_024322_run_final_0_dampier_nbartzis' # MSL dampier
+#timestamp_dir = '20070604_015217_run_final_1.4_exmouth_nbartzis' # HAT exmouth parallel 4
+#timestamp_dir = '20070615_023718_run_final_0_exmouth_nbartzis' # MSL exmouth parallel 2
+#timestamp_dir = '20070615_023954_run_final_1.4_onslow_nbartzis' # HAT onslow
+#timestamp_dir = '20070615_023908_run_final_0_onslow_nbartzis' # MSL onslow parallel 2
+
+file_loc = project.output_dir + timestampdir + sep 
+swwfile = file_loc + project.scenario_name + '.sww'
+buildings_filename = project.buildings_filename
+buildings_filename_out = file_loc + project.buildings_filename_out
+
+#add_depth_and_momentum2csv(swwfile, buildings_filename, buildings_filename_out)
+inundation_damage(swwfile, buildings_filename, buildings_filename_out)
+
+print '\n Augmented building file written to %s \n' \
+      %buildings_filename_out
Index: /anuga_work/production/wa/exmouth_2006/run_exmouth.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/run_exmouth.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/run_exmouth.py	(revision 7411)
@@ -0,0 +1,270 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+def run_model(**kwargs):
+    
+    #scenario_name = kwargs['aa_scenario_name']
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+
+    #copy script must be before screen_catcher
+    print 'tide',kwargs['tide']
+    kwargs['est_num_trigs']=project.trigs_min
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project.host
+    kwargs['res_factor']=project.res_factor
+    kwargs['starttime']=project.starttime
+    kwargs['yieldstep']=project.yieldstep
+    kwargs['finaltime']=project.finaltime
+    
+    kwargs['output_dir']=project.output_run_time_dir
+    kwargs['bathy_file']=project.combined_dir_name+'.txt'
+#    kwargs['bathy_file']=project.combined_small_dir_name + '.txt'
+    kwargs['boundary_file']=project.boundaries_in_dir_name + '.sww'
+  
+    print 'output_dir',kwargs['output_dir']
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                 dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print "Processor Name:",get_processor_name()
+
+    # filenames
+#    meshes_dir_name = project.meshes_dir_name+'.msh'
+
+    # creates copy of code in output dir
+    print 'min triangles', project.trigs_min,
+    print 'Note: This is generally about 20% less than the final amount'
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    #IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+    if myid == 0:
+    
+        print 'start create mesh from regions'
+
+        create_mesh_from_regions(project.poly_all,
+                         boundary_tags={'back': [3,4,5], 'side': [2,6],
+                                        'ocean': [0,1,7]},
+                             maximum_triangle_area=project.res_poly_all,
+                             interior_regions=project.interior_regions,
+                             filename=project.meshes_dir_name+'.msh',
+                             use_cache=False,
+                             verbose=True)
+    barrier()
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    #domain = cache(Domain, (meshes_dir_name), {'use_cache':True, 'verbose':True}, verbose=True)
+    #above don't work
+    domain = Domain(project.meshes_dir_name+'.msh', use_cache=False, verbose=True)
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    if myid == 0:
+
+        print 'Setup initial conditions'
+
+        from polygon import Polygon_function
+        #following sets the stage/water to be offcoast only
+        IC = Polygon_function( [(project.poly_mainland, -1.0)], default = kwargs['tide'],
+                                 geo_reference = domain.geo_reference)
+        domain.set_quantity('stage', IC)
+        domain.set_quantity('friction', kwargs['friction']) 
+        
+        print 'Start Set quantity'
+
+        domain.set_quantity('elevation', 
+                            filename = kwargs['bathy_file'],
+                            use_cache = True,
+                            verbose = True,
+                            alpha = kwargs['alpha'])
+        print 'Finished Set quantity'
+    barrier()
+
+    #------------------------------------------------------
+    # Distribute domain to implement parallelism !!!
+    #------------------------------------------------------
+
+    if numprocs > 1:
+        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['aa_scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2) # Apply second order scheme
+    domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    #domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+    #print 'domain id', id(domain)
+
+    #domain.H0=0.01 #controls the flux limiter (limiter2007)
+    domain.tight_slope_limiters = 0 #minimises creep
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+    #print 'Reading Boundary file',project.boundaries_dir_namea + '.sww'
+
+    Bf = Field_boundary(kwargs['boundary_file'],
+                    domain, time_thinning=kwargs['time_thinning'], mean_stage=kwargs['tide'], 
+                    use_cache=True, verbose=True)
+                    
+    kwargs['input_start_time']=domain.starttime
+
+    print 'finished reading boundary file'
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([kwargs['tide'],0,0])
+
+    print'set_boundary'
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf}) 
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #----------------------------------------------------------------------------
+
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['starttime']): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+
+    for t in domain.evolve(yieldstep = kwargs['yieldstep'], finaltime = 21600
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+    
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')   
+
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'That took %.2f seconds' %(time.time()-t0)
+
+    #kwargs 'completed' must be added to write the final parameters to file
+    kwargs['completed']=str(time.time()-t0)
+    
+    
+    if myid == 0:
+        store_parameters(**kwargs)
+        
+        print 'memory usage before del domain',mem_usage()
+        #del domain
+        print 'memory usage after del domain',mem_usage()
+        
+        swwfile = kwargs['output_dir']+kwargs['aa_scenario_name']
+        export_grid(swwfile, extra_name_out = 'town',
+                quantities = ['speed'], # '(xmomentum**2 + ymomentum**2)**0.5' defaults to elevation
+#                quantities = ['elevation','depth','speed','stage'], # '(xmomentum**2 + ymomentum**2)**0.5' defaults to elevation
+                timestep = None,
+                reduction = max,
+                cellsize = 25,
+                NODATA_value = -9999,
+                easting_min = project.eastingmin,
+                easting_max = project.eastingmax,
+                northing_min = project.northingmin,
+                northing_max = project.northingmax,
+                verbose = True,
+                origin = None,
+                datum = 'WGS84',
+                format = 'asc')
+    
+        buildings_filename = project.buildings_filename
+        buildings_filename_out = project.buildings_filename_out
+                
+        #inundation_damage(swwfile+'.sww', buildings_filename, buildings_filename_out)
+        print '\n Augmented building file written to %s \n' %buildings_filename_out
+    
+    barrier()
+    
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+    run_model(file_name=project.home+'detail.csv', aa_scenario_name=project.scenario_name,
+              ab_time=project.time, res_factor= project.res_factor, tide=project.tide, user=project.user,
+              alpha = project.alpha, friction=project.friction,
+              time_thinning = project.time_thinning,
+              dir_comment=project.dir_comment)
+
+
Index: /anuga_work/production/wa/exmouth_2006/run_store.py
===================================================================
--- /anuga_work/production/wa/exmouth_2006/run_store.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2006/run_store.py	(revision 7411)
@@ -0,0 +1,101 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+def run_model(**kwargs):
+    
+#    tide = kwargs['tide']
+#    alpha = kwargs['alpha']
+#    friction = kwargs['friction']
+#    time_thinning = kwargs['time_thinning']
+    scenario_name = kwargs['aa_scenario_name']
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+    '''
+    #copy script must be before screen_catcher
+    print 'tide',tide
+    kwargs['est_num_trigs']=444444
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project.host
+    kwargs['res_factor']=project.res_factor
+    kwargs['starttime']=project.starttime
+    kwargs['yieldstep']=project.yieldstep
+    kwargs['finaltime']=project.finaltime
+'''    
+    kwargs['output_dir']=project.output_run_time_dir
+    kwargs['bathy_file']=project.combined_dir_name+'.txt'
+    kwargs['boundary_file']=project.boundaries_dir_name + '.sww'
+    
+    print 'output_dir',kwargs['output_dir']
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                 dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+    '''
+  
+    kwargs['act_num_trigs']=7777777
+
+    kwargs['input_start_time']=666
+    #kwargs 'completed' must be added to write the final parameters to file
+    '''   
+    kwargs['completed']=6
+    if myid == 0:
+        store_parameters(**kwargs)
+    barrier()
+
+
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+    run_model(file_name=project.home+'detail_test.csv', aa_scenario_name='test_store_parameters',
+              ab_time=project.time, res_factor= project.res_factor,
+#               tide=project.tide, user=project.user,
+#              alpha = project.alpha, friction=project.friction,
+#              time_thinning = project.time_thinning,
+              dir_comment=project.dir_comment)
+
+
Index: /anuga_work/production/wa/exmouth_2009/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,83 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\exmouth_tsunami_scenario_2009\\"
+output_dir="anuga\\outputs\\"
+
+time_dir1 = '20090624_145617_run_final_0.0_27283_mhingee'
+##time_dir2 = ''
+##time_dir3 = ''
+
+##time_dir2 = ''
+
+time_dirs = [time_dir1]#, time_dir2]#, time_dir3]
+
+for time_dir in time_dirs:
+    # Local variables...
+    folder = scenario_dir + output_dir +  time_dir +'\\'
+    raster_gbd = folder + 'raster.gdb'
+##    land = scenario_dir + "map_work\\\port_hedland.gdb\\outlines\\initial_condition"
+##    ocean = scenario_dir + "map_work\\\port_hedland.gdb\\outlines\\initial_conditions_ocean"
+
+    print 'Process: Create File GDB'
+    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    print gp.Workspace
+    
+    #replication dictionary
+    replicate = (('exmouth', ''),('_', ''),('max','_M'),
+                 ('CBD', 'CDB'),('All',''),
+                 ('depth','_depth'),('speed', '_speed'),
+                 ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection'
+        #GDA_1994_MGA_Zone_54
+        gp.DefineProjection_management(output_DEM, "PROJCS['CM_114',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',114.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+##        output_extract = output_DEM + 'E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+
Index: /anuga_work/production/wa/exmouth_2009/build_elevation.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/build_elevation.py	(revision 7411)
@@ -0,0 +1,100 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+##print 'project.bounding_polygon', project.bounding_polygon
+##print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' # except', project.offshore_name5
+G = None
+for key in geospatial_data:
+    #if key == project.point_filenames[4] or key == project.ascii_filenames[1]:
+    #    # Skip these files for now
+    #    continue
+    
+    G += geospatial_data[key]
+        
+#print 'Clip combined geospatial data'
+##G_clip = G.clip_outside(project.poly_aoi1)
+##G_all = G_clip + geospatial_data[project.point_filenames[4]] 
+#G_clipped = G_all.clip(project.poly_all)
+#G_clip = G.clip(project.bounding_polygon)
+
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/exmouth_2009/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                central_meridian=project.central_meridian,
+                zone=project.zone,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                central_meridian=project.central_meridian,
+                zone=project.zone,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/exmouth_2009/export_results.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/export_results.py	(revision 7411)
@@ -0,0 +1,121 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+time_dir1 = '20090624_145617_run_final_0.0_27283_mhingee'
+##time_dir2 = ''
+##time_dir3 = ''
+##time_dir4 = ''
+##time_dir5 = ''
+##time_dir6 = ''
+##
+time_dirs = [time_dir1]#, time_dir2]# , time_dir4, time_dir5, time_dir6]
+  
+
+cellsize = 250
+##cellsize = 5
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+#area = ['Exmouth']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation','stage']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            #name2 = join(directory, time_dir, project.scenario_name)+'_time_39600_0'
+            #name3 = join(directory, time_dir, project.scenario_name)+'_time_79200_0'
+
+            names = [name1] #, name2]#, name3]
+      
+           # asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/exmouth_2009/export_results_Exmouth.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/export_results_Exmouth.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/export_results_Exmouth.py	(revision 7411)
@@ -0,0 +1,121 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+time_dir1 = '20090624_145617_run_final_0.0_27283_mhingee'
+##time_dir2 = ''
+##time_dir3 = ''
+##time_dir4 = ''
+##time_dir5 = ''
+##time_dir6 = ''
+##
+time_dirs = [time_dir1]#, time_dir2]# , time_dir4, time_dir5, time_dir6]
+  
+
+##cellsize = 250
+cellsize = 20
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+area = ['Exmouth']  # strings must match keys in var_equations below
+##area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation','stage']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            #name2 = join(directory, time_dir, project.scenario_name)+'_time_39600_0'
+            #name3 = join(directory, time_dir, project.scenario_name)+'_time_79200_0'
+
+            names = [name1] #, name2]#, name3]
+      
+           # asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/exmouth_2009/file_length.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/exmouth_2009/project.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/project.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/project.py	(revision 7411)
@@ -0,0 +1,252 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'exmouth'
+scenario_folder = 'exmouth_tsunami_scenario_2009'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0                # difference between MSL and HAT in metres
+zone = None
+central_meridian = 114   # specify the central merdian for the data
+event_number = 27283    # the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=1000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number]
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['extract_dli', 'extract_dted'] # onshore elevation data
+
+
+    # Format for point is x,y,elevation (with header)
+point_filenames = ['coastline.txt',  # coastline points with 0m elevation
+                   'Exmouth.txt',    # combined bathymetry for most of model
+                   'extract_dgap_cs100.txt',  # interpolated bathy. for gap in data just NE of Exmouth itself
+                   'extract_rivoli100.txt']     # interpolated bathy. for gap in data near Rivoli islands
+                   #'exmouth_aoi_aos_gridded.txt']  # fine grid of data interpolated from Exmouth.txt for use in refined grids (aoi and aos)
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'bounding_polygon.csv'
+bounding_polygon_maxarea = 1000000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+
+interior_regions_data = [['aoi.csv', 500]]
+PriorityArea_filename = 'aos.csv'
+    
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing (no header)
+land_initial_conditions_filename = 'initial_conditions_simple.csv'
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = '' #'TideGaugesPoints.csv' #'tsunamipointsMGA.csv'
+
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = '' # from NEXIS
+
+# AREA OF IMAGES - Extent of each image to find out highest runup
+# Header - easting,northing,id,value
+# Used in get_runup.py
+images_filename = 'images.csv'
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'thinned_boundary_ordering.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_bounding_polygon.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+##mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+##multi_mux = False
+mux_input_filename = 'event.list'
+multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# ASCII export grid for Exmouth
+xminExmouth = 511000
+xmaxExmouth = 516000
+yminExmouth = 7567700
+ymaxExmouth = 7576500
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# The absolute pathname for the image file
+# Used for get_runup.py
+if images_filename:
+    images = join(polygons_folder, images_filename)
+
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
+#Multiple polygons in one CSV file to make internal polygons
+if not PriorityArea_filename == None:
+    PriorityAreas = join(polygons_folder, PriorityArea_filename)
+
+
Index: /anuga_work/production/wa/exmouth_2009/run_model.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/run_model.py	(revision 7411)
@@ -0,0 +1,162 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/exmouth_2009/setup_model.py
===================================================================
--- /anuga_work/production/wa/exmouth_2009/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/exmouth_2009/setup_model.py	(revision 7411)
@@ -0,0 +1,198 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+from anuga.shallow_water.data_manager import csv2polygons
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+# if it's a list, then it's a list of land condition filenames
+# else it's a string - a single file, multiple land conditions
+if isinstance(project.land_initial_conditions_filename, list):
+    for filename, MSL in project.land_initial_conditions_filename:
+        polygon = read_polygon(join(project.polygons_folder, filename))
+        project.land_initial_conditions.append([polygon, MSL])
+elif isinstance(project.land_initial_conditions_filename, basestring):
+    polygons, MSL = csv2polygons(join(project.polygons_folder,
+                                      project.land_initial_conditions_filename))
+    for i, key in enumerate(polygons):
+        if i%100==0: print i
+        poly = polygons[key]
+        land = float(MSL[key])
+        project.land_initial_conditions.append([poly, land])
+else:
+    msg = ('project.land_initial_conditions_filename must be a list or '
+           'string, got %s'
+           % type(project.land_initial_conditions_filename))
+    raise Exception, msg
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+
+if project.PriorityArea_filename is not None:
+    polygons, maxareas = csv2polygons(project.PriorityAreas)
+    print 'Creating %d internal polygons' % len(polygons)
+    #def create_polygon_function(polygons, geo_reference=None):
+    project.interior_regions = []
+    for i, key in enumerate(polygons):
+        if i%100==0: print i
+        poly = polygons[key]
+        maxarea = float(maxareas[key])
+        project.interior_regions.append([poly,
+                                         maxarea*project.scale_factor])
+
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/geraldton/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/geraldton/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,88 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\geraldton_tsunami_scenario\\"
+output_dir="anuga\\outputs\\"
+
+##time_dir1 = '20081209_155330_run_final_0_27255_250m_none_lfountai'
+##time_dir2 = '20081209_161229_run_final_0_68693_250m_none_lfountai' 
+##time_dirs = [time_dir1, time_dir2]
+
+##time_dir1 = '20081117_141353_run_final_0_27283_alpha0.1_kvanputt'
+##time_dir2 = '20081117_141443_run_final_0.6_27283_alpha0.1_kvanputt' 
+time_dir3 = '20081117_141520_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir4 = '20081117_141558_run_final_0.6_27255_alpha0.1_kvanputt'
+time_dir5 = '20081117_141634_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir6 = '20081117_141717_run_final_0.6_68693_alpha0.1_kvanputt'
+##
+time_dirs = [time_dir3, time_dir5] #, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder = scenario_dir + output_dir +  time_dir +'\\'
+    raster_gbd = folder + 'raster.gdb'
+    land = scenario_dir + "map_work\\\Geraldton.gdb\\outlines\\initial_condition"
+    ocean = scenario_dir + "map_work\\\Geraldton.gdb\\outlines\\initial_conditions_ocean"
+
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    #print gp.Workspace
+    
+    #replication dictionary
+    replicate = (('geraldton', ''),('_', ''),('max','_M'),
+                 ('CBD', 'CDB'),
+                 ('depth','_depth'),('speed', '_speed'),
+                 ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*stage_max.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection' 
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+##        output_extract = output_DEM + 'E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+
Index: /anuga_work/production/wa/geraldton/Arc_txt2feature_class.py
===================================================================
--- /anuga_work/production/wa/geraldton/Arc_txt2feature_class.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/Arc_txt2feature_class.py	(revision 7411)
@@ -0,0 +1,52 @@
+# ---------------------------------------------------------------------------
+# txt2fc_field.py
+# Created on: Thu Nov 27 2008 01:48:26 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\geraldton_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20081117_141353_run_final_0_27283_alpha0.1_kvanputt'
+time_dir2 = '20081117_141443_run_final_0.6_27283_alpha0.1_kvanputt' 
+time_dir3 = '20081117_141520_run_final_0_27255_alpha0.1_kvanputt'
+time_dir4 = '20081117_141558_run_final_0.6_27255_alpha0.1_kvanputt'
+time_dir5 = '20081117_141634_run_final_0_68693_alpha0.1_kvanputt'
+time_dir6 = '20081117_141717_run_final_0.6_68693_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'geraldton_runup.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+    
+    print 'Process: Create File GDB'
+    gp.CreateFileGDB_management(folder, "raster")
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "x", "y", layer, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM"
+                                   "['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT"
+                                   "['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting'"
+                                   ",500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER"
+                                   "['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "geraldton_runup", "", "area area true true false 255 Text 0 0 ,First,#,geraldton_runup.csv_Features,area,-1,-1;q q true true false 8 Double 0 0 ,First,#,geraldton_runup.csv_Features,q,-1,-1;x x true true false 8 Double 0 0 ,First,#,geraldton_runup.csv_Features,x,-1,-1;y y true true false 8 Double 0 0 ,First,#,geraldton_runup.csv_Features,y,-1,-1", "")
+
+
+  
Index: /anuga_work/production/wa/geraldton/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/geraldton/Arc_txt2feature_class_res.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/Arc_txt2feature_class_res.py	(revision 7411)
@@ -0,0 +1,45 @@
+# ---------------------------------------------------------------------------
+# txt2fc_res.py
+# Created on: Mon Dec 01 2008 11:36:17 AM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\geraldton_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20081117_141353_run_final_0_27283_alpha0.1_kvanputt'
+time_dir2 = '20081117_141443_run_final_0.6_27283_alpha0.1_kvanputt' 
+time_dir3 = '20081117_141520_run_final_0_27255_alpha0.1_kvanputt'
+time_dir4 = '20081117_141558_run_final_0.6_27255_alpha0.1_kvanputt'
+time_dir5 = '20081117_141634_run_final_0_68693_alpha0.1_kvanputt'
+time_dir6 = '20081117_141717_run_final_0.6_68693_alpha0.1_kvanputt'
+
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'geraldton_res.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+    
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "longitude", "latitude", layer, "GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "geraldton_res", "", "OBJECTID OBJECTID true true false 4 Long 0 10 ,First,#,geraldton_res.csv_Features,OBJECTID,-1,-1;LONGITUDE LONGITUDE true true false 8 Double 0 0 ,First,#,geraldton_res.csv_Features,LONGITUDE,-1,-1;LATITUDE LATITUDE true true false 8 Double 0 0 ,First,#,geraldton_res.csv_Features,LATITUDE,-1,-1;STRUCT_INUNDATED STRUCT_INUNDATED true true false 4 Long 0 10 ,First,#,geraldton_res.csv_Features,STRUCT_INUNDATED,-1,-1;STRUCT_DAMAGE_fraction STRUCT_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,geraldton_res.csv_Features,STRUCT_DAMAGE_fraction,-1,-1;COLLAPSE_CSV_INFO COLLAPSE_CSV_INFO true true false 255 Text 0 0 ,First,#,geraldton_res.csv_Features,COLLAPSE_CSV_INFO,-1,-1;MAX_DEPTH_m MAX_DEPTH_m true true false 8 Double 0 0 ,First,#,geraldton_res.csv_Features,MAX_DEPTH_m,-1,-1;STRUCT_COLLAPSED STRUCT_COLLAPSED true true false 255 Text 0 0 ,First,#,geraldton_res.csv_Features,STRUCT_COLLAPSED,-1,-1;STRUCT_LOSS STRUCT_LOSS true true false 8 Double 0 0 ,First,#,geraldton_res.csv_Features,STRUCT_LOSS,-1,-1;CONTENTS_DAMAGE_fraction CONTENTS_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,geraldton_res.csv_Features,CONTENTS_DAMAGE_fraction,-1,-1;CONTENTS_LOSS CONTENTS_LOSS true true false 8 Double 0 0 ,First,#,geraldton_res.csv_Features,CONTENTS_LOSS,-1,-1", "")
+
Index: /anuga_work/production/wa/geraldton/NewScripts/README.txt
===================================================================
--- /anuga_work/production/wa/geraldton/NewScripts/README.txt	(revision 7411)
+++ /anuga_work/production/wa/geraldton/NewScripts/README.txt	(revision 7411)
@@ -0,0 +1,17 @@
+This area aims at collecting the best practices in setting up ANUGA models and
+show them as a running demo.
+
+The intent is to make setting up and running of models easier to do and more standardised (without compromising one bit of creativity, of course :-). One principle is that information should never have to be entered more than once.
+
+
+The ideas are:
+
+* Collect all elevation data files in lists for batch processing (as in Shark Bay 200&)
+
+* Roll all the urs2sts work into an ANUGA function (see ticket:317)
+ 
+* Get rid of kwargs and use project.* for all parameters and filenames.
+
+* Migrate towards unified anuga interface (as in the Patong scenario).
+
+*
Index: /anuga_work/production/wa/geraldton/NewScripts/build_elevation.py
===================================================================
--- /anuga_work/production/wa/geraldton/NewScripts/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/NewScripts/build_elevation.py	(revision 7411)
@@ -0,0 +1,96 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        geospatial_data[filename] = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        geospatial_data[filename] = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' # except', project.offshore_name5
+G = None
+for key in geospatial_data:
+    #if key == project.point_filenames[4] or key == project.ascii_filenames[1]:
+    #    # Skip these files for now
+    #    continue
+    
+    G += geospatial_data[key]
+        
+print 'Clip combined geospatial data'
+##G_clip = G.clip_outside(project.poly_aoi1)
+##G_all = G_clip + geospatial_data[project.point_filenames[4]] 
+#G_clipped = G_all.clip(project.poly_all)
+G_clip = G.clip(project.bounding_polygon)
+
+
+print 'Export combined DEM file'
+G_clip.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G_clip.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/geraldton/NewScripts/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/geraldton/NewScripts/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/NewScripts/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,169 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                zone=project.zone,
+                mean_stage=project.tide,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                mean_stage=project.tide,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/geraldton/NewScripts/export_results_max.py
===================================================================
--- /anuga_work/production/wa/geraldton/NewScripts/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/NewScripts/export_results_max.py	(revision 7411)
@@ -0,0 +1,128 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+##time_dir1 = '20081217_101310_run_final_0_27283_250m_none_dt_kvanputt'
+##time_dir2 = '20081217_115336_run_final_0_27283_250m_none_dp_kvanputt'
+###time_dir1 = '20080924_123626_run_final_0_27283_250m_all_kvanputt' # This uses the 250m bathymetry with all interior polygons
+###time_dir2 = '20080912_154716_run_final_0_27283_alpha0.1_kvanputt' # This uses original bathyemetry data
+###time_dir3 = '20080924_123601_run_final_0_27283_250m_none_kvanputt' # This uses the 250m bathymetry without any interior polygons
+##time_dirs = [time_dir1, time_dir2]#, time_dir3]
+
+time_dir1 = '20090225_171439_run_final_0_wa04_val_kvanputt'
+##time_dir2 = '20081211_162311_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir3 = '20081211_162346_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir4 = '20081211_162433_run_final_0.6_68693_alpha0.1_kvanputt'
+##time_dir5 = '20081211_162656_run_final_0.6_27283_alpha0.1_kvanputt'
+##time_dir6 = '20081211_162744_run_final_0_27283_alpha0.1_kvanputt'
+##
+time_dirs = [time_dir1] #5, time_dir4]# , time_dir4, time_dir5, time_dir6]
+  
+
+cellsize = 20
+##cellsize = 5
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+#area = ['Bunbury', 'Busselton']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation','stage']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            #name2 = join(directory, time_dir, project.scenario_name)+'_time_39600_0'
+            #name3 = join(directory, time_dir, project.scenario_name)+'_time_79200_0'
+
+            names = [name1] #, name2]#, name3]
+      
+           # asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/geraldton/NewScripts/file_length.py
===================================================================
--- /anuga_work/production/wa/geraldton/NewScripts/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/NewScripts/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/geraldton/NewScripts/project.py
===================================================================
--- /anuga_work/production/wa/geraldton/NewScripts/project.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/NewScripts/project.py	(revision 7411)
@@ -0,0 +1,238 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'geraldton'
+scenario_folder = 'geraldton_tsunami_scenario'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0.0               # difference between MSL and HAT
+zone = 50               # specify zone of model
+event_number = 'wa04_val'   # the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=80000          # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number]
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['landgate_dem_clip',   # Topo
+                        'dted_srtm_islands'] # Geraldton Island Topo
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['XYcoastline_KVP.txt',      # Coastline
+                   'DPI_Data.txt',             # DPI Bathymetry
+                   'Geraldton_bathymetry.txt', # Original Bathymetry 
+                   'Top_bathymetry.txt',       # Top bathymetry
+                   'grid250.txt']              # Grid 250m
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'poly_all.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['CBD_500m.csv', 500],
+                         ['CBD_1km.csv', 800],
+                         ['island_wallabi_poly2.csv', 5000],
+                         ['island_dingiville_poly.csv', 5000],
+                         ['island_pelsaert_poly.csv', 5000],
+                         ['neg20_pos20.csv', 25000]]
+
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing (no header)
+land_initial_conditions_filename = [['land_initial_condition.csv', 0]]
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = 'nick_geraldton_gauges.csv'
+
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = 'geraldton_res_clip.csv' # from NEXIS
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'urs_order.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_boundary.csv'
+
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+multi_mux = False
+#mux_input_filename = 'event.list'
+#multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# ASCII export grid for Busselton
+xminBusselton = 340000
+xmaxBusselton = 352000
+yminBusselton = 6271500
+ymaxBusselton = 6280000
+
+# ASCII export grid for Bunbury
+xminBunbury = 369000
+xmaxBunbury = 381000
+yminBunbury = 6308000
+ymaxBunbury = 6316500
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+meshes_folder = join(anuga_folder, 'meshes')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(meshes_folder, scenario_name) + '.msh'
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+building_exposure = join(gauges_folder, building_exposure_filename)
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
Index: /anuga_work/production/wa/geraldton/NewScripts/run_model.py
===================================================================
--- /anuga_work/production/wa/geraldton/NewScripts/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/NewScripts/run_model.py	(revision 7411)
@@ -0,0 +1,163 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bd,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/geraldton/NewScripts/setup_model.py
===================================================================
--- /anuga_work/production/wa/geraldton/NewScripts/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/NewScripts/setup_model.py	(revision 7411)
@@ -0,0 +1,160 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.meshes_folder):
+    print "Sorry, meshes directory '%s' doesn't exist" % project.meshes_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+for filename, MSL in project.land_initial_conditions_filename:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.land_initial_conditions.append([polygon, MSL])
+
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/geraldton/build_boundary_27255.py
===================================================================
--- /anuga_work/production/wa/geraldton/build_boundary_27255.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/build_boundary_27255.py	(revision 7411)
@@ -0,0 +1,150 @@
+"""
+Script for building boundary to run a tsunami inundation scenario for geraldton,
+WA, Australia.  The boundary is sourced from the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_geraldton.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+# location of mux files
+# Note, this may change when all mux files are on the GA network
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+# Note, this is specific to the event and will be supplied by David.
+# In time, this will become more automated.
+urs_filenames = [
+    os.path.join(dir,'Java-0017-z.grd'),  
+    os.path.join(dir,'Java-0018-z.grd'),
+    os.path.join(dir,'Java-0019-z.grd'),
+    os.path.join(dir,'Java-0022-z.grd'),  
+    os.path.join(dir,'Java-0023-z.grd'),  
+    os.path.join(dir,'Java-0024-z.grd'),  
+    os.path.join(dir,'Java-0027-z.grd'),  
+    os.path.join(dir,'Java-0028-z.grd'),  
+    os.path.join(dir,'Java-0031-z.grd'),  
+    os.path.join(dir,'Java-0032-z.grd')]  
+ 
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 10: #change per event
+
+    weight_factor = 30.84050 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #------------------------------------------------------------------------------
+    # Get maxium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+    #------------------------------------------------------------------------------
+    # Get minium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+    #------------------------------------------------------------------------------
+    # End of the get gauges
+    #------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/geraldton/build_boundary_27283.py
===================================================================
--- /anuga_work/production/wa/geraldton/build_boundary_27283.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/build_boundary_27283.py	(revision 7411)
@@ -0,0 +1,187 @@
+"""
+Script for building boundary to run tsunami inundation scenario for geraldton,
+WA, Australia.  The boundary is based on the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_geraldton.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+urs_filenames = [
+    os.path.join(dir,'Java-0000-z.grd'),
+    os.path.join(dir,'Java-0001-z.grd'),
+    os.path.join(dir,'Java-0002-z.grd'),
+    os.path.join(dir,'Java-0003-z.grd'),
+    os.path.join(dir,'Java-0005-z.grd'), 
+    os.path.join(dir,'Java-0006-z.grd'), 
+    os.path.join(dir,'Java-0007-z.grd'), 
+    os.path.join(dir,'Java-0008-z.grd'), 
+    os.path.join(dir,'Java-0010-z.grd'), 
+    os.path.join(dir,'Java-0011-z.grd'), 
+    os.path.join(dir,'Java-0012-z.grd'), 
+    os.path.join(dir,'Java-0013-z.grd'),  
+    os.path.join(dir,'Java-0015-z.grd'),  
+    os.path.join(dir,'Java-0016-z.grd'),  
+    os.path.join(dir,'Java-0017-z.grd'),  
+    os.path.join(dir,'Java-0018-z.grd'),  
+    os.path.join(dir,'Java-0020-z.grd'),  
+    os.path.join(dir,'Java-0021-z.grd'),  
+    os.path.join(dir,'Java-0022-z.grd'),  
+    os.path.join(dir,'Java-0023-z.grd'),  
+    os.path.join(dir,'Java-0025-z.grd'),  
+    os.path.join(dir,'Java-0026-z.grd'),  
+    os.path.join(dir,'Java-0027-z.grd'),  
+    os.path.join(dir,'Java-0028-z.grd'),  
+    os.path.join(dir,'Java-0029-z.grd'),  
+    os.path.join(dir,'Java-0030-z.grd'),  
+    os.path.join(dir,'Java-0031-z.grd'),  
+    os.path.join(dir,'Java-0032-z.grd'),  
+    os.path.join(dir,'Java-0033-z.grd'),  
+    os.path.join(dir,'Java-0034-z.grd'),  
+    os.path.join(dir,'Java-0035-z.grd'),  
+    os.path.join(dir,'Java-0036-z.grd'),  
+    os.path.join(dir,'Java-0037-z.grd'),  
+    os.path.join(dir,'Java-0038-z.grd'),  
+    os.path.join(dir,'Java-0039-z.grd'),  
+    os.path.join(dir,'Java-0040-z.grd'),  
+    os.path.join(dir,'Java-0041-z.grd'),  
+    os.path.join(dir,'Java-0042-z.grd'),  
+    os.path.join(dir,'Java-0043-z.grd'),  
+    os.path.join(dir,'Java-0044-z.grd'),  
+    os.path.join(dir,'Java-0045-z.grd'),  
+    os.path.join(dir,'Java-0046-z.grd'),  
+    os.path.join(dir,'Java-0047-z.grd'),
+    os.path.join(dir,'Java-0048-z.grd')]    
+ 
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 44: #change per event
+
+# AS per David Burbidge email on Friday 4th July the mag 9.3 event
+# has 1m worth of slip on each sub fault therefore mutliple each unit
+# source by the slip (10.4544) and sum the 44 time series together to
+# get the time series for this event at the points on your boundary. 
+
+    weight_factor = 10.4544 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            zone=50,
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+#------------------------------------------------------------------------------
+# Get Maxium wave height throughout timeseries at each index point
+#------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+#------------------------------------------------------------------------------
+# Get Minium wave height throughout timeseries at each index point
+#------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+#------------------------------------------------------------------------------
+# End of the get gauges
+#------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/geraldton/build_boundary_68693.py
===================================================================
--- /anuga_work/production/wa/geraldton/build_boundary_68693.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/build_boundary_68693.py	(revision 7411)
@@ -0,0 +1,152 @@
+"""
+Script for building boundary to run a tsunami inundation scenario for onslow,
+WA, Australia.  The boundary is sourced from the National Hazard Map.
+
+Input: order_filename from project.py
+       event_number needs to be reflected in the project file 
+Output: creates a sts file and csv files stored in project.boundaries_dir_event.
+The run_onslow.py is reliant on the output of this script.
+"""
+import os
+from os import sep
+import project
+
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+    compress,zeros,fabs,allclose,ones
+from anuga.utilities.polygon import inside_polygon,read_polygon
+from time import localtime, strftime, gmtime
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+
+#--------------------------------------------------------------------------
+# Create sts boundary from mux2files 
+#--------------------------------------------------------------------------
+# location of mux files
+# Note, this may change when all mux files are on the GA network
+dir=os.path.join(project.muxhome,'mux')
+
+# Refer to event_027255.list in home+state+sep+event08 for event details
+# taken from David's event list for 27255
+# Note, this is specific to the event and will be supplied by David.
+# In time, this will become more automated.
+urs_filenames = [
+    os.path.join(dir,'Sumatra-0026-z.grd'),
+    os.path.join(dir,'Sumatra-0027-z.grd'),
+    os.path.join(dir,'Sumatra-0028-z.grd'),
+    os.path.join(dir,'Sumatra-0029-z.grd'),
+    os.path.join(dir,'Sumatra-0030-z.grd'),
+    os.path.join(dir,'Sumatra-0031-z.grd'),
+    os.path.join(dir,'Sumatra-0033-z.grd'),
+    os.path.join(dir,'Sumatra-0034-z.grd'),
+    os.path.join(dir,'Sumatra-0035-z.grd'),
+    os.path.join(dir,'Sumatra-0037-z.grd'),
+    os.path.join(dir,'Sumatra-0038-z.grd'),
+    os.path.join(dir,'Sumatra-0039-z.grd')]
+        
+print 'number of sources', len(urs_filenames)
+
+if len(urs_filenames) == 12: #change per event
+
+    weight_factor = 27.3603 #change per event
+    weights=weight_factor*ones(len(urs_filenames),Float)
+
+    scenario_name=project.scenario_name
+    order_filename=os.path.join(project.order_filename_dir)
+
+    print 'reading', order_filename
+    # Create ordered sts file
+    print 'creating sts file'
+
+    urs2sts(urs_filenames,
+            basename_out=os.path.join(project.boundaries_dir_event,scenario_name),
+            ordering_filename=order_filename,
+            weights=weights,
+            mean_stage=project.tide,
+            verbose=True)
+else:
+    print 'number of sources do not match event.list'
+
+#------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#------------------------------------------------------------------------------
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #------------------------------------------------------------------------------
+    # Get maxium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+      
+    #------------------------------------------------------------------------------
+    # Get minium wave height throughout timeseries at each index point
+    #------------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(project.boundaries_dir_event+sep+minname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_min.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage))
+        fid_min.write(s)
+        
+
+
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+
+    #------------------------------------------------------------------------------
+    # End of the get gauges
+    #------------------------------------------------------------------------------
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+
+
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
+
Index: /anuga_work/production/wa/geraldton/build_geraldton.py
===================================================================
--- /anuga_work/production/wa/geraldton/build_geraldton.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/build_geraldton.py	(revision 7411)
@@ -0,0 +1,125 @@
+"""
+Script for building the elevation data to run a tsunami inundation scenario
+for geraldton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_geraldton.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.geospatial_data.geospatial_data import *
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files
+
+# Application specific imports
+import project   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project.output_build_time_dir,__file__, 
+               dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+start_screen_catcher(project.output_build_time_dir)
+
+print 'USER:    ', project.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print "project.poly_all", project.poly_all
+print "project.combined_dir_name", project.combined_dir_name
+
+# input elevation directory filenames
+onshore_in_dir_name = project.onshore_in_dir_name
+coast_in_dir_name = project.coast_in_dir_name
+island_in_dir_name = project.island_in_dir_name
+offshore_in_dir_name = project.offshore_in_dir_name
+offshore_in_dir_name1 = project.offshore_in_dir_name1
+offshore_in_dir_name2 = project.offshore_in_dir_name2
+offshore_in_dir_name3 = project.offshore_in_dir_name3
+
+# output elevation directory filenames
+onshore_dir_name = project.onshore_dir_name
+coast_dir_name = project.coast_dir_name
+island_dir_name = project.island_dir_name
+offshore_dir_name = project.offshore_dir_name
+offshore_dir_name1 = project.offshore_dir_name1
+offshore_dir_name2 = project.offshore_dir_name2
+offshore_dir_name3 = project.offshore_dir_name3
+
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name, basename_out=onshore_dir_name, use_cache=True, verbose=True)
+convert_dem_from_ascii2netcdf(island_in_dir_name, basename_out=island_dir_name, use_cache=True, verbose=True)
+
+# creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name, use_cache=True,verbose=True)
+
+# creates pts file for island DEM
+dem2pts(island_dir_name, use_cache=True, verbose=True)
+
+# create onshore pts files
+print'create Geospatial data1 objects from topographies'
+G1 = Geospatial_data(file_name = onshore_dir_name + '.pts')
+print'create Geospatial data2 objects from topographies'
+G2 = Geospatial_data(file_name = island_dir_name + '.pts')
+
+# create coastal and offshore pts files
+print'create Geospatial data6 objects from topographies'
+G_coast = Geospatial_data(file_name = coast_in_dir_name)
+print'create Geospatial data7 objects from topographies'
+G_off1 = Geospatial_data(file_name = offshore_in_dir_name)
+print'create Geospatial data8 objects from topographies'
+G_off2 = Geospatial_data(file_name = offshore_in_dir_name1)
+print'create Geospatial data9 objects from topographies'
+G_off3 = Geospatial_data(file_name = offshore_in_dir_name2)
+print'create Geospatial data10 objects from topographies'
+G_off4 = Geospatial_data(file_name = offshore_in_dir_name3)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'clipping port data to area of significance'
+G_off2_clip = G_off2.clip(project.poly_buffer_20m, verbose=True)
+print 'add all bathymetry files'
+G_off = G_off1 + G_off2_clip + G_off3 + G_off4
+print 'clipping data to coast'
+G_off_clip = G_off.clip(project.poly_ocean, verbose=True)
+G1_clip = G1.clip(project.poly_mainland, verbose=True)
+
+print'add all geospatial objects'
+G = G1_clip + G2 + G_off_clip
+
+print'clip combined geospatial object by bounding polygon'
+G_clipped = G.clip(project.poly_all)
+
+print'export combined DEM file'
+if access(project.topographies_dir,F_OK) == 0:
+    mkdir (project.topographies_dir)
+G_clipped.export_points_file(project.combined_dir_name + '.pts')
+#G_clipped.export_points_file(project.combined_dir_name + '.txt') #Use for comparision in ARC
+
Index: /anuga_work/production/wa/geraldton/build_geraldton_250m.py
===================================================================
--- /anuga_work/production/wa/geraldton/build_geraldton_250m.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/build_geraldton_250m.py	(revision 7411)
@@ -0,0 +1,84 @@
+"""
+Script for building the elevation data to run a tsunami inundation scenario
+for geraldton, WA, Australia.
+
+Input: elevation data from project_250m.py
+Output: pts file stored in project_250m.topographies_dir 
+The run_geraldton.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.geospatial_data.geospatial_data import *
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files
+
+# Application specific imports
+import project_250m   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project_250m.output_build_time_dir,__file__, 
+               dirname(project_250m.__file__)+sep+ project_250m.__name__+'.py' )
+
+start_screen_catcher(project_250m.output_build_time_dir)
+
+print 'USER:    ', project_250m.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print "project_250m.poly_all", project_250m.poly_all
+print "project_250m.combined_dir_name", project_250m.combined_dir_name
+
+# input elevation directory filenames
+onshore_in_dir_name = project_250m.onshore_in_dir_name
+
+# output elevation directory filenames
+onshore_dir_name = project_250m.onshore_dir_name
+
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name, basename_out=onshore_dir_name, use_cache=True, verbose=True)
+
+# creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name ,use_cache=True,verbose=True)
+
+# create onshore pts files
+print'create Geospatial data1 objects from topographies'
+G = Geospatial_data(file_name = onshore_dir_name + '.pts')
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print'clip combined geospatial object by bounding polygon'
+G_clipped = G.clip(project_250m.poly_all)
+
+print'export combined DEM file'
+if access(project_250m.topographies_dir,F_OK) == 0:
+    mkdir (project_250m.topographies_dir)
+G_clipped.export_points_file(project_250m.combined_dir_name + '.pts')
+#G_clipped.export_points_file(project_250m.combined_dir_name + '.txt') #Use for comparision in ARC
+
Index: /anuga_work/production/wa/geraldton/export_results.py
===================================================================
--- /anuga_work/production/wa/geraldton/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/export_results.py	(revision 7411)
@@ -0,0 +1,77 @@
+import project_250m, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+
+
+time_dir = '20080925_162836_run_final_0_27283_250m_none_kvanputt'
+
+cellsize = 25
+#cellsize = 150
+#timestep = 0
+directory = project_250m.output_dir
+name = directory+sep+time_dir+sep+project_250m.scenario_name
+
+var = [0,4] 
+#var = [2] # depth and Speed
+#var = [2,3] # elevation, depth and Speed
+
+is_parallel = False
+#is_parallel = True
+
+if is_parallel == True: nodes = 4
+print 'output dir:', name
+
+name = directory+time_dir+sep+project_250m.scenario_name
+
+for which_var in var:
+    if which_var == 0:  # Stage
+        outname = name + '_stage'
+        quantityname = 'stage'
+
+    if which_var == 1:  # Absolute Momentum
+        outname = name + '_momentum'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+    if which_var == 2:  # Depth
+        outname = name + '_depth'
+        quantityname = 'stage-elevation'  
+
+    if which_var == 3:  # Speed
+        outname = name + '_speed'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+    if which_var == 4:  # Elevation
+        outname = name + '_elevation'
+        quantityname = 'elevation'  #Elevation
+
+    if is_parallel == True:
+    #    print 'is_parallel',is_parallel
+        for i in range(0,nodes):
+            namei = name + '_P%d_%d' %(i,nodes)
+            outnamei = outname + '_P%d_%d' %(i,nodes)
+            print 'start sww2dem for sww file %d' %(i)
+            sww2dem(namei, basename_out = outnamei,
+                        quantity = quantityname,
+                        #timestep = timestep,
+                        cellsize = cellsize,      
+                        easting_min = project_grad.e_min_area,
+                        easting_max = project_grad.e_max_area,
+                        northing_min = project_grad.n_min_area,
+                        northing_max = project_grad.n_max_area,        
+                        reduction = max, 
+                        verbose = True,
+                        format = 'asc')
+    else:
+        print 'start sww2dem'
+        sww2dem(name, basename_out = outname,
+                    quantity = quantityname,
+                    #timestep = timestep,
+                    cellsize = cellsize,
+                    number_of_decimal_places = 4,
+                    reduction = max, 
+                    verbose = True,
+                    format = 'asc')
+
Index: /anuga_work/production/wa/geraldton/export_results_max.py
===================================================================
--- /anuga_work/production/wa/geraldton/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/export_results_max.py	(revision 7411)
@@ -0,0 +1,123 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_dir
+time_dir1 = '20090225_171439_run_final_0_wa04_val_kvanputt'
+##time_dir2 = '20081209_161229_run_final_0_68693_250m_none_lfountai' 
+##time_dirs = [time_dir1, time_dir2]
+
+##time_dir1 = '20081117_141353_run_final_0_27283_alpha0.1_kvanputt'
+##time_dir2 = '20081117_141443_run_final_0.6_27283_alpha0.1_kvanputt' 
+##time_dir3 = '20081117_141520_run_final_0_27255_alpha0.1_kvanputt'
+##time_dir4 = '20081117_141558_run_final_0.6_27255_alpha0.1_kvanputt'
+##time_dir5 = '20081117_141634_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir6 = '20081117_141717_run_final_0.6_68693_alpha0.1_kvanputt'
+##
+time_dirs = [time_dir1] #, time_dir3, time_dir4, time_dir5, time_dir6]
+
+  
+
+#cellsize = 10
+cellsize = 250
+
+##timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+#area = ['CBD']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['stage,elevation']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = directory+time_dir+sep+project.scenario_name
+#            name2 = directory+time_dir+sep+project.scenario_name+'_time_41820_0'
+            
+            names = [name1]
+      
+            asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+                asc_name.append(outname + '.asc')
+    
+            maxasc_outname = directory+time_dir+sep+project.scenario_name+'_'+which_area+'_'+which_var+'_max.asc'
+
+            print 'max asc outname ', maxasc_outname
+            print 'asc_name ', str(asc_name)
+            
+            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/geraldton/export_results_max_multiple_timesteps.py
===================================================================
--- /anuga_work/production/wa/geraldton/export_results_max_multiple_timesteps.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/export_results_max_multiple_timesteps.py	(revision 7411)
@@ -0,0 +1,124 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+directory = project.output_dir
+
+##time_dir1 = '20081209_155330_run_final_0_27255_250m_none_lfountai'
+##time_dir2 = '20081209_161229_run_final_0_68693_250m_none_lfountai' 
+##time_dirs = [time_dir1, time_dir2]
+
+##time_dir1 = '20081117_141353_run_final_0_27283_alpha0.1_kvanputt'
+##time_dir2 = '20081117_141443_run_final_0.6_27283_alpha0.1_kvanputt' 
+time_dir3 = '20081117_141520_run_final_0_27255_alpha0.1_kvanputt'
+time_dir4 = '20081117_141558_run_final_0.6_27255_alpha0.1_kvanputt'
+##time_dir5 = '20081117_141634_run_final_0_68693_alpha0.1_kvanputt'
+##time_dir6 = '20081117_141717_run_final_0.6_68693_alpha0.1_kvanputt'
+##
+time_dirs = [time_dir3, time_dir4] #, time_dir3, time_dir4, time_dir5, time_dir6]
+ 
+
+#cellsize = 20
+cellsize = 250
+
+#timestep = None    # None means no timestep!
+timesteps = [300] #range(42000,55000,1000)
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+#area = ['CBD']  # strings must match keys in var_equations below
+area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['stage','depth','elevation']
+
+######
+# Start running the various conversions we require.
+######
+for timestep in timesteps:
+    for which_var in var:
+        if which_var not in var_equations:
+            print 'Unrecognized variable name: %s' % which_var
+            break
+
+        for which_area in area:
+            if which_area == 'All':
+                easting_min = None
+                easting_max = None
+                northing_min = None
+                northing_max = None
+            else:
+                try:
+                    easting_min = eval('project.xmin%s' % which_area)
+                    easting_max = eval('project.xmax%s' % which_area)
+                    northing_min = eval('project.ymin%s' % which_area)
+                    northing_max = eval('project.ymax%s' % which_area)
+                except AttributeError:
+                    print 'Unrecognized area name: %s' % which_area
+                    break
+
+            for time_dir in time_dirs:
+
+                name1 = directory+time_dir+sep+project.scenario_name
+                name2 = directory+time_dir+sep+project.scenario_name+'_time_41820_0'
+##                name3 = directory+time_dir+sep+project.scenario_name+'_time_78600_0'
+
+                names = [name2] #[name1, name2, name3]
+          
+##                asc_name = []   
+                   
+                for name in names:
+                             
+                    outname = name + '_' + which_area + '_' + which_var + '_' + str(timestep)
+                    quantityname = var_equations[which_var]
+
+                    print 'start sww2dem: time_dir=%s' % time_dir
+                    
+                    sww2dem(name, basename_out = outname,
+                                quantity = quantityname,
+                                timestep = timestep,
+                                cellsize = cellsize,      
+                                easting_min = easting_min,
+                                easting_max = easting_max,
+                                northing_min = northing_min,
+                                northing_max = northing_max,        
+                                reduction = max, 
+                                verbose = True,
+                                format = 'asc')
+
+##                    asc_name.append(outname + '.asc')
+##        
+##                maxasc_outname = directory+time_dir+sep+project.scenario_name+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##                print 'max asc outname ', maxasc_outname
+##                print 'asc_name ', str(asc_name)
+##                
+##                MaxAsc(maxasc_outname, asc_name)
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,84 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\geraldton_tsunami_scenario\\"
+output_dir="anuga\\outputs\\"
+
+time_dir1 = '20090324_134504_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140411_run_final_0.6_27283_Bt_kvanputt'
+time_dir3 = '20090324_140741_run_final_0.6_68693_Bt_kvanputt'
+time_dir4 = '20090327_155230_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_160022_run_final_0_27283_Bt_kvanputt'
+time_dir6 = '20090327_160043_run_final_0_27255_Bt_kvanputt'
+
+time_dirs = [time_dir1] #, time_dir2, time_dir3]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder = scenario_dir + output_dir +  time_dir +'\\'
+    raster_gbd = folder + 'raster.gdb'
+    land = scenario_dir + "map_work\\\Geraldton.gdb\\outlines\\initial_condition"
+    ocean = scenario_dir + "map_work\\\Geraldton.gdb\\outlines\\initial_conditions_ocean"
+
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    #print gp.Workspace
+    
+    #replication dictionary
+    replicate = (('geraldton', ''),('_', ''),('max','_M'),
+                 ('CBD', 'CDB'),
+                 ('depth','_depth'),('speed', '_speed'),
+                 ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*elevation.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection' 
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+##        output_extract = output_DEM + 'E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+##
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_txt2feature_class.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_txt2feature_class.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_txt2feature_class.py	(revision 7411)
@@ -0,0 +1,52 @@
+# ---------------------------------------------------------------------------
+# txt2fc_field.py
+# Created on: Thu Nov 27 2008 01:48:26 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\geraldton_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_134504_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140411_run_final_0.6_27283_Bt_kvanputt'
+time_dir3 = '20090324_140741_run_final_0.6_68693_Bt_kvanputt'
+time_dir4 = '20090327_155230_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_160022_run_final_0_27283_Bt_kvanputt'
+time_dir6 = '20090327_160043_run_final_0_27255_Bt_kvanputt'
+
+time_dirs = [time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'geraldton_runup.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+    
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "x", "y", layer, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM"
+                                   "['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT"
+                                   "['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting'"
+                                   ",500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER"
+                                   "['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "geraldton_runup", "", "area area true true false 255 Text 0 0 ,First,#,geraldton_runup.csv_Features,area,-1,-1;q q true true false 8 Double 0 0 ,First,#,geraldton_runup.csv_Features,q,-1,-1;x x true true false 8 Double 0 0 ,First,#,geraldton_runup.csv_Features,x,-1,-1;y y true true false 8 Double 0 0 ,First,#,geraldton_runup.csv_Features,y,-1,-1", "")
+
+
+  
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_txt2feature_class_res.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/Arc_txt2feature_class_res.py	(revision 7411)
@@ -0,0 +1,66 @@
+# ---------------------------------------------------------------------------
+# txt2fc_res.py
+# Created on: Mon Dec 01 2008 11:36:17 AM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+from os.path import join
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\geraldton_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_134504_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140411_run_final_0.6_27283_Bt_kvanputt'
+time_dir3 = '20090324_140741_run_final_0.6_68693_Bt_kvanputt'
+time_dir4 = '20090327_155230_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_160022_run_final_0_27283_Bt_kvanputt'
+time_dir6 = '20090327_160043_run_final_0_27255_Bt_kvanputt'
+
+time_dirs = [time_dir6] #1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+def replace_in_file(filename, instr, repstr):
+    '''Replace one string with another in a file.'''
+    
+    # get the file contents
+    fd = open(filename, 'r')
+    lines = fd.readlines()
+    fd.close()
+
+    # convert list to one string
+    newlines = ''.join(lines)
+    
+    # replace 'instr' with 'repstr'
+    newlines = newlines.replace(instr, repstr)
+    
+    # write changed lines back to file
+    fd = open(filename, 'w')
+    fd.write(newlines)
+    fd.close()
+
+for time_dir in time_dirs:
+    print 'time_dir = ', time_dir
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'geraldton_res.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+
+    print 'replace _$ with nothing'
+    replace_in_file(input_dir_name, '_$', '')
+    
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "longitude", "latitude", layer, "GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "geraldton_res", "", "OBJECTID OBJECTID true true false 4 Long 0 10 ,First,#,carnarvon_res.csv_Features,OBJECTID,-1,-1;LONGITUDE LONGITUDE true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,LONGITUDE,-1,-1;LATITUDE LATITUDE true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,LATITUDE,-1,-1;STRUCT_INUNDATED STRUCT_INUNDATED true true false 4 Long 0 10 ,First,#,carnarvon_res.csv_Features,STRUCT_INUNDATED,-1,-1;STRUCT_DAMAGE_fraction STRUCT_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,STRUCT_DAMAGE_fraction,-1,-1;COLLAPSE_CSV_INFO COLLAPSE_CSV_INFO true true false 255 Text 0 0 ,First,#,carnarvon_res.csv_Features,COLLAPSE_CSV_INFO,-1,-1;MAX_DEPTH_m MAX_DEPTH_m true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,MAX_DEPTH_m,-1,-1;STRUCT_COLLAPSED STRUCT_COLLAPSED true true false 255 Text 0 0 ,First,#,carnarvon_res.csv_Features,STRUCT_COLLAPSED,-1,-1;STRUCT_LOSS STRUCT_LOSS true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,STRUCT_LOSS,-1,-1;CONTENTS_DAMAGE_fraction CONTENTS_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,CONTENTS_DAMAGE_fraction,-1,-1;CONTENTS_LOSS CONTENTS_LOSS true true false 8 Double 0 0 ,First,#,carnarvon_res.csv_Features,CONTENTS_LOSS,-1,-1", "")
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/Geraldton4distribution.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/Geraldton4distribution.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/Geraldton4distribution.py	(revision 7411)
@@ -0,0 +1,128 @@
+# ---------------------------------------------------------------------------
+# Carnarvon4distribution.py
+# Created on: Thu Apr 30 2009 03:51:03 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+community = 'Geraldton'
+output_loc = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\FESA_outputs_Dec_08\\ARCgrids\\April_2009\\"
+input_scenario = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\geraldton_tsunami_scenario\\"
+input_output = input_scenario + "\\anuga\\outputs\\"
+
+location = 'CBD'
+in_Tsunami_1_HAT = input_output + "20090324_140411_run_final_0.6_27283_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_1_MSL = input_output + "20090327_160022_run_final_0_27283_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_2_HAT = input_output + "20090324_134504_run_final_0.6_27255_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_2_MSL = input_output + "20090327_160043_run_final_0_27255_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_3_HAT = input_output + "20090324_140741_run_final_0.6_68693_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_3_MSL = input_output + "20090327_155230_run_final_0_68693_Bt_kvanputt\\raster.gdb\\"
+
+Tsunami_1_HAT = output_loc + "Tsunami1-Exmouth\\" + community + "_HAT.gdb\\"
+Tsunami_1_MSL = output_loc + "Tsunami1-Exmouth\\" + community + "_MSL.gdb\\"
+Tsunami_2_HAT = output_loc + "Tsunami2-Perth\\" + community + "_HAT.gdb\\"
+Tsunami_2_MSL = output_loc + "Tsunami2-Perth\\" + community + "_MSL.gdb\\"
+Tsunami_3_HAT = output_loc + "Tsunami3-1833\\" + community + "_HAT.gdb\\"
+Tsunami_3_MSL = output_loc + "Tsunami3-1833\\" + community + "_MSL.gdb\\"
+
+depth = 'CDB_depth_E'
+speed = 'CDB_speed_'
+hr = community + '_runup'
+
+# Local variables...
+# polygon clip
+if location == 'CBD':
+    extent = input_scenario + "map_work\\Geraldton.gdb\Internal_Polygons\CBD_500m"
+
+# Output locations
+
+
+
+hr_1_HAT = Tsunami_1_HAT +"highest_runup"
+hr_1_MSL = Tsunami_1_MSL +"highest_runup"
+hr_2_HAT = Tsunami_2_HAT +"highest_runup"
+hr_2_MSL = Tsunami_2_MSL +"highest_runup"
+hr_3_HAT = Tsunami_3_HAT +"highest_runup"
+hr_3_MSL = Tsunami_3_MSL +"highest_runup"
+
+depth_1_HAT = Tsunami_1_HAT + location + "_depth"
+depth_1_MSL = Tsunami_1_MSL + location + "_depth"
+depth_2_HAT = Tsunami_2_HAT + location + "_depth"
+depth_2_MSL = Tsunami_2_MSL + location + "_depth"
+depth_3_HAT = Tsunami_3_HAT + location + "_depth"
+depth_3_MSL = Tsunami_3_MSL + location + "_depth"
+
+speed_1_HAT = Tsunami_1_HAT + location + "_speed"
+speed_1_MSL = Tsunami_1_MSL + location + "_speed"
+speed_2_HAT = Tsunami_2_HAT + location + "_speed"
+speed_2_MSL = Tsunami_2_MSL + location + "_speed"
+speed_3_HAT = Tsunami_3_HAT + location + "_speed"
+speed_3_MSL = Tsunami_3_MSL + location + "_speed"
+
+
+# Input locations
+
+in_depth_1_HAT = in_Tsunami_1_HAT + depth
+in_depth_1_MSL = in_Tsunami_1_MSL + depth
+in_depth_2_HAT = in_Tsunami_2_HAT + depth
+in_depth_2_MSL = in_Tsunami_2_MSL + depth
+in_depth_3_HAT = in_Tsunami_3_HAT + depth
+in_depth_3_MSL = in_Tsunami_3_MSL + depth
+
+in_speed_1_HAT = in_Tsunami_1_HAT + speed
+in_speed_1_MSL = in_Tsunami_1_MSL + speed
+in_speed_2_HAT = in_Tsunami_2_HAT + speed
+in_speed_2_MSL = in_Tsunami_2_MSL + speed
+in_speed_3_HAT = in_Tsunami_3_HAT + speed
+in_speed_3_MSL = in_Tsunami_3_MSL + speed
+
+in_hr_1_HAT = in_Tsunami_1_HAT + hr
+in_hr_1_MSL = in_Tsunami_1_MSL + hr
+in_hr_2_HAT = in_Tsunami_2_HAT + hr
+in_hr_2_MSL = in_Tsunami_2_MSL + hr
+in_hr_3_HAT = in_Tsunami_3_HAT + hr
+in_hr_3_MSL = in_Tsunami_3_MSL + hr
+
+
+# Process: Extract by Mask
+
+print 'Extract by mask for depth'
+gp.ExtractByMask_sa(in_depth_1_HAT, extent, depth_1_HAT)
+gp.ExtractByMask_sa(in_depth_1_MSL, extent, depth_1_MSL)
+gp.ExtractByMask_sa(in_depth_2_HAT, extent, depth_2_HAT)
+gp.ExtractByMask_sa(in_depth_2_MSL, extent, depth_2_MSL)
+gp.ExtractByMask_sa(in_depth_3_HAT, extent, depth_3_HAT)
+gp.ExtractByMask_sa(in_depth_3_MSL, extent, depth_3_MSL)
+
+print 'Extract by mask for speed'
+gp.ExtractByMask_sa(in_speed_1_HAT, extent, speed_1_HAT)
+gp.ExtractByMask_sa(in_speed_1_MSL, extent, speed_1_MSL)
+gp.ExtractByMask_sa(in_speed_2_HAT, extent, speed_2_HAT)
+gp.ExtractByMask_sa(in_speed_2_MSL, extent, speed_2_MSL)
+gp.ExtractByMask_sa(in_speed_3_HAT, extent, speed_3_HAT)
+gp.ExtractByMask_sa(in_speed_3_MSL, extent, speed_3_MSL)
+
+
+# Process: Copy Features...
+
+print 'Copy Highest Runup'
+gp.CopyFeatures_management(in_hr_1_HAT, hr_1_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_1_MSL, hr_1_MSL, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_2_HAT, hr_2_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_2_MSL, hr_2_MSL, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_3_HAT, hr_3_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_3_MSL, hr_3_MSL, "", "0", "0", "0")
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/Inundation_polygon.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/Inundation_polygon.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/Inundation_polygon.py	(revision 7411)
@@ -0,0 +1,69 @@
+# ---------------------------------------------------------------------------
+# Inundation_line.py
+# Created on: Tue May 12 2009 01:50:45 PM
+#   (generated by ArcGIS/ModelBuilder)
+# Usage: Inundation_line <Bun_depth_M_E> <Bus_depth_M_E> <bunbury_1km> <busselton_1km> 
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+gp.overwriteoutput = 1
+
+# Set the necessary product code
+gp.SetProduct("ArcInfo")
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Analysis Tools.tbx")
+
+# Script arguments...
+time_dir1 = '20090324_134504_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140411_run_final_0.6_27283_Bt_kvanputt'
+time_dir3 = '20090324_140741_run_final_0.6_68693_Bt_kvanputt'
+time_dir4 = '20090327_155230_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_160022_run_final_0_27283_Bt_kvanputt'
+time_dir6 = '20090327_160043_run_final_0_27255_Bt_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]   
+
+community = 'geraldton'
+scenario = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\" + community +"_tsunami_scenario\\"
+output_folder = scenario + "anuga\\outputs\\"
+location = 'CBD'
+extent = scenario + "map_work\\Geraldton.gdb\Internal_Polygons\CBD_500m_clip"
+depth = 'CDB_depth_E'
+
+for time_dir in time_dirs:
+    
+    raster = output_folder + time_dir + "\\raster.gdb\\"
+
+    print 'time_dir', time_dir
+    
+    # Local variables...
+    Output_raster = raster +"Temp_raster_"+ location
+    Output_polygon_features = raster +"Temp_polygon_"+ location
+    Output_Feature_Class = raster +"Temp_line_"+ location
+    Reclassification = "0 0.05 NODATA;0.05 4.5840001106262207 1"
+    Inundation = raster + "Inundation_" + location + "_polygon"
+    depth_loc = raster + depth
+    
+    print 'Process: Reclassify'
+    gp.Reclassify_sa(depth_loc, "Value", Reclassification, Output_raster, "DATA")
+    
+    print 'Process: Raster to Polygon'
+    gp.RasterToPolygon_conversion(Output_raster, Output_polygon_features, "SIMPLIFY", "VALUE")
+
+    print 'Process: Clip'
+    gp.Clip_analysis(Output_polygon_features, extent, Inundation, "")
+
+    print 'Process: Delete'
+    gp.Delete_management(Output_raster, "RasterDataset")
+    gp.Delete_management(Output_polygon_features, "FeatureClass")
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/README.txt
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/README.txt	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/README.txt	(revision 7411)
@@ -0,0 +1,17 @@
+This area aims at collecting the best practices in setting up ANUGA models and
+show them as a running demo.
+
+The intent is to make setting up and running of models easier to do and more standardised (without compromising one bit of creativity, of course :-). One principle is that information should never have to be entered more than once.
+
+
+The ideas are:
+
+* Collect all elevation data files in lists for batch processing (as in Shark Bay 200&)
+
+* Roll all the urs2sts work into an ANUGA function (see ticket:317)
+ 
+* Get rid of kwargs and use project.* for all parameters and filenames.
+
+* Migrate towards unified anuga interface (as in the Patong scenario).
+
+*
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/build_elevation.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/build_elevation.py	(revision 7411)
@@ -0,0 +1,107 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+from anuga.utilities.polygon import read_polygon
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+extent_polygons = []
+for extent_polygon_filename in project.extent_polygon_filenames:
+    p = read_polygon(join(project.polygons_folder, extent_polygon_filename))
+    extent_polygons.append(p)
+    
+print 'Add geospatial objects except ', project.point_filenames[2]
+G = None
+for key in geospatial_data:
+    if key == project.point_filenames[2]:
+        D = geospatial_data[key]
+        D = D.clip(extent_polygons[0])
+        G += D
+    elif key == project.point_filenames[0] or key == project.point_filenames[1] or key == project.point_filenames[3] or key == project.point_filenames[4]:
+        D = geospatial_data[key]
+        D = D.clip(extent_polygons[1])
+        G += D
+    elif key == project.ascii_grid_filenames[0] or key == project.ascii_grid_filenames[1]:
+        D = geospatial_data[key]
+        D = D.clip(extent_polygons[2])
+        G += D
+
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,168 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                zone=project.zone,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                zone=project.zone,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/export_results_max.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/export_results_max.py	(revision 7411)
@@ -0,0 +1,121 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+
+time_dir1 = '20090324_134504_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140411_run_final_0.6_27283_Bt_kvanputt'
+time_dir3 = '20090324_140741_run_final_0.6_68693_Bt_kvanputt'
+time_dir4 = '20090327_155230_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_160022_run_final_0_27283_Bt_kvanputt'
+time_dir6 = '20090327_160043_run_final_0_27255_Bt_kvanputt'
+
+time_dirs = [time_dir1] #4, time_dir5, time_dir6]
+  
+
+#cellsize = 250
+cellsize = 10
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+area = ['CBD']  # strings must match keys in var_equations below
+#area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            name2 = join(directory, time_dir, project.scenario_name)+'_time_42900_0'
+           
+            names = [name1] #, name2]
+      
+           # asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/file_length.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/get_runup.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/get_runup.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/get_runup.py	(revision 7411)
@@ -0,0 +1,66 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from os.path import join
+from anuga.utilities.polygon import read_polygon
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+        
+# Application specific imports
+from setup_model import project  # Definition of file names and polygons
+import csv
+directory = project.output_folder
+
+time_dir1 = '20090324_134504_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140411_run_final_0.6_27283_Bt_kvanputt'
+time_dir3 = '20090324_140741_run_final_0.6_68693_Bt_kvanputt'
+time_dir4 = '20090327_155230_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_160022_run_final_0_27283_Bt_kvanputt'
+time_dir6 = '20090327_160043_run_final_0_27255_Bt_kvanputt'
+
+time_dirs = [time_dir6] #, time_dir3]
+  
+interior_region = []
+for region in project.interior_regions_data[:1]:
+    polygon = read_polygon(join(project.polygons_folder,
+                                region[0]))
+    interior_region.append(polygon)
+
+area_dictionary = {'Geraldton': interior_region[0]}
+
+area = ['Geraldton'] 
+
+for time_dir in time_dirs:
+
+    basename = join(directory, time_dir, project.scenario_name)
+
+    out_file = basename+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+    print 'basename ',basename 
+
+    for which_area in area:
+        if which_area not in area_dictionary:
+            print 'Unrecognized variable name: %s' % which_area
+            break
+
+        polygon = area_dictionary[which_area]
+        
+        print 'Which area ',which_area
+
+        q, loc = get_maximum_inundation_data(basename+'.sww',
+                                             polygon=polygon, verbose=True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/get_timeseries.py	(revision 7411)
@@ -0,0 +1,34 @@
+"""
+Generate time series of nominated "gauges".
+Input: sww file from run_perth.py
+       gauges project.gauge_filename
+Output: csv files stage,speed,depth,elevation over time
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+Can run different sww files at the same time
+make sure if there is a second sww file that it is placed into a folder called sww2
+Can run different gauges at the same time - ie testing boundary index point
+"""
+
+from os import sep, rename, listdir, system
+from os.path import join
+from anuga.abstract_2d_finite_volumes.util import sww2csv_gauges,csv2timeseries_graphs
+import project
+
+directory = project.output_folder
+
+time_dir1 = '20090324_134504_run_final_0.6_27255_Bt_kvanputt'
+
+time_dirs = [time_dir1] #1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+print 'time directories', time_dirs
+
+for time_dir in time_dirs:
+    name = join(directory,time_dir,project.scenario_name)
+    gauge = project.gauges_myall
+    sww2csv_gauges(name+'.sww',gauge,
+                   quantities = ['stage','speed','depth','elevation'],
+                   verbose=True)
+  
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/project.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/project.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/project.py	(revision 7411)
@@ -0,0 +1,264 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'geraldton'
+scenario_folder = 'geraldton_tsunami_scenario'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0                # difference between MSL and HAT in metres
+zone = 50               # specify zone of model
+#event_number = 27255    # the event number or the mux file name
+event_number = 'wa04_val'    # the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=1000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number, 'Bt']
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['landgate_dem_clip',   # Topo
+                        'dted_srtm_islands'] # Islands Topo
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['XYcoastline_KVP.txt',    # Coastline
+                   'Geraldton_bathymetry.txt', # Original data
+                   'DPI_Data.txt',   # new bathymetry from DPI
+                   'grid250.txt',       # Wholes use 250m grid 2005
+                   'Top_bathymetry.txt']            # To extend boundary
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+extent_polygon_filenames = ['buffer_20m.csv',
+                            'ocean_initial_condition.csv',
+                            'land_initial_condition.csv']
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'poly_all.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['harbour.csv', 20],
+                         ['CBD_500m.csv', 500],
+                         ['CBD_1km.csv', 800],
+                         ['island_wallabi_poly2.csv', 5000],
+                         ['island_dingiville_poly.csv', 5000],
+                         ['island_pelsaert_poly.csv', 5000]]
+
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing (no header)
+land_initial_conditions_filename = [['land_initial_condition.csv', 0],
+                                    ['ocean_initial_condition.csv', 0]]
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+#gauges_filename = 'MH_gauges.csv'
+gauges_filename = 'nick_geraldton_gauges.csv'
+gauges_myall_filename = 'MH_gauges2.csv'
+
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = 'geraldton_res_clip.csv' # from NEXIS
+
+# barrier
+barrier_filename = 'CBD.csv'
+barrier_filename1 = 'wall.csv'
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+#urs_order_filename = 'thinned_boundary_ordering.csv'
+urs_order_filename = 'urs_order.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+#landward_boundary_filename = 'landward_bounding_polygon.csv'
+landward_boundary_filename = 'landward_boundary.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+multi_mux = False
+##mux_input_filename = 'event.list'
+##multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# Geraldton CBD extract ascii grid
+xminCBD = 262700
+xmaxCBD = 267600
+yminCBD = 6811500
+ymaxCBD = 6816400
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+meshes_folder = join(anuga_folder, 'meshes')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+if gauges_myall_filename:
+    gauges_myall = join(gauges_folder, gauges_myall_filename)  
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if barrier_filename:
+    barrier = join(meshes_folder, barrier_filename)
+if barrier_filename1:
+    barrier1 = join(meshes_folder, barrier_filename1)
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,72 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from setup_model import project
+from os.path import join
+import csv
+
+directory = project.output_folder + sep
+
+time_dir1 = '20090324_134504_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_140411_run_final_0.6_27283_Bt_kvanputt'
+time_dir3 = '20090324_140741_run_final_0.6_68693_Bt_kvanputt'
+time_dir4 = '20090327_155230_run_final_0_68693_Bt_kvanputt'
+time_dir5 = '20090327_160022_run_final_0_27283_Bt_kvanputt'
+time_dir6 = '20090327_160043_run_final_0_27255_Bt_kvanputt'
+
+time_dirs = [time_dir6] #1, time_dir2, time_dir3, time_dir4, time_dir5]
+
+buildings = project.building_exposure
+
+for time_dir in time_dirs:
+    
+    time_dir_name = time_dir[-25:][:-11]
+       
+    building_marker = '_m_'+ time_dir_name
+    basename = join(directory, time_dir, project.scenario_name) #basename for the sww files 
+    
+    inundation_damage(basename, buildings, building_marker)
+    #add_depth_and_momentum2csv(name, buildings, building_marker)
+    
+    building_marker_dir_name = join(project.gauges_folder,
+                                    project.building_exposure_filename[:-4]) + building_marker + '.csv'
+    out_file = basename+ '_res.csv'
+    print 'out file %s' %out_file
+    print 'building_marker_dir_name %s' %building_marker_dir_name
+    csv_fd = open(building_marker_dir_name, 'r')
+    output_file = open(out_file, 'w')
+
+    reader = csv.reader(csv_fd)
+    writer = csv.writer(output_file, lineterminator='\n')
+
+    for record in reader:
+       newline = record[-8:]
+       newline.insert(0,record[0])
+       newline.insert(1,record[1])
+       newline.insert(2,record[2])
+       writer.writerow(newline)
+       
+    print 'output file printed to: %s' %out_file
+    csv_fd.close()
+    output_file.close()
+     
+
+    
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/run_model.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/run_model.py	(revision 7411)
@@ -0,0 +1,176 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+from anuga.pmesh.mesh import importMeshFromFile
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+
+m = importMeshFromFile(project.meshes)
+# load points from a points file
+m.add_points_and_segments(Geospatial_data(project.barrier))
+m.add_points_and_segments(Geospatial_data(project.barrier1))
+m.generate_mesh()
+m.export_mesh_file(project.meshes)
+
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bno = Time_boundary(domain=domain, # Time dependent boundary
+                    f=lambda t: [0.0, 0.0, 0.0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bno}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/geraldton/geraldton_rerun/setup_model.py
===================================================================
--- /anuga_work/production/wa/geraldton/geraldton_rerun/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/geraldton_rerun/setup_model.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+for filename, MSL in project.land_initial_conditions_filename:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.land_initial_conditions.append([polygon, MSL])
+
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/geraldton/get_gauges.py
===================================================================
--- /anuga_work/production/wa/geraldton/get_gauges.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/get_gauges.py	(revision 7411)
@@ -0,0 +1,58 @@
+import os
+from os import sep
+import project
+try:
+    from pylab import plot,show,xlabel,ylabel,legend,title,savefig,hold
+except:
+    print 'Cannot import pylab plotting will not work. Csv files are still created'
+from anuga.utilities.polygon import inside_polygon
+from anuga.utilities.numerical_tools import ensure_numeric
+from Scientific.IO.NetCDF import NetCDFFile
+
+def get_sts_gauge_data(filename,verbose=False):
+    from Numeric import asarray,transpose,sqrt,argmax,argmin,arange,Float,\
+        compress,zeros,fabs,take
+    fid = NetCDFFile(filename+'.sts', 'r')    #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:]+fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:]+fid.yllcorner   #y-coordinates of vertices
+    points=transpose(asarray([x.tolist(),y.tolist()]))
+    time=fid.variables['time'][:]+fid.starttime
+    elevation=fid.variables['elevation'][:]
+       
+    basename='sts_gauge'
+    quantity_names=['stage','xmomentum','ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    maxname = 'max_sts_stage.csv'
+    fid_max = open(project.boundaries_dir_event+sep+maxname,'w')
+    s = 'index, x, y, max_stage \n'
+    fid_max.write(s)    
+    for j in range(len(x)):
+        index= permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        s = '%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], max(stage))
+        fid_max.write(s)
+        
+        fid_sts = open(project.boundaries_dir_event+sep+basename+'_'+ str(index)+'.csv', 'w')
+        s = 'time, stage, xmomentum, ymomentum \n'
+        fid_sts.write(s)
+        
+        for k in range(len(time)-1):
+            s = '%.6f, %.6f, %.6f, %.6f\n' %(time[k], stage[k], xmomentum[k], ymomentum[k])
+            fid_sts.write(s)
+
+        fid_sts.close()      
+
+    fid.close()
+        
+    return quantities,elevation,time
+
+quantities,elevation,time=get_sts_gauge_data(os.path.join(project.boundaries_dir_event,project.scenario_name),verbose=False)
+
+print len(elevation), len(quantities['stage'][0,:])
Index: /anuga_work/production/wa/geraldton/get_runup.py
===================================================================
--- /anuga_work/production/wa/geraldton/get_runup.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/get_runup.py	(revision 7411)
@@ -0,0 +1,57 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+        
+# Application specific imports
+import project  # Definition of file names and polygons
+import csv
+directory = project.output_dir
+
+time_dir1 = '20081117_141353_run_final_0_27283_alpha0.1_kvanputt'
+time_dir2 = '20081117_141443_run_final_0.6_27283_alpha0.1_kvanputt' 
+time_dir3 = '20081117_141520_run_final_0_27255_alpha0.1_kvanputt'
+time_dir4 = '20081117_141558_run_final_0.6_27255_alpha0.1_kvanputt'
+time_dir5 = '20081117_141634_run_final_0_68693_alpha0.1_kvanputt'
+time_dir6 = '20081117_141717_run_final_0.6_68693_alpha0.1_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+area_dictionary = {'CBD': project.poly_aoi1}
+
+area = ['CBD'] 
+
+for time_dir in time_dirs:
+
+    name = directory+time_dir+sep+project.scenario_name
+
+    out_file = name+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+    print 'name ',name 
+
+    for which_area in area:
+        if which_area not in area_dictionary:
+            print 'Unrecognized variable name: %s' % which_area
+            break
+
+        polygon = area_dictionary[which_area]
+        
+        print 'Which area ',which_area
+
+        q, loc = get_maximum_inundation_data (name+'.sww', polygon = polygon, verbose= True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/geraldton/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/geraldton/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/get_timeseries.py	(revision 7411)
@@ -0,0 +1,36 @@
+"""
+Generate time series of nominated "gauges".
+Input: sww file from run_perth.py
+       gauges project.gauge_filename
+Output: csv files stage,speed,depth,elevation over time
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+Can run different sww files at the same time
+make sure if there is a second sww file that it is placed into a folder called sww2
+Can run different gauges at the same time - ie testing boundary index point
+"""
+
+from os import sep, rename, listdir, system
+from anuga.abstract_2d_finite_volumes.util import sww2csv_gauges,csv2timeseries_graphs
+import project
+
+directory = project.output_dir
+
+##time_dir1 = '20081117_141353_run_final_0_27283_alpha0.1_kvanputt'+sep+'gauge'
+##time_dir2 = '20081117_141443_run_final_0.6_27283_alpha0.1_kvanputt'+sep+'gauge'
+##time_dir3 = '20081117_141520_run_final_0_27255_alpha0.1_kvanputt'+sep+'gauge'
+time_dir4 = '20081117_141558_run_final_0.6_27255_alpha0.1_kvanputt'
+##time_dir5 = '20081117_141634_run_final_0_68693_alpha0.1_kvanputt'+sep+'gauge'
+##time_dir6 = '20081117_141717_run_final_0.6_68693_alpha0.1_kvanputt'+sep+'gauge'
+
+time_dirs = [time_dir4] #[time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+for time_dir in time_dirs:
+    name = directory+time_dir+sep+project.scenario_name 
+    gauge = project.gauges_dir_name
+    sww2csv_gauges(name+'.sww',gauge,
+                   quantities = ['stage','speed','depth','elevation'],
+                   verbose=True)
+  
+
Index: /anuga_work/production/wa/geraldton/ph2_compare.py
===================================================================
--- /anuga_work/production/wa/geraldton/ph2_compare.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/ph2_compare.py	(revision 7411)
@@ -0,0 +1,139 @@
+"""
+Read in event time series and determine max stage for Ph2 comparison
+Compare with Green's function (no focussing)
+Compare with ANUGA outputs (full model, 250m no polys, 250m all polys)
+Leharne Fountain and Jane Sexton, 2008
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid, figure
+from os import sep
+
+###################################################
+# Relevant definitions
+###################################################
+
+def get_max_boundary_data(filename):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[3]))
+    return mean(stage)
+
+def get_stage_data(filename,depth,no_models):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    mean_stages = zeros((len(depth),no_models), Float)
+    max_stages = zeros((len(depth),no_models), Float)
+    for i in range(no_models):
+        stage5 = []
+        stage10 = []
+        stage20 = []
+        stage50 = []
+        for line in lines[1:]:
+            fields = line.split(',')
+            x = float(fields[0])
+            # based on csv file output from ArcGIS: depth, x,y, no poly, all poly, and orig
+            y = float(fields[i+3]) 
+            if x == -depth[0]:
+                stage5.append(y)
+            if x == -depth[1]:
+                stage10.append(y)
+            if x == -depth[2]:
+                stage20.append(y)
+            if x == -depth[3]:
+                stage50.append(y)
+            
+        mean_stages[:,i] = [mean(stage5), mean(stage10), mean(stage20), mean(stage50)]
+        max_stages[:,i] = [max(stage5), max(stage10), max(stage20), max(stage50)]
+    return mean_stages, max_stages
+
+###################################################
+# Determine max stage at boundary points
+###################################################
+
+event_number = 27283
+boundary_mean = get_max_boundary_data(project.boundaries_dir+str(event_number)+sep+'max_sts_stage.csv')
+
+###################################################
+# Read in max data from all models
+###################################################
+
+from Numeric import zeros, Float
+directory = project.home+project.state+sep+project.scenario+sep+'map_work'
+depth = [5.0,10.,20.,50.]
+no_models = 3
+filename = directory + sep + 'Geraldton_ph2_compare.csv'
+mean_stages, max_stages = get_stage_data(filename, depth, no_models)
+
+###################################################
+# Compare with Green's function and plot
+###################################################
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 100.
+d2 = arange(d1,1,-0.1)
+h1 = boundary_mean
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+
+ion()
+figure(1)
+plot(depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Geraldton')
+legend(['original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Geraldton_mean_ORIG_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(2)
+plot(depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Geraldton')
+legend(['250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Geraldton_mean_250AP_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(3)
+plot(depth,mean_stages[:,0],'ob',depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+for event 27283 at Geraldton')
+legend(['250m no poly','250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Geraldton_mean_ALL_' + str(event_number) + '_mean'
+savefig(figname)
+
+figure(4)
+plot(depth,max_stages[:,0],'ob',depth,max_stages[:,1],'+r',depth,max_stages[:,2],'>g',d2,green,'-g')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA outputs (max stage) versus Green\'s approximation \n \
+for event 27283 at Geraldton')
+legend(['250m no poly','250m poly','original','Green\'s law'])
+#axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+grid(True)
+figname = 'ph2compare_Geraldton_max_ALL_' + str(event_number) + '_mean'
+savefig(figname)
+close('all')
+
Index: /anuga_work/production/wa/geraldton/ph2_compare_table.py
===================================================================
--- /anuga_work/production/wa/geraldton/ph2_compare_table.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/ph2_compare_table.py	(revision 7411)
@@ -0,0 +1,206 @@
+"""
+Read in event time series and determine max stage for Ph2 comparison
+Compare with Green's function (no focussing)
+Compare with ANUGA outputs (full model, 250m no polys, 250m all polys)
+Leharne Fountain and Jane Sexton, 2008
+"""
+
+import project
+#from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid, figure
+from os import sep
+
+###################################################
+# Relevant definitions
+###################################################
+
+def get_max_boundary_data(filename):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[3]))
+    return mean(stage)
+
+def get_stage_data(filename,depth,no_models):
+    from anuga.utilities.numerical_tools import mean
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    mean_stages = zeros((len(depth),no_models), Float)
+    max_stages = zeros((len(depth),no_models), Float)
+    for i in range(no_models):
+        stage5 = []
+        stage10 = []
+        stage20 = []
+        stage50 = []
+        for line in lines[1:]:
+            fields = line.split(',')
+            x = float(fields[0])
+            # based on csv file output from ArcGIS: depth, x,y, no poly, all poly, and orig
+            y = float(fields[i+3]) 
+            if x == -depth[0]:
+                stage5.append(y)
+            if x == -depth[1]:
+                stage10.append(y)
+            if x == -depth[2]:
+                stage20.append(y)
+            if x == -depth[3]:
+                stage50.append(y)
+            
+        mean_stages[:,i] = [mean(stage5), mean(stage10), mean(stage20), mean(stage50)]
+        max_stages[:,i] = [max(stage5), max(stage10), max(stage20), max(stage50)]
+    return mean_stages, max_stages
+
+def calc_M(mean_stages,boundary_mean):
+    #M_value=zeros(no_models,Float)
+    M_value=mean_stages[1,:]/boundary_mean
+    return M_value
+
+def calc_errors(mean_stages,no_models):
+    abs_error = zeros(len(mean_stages[1,:]),Float)
+    rel_error = zeros(len(mean_stages[1,:]),Float)
+    for i in range(len(mean_stages[1,:])):
+        abs_error[i] = (mean_stages[1,i]-mean_stages[1,no_models-1])
+        rel_error[i]= (abs_error[i]/mean_stages[1,no_models-1])*100
+    return abs_error,rel_error
+
+###################################################
+# Determine max stage at boundary points
+###################################################
+
+event_number = 27255
+boundary_mean = get_max_boundary_data(project.boundaries_dir+str(event_number)+sep+'max_sts_stage.csv')
+
+###################################################
+# Read in max data from all models
+###################################################
+
+from Numeric import zeros, Float
+directory = project.home+project.state+sep+project.scenario+sep+'map_work'
+depth = [5.0,10.,20.,50.]
+no_models = 2
+#plot?
+plot_flag = False
+#Table??
+table_flag = True
+filename = directory + sep + 'Geraldton_Ph2_compare_'+str(event_number)+'.csv'
+
+mean_stages, max_stages = get_stage_data(filename, depth, no_models)
+print mean_stages
+###################################################
+# Compare with Green's function and plot
+###################################################
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 100.
+d2 = arange(d1,1,-0.1)
+h1 = boundary_mean
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+
+###################################################
+#calculate M values (scaling of 100 m depth mean to 10 m)
+###################################################
+M_value = calc_M(mean_stages,boundary_mean)
+
+
+###################################################
+#calculate absolute and relative errors 
+###################################################
+abs_error,rel_error=calc_errors(mean_stages,no_models)
+
+
+##if plot_flag==True:
+##    ion()
+##    figure(1)
+##    plot(depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Geraldton')
+##    legend(['original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Geraldton_mean_ORIG_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(2)
+##    plot(depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Geraldton')
+##    legend(['250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Geraldton_mean_250AP_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(3)
+##    plot(depth,mean_stages[:,0],'ob',depth,mean_stages[:,1],'+r',depth,mean_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (average stage) versus Green\'s approximation \n \
+##    for event 27283 at Geraldton')
+##    legend(['250m no poly','250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Geraldton_mean_ALL_' + str(event_number) + '_mean'
+##    savefig(figname)
+##
+##    figure(4)
+##    plot(depth,max_stages[:,0],'ob',depth,max_stages[:,1],'+r',depth,max_stages[:,2],'>g',d2,green,'-g')
+##    xlabel('depth (m)') 
+##    ylabel('stage (m)')
+##    title('ANUGA outputs (max stage) versus Green\'s approximation \n \
+##    for event 27283 at Geraldton')
+##    legend(['250m no poly','250m poly','original','Green\'s law'])
+##    #axis([5,105,min(min(stages))*0.9,max(max(stages))*1.1])
+##    grid(True)
+##    figname = 'ph2compare_Geraldton_max_ALL_' + str(event_number) + '_mean'
+##    savefig(figname)
+##    close('all')
+
+if table_flag==True:
+    import csv
+    csvfile = directory+sep+'ph2compare_Geraldton_max_ALL_' + str(event_number) + '_mean.csv'
+    fid1 = open(csvfile,'w')
+    writer = csv.writer(fid1,delimiter=',',)
+
+    if no_models==1:
+        writer.writerow(('depth (m)','250m no poly'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0]))
+        writer.writerow(('100',boundary_mean,))
+        writer.writerow(('M-value',M_value[0]))
+        #writer.writerow(('Absolute Error', abs_error[0],abs_error[1]))
+        #writer.writerow(('Relative Error %', rel_error[0],rel_error[1]))
+
+    if no_models==2:
+        writer.writerow(('depth (m)','250m no poly','original'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0],mean_stages[i,1]))
+        writer.writerow(('100',boundary_mean,boundary_mean))
+        writer.writerow(('M-value',M_value[0],M_value[1]))
+        writer.writerow(('Absolute Error', abs_error[0],abs_error[1]))
+        writer.writerow(('Relative Error %', rel_error[0],rel_error[1]))
+        
+    if no_models==3:
+        writer.writerow(('depth (m)','250m no poly','250m poly','original'))
+        for i in range(len(depth)):
+            writer.writerow((depth[i],mean_stages[i,0],mean_stages[i,1],mean_stages[i,2]))
+        writer.writerow(('100',boundary_mean,boundary_mean,boundary_mean))
+        writer.writerow(('M-value',M_value[0],M_value[1],M_value[2]))
+        writer.writerow(('Absolute Error', abs_error[0],abs_error[1],abs_error[2]))
+        writer.writerow(('Relative Error %', rel_error[0],rel_error[1],rel_error[2]))
+
+    fid1.close()
+    
+    
Index: /anuga_work/production/wa/geraldton/project.py
===================================================================
--- /anuga_work/production/wa/geraldton/project.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/project.py	(revision 7411)
@@ -0,0 +1,249 @@
+"""Common filenames and locations for elevation, meshes and outputs.
+This script is the heart of all scripts in the folder
+"""
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, is_inside_polygon, number_mesh_triangles
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+
+#------------------------------------------------------------------------------
+# Directory setup
+#------------------------------------------------------------------------------
+# Note: INUNDATIONHOME is the inundation directory, not the data directory.
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent diruser = get_user_name()
+muxhome = getenv('MUXHOME')
+user = get_user_name()
+host = get_host_name()
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S',localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S',gmtime()) 
+build_time = time+'_build'
+run_time = time+'_run'
+
+#------------------------------------------------------------------------------
+# Initial Conditions
+#------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'geraldton'
+scenario = 'geraldton_tsunami_scenario'
+
+# Model specific parameters. One or all can be changed each time the
+# run_scenario script is executed
+tide = 0.6         #0.6
+#event_number = 27255 # Java 9.3 worst case for Perth
+event_number = 68693 # Sumatra 9.2
+#event_number = 27283  # Java 9.3 original
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             
+finaltime=80000       # final time for simulation
+
+setup='final'  # Final can be replaced with trial or basic.
+               # Either will result in a coarser mesh that will allow a
+               # faster, but less accurate, simulation.
+
+if setup =='coarse':
+    print'coarse'
+    res_factor=10000000
+    time_thinning=48
+    yieldstep=240
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=4
+    yieldstep=60
+
+#------------------------------------------------------------------------------
+# Output Filename
+#------------------------------------------------------------------------------
+# Important to distinguish each run - ensure str(user) is included!
+# Note, the user is free to include as many parameters as desired
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(event_number)+'_'+ 'alpha' +str(alpha)+'_'+str(user)
+
+#------------------------------------------------------------------------------
+# Input Data
+#------------------------------------------------------------------------------
+
+# elevation data used in build_geraldton.py
+# onshore data: format ascii grid with accompanying projection file
+onshore_name = 'landgate_dem_clip' 
+# island: format ascii grid with accompanying projection file
+island_name = 'dted_srtm_islands' 
+# coastline: format x,y,elevation (with title)
+coast_name = 'XYcoastline_KVP.txt'
+# bathymetry: format x,y,elevation (with title)
+offshore_name = 'Geraldton_bathymetry.txt'
+offshore_name1 = 'DPI_Data.txt'
+offshore_name2 = 'grid250.txt'
+offshore_name3 = 'Top_bathymetry.txt'
+
+# gauges - used in get_timeseries.py
+gauge_name = 'MH_gauges.csv'  #'geraldton.csv'
+gauge_name2 = 'thinned_MGA50.csv'
+
+#buildings - used in run_building_inundation.py
+building = 'geraldton_res_clip'
+
+# barrier
+barrier = 'CBD.csv'
+barrier1 = 'wall.csv'
+
+# BOUNDING POLYGON - used in build_boundary.py and run_geraldton.py respectively
+# NOTE: when files are put together the points must be in sequence - for ease go clockwise!
+# Check the run_geraldton.py for boundary_tags
+# thinned ordering file from Hazard Map: format is index,latitude,longitude (with title)
+order_filename = 'thinned_boundary_ordering.csv'
+#landward bounding points
+landward = 'landward_bounding_polygon.csv'
+
+#------------------------------------------------------------------------------
+# Output Elevation Data
+#------------------------------------------------------------------------------
+# Output filename for elevation
+# this is a combination of all the data (utilisied in build_boundary)
+combined_name ='geraldton_combined_elevation'
+combined_smaller_name = 'geraldton_combined_elevation_smaller'
+
+#------------------------------------------------------------------------------
+# Directory Structure
+#------------------------------------------------------------------------------
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+boundaries_dir = anuga_dir+'boundaries'+ sep 
+output_dir = anuga_dir+'outputs'+sep
+gauges_dir = anuga_dir+'gauges'+sep
+meshes_dir = anuga_dir+'meshes'+sep
+
+#------------------------------------------------------------------------------
+# Location of input and output data
+#------------------------------------------------------------------------------
+# where the input data sits
+onshore_in_dir_name = topographies_in_dir + onshore_name
+island_in_dir_name = topographies_in_dir + island_name
+coast_in_dir_name = topographies_in_dir + coast_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+offshore_in_dir_name1 = topographies_in_dir + offshore_name1
+offshore_in_dir_name2 = topographies_in_dir + offshore_name2
+offshore_in_dir_name3 = topographies_in_dir + offshore_name3
+
+# where the output data sits
+onshore_dir_name = topographies_dir + onshore_name
+island_dir_name = topographies_dir + island_name
+coast_dir_name = topographies_dir + coast_name
+offshore_dir_name = topographies_dir + offshore_name
+offshore_dir_name1 = topographies_dir + offshore_name1
+offshore_dir_name2 = topographies_dir + offshore_name2
+offshore_dir_name3 = topographies_dir + offshore_name3
+
+# where the combined elevation file sits
+combined_dir_name = topographies_dir + combined_name
+combined_smaller_name_dir = topographies_dir + combined_smaller_name
+
+# where the mesh sits (this is created during the run_geraldton.py)
+meshes_dir_name = meshes_dir + scenario_name+'.msh'
+barrier_dir_name = meshes_dir + barrier
+barrier_dir_name1 = meshes_dir + barrier1
+
+# where the boundary ordering files sit (this is used within build_boundary.py)
+order_filename_dir = boundaries_dir + order_filename
+
+# where the landward points of boundary extent sit (this is used within run_geraldton.py)
+landward_dir = boundaries_dir + landward
+
+# where the event sts files sits (this is created during the build_boundary.py)
+boundaries_dir_event = boundaries_dir + str(event_number) + sep
+boundaries_dir_mux = muxhome
+
+# where the directory of the output filename sits
+output_build_time_dir = output_dir+build_time+dir_comment+sep   #used for build_geraldton.py
+output_run_time_dir = output_dir+run_time+dir_comment+sep       #used for run_geraldton.py
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+# where the directory of the gauges sit
+gauges_dir_name = gauges_dir + gauge_name       #used for get_timeseries.py
+gauges_dir_name2 = gauges_dir + gauge_name2     #used for get_timeseries.py
+building_in_dir_name = gauges_dir + building + '.csv'    #used for run_building_inundation.py
+
+#------------------------------------------------------------------------------
+# Interior region definitions
+#------------------------------------------------------------------------------
+
+#Land, to set the initial stage/water to be offcoast only
+#Land and Ocean to clip data
+poly_mainland=read_polygon(polygons_dir +'land_initial_condition.csv')
+poly_ocean=read_polygon(polygons_dir +'ocean_initial_condition.csv')
+poly_buffer_20m=read_polygon(polygons_dir +'buffer_20m.csv')
+
+# Initial bounding polygon for data clipping 
+poly_all = read_polygon(polygons_dir+'poly_all.csv')
+res_poly_all = 100000*res_factor
+
+# Area of Interest 1 (Geraldton)
+poly_aoi1 = read_polygon(polygons_dir+'CBD_500m.csv')
+res_aoi1 = 500*res_factor
+
+# Area of Significance 1 (Geraldton)
+poly_aos1 = read_polygon(polygons_dir+'CBD_1km.csv')
+res_aos1 = 800*res_factor
+
+# Area of Significance 2 (island1)
+poly_aos2 = read_polygon(polygons_dir+'island_wallabi_poly.csv')
+res_aos2 = 5000*res_factor
+
+# Area of Significance 3 (island2)
+poly_aos3 = read_polygon(polygons_dir+'island_dingiville_poly.csv')
+res_aos3 = 5000*res_factor
+
+# Area of Significance 4 (island3)
+poly_aos4 = read_polygon(polygons_dir+'island_pelsaert_poly.csv')
+res_aos4 = 5000*res_factor
+
+# Shallow water 1
+poly_sw1 = read_polygon(polygons_dir+'neg20_pos20.csv')
+res_sw1 = 25000*res_factor
+
+# Combined all regions, must check that all are included!
+interior_regions = [[poly_aoi1,res_aoi1],[poly_aos1,res_aos1]
+                     ,[poly_aos2,res_aos2],[poly_aos3,res_aos3]
+                     ,[poly_aos4,res_aos4],[poly_sw1,res_sw1]]
+
+    
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+print 'min estimated number of triangles', trigs_min
+   
+#------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#------------------------------------------------------------------------------
+
+# Geraldton CBD extract ascii grid
+xminCBD = 262700
+xmaxCBD = 267600
+yminCBD = 6811500
+ymaxCBD = 6816400
Index: /anuga_work/production/wa/geraldton/project_250m.py
===================================================================
--- /anuga_work/production/wa/geraldton/project_250m.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/project_250m.py	(revision 7411)
@@ -0,0 +1,217 @@
+"""Common filenames and locations for elevation, meshes and outputs.
+This script is the heart of all scripts in the folder
+"""
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, is_inside_polygon, number_mesh_triangles
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from anuga.shallow_water.data_manager import urs2sts,create_sts_boundary
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+
+#------------------------------------------------------------------------------
+# Directory setup
+#------------------------------------------------------------------------------
+# Note: INUNDATIONHOME is the inundation directory, not the data directory.
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent diruser = get_user_name()
+muxhome = getenv('MUXHOME')
+user = get_user_name()
+host = get_host_name()
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S',localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S',gmtime()) 
+build_time = time+'_build'
+run_time = time+'_run'
+
+#------------------------------------------------------------------------------
+# Initial Conditions
+#------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'geraldton'
+scenario = 'geraldton_tsunami_scenario'
+
+# Model specific parameters. One or all can be changed each time the
+# run_scenario script is executed
+tide = 0                #0.6
+#event_number = 27255   # linked to hazard map
+event_number = 27283
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             
+finaltime=80000         # final time for simulation
+
+interior_mesh = 'all' # Can have 'all' or 'none' for Phase 2 study
+
+setup='final'  # Final can be replaced with trial or basic.
+               # Either will result in a coarser mesh that will allow a
+               # faster, but less accurate, simulation.
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=4
+    yieldstep=60
+
+#------------------------------------------------------------------------------
+# Output Filename
+#------------------------------------------------------------------------------
+# Important to distinguish each run - ensure str(user) is included!
+# Note, the user is free to include as many parameters as desired
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(event_number)+'_250m_' + str(interior_mesh) +'_'+str(user)
+
+#------------------------------------------------------------------------------
+# Input Data
+#------------------------------------------------------------------------------
+
+# elevation data used in build_geraldton.py
+# onshore data: format ascii grid with accompanying projection file
+onshore_name = 'grid_250m_2005' 
+
+# gauges - used in get_timeseries.py
+gauge_name = 'geraldton.csv'
+gauge_name2 = 'thinned_MGA50.csv'
+
+# BOUNDING POLYGON - used in build_boundary.py and run_geraldton.py respectively
+# NOTE: when files are put together the points must be in sequence - for ease go clockwise!
+# Check the run_geraldton.py for boundary_tags
+# thinned ordering file from Hazard Map: format is index,latitude,longitude (with title)
+order_filename = 'thinned_boundary_ordering.txt'
+#landward bounding points
+landward = 'landward_bounding_polygon.txt'
+
+#------------------------------------------------------------------------------
+# Output Elevation Data
+#------------------------------------------------------------------------------
+# Output filename for elevation
+# this is a combination of all the data (utilisied in build_boundary)
+combined_name ='geraldton_combined_elevation_250m'
+
+#------------------------------------------------------------------------------
+# Directory Structure
+#------------------------------------------------------------------------------
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+boundaries_dir = anuga_dir+'boundaries'+ sep 
+output_dir = anuga_dir+'outputs'+sep
+gauges_dir = anuga_dir+'gauges'+sep
+meshes_dir = anuga_dir+'meshes'+sep
+
+#------------------------------------------------------------------------------
+# Location of input and output data
+#------------------------------------------------------------------------------
+# where the input data sits
+onshore_in_dir_name = topographies_in_dir + onshore_name
+
+# where the output data sits
+onshore_dir_name = topographies_dir + onshore_name
+
+# where the combined elevation file sits
+combined_dir_name = topographies_dir + combined_name
+
+# where the mesh sits (this is created during the run_geraldton.py)
+meshes_dir_name = meshes_dir + scenario_name+ interior_mesh +'.msh'
+
+# where the boundary ordering files sit (this is used within build_boundary.py)
+order_filename_dir = boundaries_dir + order_filename
+
+# where the landward points of boundary extent sit (this is used within run_geraldton.py)
+landward_dir = boundaries_dir + landward
+
+# where the event sts files sits (this is created during the build_boundary.py)
+boundaries_dir_event = boundaries_dir + str(event_number) + sep
+boundaries_dir_mux = muxhome
+
+# where the directory of the output filename sits
+output_build_time_dir = output_dir+build_time+dir_comment+sep   #used for build_geraldton.py
+output_run_time_dir = output_dir+run_time+dir_comment+sep       #used for run_geraldton.py
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#w here the directory of the gauges sit
+gauges_dir_name = gauges_dir + gauge_name       #used for get_timeseries.py
+gauges_dir_name2 = gauges_dir + gauge_name2     #used for get_timeseries.py
+
+#------------------------------------------------------------------------------
+# Interior region definitions
+#------------------------------------------------------------------------------
+
+#Land, to set the initial stage/water to be offcoast only
+#Land and Ocean to clip data
+poly_mainland=read_polygon(polygons_dir +'land_initial_condition.csv')
+poly_ocean=read_polygon(polygons_dir +'ocean_initial_condition.csv')
+
+# Initial bounding polygon for data clipping 
+poly_all = read_polygon(polygons_dir+'poly_all.csv')
+res_poly_all = 100000*res_factor
+
+# Area of Interest 1 (Geraldton)
+poly_aoi1 = read_polygon(polygons_dir+'CBD_500m.csv')
+res_aoi1 = 500*res_factor
+
+# Area of Significance 1 (Geraldton)
+poly_aos1 = read_polygon(polygons_dir+'CBD_1km.csv')
+res_aos1 = 800*res_factor
+
+# Area of Significance 2 (island1)
+poly_aos2 = read_polygon(polygons_dir+'island_wallabi_poly.csv')
+res_aos2 = 5000*res_factor
+
+# Area of Significance 3 (island2)
+poly_aos3 = read_polygon(polygons_dir+'island_dingiville_poly.csv')
+res_aos3 = 5000*res_factor
+
+# Area of Significance 4 (island3)
+poly_aos4 = read_polygon(polygons_dir+'island_pelsaert_poly.csv')
+res_aos4 = 5000*res_factor
+
+# Shallow water 1
+poly_sw1 = read_polygon(polygons_dir+'neg20_pos20.csv')
+res_sw1 = 25000*res_factor
+
+# Combined all regions, must check that all are included!
+
+if interior_mesh =='all':
+    print'Mesh = all'
+    interior_regions = [[poly_aoi1,res_aoi1],[poly_aos1,res_aos1]
+                     ,[poly_aos2,res_aos2],[poly_aos3,res_aos3]
+                     ,[poly_aos4,res_aos4],[poly_sw1,res_sw1]]
+if interior_mesh =='none': 
+    print'Mesh = none'
+    interior_regions = []
+     
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+print 'min estimated number of triangles', trigs_min
+   
+#------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#------------------------------------------------------------------------------
+
+# Geraldton CBD extract ascii grid
+xminCBD = 262700
+xmaxCBD = 267600
+yminCBD = 6811500
+ymaxCBD = 6816400
+
Index: /anuga_work/production/wa/geraldton/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/geraldton/run_boundary_points.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/run_boundary_points.py	(revision 7411)
@@ -0,0 +1,47 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+
+# # Related major packages
+# from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import URS_points_needed_to_file, \
+     urs_ungridded2sww
+import project                 # Definition of file names and polygons
+
+#-----------------------------------------------------------------------------
+# run_boundary_points
+#-----------------------------------------------------------------------------
+  
+LL_LAT = -50.0          #ll_lat - lower left latitude, in decimal degrees
+LL_LONG = 80.0          #ll-long - lower left longitude, in decimal degrees
+GRID_SPACING = 2.0/60.0 #grid_spacing - in deciamal degrees
+LAT_AMOUNT = 4800       #lat_amount - number of latitudes 
+LONG_AMOUNT = 3600      #long_amount- number of longs
+ZONE = 49
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+poly = project.poly_all
+print "poly", poly
+print "project.boundaries_in_dir_name",project.boundaries_in_dir_name
+URS_points_needed_to_file(project.boundaries_in_dir_name,poly, ZONE,
+                          LL_LAT, LL_LONG,GRID_SPACING,LAT_AMOUNT, LONG_AMOUNT,export_csv=True)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True)
+#urs_ungridded2sww(project.boundaries_in_dir_name2, project.boundaries_dir_name5, mean_stage= project.tide,  verbose=True)
Index: /anuga_work/production/wa/geraldton/run_geraldton.py
===================================================================
--- /anuga_work/production/wa/geraldton/run_geraldton.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/run_geraldton.py	(revision 7411)
@@ -0,0 +1,252 @@
+"""Script for running a tsunami inundation scenario for geraldton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data is compiled into a pts file through build_geraldton.py
+and a simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_geraldton.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid, create_sts_boundary
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.pmesh.mesh import importMeshFromFile
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+from anuga.geospatial_data.geospatial_data import find_optimal_smoothing_parameter,Geospatial_data
+from polygon import Polygon_function
+
+
+# Application specific imports
+import project  # Definition of file names and polygons
+numprocs = 1
+myid = 0
+
+def run_model(**kwargs):
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+    print "Processor Name:",get_processor_name()
+
+    #copy script must be before screen_catcher
+
+    print 'output_dir',kwargs['output_dir']
+    
+    copy_code_files(kwargs['output_dir'],__file__, 
+             dirname(project.__file__)+sep+ project.__name__+'.py' )
+
+    store_parameters(**kwargs)
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print "Processor Name:",get_processor_name()
+    
+    #-----------------------------------------------------------------------
+    # Domain definitions
+    #-----------------------------------------------------------------------
+
+    # Read in boundary from ordered sts file
+    urs_bounding_polygon=create_sts_boundary(os.path.join(project.boundaries_dir_event,project.scenario_name))
+
+    # Reading the landward defined points, this incorporates the original clipping
+    # polygon minus the 100m contour
+    landward_bounding_polygon = read_polygon(project.landward_dir)
+
+    # Combine sts polyline with landward points
+    bounding_polygon = urs_bounding_polygon + landward_bounding_polygon
+    
+    # counting segments
+    N = len(urs_bounding_polygon)-1
+
+    # boundary tags refer to project.landward 4 points equals 5 segments start at N
+    boundary_tags={'back': [N+2,N+3], 'side': [N,N+1,N+4], 'ocean': range(N)}
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a tagged
+    # boundary and interior regions defined in project.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    # IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+        
+    print 'start create mesh from regions'
+
+    create_mesh_from_regions(bounding_polygon,
+                         boundary_tags=boundary_tags,
+                         maximum_triangle_area=project.res_poly_all,
+                         interior_regions=project.interior_regions,
+                         filename=project.meshes_dir_name,
+                         use_cache=False,
+                         verbose=True)
+
+    m = importMeshFromFile(project.meshes_dir_name)
+    # load points from a points file
+    m.add_points_and_segments(Geospatial_data(project.barrier_dir_name))
+    m.add_points_and_segments(Geospatial_data(project.barrier_dir_name1))
+    m.generate_mesh()
+    m.export_mesh_file(project.meshes_dir_name)
+   
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    domain = Domain(project.meshes_dir_name, use_cache=False, verbose=True)
+    print 'memory usage before del domain',mem_usage()
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    print 'Setup initial conditions'
+
+    # sets the initial stage in the offcoast region only
+    IC = Polygon_function( [(project.poly_mainland, 0)], default = kwargs['tide'],
+                             geo_reference = domain.geo_reference)
+    domain.set_quantity('stage', IC)
+    #domain.set_quantity('stage',kwargs['tide'] )
+    domain.set_quantity('friction', kwargs['friction']) 
+    
+    print 'Start Set quantity',kwargs['elevation_file']
+
+    domain.set_quantity('elevation', 
+                        filename = kwargs['elevation_file'],
+                        use_cache = False,
+                        verbose = True,
+                        alpha = kwargs['alpha'])
+    print 'Finished Set quantity'
+
+##   #------------------------------------------------------
+##    # Distribute domain to implement parallelism !!!
+##    #------------------------------------------------------
+##
+##    if numprocs > 1:
+##        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2)                 # Apply second order scheme
+    domain.set_minimum_storable_height(0.01)    # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.tight_slope_limiters = 1
+    print 'domain id', id(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+   
+    boundary_urs_out=project.boundaries_dir_event + sep + project.scenario_name
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([kwargs['tide'],0,0])
+    
+    print 'Available boundary tags', domain.get_boundary_tags()
+    Bf = Field_boundary(boundary_urs_out+'.sts',  # Change from file_boundary
+                   domain, mean_stage= project.tide,
+                   time_thinning=1,
+                   default_boundary=Bd,
+                   use_cache=True,
+                   verbose = True,
+                   boundary_polygon=bounding_polygon)
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf}) 
+
+    kwargs['input_start_time']=domain.starttime
+
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #--------------------------------------------------------------------
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = project.yieldstep, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = False): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')
+
+    # these outputs should be checked with the resultant inundation map
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'Simulation took %.2f seconds' %(time.time()-t0)
+
+    #kwargs 'completed' must be added to write the final parameters to file
+    kwargs['completed']=str(time.time()-t0)
+     
+    store_parameters(**kwargs)
+     
+    print 'memory usage before del domain1',mem_usage()
+    
+    
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    
+    kwargs={}
+    kwargs['file_name']=project.dir_comment
+    kwargs['finaltime']=project.finaltime
+    kwargs['output_dir']=project.output_run_time_dir
+    kwargs['elevation_file']=project.combined_dir_name+'.pts'
+    kwargs['scenario_name']=project.scenario_name
+    kwargs['tide']=project.tide
+    kwargs['alpha'] = project.alpha
+    kwargs['friction']=project.friction
+    #kwargs['num_cpu']=numprocs
+    #kwargs['host']=project.host
+    #kwargs['starttime']=project.starttime
+    #kwargs['yieldstep']=project.yieldstep
+    #kwargs['user']=project.user
+    #kwargs['time_thinning'] = project.time_thinning
+      
+    run_model(**kwargs)
+      
+   
Index: /anuga_work/production/wa/geraldton/run_geraldton_250m.py
===================================================================
--- /anuga_work/production/wa/geraldton/run_geraldton_250m.py	(revision 7411)
+++ /anuga_work/production/wa/geraldton/run_geraldton_250m.py	(revision 7411)
@@ -0,0 +1,237 @@
+"""Script for running a tsunami inundation scenario for geraldton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project_250m.polygon,
+the elevation data is compiled into a pts file through build_geraldton.py
+and a simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_geraldton.py)
+       information from project file
+Outputs: sww file stored in project_250m.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid, create_sts_boundary
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon
+from anuga.geospatial_data.geospatial_data import find_optimal_smoothing_parameter
+from polygon import Polygon_function
+    
+# Application specific imports
+import project_250m  # Definition of file names and polygons
+numprocs = 1
+myid = 0
+
+def run_model(**kwargs):
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+    print "Processor Name:",get_processor_name()
+
+    #copy script must be before screen_catcher
+
+    print 'output_dir',kwargs['output_dir']
+    
+    copy_code_files(kwargs['output_dir'],__file__, 
+             dirname(project_250m.__file__)+sep+ project_250m.__name__+'.py' )
+
+    store_parameters(**kwargs)
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print "Processor Name:",get_processor_name()
+    
+    #-----------------------------------------------------------------------
+    # Domain definitions
+    #-----------------------------------------------------------------------
+
+    # Read in boundary from ordered sts file
+    urs_bounding_polygon=create_sts_boundary(os.path.join(project_250m.boundaries_dir_event,project_250m.scenario_name))
+
+    # Reading the landward defined points, this incorporates the original clipping
+    # polygon minus the 100m contour
+    landward_bounding_polygon = read_polygon(project_250m.landward_dir)
+
+    # Combine sts polyline with landward points
+    bounding_polygon = urs_bounding_polygon + landward_bounding_polygon
+    
+    # counting segments
+    N = len(urs_bounding_polygon)-1
+
+    # boundary tags refer to project_250m.landward 4 points equals 5 segments start at N
+    boundary_tags={'back': [N+2,N+3], 'side': [N,N+1,N+4], 'ocean': range(N)}
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a tagged
+    # boundary and interior regions defined in project_250m.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    # IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+        
+    print 'start create mesh from regions'
+
+    create_mesh_from_regions(bounding_polygon,
+                         boundary_tags=boundary_tags,
+                         maximum_triangle_area=project_250m.res_poly_all,
+                         interior_regions=project_250m.interior_regions,
+                         filename=project_250m.meshes_dir_name,
+                         use_cache=True,
+                         verbose=True)
+   
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    domain = Domain(project_250m.meshes_dir_name, use_cache=False, verbose=True)
+    print 'memory usage before del domain',mem_usage()
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    print 'Setup initial conditions'
+
+    # sets the initial stage in the offcoast region only
+    IC = Polygon_function( [(project_250m.poly_mainland, 0)], default = kwargs['tide'],
+                             geo_reference = domain.geo_reference)
+    domain.set_quantity('stage', IC)
+    #domain.set_quantity('stage',kwargs['tide'] )
+    domain.set_quantity('friction', kwargs['friction']) 
+    
+    print 'Start Set quantity',kwargs['elevation_file']
+
+    domain.set_quantity('elevation', 
+                        filename = kwargs['elevation_file'],
+                        use_cache = False,
+                        verbose = True,
+                        alpha = kwargs['alpha'])
+    print 'Finished Set quantity'
+
+##   #------------------------------------------------------
+##    # Distribute domain to implement parallelism !!!
+##    #------------------------------------------------------
+##
+##    if numprocs > 1:
+##        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2)                 # Apply second order scheme
+    domain.set_minimum_storable_height(0.01)    # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.tight_slope_limiters = 1
+    print 'domain id', id(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+   
+    boundary_urs_out=project_250m.boundaries_dir_event + sep + project_250m.scenario_name
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([kwargs['tide'],0,0])
+    
+    print 'Available boundary tags', domain.get_boundary_tags()
+    Bf = Field_boundary(boundary_urs_out+'.sts',  # Change from file_boundary
+                   domain, mean_stage= project_250m.tide,
+                   time_thinning=1,
+                   default_boundary=Bd,
+                   use_cache=True,
+                   verbose = True,
+                   boundary_polygon=bounding_polygon)
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf}) 
+
+    kwargs['input_start_time']=domain.starttime
+
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #--------------------------------------------------------------------
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = project_250m.yieldstep, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = False): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')
+
+    # these outputs should be checked with the resultant inundation map
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'Simulation took %.2f seconds' %(time.time()-t0)
+
+    #kwargs 'completed' must be added to write the final parameters to file
+    kwargs['completed']=str(time.time()-t0)
+     
+    store_parameters(**kwargs)
+     
+    print 'memory usage before del domain1',mem_usage()
+    
+    
+#-------------------------------------------------------------
+if __name__ == "__main__":
+    
+    kwargs={}
+    kwargs['file_name']=project.dir_comment
+    kwargs['finaltime']=project_250m.finaltime
+    kwargs['output_dir']=project_250m.output_run_time_dir
+    kwargs['elevation_file']=project_250m.combined_dir_name+'.pts'
+    kwargs['scenario_name']=project_250m.scenario_name
+    kwargs['tide']=project_250m.tide
+    kwargs['alpha'] = project_250m.alpha
+    kwargs['friction']=project_250m.friction
+     
+    run_model(**kwargs)
+      
+   
Index: /anuga_work/production/wa/karratha_2005/all_bld_ind.csv
===================================================================
--- /anuga_work/production/wa/karratha_2005/all_bld_ind.csv	(revision 7411)
+++ /anuga_work/production/wa/karratha_2005/all_bld_ind.csv	(revision 7411)
@@ -0,0 +1,91 @@
+FID_inunda,ROE_BLD_,ROE_BLD_ID,GNAF_PID,BUILDING_N,LONGITUDE,LATITUDE,UNIT_NUM,UNIT_SFX,STR_PFX,STR_NUM,STR_SFX,STR_NAME,STR_TYPE,SUBURB,STATE,LAST_NUM,FULL_ADDR,GNAF_TYPE,PARCEL_ID,BLOCKSIZE,CD_CODE,CD_AREA,SD,FLR_AREA,USAGE,RESIDENCES,TYPE,ROOF_TYPE,WALLS,STR_COST,STR_VALUE,IGROUP,C_COST,C_VALUE,PEOPLE,INUNDATION,MOMENTUM,DISTANCE_C,PR_COLLAPS,FID_meshbl,MB_CODE,MB_TYPE,CATEGORY,MOD_DATE
+0,4858,4858,GAWA_161585250,,116.7035,-20.6667,0,,LOT,166,,THE ESPLANADE,,DAMPIER,WA,,LOT 166 THE ESPLANADE,,DEWITL  00166,23130.79375810000,5011201,13709376.231,WAR,300,Parkland,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,0.26,6.58,112.36,,17948,50179490000,U,Parkland,6/7/2005
+1,4941,4941,GAWA_161549316,,116.7043,-20.6648,0,,LOT,379,,HAIG,CLOSE,DAMPIER,WA,,LOT 379 HAIG CLOSE,,P017814     379,1405.47911150000,5011201,13709376.231,WAR,300,Commercial,1,SH,Tiles,Double Brick,758.10,227430,PRESTIGE,1380,414000,0.00,0.75,13.13,191.11,,17968,50179690000,U,Commercial,6/7/2005
+2,4944,4944,GAWA_161585260,,116.7037,-20.6647,0,,LOT,381,,THE ESPLANADE,,DAMPIER,WA,,LOT 381 THE ESPLANADE,,P017814     381,5836.90203273000,5011201,13709376.231,WAR,300,Commercial,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,1.41,0.00,126.35,,17968,50179690000,U,Commercial,6/7/2005
+3,4962,4962,GAWA_161549318,,116.7042,-20.6644,0,,LOT,4,,HAIG,CLOSE,DAMPIER,WA,,LOT 4 HAIG CLOSE,,P018331       4,2019.09705015000,5011201,13709376.231,WAR,300,Commercial,1,SH,Tiles,Double Brick,758.10,227430,PRESTIGE,1380,414000,0.00,1.62,17.12,177.71,,17968,50179690000,U,Commercial,6/7/2005
+4,4972,4972,GAWA_161533982,,116.7073,-20.6642,0,,LOT,372,,CHURCH,ROAD,DAMPIER,WA,,LOT 372 CHURCH ROAD,,P015796     372,3408.99392644000,5011201,13709376.231,WAR,300,Commercial,1,SH,Metal,Timber,665.90,199770,PRESTIGE,1380,414000,0.00,0.32,13.16,450.47,,17968,50179690000,U,Commercial,6/7/2005
+5,4977,4977,GAWA_161585261,,116.7036,-20.6640,0,,LOT,382,,THE ESPLANADE,,DAMPIER,WA,,LOT 382 THE ESPLANADE,,P017814     382,6120.13126721000,5011201,13709376.231,WAR,300,Commercial,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,3.17,21.46,114.90,,17968,50179690000,U,Commercial,6/7/2005
+6,4990,4990,GAWA_147386848,PRESBYTERY,116.7079,-20.6638,0,,,371,,HIGH,STREET,DAMPIER,WA,,371 HIGH STREET,,P015796     371,3660.53604881000,5011201,13709376.231,WAR,300,Commercial,2,SD,Metal,Brick veneer,727.30,218190,PRESTIGE,1161,348300,0.00,0.05,10.80,444.21,,17968,50179690000,U,Commercial,6/7/2005
+7,4997,4997,GAWA_161549317,,116.7043,-20.6637,0,,LOT,3,,HAIG,CLOSE,DAMPIER,WA,,LOT 3 HAIG CLOSE,,P018331       3,9062.54572207000,5011201,13709376.231,WAR,300,Commercial,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,2.50,21.12,194.30,,17968,50179690000,U,Commercial,6/7/2005
+8,5005,5005,GAWA_161585262,,116.7033,-20.6635,0,,LOT,383,,THE ESPLANADE,,DAMPIER,WA,,LOT 383 THE ESPLANADE,,P017814     383,2948.39083282000,5011201,13709376.231,WAR,300,Commercial,1,SH,Tiles,Double Brick,758.10,227430,PRESTIGE,1380,414000,0.00,4.71,25.80,104.96,,17968,50179690000,U,Commercial,6/7/2005
+9,5009,5009,GAWA_161585258,,116.7027,-20.6634,0,,LOT,361,,THE ESPLANADE,,DAMPIER,WA,,LOT 361 THE ESPLANADE,,D065647     361,6631.78117853000,5011201,13709376.231,WAR,300,Parkland,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,5.37,26.14,44.79,,17948,50179490000,U,Parkland,6/7/2005
+10,5012,5012,GAWA_147386852,DAMPIER POLICE STATION,116.7059,-20.6633,0,,LOT,376,,NIELSEN,PLACE,DAMPIER,WA,,LOT 376 NIELSEN PLACE,,P015796     376,2346.78547604000,5011201,13709376.231,WAR,300,Commercial,1,SH,Tiles,Double Brick,758.10,227430,PRESTIGE,1380,414000,0.00,1.71,24.09,292.12,,17968,50179690000,U,Commercial,6/7/2005
+11,5013,5013,GAWA_161552060,,116.7072,-20.6633,0,,LOT,373,,HIGH,STREET,DAMPIER,WA,,LOT 373 HIGH STREET,,P015796     373,18524.82311760000,5011201,13709376.231,WAR,300,Commercial,1,SD,Metal,Brick veneer,727.30,218190,PRESTIGE,1161,348300,0.00,0.71,17.37,356.47,,17968,50179690000,U,Commercial,6/7/2005
+12,5017,5017,GAWA_160937071,CUSTOMS FLATS,116.7063,-20.6631,1,,LOT,375,,NIELSEN,PLACE,DAMPIER,WA,,LOT 375 NIELSEN PLACE,,P015796     375,1295.29199053000,5011201,13709376.231,WAR,300,Commercial,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,1.29,23.23,287.29,,17968,50179690000,U,Commercial,6/7/2005
+13,5018,5018,GAWA_161585251,,116.7037,-20.6631,0,,LOT,1,,THE ESPLANADE,,DAMPIER,WA,,LOT 1 THE ESPLANADE,,P018331       1,3937.29361779000,5011201,13709376.231,WAR,300,Commercial,1,SH,Tiles,Double Brick,758.10,227430,PRESTIGE,1380,414000,0.00,4.93,29.45,132.99,,17968,50179690000,U,Commercial,6/7/2005
+14,5026,5026,GAWA_147120681,THE ESPLANADE MERCURE INN,116.7050,-20.6629,0,,LOT,386,,NIELSEN,PLACE,DAMPIER,WA,,LOT 386 NIELSEN PLACE,,P017814     386,20003.59307040000,5011201,13709376.231,WAR,300,Commercial,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,3.20,27.98,201.10,,17968,50179690000,U,Commercial,6/7/2005
+15,5030,5030,GAWA_161552061,,116.7067,-20.6628,0,,LOT,374,,HIGH,STREET,DAMPIER,WA,,LOT 374 HIGH STREET,,P015796     374,2144.34279230000,5011201,13709376.231,WAR,300,Commercial,1,SH,Fibro,Double Brick,652.80,195840,PRESTIGE,1380,414000,0.00,0.94,19.76,280.28,,17968,50179690000,U,Commercial,6/7/2005
+16,5032,5032,GAWA_161585257,,116.7040,-20.6628,0,,LOT,2,,THE ESPLANADE,,DAMPIER,WA,,LOT 2 THE ESPLANADE,,P018331       2,2268.75490699000,5011201,13709376.231,WAR,300,Commercial,1,SH,Tiles,Double Brick,758.10,227430,PRESTIGE,1380,414000,0.00,4.34,29.11,126.47,,17968,50179690000,U,Commercial,6/7/2005
+17,5043,5043,GAWA_161585259,,116.7029,-20.6625,0,,LOT,362,,THE ESPLANADE,,DAMPIER,WA,,LOT 362 THE ESPLANADE,,P014280     362,4869.68028625000,5011201,13709376.231,WAR,300,Parkland,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,7.30,33.93,34.02,,17948,50179490000,U,Parkland,6/7/2005
+18,5044,5044,GAWA_161552063,,116.7070,-20.6625,0,,LOT,390,,HIGH,STREET,DAMPIER,WA,,LOT 390 HIGH STREET,,P015796     390,2344.66040645000,5011201,13709376.231,WAR,300,Commercial,1,SH,Fibro,Double Brick,652.80,195840,PRESTIGE,1380,414000,0.00,0.47,16.19,269.04,,17968,50179690000,U,Commercial,6/7/2005
+19,5046,5046,GAWA_161602818,,116.7064,-20.6622,2,,LOT,389,,HIGH,STREET,DAMPIER,WA,,LOT 389 HIGH STREET,,D068176     389,12997.23037270000,5011201,13709376.231,WAR,300,Commercial,16,SD,Metal,Brick veneer,727.30,218190,PRESTIGE,1161,348300,0.00,0.82,19.68,211.47,,17968,50179690000,U,Commercial,6/7/2005
+20,5054,5054,GAWA_161585263,,116.7046,-20.6621,0,,LOT,387,,THE ESPLANADE,,DAMPIER,WA,,LOT 387 THE ESPLANADE,,D076644     387,7341.61464141000,5011201,13709376.231,WAR,300,Commercial,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,6.31,34.49,108.20,,17968,50179690000,U,Commercial,6/7/2005
+21,5068,5068,GAWA_161523288,,116.7075,-20.6618,0,,LOT,40,,ASHBURTON,CRESCENT,DAMPIER,WA,,LOT 40 ASHBURTON CRESCENT,,P017812      40,1428.58777496000,5011201,13709376.231,WAR,300,Residential,2,SD,Metal,Brick veneer,727.30,218190,PRESTIGE,1161,348300,2.31,0.01,12.62,263.21,0,18155,50181560000,U,Residential,6/7/2005
+22,5086,5086,GAWA_161585264,,116.7058,-20.6614,0,,LOT,388,,THE ESPLANADE,,DAMPIER,WA,,LOT 388 THE ESPLANADE,,P015796     388,16109.07923940000,5011201,13709376.231,WAR,300,Commercial,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,5.93,29.82,103.77,,17968,50179690000,U,Commercial,6/7/2005
+23,5095,5095,GAWA_161561616,,116.7071,-20.6613,0,,LOT,3025,,MAITLAND,COURT,DAMPIER,WA,,LOT 3025 MAITLAND COURT,,P017812    3025,951.15875681600,5011201,13709376.231,WAR,150,Residential,1,SH,Tiles,Double Brick,873.90,131085,PRESTIGE,1818,272700,3.22,2.02,18.12,202.96,0.25,18155,50181560000,U,Residential,6/7/2005
+24,5097,5097,GAWA_161561615,,116.7073,-20.6612,0,,LOT,2025,,MAITLAND,COURT,DAMPIER,WA,,LOT 2025 MAITLAND COURT,,P017812    2025,981.10850338400,5011201,13709376.231,WAR,150,Residential,1,SH,Tiles,Double Brick,873.90,131085,PRESTIGE,1818,272700,3.22,2.02,18.12,218.95,0.25,18155,50181560000,U,Residential,6/7/2005
+25,5105,5105,GAWA_161561614,,116.7075,-20.6611,0,,LOT,1025,,MAITLAND,COURT,DAMPIER,WA,,LOT 1025 MAITLAND COURT,,P017812    1025,849.03171479400,5011201,13709376.231,WAR,150,Residential,1,SH,Tiles,Double Brick,873.90,131085,PRESTIGE,1818,272700,3.22,0.28,13.57,238.04,0.01,18155,50181560000,U,Residential,6/7/2005
+26,5126,5126,GAWA_147115934,,116.7070,-20.6606,0,,,16,,MINILYA,CRESCENT,DAMPIER,WA,,16 MINILYA CRESCENT,,P017812      16,1136.65687507000,5011201,13709376.231,WAR,300,Residential,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,3.31,19.11,176.79,0.7,18156,50181570000,U,Residential,6/7/2005
+27,5130,5130,GAWA_147373543,,116.7073,-20.6605,0,,,17,,MINILYA,CRESCENT,DAMPIER,WA,,17 MINILYA CRESCENT,,P017812      17,839.55855379400,5011201,13709376.231,WAR,150,Residential,2,SD,Tiles,Double Brick,810.85,121627,PRESTIGE,1161,174150,2.31,3.31,19.11,199.60,0.7,18156,50181570000,U,Residential,6/7/2005
+28,5135,5135,GAWA_161565313,,116.7075,-20.6604,0,,LOT,18,,MINILYA,CRESCENT,DAMPIER,WA,,LOT 18 MINILYA CRESCENT,,P017812      18,1016.49351922000,5011201,13709376.231,WAR,300,Residential,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,2.61,15.56,215.40,0.25,18156,50181570000,U,Residential,6/7/2005
+29,5140,5140,GAWA_161565314,,116.7077,-20.6603,0,,LOT,19,,MINILYA,CRESCENT,DAMPIER,WA,,LOT 19 MINILYA CRESCENT,,P017812      19,1180.72204057000,5011201,13709376.231,WAR,300,Residential,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,2.61,15.56,223.83,0.25,18156,50181570000,U,Residential,6/7/2005
+30,5142,5142,GAWA_147373537,,116.7079,-20.6602,0,,,20,,MINILYA,CRESCENT,DAMPIER,WA,,20 MINILYA CRESCENT,,P017812      20,1022.54822317000,5011201,13709376.231,WAR,300,Residential,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,0.56,11.99,236.73,0.01,18156,50181570000,U,Residential,6/7/2005
+31,5143,5143,GAWA_161565317,,116.7082,-20.6602,0,,LOT,21,,MINILYA,CRESCENT,DAMPIER,WA,,LOT 21 MINILYA CRESCENT,,P017812      21,987.58003884300,5011201,13709376.231,WAR,150,Residential,2,SD,Tiles,Double Brick,810.85,121627,PRESTIGE,1161,174150,2.31,0.56,11.99,253.42,0,18156,50181570000,U,Residential,6/7/2005
+32,5145,5145,GAWA_161585265,,116.7067,-20.6602,0,,LOT,404,,THE ESPLANADE,,DAMPIER,WA,,LOT 404 THE ESPLANADE,,P017817     404,16711.86223660000,5011201,13709376.231,WAR,300,Residential,1,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,6.33,24.65,142.19,0.9,18156,50181570000,U,Residential,6/7/2005
+33,5169,5169,GAWA_161541011,,116.7072,-20.6596,0,,LOT,15,,DURACK,CRESCENT,DAMPIER,WA,,LOT 15 DURACK CRESCENT,,P017817      15,7659.71046077000,5011201,13709376.231,WAR,300,Residential,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,5.47,21.47,132.06,0.9,18156,50181570000,U,Residential,6/7/2005
+34,5170,5170,GAWA_147377267,,116.7078,-20.6595,0,,,14,,DURACK,CRESCENT,DAMPIER,WA,,14 DURACK CRESCENT,,P017817      14,1017.04784443000,5011201,13709376.231,WAR,300,Residential,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,3.42,18.17,171.44,0.7,18156,50181570000,U,Residential,6/7/2005
+35,5171,5171,GAWA_161541009,,116.7080,-20.6595,0,,LOT,13,,DURACK,CRESCENT,DAMPIER,WA,,LOT 13 DURACK CRESCENT,,P017817      13,899.65083881800,5011201,13709376.231,WAR,150,Residential,2,SD,Tiles,Double Brick,810.85,121627,PRESTIGE,1161,174150,2.31,1.36,14.87,188.16,0.3,18156,50181570000,U,Residential,6/7/2005
+36,5172,5172,GAWA_161541008,,116.7082,-20.6595,0,,LOT,12,,DURACK,CRESCENT,DAMPIER,WA,,LOT 12 DURACK CRESCENT,,P017817      12,909.39566087700,5011201,13709376.231,WAR,150,Residential,2,SD,Tiles,Double Brick,810.85,121627,PRESTIGE,1161,174150,2.31,1.36,14.87,204.15,0.1,18156,50181570000,U,Residential,6/7/2005
+37,5195,5195,GAWA_161527166,,116.7081,-20.6589,0,,LOT,1,,BLACKWOOD,CRESCENT,DAMPIER,WA,,LOT 1 BLACKWOOD CRESCENT,,P017817       1,1071.51808031000,5011201,13709376.231,WAR,300,Residential,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,2.98,20.63,145.24,0.4,18156,50181570000,U,Residential,6/7/2005
+38,5196,5196,GAWA_147377244,,116.7083,-20.6589,0,,,2,,BLACKWOOD,CRESCENT,DAMPIER,WA,,2 BLACKWOOD CRESCENT,,P017817       2,934.03857373100,5011201,13709376.231,WAR,150,Residential,2,SD,Tiles,Double Brick,810.85,121627,PRESTIGE,1161,174150,2.31,0.93,17.33,166.93,0.02,18156,50181570000,U,Residential,6/7/2005
+39,5197,5197,GAWA_147377243,,116.7085,-20.6589,0,,,3,,BLACKWOOD,CRESCENT,DAMPIER,WA,,3 BLACKWOOD CRESCENT,,P017817       3,861.71847256100,5011201,13709376.231,WAR,150,Residential,2,SD,Tiles,Double Brick,810.85,121627,PRESTIGE,1161,174150,2.31,0.93,17.33,187.86,0.02,18156,50181570000,U,Residential,6/7/2005
+40,5198,5198,GAWA_161527169,,116.7088,-20.6589,0,,LOT,4,,BLACKWOOD,CRESCENT,DAMPIER,WA,,LOT 4 BLACKWOOD CRESCENT,,P017817       4,1007.52948351000,5011201,13709376.231,WAR,300,Residential,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,2.31,0.93,17.33,206.27,0.01,18156,50181570000,U,Residential,6/7/2005
+41,5199,5199,GAWA_147362853,,116.7090,-20.6588,0,,,5,,BLACKWOOD,CRESCENT,DAMPIER,WA,,5 BLACKWOOD CRESCENT,,P017817       5,951.39593974400,5011201,13709376.231,WAR,150,Residential,2,SD,Tiles,Double Brick,810.85,121627,PRESTIGE,1161,174150,2.31,0.25,14.03,221.88,0.01,18156,50181570000,U,Residential,6/7/2005
+42,5203,5203,GAWA_161527171,,116.7092,-20.6587,0,,LOT,6,,BLACKWOOD,CRESCENT,DAMPIER,WA,,LOT 6 BLACKWOOD CRESCENT,,P017817       6,930.21293851700,5011201,13709376.231,WAR,150,Residential,2,SD,Tiles,Double Brick,810.85,121627,PRESTIGE,1161,174150,2.31,0.25,14.03,240.08,0.01,18156,50181570000,U,Residential,6/7/2005
+43,5222,5222,GAWA_161585253,,116.7078,-20.6577,0,,LOT,248,,THE ESPLANADE,,DAMPIER,WA,,LOT 248 THE ESPLANADE,,DEWITL  00248,4028.84789213000,5011201,13709376.231,WAR,300,Parkland,2,SD,Tiles,Double Brick,736.00,220800,PRESTIGE,1161,348300,0.00,6.54,29.73,83.67,,17769,50177700000,U,Parkland,6/7/2005
+44,5223,5223,GAWA_161585252,,116.7091,-20.6571,0,,LOT,247,,THE ESPLANADE,,DAMPIER,WA,,LOT 247 THE ESPLANADE,,DEWITL  00247,38233.90935850000,5011202,2823116.719,WAR,350,Parkland,2,SD,Tiles,Double Brick,711.05,248867,PRESTIGE,1161,406350,0.00,2.63,25.56,219.58,,17769,50177700000,U,Parkland,6/7/2005
+45,5224,5224,GAWA_161585256,,116.7109,-20.6560,0,,LOT,255,,THE ESPLANADE,,DAMPIER,WA,,LOT 255 THE ESPLANADE,,DEWITL  00255,393.27924444100,5011202,2823116.719,WAR,118,Parkland,2,SD,Tiles,Double Brick,826.82,97565,PRESTIGE,1161,136998,0.00,3.35,17.35,221.59,,17769,50177700000,U,Parkland,6/7/2005
+46,5225,5225,GAWA_161585255,,116.7104,-20.6554,0,,LOT,254,,THE ESPLANADE,,DAMPIER,WA,,LOT 254 THE ESPLANADE,,DEWITL  00254,25493.01186440000,5011202,2823116.719,WAR,350,Parkland,2,SD,Tiles,Double Brick,711.05,248867,PRESTIGE,1161,406350,0.00,6.77,24.85,148.80,,17769,50177700000,U,Parkland,6/7/2005
+47,5226,5226,GAWA_161585254,,116.7090,-20.6551,0,,LOT,253,,THE ESPLANADE,,DAMPIER,WA,,LOT 253 THE ESPLANADE,,DEWITL  00253,13919.41826280000,5011202,2823116.719,WAR,350,Parkland,2,SD,Tiles,Double Brick,711.05,248867,PRESTIGE,1161,406350,0.00,10.30,35.40,50.65,,17769,50177700000,U,Parkland,6/7/2005
+48,5377,1,,,116.6952,-20.6740,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,3.01,15.39,119.80,0.95,18169,50181700000,R,Agricultural,6/7/2005
+49,5378,2,,,116.7065,-20.6646,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,0.31,13.10,418.14,0,17969,50179700000,U,Education,6/7/2005
+50,5379,3,,,116.7064,-20.6644,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,0.60,15.59,407.26,0,17969,50179700000,U,Education,6/7/2005
+51,5380,4,,,116.7138,-20.6562,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,0.12,8.05,364.50,0,18011,50180120000,U,Parkland,6/7/2005
+52,5381,5,,,116.7140,-20.6559,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,0.73,10.45,359.70,0,18011,50180120000,U,Parkland,6/7/2005
+53,5382,6,,,116.7146,-20.6554,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,0.15,6.78,356.73,0,18011,50180120000,U,Parkland,6/7/2005
+54,5383,7,,,116.7116,-20.6551,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,5.83,18.63,138.27,0.9,17769,50177700000,U,Parkland,6/7/2005
+55,5384,8,,,116.7120,-20.6551,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,5.24,15.81,161.56,0.9,17769,50177700000,U,Parkland,6/7/2005
+56,5385,9,,,116.7149,-20.6550,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,0.15,6.78,337.54,0,18011,50180120000,U,Parkland,6/7/2005
+57,5386,10,,,116.7140,-20.6550,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,1.89,11.82,286.84,0.05,18011,50180120000,U,Parkland,6/7/2005
+58,5387,11,,,116.7127,-20.6549,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,5.06,16.16,186.66,0.9,17769,50177700000,U,Parkland,6/7/2005
+59,5388,12,,,116.7122,-20.6549,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,5.97,16.63,153.71,0.9,17769,50177700000,U,Parkland,6/7/2005
+60,5389,13,,,116.7118,-20.6549,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,6.68,17.86,124.37,0.99,17769,50177700000,U,Parkland,6/7/2005
+61,5390,14,,,116.7124,-20.6547,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,5.97,16.63,145.13,0.9,17769,50177700000,U,Parkland,6/7/2005
+62,5391,15,,,116.7129,-20.6546,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,5.06,16.16,177.86,0.9,17769,50177700000,U,Parkland,6/7/2005
+63,5392,16,,,116.7120,-20.6546,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,6.68,17.86,115.68,0.99,17769,50177700000,U,Parkland,6/7/2005
+64,5393,17,,,116.7154,-20.6544,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,1.15,7.14,294.59,0.05,18011,50180120000,U,Parkland,6/7/2005
+65,5394,18,,,116.7130,-20.6544,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,6.24,17.79,167.64,0.9,17769,50177700000,U,Parkland,6/7/2005
+66,5395,19,,,116.7125,-20.6544,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,7.23,0.00,134.58,0.9,17769,50177700000,U,Parkland,6/7/2005
+67,5397,21,,,116.7145,-20.6543,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,3.33,12.67,249.78,0.5,18011,50180120000,U,Parkland,6/7/2005
+68,5398,22,,,116.7127,-20.6542,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,6.24,17.79,128.70,0.9,17769,50177700000,U,Parkland,6/7/2005
+69,5399,23,,,116.7132,-20.6542,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,5.25,16.08,158.95,0.9,17769,50177700000,U,Parkland,6/7/2005
+70,5400,24,,,116.7155,-20.6542,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,1.15,7.14,267.33,0.05,18011,50180120000,U,Parkland,6/7/2005
+71,5401,25,,,116.7133,-20.6540,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,6.43,17.36,154.02,0.9,17769,50177700000,U,Parkland,6/7/2005
+72,5402,26,,,116.7129,-20.6540,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,7.43,19.07,121.58,0.99,17769,50177700000,U,Parkland,6/7/2005
+73,5403,27,,,116.7154,-20.6537,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,2.19,9.08,211.80,0.25,18169,50181700000,R,Agricultural,6/7/2005
+74,5404,28,,,116.7151,-20.6537,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,2.19,9.08,202.80,0.25,18169,50181700000,R,Agricultural,6/7/2005
+75,5405,29,,,116.7153,-20.6534,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,3.91,10.85,179.84,0.7,18169,50181700000,R,Agricultural,6/7/2005
+76,5406,30,,,116.7133,-20.6534,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,7.58,19.36,91.66,0.99,18169,50181700000,R,Agricultural,6/7/2005
+77,5407,31,,,116.6770,-20.6529,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,1.04,15.68,165.59,0.3,17767,50177680000,R,Parkland,6/7/2005
+78,5408,32,,,116.7144,-20.6529,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,7.59,19.11,127.57,0.9,18169,50181700000,R,Agricultural,6/7/2005
+79,5409,33,,,116.7147,-20.6528,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,6.70,15.75,115.19,0.99,18169,50181700000,R,Agricultural,6/7/2005
+80,5410,34,,,116.7148,-20.6528,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,6.70,15.75,109.27,0.99,18169,50181700000,R,Agricultural,6/7/2005
+81,5411,35,,,116.6768,-20.6527,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,1.04,15.68,138.20,0.3,17767,50177680000,R,Parkland,6/7/2005
+82,5412,36,,,116.7144,-20.6527,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,7.59,19.11,115.82,0.99,18169,50181700000,R,Agricultural,6/7/2005
+83,5413,37,,,116.7146,-20.6527,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,8.55,18.03,100.17,0.99,18169,50181700000,R,Agricultural,6/7/2005
+84,5414,38,,,116.7148,-20.6527,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,8.55,18.03,95.46,0.99,18169,50181700000,R,Agricultural,6/7/2005
+85,5415,39,,,116.7162,-20.6525,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,6.23,10.34,119.77,0.99,18169,50181700000,R,Agricultural,6/7/2005
+86,5416,40,,,116.7189,-20.6517,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,2.22,9.10,243.92,0.25,18011,50180120000,U,Parkland,6/7/2005
+87,5417,41,,,116.7187,-20.6513,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,11.14,16.92,193.91,0.9,18011,50180120000,U,Parkland,6/7/2005
+88,5418,42,,,116.7185,-20.6511,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,11.14,16.92,166.24,0.9,18169,50181700000,R,Agricultural,6/7/2005
+89,5420,44,,,116.7220,-20.6482,0,,,0,,,,DAMPIER,WA,,,,,0.00000000000,0,0.000,WAR,150,Residential,1,SD,Tiles,Double Brick,727.00,248867,PRESTIGE,1161,174150,2.31,1.18,17.70,168.75,0.3,18169,50181700000,R,Agricultural,6/7/2005
Index: /anuga_work/production/wa/karratha_2005/export_results.py
===================================================================
--- /anuga_work/production/wa/karratha_2005/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/karratha_2005/export_results.py	(revision 7411)
@@ -0,0 +1,32 @@
+import project, os
+
+from anuga.pyvolution.data_manager import sww2dem
+from anuga.pyvolution.ermapper_grids import read_ermapper_grid
+
+
+#name = project.outputname + '_0.0tide_notsunami'
+#name = project.outputname + '_0.0tide'
+
+name = project.outputname
+
+#sww2dem(name, basename_out = name + '_speed',
+sww2dem(name, basename_out = name + '_momentum',
+        #quantity = 'stage-elevation',  #Depth
+        quantity = '(xmomentum**2 + ymomentum**2)**0.5',  #Absolute momentum
+        #quantity = '((xmomentum/(stage-elevation))**2 + (ymomentum/(stage-elevation))**2)**0.5',  #Speed
+        cellsize = 50,
+        #cellsize = 500,
+        #cellsize = 10,        
+        #easting_min = 465646,
+        #easting_max = 480286,
+        #northing_min = 7712865,
+        #northing_max = 7724233,        
+        reduction = max,
+        verbose = True,
+        format = 'asc')
+
+
+#Check
+
+#data = read_ermapper_grid(name)
+#print 'Values from %s are in [%f, %f]' %(name, min(data.flat), max(data.flat))
Index: /anuga_work/production/wa/karratha_2005/get_cross_section.py
===================================================================
--- /anuga_work/production/wa/karratha_2005/get_cross_section.py	(revision 7411)
+++ /anuga_work/production/wa/karratha_2005/get_cross_section.py	(revision 7411)
@@ -0,0 +1,106 @@
+"""Read in sww file, read points along specified cross section and time and plot
+"""
+
+import project
+from anuga.pyvolution.util import file_function
+from anuga.pyvolution.coordinate_transforms.redfearn import degminsec2decimal_degrees, redfearn
+
+
+#swwfile = project.outputdir + project.basename + '.sww'
+#swwfile = project.outputname + '_0.0tide' + '.sww'
+swwfile = project.outputname + '.sww'
+swwfile = project.outputname + '_notsunami.sww'
+#swwfile = project.outputdir + 'karratha_100m_12m.sww'
+
+
+time = 0
+
+#E-W cross section 
+start = [468500, 7715177]
+end = [469500, 7715177]
+step = 1
+
+#Generate points (from west to east)
+points = []
+x = start[0]
+y = start[1]
+while x <= end[0]:
+    points.append( [x,y] )
+    x += step
+
+
+#Read model output
+from caching import cache
+f = cache(file_function, swwfile,
+          {'quantities': ['stage', 'elevation', 'xmomentum', 'ymomentum'],
+           'interpolation_points': points,
+           'verbose': True},
+          compression = False, 
+          dependencies = [swwfile],
+          verbose = True)
+
+#print f
+
+T = f.get_time()
+from math import sqrt
+for time in [T[0], T[0] + 10]:
+
+    abscissa = []
+    stages = []
+    elevations = []
+    momenta = []
+    
+    for k, p in enumerate(points):
+        #
+        #print time, k, p
+        w = f(time, point_id = k)[0]
+        z = f(time, point_id = k)[1]
+        uh = f(time, point_id = k)[2]
+        vh = f(time, point_id = k)[3]
+
+        abscissa.append( points[k][0] )
+        stages.append(w)
+        elevations.append(z) 
+        momenta.append( sqrt(uh*uh + vh*vh) )  #Absolute momentum
+
+    from pylab import *
+    
+    ion()
+    hold(False)
+
+    if elevations[0] < -10:
+        plot(abscissa, stages, '-b')
+    else:    
+        plot(abscissa, stages, '-b',
+             abscissa, elevations, '-k')
+    name = 'Cross section (time = %.1f)' %(time)
+    title(name)
+
+    title('%s (stage)' %name)
+    xlabel('time [s]')
+    ylabel('elevation [m]')    
+    legend(('Stage', 'Bed = %.1f' %elevations[0]),
+           shadow=True,
+           loc='upper right')
+    savefig('Cross_section_%d' %int(time))
+
+    raw_input('Next')
+
+
+    #Momentum plot
+    ion()
+    hold(False)
+    plot(abscissa, momenta, '-r')
+    title(name)
+
+    title('%s (momentum)' %name)
+    xlabel('time [s]')
+    ylabel('sqrt( uh^2 + vh^2 ) [m^2/s]')    
+    savefig('Cross_section_%d_momentum' %int(time))
+
+    raw_input('Next')
+    
+
+    
+show()
+
Index: /anuga_work/production/wa/karratha_2005/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/karratha_2005/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/karratha_2005/get_timeseries.py	(revision 7411)
@@ -0,0 +1,131 @@
+"""Read in sww file, interpolate at specified locations and plot time series
+
+"""
+
+import project
+from anuga.pyvolution.util import file_function
+from anuga.pyvolution.coordinate_transforms.redfearn import degminsec2decimal_degrees, redfearn
+from pylab import *
+
+
+    
+swwfile = project.outputname + '.sww'
+
+#MOST Boundary directly north of Legendre island
+lat = project.north
+lon = (project.p3[1] + project.p4[1])/2 
+z, easting, northing  = redfearn(lat, lon)
+
+#Time interval to plot
+tmin = 13000
+tmax = 21000
+
+def get_gauges_from_file(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+
+    gauges = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        lon = float(fields[4])
+        lat = float(fields[5])
+
+        z, easting, northing  = redfearn(lat, lon)        
+        gauges.append([easting, northing])
+
+    #Return gauges and raw data for subsequent storage    
+    return gauges, lines
+
+gauges, buildings = get_gauges_from_file(project.gauge_filename)
+
+gauges = [[easting, northing-10]]
+
+
+#Read model output
+quantities = ['stage', 'elevation', 'xmomentum', 'ymomentum']
+f = file_function(swwfile,
+                  quantities = quantities,
+                  interpolation_points = gauges,
+                  verbose = True,
+                  use_cache = True)
+
+
+               
+from math import sqrt
+N = len(gauges)
+for k, g in enumerate(gauges):
+    if k%((N+10)/10)==0:
+        print 'Doing row %d of %d' %(k, N)
+
+    model_time = []
+    stages = []
+    elevations = []
+    momenta = []
+
+    max_depth = 0
+    max_momentum = 0    
+    for i, t in enumerate(f.get_time()): # T is a list of times
+        #if tmin < t < tmax:
+        w = f(t, point_id = k)[0]
+        z = f(t, point_id = k)[1]
+        uh = f(t, point_id = k)[2]
+        vh = f(t, point_id = k)[3]        
+
+        m = sqrt(uh*uh + vh*vh)   #Absolute momentum
+        
+        model_time.append(t)        
+        stages.append(w)
+        elevations.append(z)  #Should be constant over time
+        momenta.append(m) 
+
+        if w-z > max_depth:
+            max_depth = w-z
+        if m > max_momentum:            
+            max_momentum = m    
+
+    
+
+    #Plot only those gauges that have been inundated by more than a threshold
+    #if max_depth < 0.2:
+    #    print 'Skipping gauge %d' %k
+    #    continue
+
+    ion()
+    hold(False)
+
+    if elevations[0] < -10:
+        plot(model_time, stages, '-b')
+    else:    
+        plot(model_time, stages, '-b',
+             model_time, elevations, '-k')
+    name = 'Gauge_%d: (%.1f, %.1f)' %(k, g[0], g[1])
+    title(name)
+
+    title('%s (stage)' %name)
+    xlabel('time [s]')
+    ylabel('elevation [m]')    
+    legend(('Stage', 'Bed = %.1f' %elevations[0]),
+           shadow=True,
+           loc='upper right')
+    savefig('Gauge_%d_stage' %k)
+
+    raw_input('Next')
+
+
+    #Momentum plot
+    ion()
+    hold(False)
+    plot(model_time, momenta, '-r')
+    title(name)
+
+    title('%s (momentum)' %name)
+    xlabel('time [s]')
+    ylabel('sqrt( uh^2 + vh^2 ) [m^2/s]')    
+    savefig('Gauge_%d_momentum' %k)
+    
+    raw_input('Next')
+    
+
+show()
+
Index: /anuga_work/production/wa/karratha_2005/process_buildings.py
===================================================================
--- /anuga_work/production/wa/karratha_2005/process_buildings.py	(revision 7411)
+++ /anuga_work/production/wa/karratha_2005/process_buildings.py	(revision 7411)
@@ -0,0 +1,150 @@
+"""Read in sww file, interpolate at specified locations and plot time series
+Additionally, store augmented building database with max inundation depths
+"""
+
+import project
+from anuga.pyvolution.util import file_function
+from anuga.pyvolution.coordinate_transforms.redfearn import degminsec2decimal_degrees, redfearn
+from pylab import *
+
+
+plot = False
+    
+swwfile = project.outputname + '.sww'
+
+#MOST Boundary directly north of Legendre island
+lat = project.north
+lon = (project.p3[1] + project.p4[1])/2 
+z, easting, northing  = redfearn(lat, lon)
+
+#Time interval to plot
+tmin = 13000
+tmax = 21000
+
+def get_gauges_from_file(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+
+    gauges = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        lon = float(fields[4])
+        lat = float(fields[5])
+
+        z, easting, northing  = redfearn(lat, lon)        
+        gauges.append([easting, northing])
+
+    #Return gauges and raw data for subsequent storage    
+    return gauges, lines
+
+gauges, buildings = get_gauges_from_file(project.gauge_filename)
+
+#Read model output
+quantities = ['stage', 'elevation', 'xmomentum', 'ymomentum']
+f = file_function(swwfile,
+                  quantities = quantities,
+                  interpolation_points = gauges,
+                  verbose = True,
+                  use_cache = True)
+
+#New header in spreadsheet
+buildings[0] = buildings[0].strip() +\
+               ',MAX INUNDATION DEPTH (m)' +\
+               ',MAX MOMENTUM (m^2/s)\n'            
+               
+from math import sqrt
+N = len(gauges)
+for k, g in enumerate(gauges):
+    if k%((N+10)/10)==0:
+        print 'Doing row %d of %d' %(k, N)
+
+    model_time = []
+    stages = []
+    elevations = []
+    momenta = []
+
+    max_depth = 0
+    max_momentum = 0    
+    for i, t in enumerate(f.get_time()):
+        w = f(t, point_id = k)[0]
+        z = f(t, point_id = k)[1]
+        uh = f(t, point_id = k)[2]
+        vh = f(t, point_id = k)[3]        
+
+        m = sqrt(uh*uh + vh*vh)   #Absolute momentum
+        
+        model_time.append(t)        
+        stages.append(w)
+        elevations.append(z)  #Should be constant over time
+        momenta.append(m) 
+
+        if w-z > max_depth:
+            max_depth = w-z
+        if m > max_momentum:            
+            max_momentum = m    
+
+    #Augment building data
+    buildings[k+1] = buildings[k+1].strip() +\
+                     ',%f' %max_depth +\
+                     ',%f\n' %max_momentum
+    
+    #print buildings[k]
+    
+    if plot is True:
+        #Plot only those gauges that have been inundated by more than a threshold
+        if max_depth < 0.2:
+            print 'Skipping gauge %d' %k
+            continue
+
+        #FIXME Reduce to tmin and tmax
+        #i0 = model_timefind
+    
+        ion()
+        hold(False)
+
+        if elevations[0] < -10:
+            plot(model_time, stages, '-b')
+        else:    
+            plot(model_time, stages, '-b',
+                 model_time, elevations, '-k')
+        name = 'Gauge_%d: (%.1f, %.1f)' %(k, g[0], g[1])
+        title(name)
+
+        title('%s (stage)' %name)
+        xlabel('time [s]')
+        ylabel('elevation [m]')    
+        legend(('Stage', 'Bed = %.1f' %elevations[0]),
+               shadow=True,
+               loc='upper right')
+        savefig('Gauge_%d_stage' %k)
+
+        raw_input('Next')
+
+
+        #Momentum plot
+        ion()
+        hold(False)
+        plot(model_time, momenta, '-r')
+        title(name)
+
+        title('%s (momentum)' %name)
+        xlabel('time [s]')
+        ylabel('sqrt( uh^2 + vh^2 ) [m^2/s]')    
+        savefig('Gauge_%d_momentum' %k)
+
+        raw_input('Next')
+    
+
+#Store new building file with max depths added
+
+FN = 'inundation_augmented_' + project.gauge_filename
+fid = open(FN, 'w')
+for line in buildings:
+    fid.write(line)
+fid.close()    
+
+
+if plot is True:    
+    show()
+
Index: /anuga_work/production/wa/karratha_2005/project.py
===================================================================
--- /anuga_work/production/wa/karratha_2005/project.py	(revision 7411)
+++ /anuga_work/production/wa/karratha_2005/project.py	(revision 7411)
@@ -0,0 +1,182 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+"""
+
+#Assume INUNDATIONHOME environment variable points to the parent directory of the source data
+
+from os import sep, environ
+from os.path import expanduser
+import sys
+
+#Making assumptions about the location of scenario data
+scenario_dir_name = 'karratha_tsunami_scenario_2005'
+#basename = 'karratha_100m'
+basename = 'elevation50m'
+boundary_basename = 'SU-AU'
+
+
+if sys.platform == 'win32':
+    home = environ["INUNDATIONHOME"]     #Sandpit's parent dir    
+    #home = '..\..\..\..\..'     #Sandpit's parent dir
+else:    
+    home = expanduser('~')
+
+
+#Derive subdirectories and filenames
+meshdir = home+sep+scenario_dir_name+sep+'meshes'+sep
+datadir = home+sep+scenario_dir_name+sep+'topographies'+sep
+outputdir = home+sep+scenario_dir_name+sep+'output'+sep
+boundarydir = home+sep+scenario_dir_name+sep+'boundaries'+sep
+
+meshname = meshdir + basename
+demname = datadir + basename
+boundaryname = boundarydir + boundary_basename
+outputname = outputdir + basename  #Used by post processing
+
+#gauge_filename = 'all_bld_ind.csv'
+gauge_filename = 'karratha_buildings_23112005.csv'
+
+
+#Georeferencing
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+
+#Origin of existing dem (FIXME: Temporary measure)
+#mesh_origin = (50, 421544.35127423, 7677669.5257159)  #250m
+mesh_origin = (50, 420468.31429902, 7677669.5257159)  #100m
+
+
+#south = degminsec2decimal_degrees(-20,45,0)
+#north = degminsec2decimal_degrees(-20,15,0)
+#west = degminsec2decimal_degrees(116,30,0)
+#east = degminsec2decimal_degrees(117,0,0)
+
+south = degminsec2decimal_degrees(-20,55,0)
+north = degminsec2decimal_degrees(-20,15,0)
+west = degminsec2decimal_degrees(116,17,0)
+east = degminsec2decimal_degrees(117,10,0)
+
+p0 = [south, degminsec2decimal_degrees(116,32,0)]
+p1 = [south, west]
+p2 = [degminsec2decimal_degrees(-20,23,0), west]
+p3 = [north, degminsec2decimal_degrees(116,45,0)]
+p4 = [north, degminsec2decimal_degrees(117,0,0)]
+p5 = [p2[0], degminsec2decimal_degrees(117,8,0)]
+p6 = [degminsec2decimal_degrees(-20,30,0), east]
+p7 = [degminsec2decimal_degrees(-20,38,0), east]
+p8 = [south, east]
+    
+polygon = [p0, p1, p2, p3, p4, p5, p6, p7, p8]
+refzone = 50
+
+
+#Interior regions
+karratha_south = degminsec2decimal_degrees(-20,44,0)
+karratha_north = degminsec2decimal_degrees(-20,42,0)
+karratha_west = degminsec2decimal_degrees(116,48,0)
+karratha_east = degminsec2decimal_degrees(116,53,30)
+
+k0 = [karratha_south, karratha_west]
+k1 = [karratha_south, karratha_east]
+k2 = [karratha_north, karratha_east]
+k3 = [karratha_north, karratha_west]    
+
+karratha_polygon = [k0, k1, k2, k3]
+
+
+#Interior regions
+dampier_south = degminsec2decimal_degrees(-20,40,0)
+dampier_north = degminsec2decimal_degrees(-20,38,10)
+dampier_west = degminsec2decimal_degrees(116,43,0)
+dampier_east = degminsec2decimal_degrees(116,45,0)
+
+d0 = [dampier_south, dampier_west]
+d1 = [dampier_south, dampier_east]
+d2 = [dampier_north, dampier_east]
+d3 = [dampier_north, dampier_west]    
+
+dampier_polygon = [d0, d1, d2, d3]
+
+
+#Interior regions
+refinery_south = degminsec2decimal_degrees(-20,37,50)
+refinery_north = degminsec2decimal_degrees(-20,36,0)
+refinery_west = degminsec2decimal_degrees(116,44,0)
+refinery_east = degminsec2decimal_degrees(116,46,10)
+
+d0 = [refinery_south, refinery_west]
+d1 = [refinery_south, refinery_east]
+d2 = [refinery_north, refinery_east]
+d3 = [refinery_north, refinery_west]    
+
+refinery_polygon = [d0, d1, d2, d3]
+
+
+#Interior region around 468899, 7715177:
+#lat (-20, 39, 44.93753), lon (116, 42, 5.09106)
+
+point_south = degminsec2decimal_degrees(-20,39,46)
+point_north = degminsec2decimal_degrees(-20,39,42)
+point_west = degminsec2decimal_degrees(116,42,0)
+point_east = degminsec2decimal_degrees(116,42,10)
+
+d0 = [point_south, point_west]
+d1 = [point_south, point_east]
+d2 = [point_north, point_east]
+d3 = [point_north, point_west]    
+
+point_polygon = [d0, d1, d2, d3]
+
+
+#Neils areas around interesting points
+neil1_point1 = [degminsec2decimal_degrees(-20,35,34),
+                degminsec2decimal_degrees(116,45,18)]
+neil1_point2 = [degminsec2decimal_degrees(-20,36,15),
+                degminsec2decimal_degrees(116,46,18)]
+neil1_point3 = [degminsec2decimal_degrees(-20,35,9),
+                degminsec2decimal_degrees(116,47,17)]
+neil1_point4 = [degminsec2decimal_degrees(-20,34,26),
+                degminsec2decimal_degrees(116,46,17)]
+
+neil1_polygon = [neil1_point1, neil1_point2, neil1_point3, neil1_point4]
+
+
+
+neil2_point1 = [degminsec2decimal_degrees(-20,39,36),
+                degminsec2decimal_degrees(116,41,33)]
+neil2_point2 = [degminsec2decimal_degrees(-20,40,10),
+                degminsec2decimal_degrees(116,42,13)]
+neil2_point3 = [degminsec2decimal_degrees(-20,38,39),
+                degminsec2decimal_degrees(116,43,49)]
+neil2_point4 = [degminsec2decimal_degrees(-20,38,5),
+                degminsec2decimal_degrees(116,43,9)]
+
+neil2_polygon = [neil2_point1, neil2_point2, neil2_point3, neil2_point4]
+
+
+
+
+#Withnell bay
+wb_point1 = [degminsec2decimal_degrees(-20,35,34),
+                degminsec2decimal_degrees(116,45,18)]
+wb_point2 = [degminsec2decimal_degrees(-20,36,15),
+                degminsec2decimal_degrees(116,46,18)]
+wb_point3 = [degminsec2decimal_degrees(-20,35,9),
+                degminsec2decimal_degrees(116,47,17)]
+wb_point4 = [degminsec2decimal_degrees(-20,34,26),
+                degminsec2decimal_degrees(116,46,17)]
+
+wb_polygon = [wb_point1, wb_point2, wb_point3, wb_point4]
+
+
+
+
+#Larger Withnell bay
+lwb_point1 = [degminsec2decimal_degrees(-20,35,59),
+                degminsec2decimal_degrees(116,42,00)]
+lwb_point2 = [degminsec2decimal_degrees(-20,36,50),
+                degminsec2decimal_degrees(116,46,50)]
+lwb_point3 = [degminsec2decimal_degrees(-20,34,00),
+                degminsec2decimal_degrees(116,47,39)]
+lwb_point4 = [degminsec2decimal_degrees(-20,33,00),
+                degminsec2decimal_degrees(116,42,50)]
+
+lwb_polygon = [lwb_point1, lwb_point2, lwb_point3, lwb_point4]
Index: /anuga_work/production/wa/karratha_2005/run_karratha.py
===================================================================
--- /anuga_work/production/wa/karratha_2005/run_karratha.py	(revision 7411)
+++ /anuga_work/production/wa/karratha_2005/run_karratha.py	(revision 7411)
@@ -0,0 +1,203 @@
+"""Script for running a tsunami inundation scenario for Karratha, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.outputdir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and boundary data obtained from a tsunami simulation done with MOST.
+
+Ole Nielsen, GA - 2005
+"""
+
+#tide = 0.75   #HMWS estimate by Colin French, GA
+tide = 0       #HMW 
+
+
+import os
+import time
+
+
+from anuga.pyvolution.shallow_water import Domain, Reflective_boundary, File_boundary,\
+     Dirichlet_boundary, Time_boundary, Transmissive_boundary
+from anuga.pyvolution.data_manager import convert_dem_from_ascii2netcdf,\
+     dem2pts, ferret2sww
+from anuga.pyvolution.pmesh2domain import pmesh_to_domain_instance 
+from caching import cache
+import project
+
+#Data preparation
+#Convert ASC 2 DEM 2 PTS using source data and store result in source data
+demname = project.demname
+
+cache(convert_dem_from_ascii2netcdf, demname, {'verbose': True},
+      dependencies = [demname + '.asc'],
+      verbose = True)
+      #evaluate = True)
+
+cache(dem2pts, demname, {'verbose': True},
+      dependencies = [demname + '.dem'],      
+      verbose = True)
+
+
+#Convert MOST boundary
+source_dir = project.boundarydir
+
+from anuga.pyvolution.data_manager import ferret2sww
+
+south = project.south 
+north = project.north
+west = project.west
+east = project.east
+
+
+#Howard: Ignore this
+#cache(ferret2sww,
+#      (source_dir+project.boundary_basename,
+#       project.boundary_basename), 
+#      {'verbose': True,
+#       'minlat': south-1,
+#       'maxlat': north+1,
+#       'minlon': west-1,
+#       'maxlon': east+1,
+#       'origin': project.mesh_origin,
+#       'mean_stage': tide,
+#       'zscale': 1,                 #Enhance tsunami
+#       'fail_on_NaN': False,
+#       'inverted_bathymetry': True},
+#      #evaluate = True,
+#      verbose = True)
+##FIXME: Dependencies
+
+    
+#ferret2sww(source_dir+project.boundary_basename,
+#           project.boundary_basename, 
+#           verbose=True,
+#           minlat=south-1, maxlat=north+1,
+#           minlon=west-1, maxlon=east+1,
+#           origin = project.mesh_origin,
+#           mean_stage = tide,
+#           zscale = 1,
+#           fail_on_NaN = False,
+#           inverted_bathymetry = True)
+
+
+#Create Triangular Mesh
+from anuga.pmesh.create_mesh import create_mesh_from_regions
+
+resolution = 4000
+interior_regions = [#[project.karratha_polygon, 25000],
+                    #[project.dampier_polygon, 2000],
+                    #[project.refinery_polygon, 2000],
+                    #[project.point_polygon, 2000]]
+                    [project.neil1_polygon, resolution],
+                    [project.neil2_polygon, 64000]]
+
+#For visualisation
+#interior_regions = [[project.wb_polygon, 400],
+#                    [project.lwb_polygon, 8000]]
+
+  
+                    
+meshname = project.meshname + '_%d.msh' %resolution
+m = cache(create_mesh_from_regions,
+          project.polygon,
+          {'boundary_tags': {'back': [7, 8], 'side': [0, 6],
+                             'ocean': [1, 2, 3, 4, 5]},
+           'resolution': 100000,
+           #'filename': project.meshname + '.msh',           
+           'filename': meshname,
+           'interior_regions': interior_regions},
+          #verbose = True)          
+          verbose = True,
+          evaluate = True)
+
+
+#Setup domain
+
+#domain = cache(pmesh_to_domain_instance, (meshname, Domain),
+#               dependencies = [meshname],                     
+#               verbose = True)
+
+
+#This is how it will be Howard!
+domain = pmesh_to_domain_instance(meshname, Domain, use_cache=True)
+
+
+domain.set_name(project.basename + '_%d' %resolution)
+domain.set_datadir(project.outputdir)
+domain.store = True
+#domain.smooth = False
+
+
+#domain.quantities_to_be_stored = ['stage', 'xmomentum', 'ymomentum']
+domain.quantities_to_be_stored = ['stage']
+        
+print 'Number of triangles = ', len(domain)
+print 'The extent is ', domain.get_extent()
+
+
+
+#Setup Initial Conditions
+domain.set_quantity('friction', 0)
+domain.set_quantity('stage', tide)
+domain.set_quantity('elevation',
+                    filename = demname + '.pts',
+                    use_cache = True,
+                    verbose = True)
+
+
+
+#Setup Boundary Conditions
+print domain.get_boundary_tags()
+
+
+#File boundary.
+#
+#Takes a arbitrary simulation output in the form of an sww file and use it to provide a boundary.
+#Values at every boundary point at every timestep are established by interpolation from the
+#values in the sww boundary file.
+#Boundary values at arbitrary timesteps needed in evolve are obtained by linear interpolation
+#
+#See also docstring for File_boundary in generic_boundary_conditions.py
+#
+Bf = File_boundary(project.boundary_basename + '.sww', domain, verbose = True)
+#domain.starttime = 3000  #Obtained from MOST
+domain.starttime = 0  #Obtained from MOST
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_boundary(domain)
+Bd = Dirichlet_boundary([tide,0,0])
+Bw = Time_boundary(domain=domain,
+                   f=lambda t: [(60<t<660)*4, 0, 0])
+
+
+domain.set_boundary( {'back': Br,'side': Bd, 'ocean': Bf} ) #MOST tsunami
+
+#domain.set_boundary( {'back': Bd,'side': Bd, 'ocean': Bd} )  #Nothing
+
+
+#Evolve
+import time
+t0 = time.time()
+
+#for t in domain.evolve(yieldstep = 1000, finaltime = 14000):
+#    domain.write_time()
+#    domain.write_boundary_statistics(tags = 'ocean') #quantities = 'stage')
+
+#for t in domain.evolve(yieldstep = 20, finaltime = 15000,
+#                       skip_initial_step = True):
+#    domain.write_time()
+#    domain.write_boundary_statistics(tags = 'ocean') #quantities = 'stage')
+    
+#for t in domain.evolve(yieldstep = 10, finaltime = 40000,
+#                       skip_initial_step = True):
+#    domain.write_time()
+#    domain.write_boundary_statistics(tags = 'ocean') #quantities = 'stage')
+
+for t in domain.evolve(yieldstep = 60, finaltime = 40000):
+#                       skip_initial_step = True):
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'ocean') #quantities = 'stage')       
+
+print 'That took %.2f seconds' %(time.time()-t0)
Index: /anuga_work/production/wa/onslow_2006/MOST_timeseries.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/MOST_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/MOST_timeseries.py	(revision 7411)
@@ -0,0 +1,104 @@
+"""
+Generate latex output comparing time series of given sww files
+
+Inputs:
+
+production dirs: dictionary of output directories with a
+                 association to simulation, eg 50m boundary, 100m boundary
+
+gauge_map:       graphical output from make_gauges.py
+
+Outputs:
+
+* latex output to generate figures for report 
+* figures used for report stored in the report_figure directory
+NOTE, this directory will need to be committed, as well as
+the latex files.
+
+June 2006                    
+"""
+
+from os import sep, getcwd, F_OK, access, mkdir
+import project
+from anuga.pyvolution.util import sww2timeseries, get_gauges_from_file
+
+# User defined inputs
+production_dirs = {'20060515_001733': '100m boundary',
+                   '20060530_102753': '50m boundary'}#,
+                   #'MOST': 'MOST'}
+
+gauge_map = 'boundarycomparison.png'
+
+# Create sections and graphs for each designated production directory
+latex_output = []
+swwfiles = {}
+for label_id in production_dirs.keys():
+    
+    file_loc = project.outputdir + label_id + sep
+    swwfile = file_loc + project.basename + '.sww'
+    if label_id == 'MOST':
+        swwfile = project.boundarydir + project.boundary_basename + '.sww'
+    swwfiles[swwfile] = label_id
+
+print 'swwfiles', swwfiles
+
+texname, vec = sww2timeseries(swwfiles,
+                              project.gauges50,#project.gauge_comparison,
+                              production_dirs,
+                              report = True,
+                              reportname = 'latexoutput_MOST_ANUGA_comparison',
+                              plot_quantity = ['stage', 'speed'],
+                              generate_fig = True,
+                              surface = False,
+                              time_min = None,
+                              time_max = None,
+                              title_on = False,
+                              verbose = True)
+
+latex_output.append(texname)
+
+from shutil import copy, move
+copy ('report' + sep + texname + '.tex', project.comparereportdir + sep + texname + '.tex')
+
+# Start report generation
+input_name = project.comparereportdir + sep + 'MOST_ANUGA_comparison_onslow.tex'
+fid = open(input_name, 'w')
+
+s = '\\begin{figure}[hbt] \n \centerline{ \includegraphics[width=150mm, height=100mm]{../report_figures/%s}}' %gauge_map
+fid.write(s)
+
+s  = """
+\caption{Point locations used to compare MOST and ANUGA for Onslow region.}  
+\label{fig:comparisonpoints}
+\end{figure}
+"""
+fid.write(s)
+    
+s = '\input{%s} \n \clearpage \n \n' %latex_output[0]
+fid.write(s)
+
+
+# Generate latex output for location points
+#s = '\\begin{table} \label{table:MOSTlocationsonslow} \n'
+#fid.write(s)
+#s = '\caption{Defined point locations for comparison study for Onslow region.}' 
+#fid.write(s)
+#s = """
+#\\begin{center}
+#\\begin{tabular}{|l|l|l|l|}\hline
+#\\bf{Point Name} & \\bf{Easting} & \\bf{Northing} & \\bf{Elevation (m)}\\\\ \hline
+#"""
+#fid.write(s)
+
+#for i, thisvec in enumerate(vec):
+#    name = thisvec[0]
+#    east = thisvec[1]
+#    north = thisvec[2]
+#    elev = thisvec[3]
+#    s = '%s & %.2f & %.2f & %.2f \\\\ \hline \n' %(name, east, north, elev)
+#    fid.write(s)
+#    for which_one in plot_quantity:
+#        move ('report_figures' + sep + 'gauge'+name.replace(' ','')+which_one+'.png', project.comparereportfigdir)
+
+#s = '\\end{tabular} \n  \end{center} \n \end{table} \n \n'
+#fid.write(s)
Index: /anuga_work/production/wa/onslow_2006/aticket160_project.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/aticket160_project.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/aticket160_project.py	(revision 7411)
@@ -0,0 +1,221 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+"""
+
+from os import sep, environ, getenv, getcwd,umask
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon, number_mesh_triangles
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees, convert_from_latlon_to_utm
+from anuga.utilities.system_tools import get_user_name, get_host_name
+
+# file and system info
+#---------------------------------
+codename = 'project.py'
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent dir   
+user = get_user_name()
+host = get_host_name()
+#needed when running using mpirun, mpirun doesn't inherit umask from .bashrc
+umask(002)
+
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+#home += sep +'data'
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+
+#tide = -1.5
+#tide = 0.0
+tide = 1.5
+
+#Maybe will try to make project a class to allow these parameters to be passed in.
+res_factor= 1000000000000000
+alpha = 0.1
+friction=0.01
+time_thinning=4
+dir_comment='_DSG_'+str(tide)+'_'+str(user)
+starttime=3600
+yieldstep=60
+finaltime=25000
+ 
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'onslow'
+scenario = 'onslow_tsunami_scenario_2006'
+
+# onshore data provided by WA DLI
+onshore_name = 'onslow_onshore_30m_dted2' # original
+onshore_name1 = 'onslow_onshore_20m_dli' # original
+
+# AHO + DPI data + colin French coastline
+coast_name = 'onslow_coast'
+islands_name = 'onslow_islands_dted2'
+offshore_name = 'onslow_offshore_points'
+offshore1_name = '1'
+offshore2_name = '2'
+
+#final topo name
+combined_name ='onslow_combined_elevation'
+combined_smaller_name = 'onslow_combined_elevation_small'
+combined_smallest_name = 'onslow_combined_elevation_smallest'
+
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+#anuga_dir_name = temp_dir + temp_time+sep
+
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'070112'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+topographies_time_dir = topographies_dir+build_time+sep
+
+
+# input topo file location
+onshore_in_dir_name = topographies_in_dir + onshore_name
+coast_in_dir_name = topographies_in_dir + coast_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+offshore1_in_dir_name = topographies_in_dir + offshore1_name
+offshore2_in_dir_name = topographies_in_dir + offshore2_name
+
+onshore_dir_name = topographies_dir + onshore_name
+coast_dir_name = topographies_dir + coast_name
+offshore_dir_name = topographies_dir + offshore_name
+offshore1_dir_name = topographies_dir + offshore1_name
+offshore2_dir_name = topographies_dir + offshore2_name
+
+#final topo files
+combined_dir_name = topographies_dir + combined_name
+combined_time_dir_name = topographies_time_dir + combined_name
+#combined_smaller_dir_name = topographies_dir + combined_smaller_name
+#combined_smallest_dir_name = topographies_dir + combined_smallest_name
+#combined_time_dir_final_name = topographies_time_dir + combined_final_name
+
+meshes_dir = anuga_dir+'meshes'+sep
+meshes_dir_name = meshes_dir + scenario_name
+
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+
+boundaries_source = ''
+boundaries_name = 'onslow_3854_17042007'
+
+#boundaries locations
+#boundaries_in_dir = anuga_dir+'boundaries'+sep
+boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'1_10000'+sep
+boundaries_in_dir_name = boundaries_in_dir + boundaries_name
+boundaries_dir = anuga_dir+'boundaries'+sep
+boundaries_dir_name = boundaries_dir + boundaries_name
+
+#output locations
+output_dir = anuga_dir+'outputs'+sep
+output_build_time_dir = output_dir+build_time+sep
+output_run_time_dir = output_dir +run_time+dir_comment+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+gauges_dir = anuga_dir+'gauges'+sep
+
+gauges_dir_name = gauges_dir + 'gauge_location_onslow.csv'
+gauges_dir_name_bindi = gauges_dir + 'gauge_location_bindi.csv'
+gauges_comparison_dir_name_50 = gauges_dir + '50_gauges.xya'
+gauges_comparison_dir_name = gauges_dir + 'MOST_comparison_gauges.xya'
+gauges_comparison_dir_name_3d = gauges_dir + 'MOST_comparison_gauges_3d.xya'
+
+community_filename = gauges_dir + 'CHINS_v2.csv'
+community_scenario = gauges_dir + 'community_onslow.csv'
+buildings_filename = gauges_dir + 'Onslow_res_Project.csv'
+buildings_filename_out = 'Onslow_res_Project_modified.csv'
+###############################
+# Domain definitions
+###############################
+
+south_boundary = degminsec2decimal_degrees(-22,15,0)
+north_boundary = degminsec2decimal_degrees(-20,30,0)
+west_boundary = degminsec2decimal_degrees(114,15,0)
+east_boundary = degminsec2decimal_degrees(115,50,0)
+
+#Updated Main Domain of Onslow: first run NB 6/4/06
+d0 = [310000, 7690000]
+d1 = [280000, 7690000]
+d2 = [270000, 7645000]
+d3 = [240000, 7625000]
+d4 = [270000, 7580000]
+d5 = [300000, 7590000]
+d6 = [340000, 7610000]
+
+poly_all = [d0, d1, d2, d3, d4, d5, d6]
+res_poly_all = 100000*res_factor
+print 'bounding polygon area', polygon_area(poly_all)/1000000.0
+#Interior region - Onslow town
+
+#for visualisation
+#i0 = [304000, 7609000]
+#i1 = [301500, 7605000]
+#i2 = [304000, 7603000]
+#i3 = [307000, 7602000]
+#i4 = [309000, 7603000]
+#i5 = [311000, 7607000]
+
+i0 = [304000, 7607000]
+i1 = [302000, 7605000]
+i2 = [304000, 7603000]
+i3 = [307000, 7602000]
+i4 = [309000, 7603000]
+i5 = [307000, 7606000]
+poly_onslow = [i0, i1, i2, i3, i4, i5]
+res_onslow = 500*res_factor
+print 'onslow polygon area', polygon_area(poly_onslow)/1000000.0
+
+#Thevenard Island
+j0 = [294000, 7629000]
+j1 = [285000, 7625000]
+j2 = [294000, 7621000]
+j3 = [299000, 7625000]
+poly_thevenard = [j0, j1, j2, j3]
+res_thevenard = 2500*res_factor
+print 'thevenard polygon area', polygon_area(poly_thevenard)/1000000.0
+
+#med res around onslow
+l0 = [300000, 7610000]
+l1 = [285000, 7600000]
+l2 = [300000, 7597500]
+l3 = [310000, 7600000]
+l4 = [315000, 7610000]
+poly_coast = [l0, l1, l2, l3, l4]
+res_coast = 2500*res_factor
+print 'coast polygon area', polygon_area(poly_coast)/1000000.0
+
+#general coast and local area to onslow region
+m0 = [270000, 7581000]
+m1 = [300000, 7591000]
+m2 = [339000, 7610000]
+m3 = [330000, 7630000]
+m4 = [290000, 7640000]
+m5 = [260000, 7600000]
+poly_region = [m0, m1, m2, m3, m4, m5]
+res_region = 20000*res_factor
+print 'region polygon area', polygon_area(poly_region)/1000000.0
+
+interior_regions = [[poly_onslow,res_onslow],[poly_coast,res_coast],
+                    [poly_region,res_region]
+#                   ,[poly_thevenard,res_thevenard]
+                    ]
+
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+
+print 'min number triangles', trigs_min
+
+
+###################################################################
+# Clipping regions for export to asc and regions for clipping data
+###################################################################
+
+poly_mainland = read_polygon(polygons_dir+'InitialCondition_points.csv')
+
+# region to export
+e_min_area = 300000
+e_max_area = 310000
+n_min_area = 7600000
+n_max_area = 7610000
+
Index: /anuga_work/production/wa/onslow_2006/boundary_plot.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/boundary_plot.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/boundary_plot.py	(revision 7411)
@@ -0,0 +1,161 @@
+"""Read in csv files and plot time series
+
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, hold, axis, close, figure, legend
+from os import sep
+ 
+time_dir1 = '20070608_060316_run_final_1.5_onslow_nbartzis'# HAT onslow
+time_dir2 = '20070608_062811_run_final_1.5_exmouth_nbartzis'# HAT exmouth
+directory = project.outputdir
+boundary_dir=project.boundaries_in_dir
+
+def get_time_series_from_file(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    t = []
+    stage = []
+    depth = []
+    speed = []
+    momentum = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        t.append((float(fields[0])/3600.0+5000./3600.))
+        stage.append(float(fields[1]))
+        depth.append(float(fields[1])-float(fields[4]))
+        speed.append(float(fields[3]))
+        momentum.append(float(fields[2]))        
+    return t, stage, depth, speed, momentum
+
+max_st = max_sp = max_mom = min_st = min_sp = min_mom = max_t = 0.
+count = j = -1
+
+#find maximums for axis for plots
+for i in range(47*2):  #could alter get_all_swwfiles to get all file extension and get csv files??
+    count += 1
+    t = str(count/2.).rfind('.')
+    if str(count/2.)[t+1] == str(0):
+        j += 1
+        extra = 'gauges_time_series_%d.csv' %(j)
+        filename = directory + time_dir2 + sep + extra
+    else:
+        extra = 'gauges_time_series_%d.csv' %(j)
+#        filename = directory + time_dir2 + sep + extra
+        filename = boundary_dir + sep + extra
+
+    t, stage, depth, speed, momentum = get_time_series_from_file(filename)
+    if max(t) > max_t: max_t = max(t)
+    if max(stage) > max_st: max_st = max(stage)
+    if max(speed) > max_sp: max_sp = max(speed)
+    if max(momentum) > max_mom: max_mom = max(momentum)
+    if min(stage) < min_st: min_st = min(stage)
+    if min(speed) < min_sp: min_sp = min(speed)
+    if min(momentum) < min_mom: min_mom = min(momentum)
+ 
+stage_axis = ([5000./3600.,max_t, min_st, max_st])
+speed_axis = ([5000/3600.,max_t, min_sp, max_sp])
+mom_axis = ([5000/3600.,max_t, min_mom, max_mom])
+
+ion()
+"""  
+hold(False)
+
+for i, filename in enumerate(filenames):
+    t, stage, depth, speed, momentum = get_time_series_from_file(filename)
+
+    i1 = filename.rfind('gauges')
+    i2 = filename.rfind('csv')
+    name = filename[i1:i2-1]
+    loc = filename.rfind('1.5') + 4
+    if filename[loc] is 'o': community = 'onslow'
+    if filename[loc] is 'e': community = 'exmouth'
+
+    figure(1)
+    plot(t, stage, '-b', linewidth=1)
+    xlabel('time (hour)')
+    ylabel('wave height (m)')
+    axis(stage_axis)
+    figname = 'stage_%s_%s.png' %(name,community)
+    savefig(figname)
+
+    figure(2)
+    plot(t, speed, '-b', linewidth=1)
+    xlabel('time (hour)')
+    ylabel('speed (m/s)')
+    axis(speed_axis)
+    figname = 'speed_%s_%s.png' %(name,community)
+    savefig(figname)
+
+    figure(3)
+    plot(t, momentum, '-b', linewidth=1)
+    xlabel('time (hour)')
+    ylabel('momentum (m^2/sec)')
+    axis(mom_axis)
+    figname = 'mom_%s_%s.png' %(name,community)
+    savefig(figname)
+
+close('all')
+"""
+
+hold(True)
+count = j = -1
+figcount = 0
+cstr = ['b', 'r']
+
+for i in range(4*2):
+
+    count += 1
+    t = str(count/2.).rfind('.')
+    if str(count/2.)[t+1] == str(0):
+        j += 1
+        ii = 0
+        extra = 'gauges_time_series_%d.csv' %(j)
+        filename = directory + time_dir2 + sep + extra
+    else:
+        ii = 1
+        extra = 'gauges_time_series_%d.csv' %(j)
+#        filename = directory + time_dir2 + sep + extra
+        filename = boundary_dir + sep + extra
+        
+    t, stage, depth, speed, momentum = get_time_series_from_file(filename)
+
+    i1 = filename.rfind('gauges')
+    i2 = filename.rfind('csv')
+    name = filename[i1:i2-1]
+    loc = filename.rfind('1.5') + 4
+#    if filename[loc] is 'o': community = 'onslow'
+#    if filename[loc] is 'e': community = 'exmouth'
+
+    print 'hello', community, filename
+    figure(100+j)
+    plot(t, stage, c = cstr[ii], linewidth=1)
+    xlabel('time (hour)')
+    ylabel('wave height (m)')
+    axis(stage_axis)
+    legend(('Onslow','Exmouth'),loc='upper right')
+    figname = 'stage_%s_both.png' %(name)
+    savefig(figname)
+
+    figure(200+j)
+    plot(t, speed, c = cstr[ii], linewidth=1)
+    xlabel('time (hour)')
+    ylabel('speed (m/s)')
+    axis(speed_axis)
+    legend(('Onslow','Exmouth'),loc='upper right')
+    figname = 'speed_%s_both.png' %(name)
+    savefig(figname)
+
+    figure(300+j)
+    plot(t, momentum, c = cstr[ii], linewidth=1)
+    xlabel('time (hour)')
+    ylabel('momentum (m^2/sec)')
+    axis(mom_axis)
+    legend(('Onslow','Exmouth'),loc='upper right')
+    figname = 'mom_%s_both.png' %(name)
+    savefig(figname)
+  
+close('all')
+
Index: /anuga_work/production/wa/onslow_2006/build_onslow.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/build_onslow.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/build_onslow.py	(revision 7411)
@@ -0,0 +1,161 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project_urs.output_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.geospatial_data.geospatial_data import *
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, copy_code_files
+from anuga_parallel.parallel_abstraction import get_processor_name
+
+# Application specific imports
+import project_urs   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project_urs.output_build_time_dir,__file__, 
+               dirname(project_urs.__file__)+sep+ project_urs.__name__+'.py' )
+
+start_screen_catcher(project_urs.output_build_time_dir)
+#print "Processor Name:",get_processor_name()
+
+print 'USER:    ', project_urs.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print"project_urs.combined_dir_name",project_urs.combined_dir_name
+
+# topography directory filenames
+onshore_in_dir_name = project_urs.onshore_in_dir_name
+coast_in_dir_name = project_urs.coast_in_dir_name
+offshore_in_dir_name = project_urs.offshore_in_dir_name
+offshore1_in_dir_name = project_urs.offshore1_in_dir_name
+offshore2_in_dir_name = project_urs.offshore2_in_dir_name
+
+onshore_dir_name = project_urs.onshore_dir_name
+coast_dir_name = project_urs.coast_dir_name
+offshore_dir_name = project_urs.offshore_dir_name
+offshore1_dir_name = project_urs.offshore1_dir_name
+offshore2_dir_name = project_urs.offshore2_dir_name
+'''
+# creates DEM from asc data
+print "creates DEMs from asc data"
+convert_dem_from_ascii2netcdf(onshore_in_dir_name,
+                              basename_out=onshore_dir_name,
+                              use_cache=True, verbose=True)
+
+convert_dem_from_ascii2netcdf(offshore1_in_dir_name,
+                              basename_out=offshore1_dir_name,
+                              use_cache=True, verbose=True)
+convert_dem_from_ascii2netcdf(offshore2_in_dir_name,
+                              basename_out=offshore2_dir_name,
+                              use_cache=True, verbose=True)
+
+#creates pts file for onshore DEM
+print "creates pts file for onshore DEM"
+dem2pts(onshore_dir_name, use_cache=True, verbose=True)
+
+#creates pts file for clipped DEMs
+dem2pts(offshore1_dir_name,
+        basename_out=offshore1_dir_name,
+        use_cache=True, verbose=True)
+dem2pts(offshore2_dir_name,
+        basename_out=offshore2_dir_name,
+        use_cache=True, verbose=True)
+
+print'create Geospatial onshore objects from topographies'
+#print'create Geospatial coastal objects from topographies'
+#print'create Geospatial nickel bay objects from topographies'
+#print'create Geospatial clipped TIN offshore objects from topographies'
+#print'create Geospatial offshore objects from topographies'
+G = Geospatial_data(file_name = onshore_dir_name + '.pts') +\
+    Geospatial_data(file_name = coast_in_dir_name + '.txt') +\
+    Geospatial_data(file_name = offshore_in_dir_name + '.txt') +\
+    Geospatial_data(file_name = offshore1_dir_name + '.pts') +\
+    Geospatial_data(file_name = offshore2_dir_name + '.pts')
+     
+
+print'add all geospatial objects'
+#G = G1 + G2 + G3 + G4 + G_off
+
+print'clip combined geospatial object by bounding polygon'
+G_clipped = G.clip(project_urs.poly_all)
+#FIXME: add a clip function to pts
+#print'shape of clipped data', G_clipped.get_data_points().shape
+
+print'export combined DEM file'
+if access(project_urs.topographies_dir,F_OK) == 0:
+    mkdir (project_urs.topographies_dir)
+G_clipped.export_points_file(project_urs.combined_dir_name + '.pts')
+#G_clipped.export_points_file(project_urs.combined_dir_name + '.txt')
+
+print'split combined data set'
+G_small, G_other = G_clipped.split(0.1, True)
+
+print'export split DEM file'
+G_small.export_points_file(project_urs.combined_dir_name + '_small' + '.pts')
+G_other.export_points_file(project_urs.combined_dir_name + '_other' + '.pts')
+
+print 'start reading:',project_urs.combined_smaller_dir_name + '.txt'
+G = Geospatial_data(file_name = project_urs.combined_smaller_dir_name + '.txt')
+print 'start split'
+G_smallest, G_other = G.split(0.1,True)
+
+print 'start export',project_urs.combined_smallest_dir_name + '.txt'
+#G.export_points_file(project_urs.combined_smaller_dir_name + '.txt')
+#G_smallest.export_points_file(project_urs.combined_smallest_dir_name + '.txt')
+'''
+#-------------------------------------------------------------------------
+# Convert URS to SWW file for boundary conditions 
+#-------------------------------------------------------------------------
+print 'starting to create boundary conditions'
+#boundaries_in_dir_name = project_urs.boundaries_in_dir_name
+
+print 'minlat=project_urs.north_boundary, maxlat=project_urs.south_boundary',project_urs.north_boundary, project_urs.south_boundary
+print 'minlon= project_urs.west_boundary, maxlon=project_urs.east_boundary',project_urs.west_boundary, project_urs.east_boundary
+       
+from anuga.shallow_water.data_manager import urs_ungridded2sww
+
+print 'boundaries_in_dir_name',project_urs.boundaries_in_dir_name
+#print 'project.boundaries_dir_name',project_urs.boundaries_dir_name
+
+urs_ungridded2sww(project_urs.boundaries_in_dir_name, project_urs.boundaries_in_dir_name,
+                  verbose=True, mint=5000, maxt=34000, zscale=1)
+
+
+
+
+
Index: /anuga_work/production/wa/onslow_2006/build_onslow_grad.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/build_onslow_grad.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/build_onslow_grad.py	(revision 7411)
@@ -0,0 +1,114 @@
+"""Script for running tsunami inundation scenario for Onslow, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_grad_urs.py
+The output sww file is stored in project_grad.output_time_dir 
+
+The scenario is defined by a triangular mesh created from project_grad_urs.polygon,
+the elevation data and a simulated tsunamigenic earthquake.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs_ungridded2sww
+from anuga_parallel.parallel_abstraction import get_processor_name
+
+# Application specific imports
+import project_grad   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project_grad.output_build_time_dir,__file__, 
+               dirname(project_grad.__file__)+sep+ project_grad.__name__+'.py' )#
+
+start_screen_catcher(project_grad.output_build_time_dir)
+
+print 'Processor Name:', get_processor_name()
+print 'User: ', project_grad.user
+
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+
+print 'project_grad.combined_dir_name', project_grad.combined_dir_name
+
+
+geospatial_data = None
+# create DEMs from asc data
+
+# FIXME (Ole): Clip data by interior regions if possible
+
+print 'creating geospatial data objects from asc data (via dem and pts formats)'
+for filename in project_grad.ascii_grid_filenames:
+    convert_dem_from_ascii2netcdf(filename,
+                                  basename_out=filename,
+                                  use_cache=True, verbose=True)
+    dem2pts(filename, use_cache=True, verbose=True)
+
+    geospatial_data += Geospatial_data(file_name=filename + '.pts',
+                                       verbose=True)
+
+
+print 'creating geospatial data objects from txt data'
+for filename in project_grad.point_filenames:
+    geospatial_data += Geospatial_data(file_name=filename + '.txt',
+                                       verbose=True)
+
+
+print 'clip combined geospatial object by bounding polygon'
+G = geospatial_data.clip(project_grad.bounding_polygon)
+
+
+print 'export combined geospatial data'
+if access(project_grad.topographies_dir, F_OK) == 0:
+    mkdir (project_grad.topographies_dir)
+G.export_points_file(project_grad.combined_dir_name + '.pts')
+
+#-------------------------------------------------------------------------
+# Convert URS to SWW file for boundary conditions 
+#-------------------------------------------------------------------------
+print 'converting boundary conditions to sww format'
+
+print 'boundary_dir', project_grad.boundaries_in_dir
+
+maxt = 40000
+urs_ungridded2sww(project_grad.boundaries_in_dir+sep+project_grad.boundaries_name,
+                  project_grad.boundaries_in_dir+sep+project_grad.boundaries_name+'_'+ str(maxt),
+                  verbose=True,
+                  mint=0, maxt=maxt, zscale=1)
+
+print 'Finished building the %s scenario' %project_grad.scenario_name
+
+
Index: /anuga_work/production/wa/onslow_2006/compare_parameter_change.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/compare_parameter_change.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/compare_parameter_change.py	(revision 7411)
@@ -0,0 +1,158 @@
+"""
+Generate latex output comparing time series of given sww files
+
+Inputs:
+
+production dirs: dictionary of output directories with a
+                 association to simulation, eg 50m boundary, 100m boundary
+
+gauge_map:       graphical output from make_gauges.py
+
+Outputs:
+
+* latex output to generate figures for report 
+* figures used for report stored in the report_figure directory
+NOTE, this directory will need to be committed, as well as
+the latex files.
+
+June 2006                    
+"""
+
+from os import sep, getcwd, F_OK, access, mkdir
+import project
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries, get_gauges_from_file
+
+# Derive scenario name
+p = getcwd().split(sep)
+scenario = p[-1] # Last element of absolute CWD path
+scenario_name = scenario.split('_2006')[0] # Strip any text past `_2006`
+test = scenario_name.split('_')
+if len(test) <> 1:
+    scenario_name = '%s %s' %(test[0], test[1])
+    
+# Create report directory
+reportdir = getcwd()+sep+'report'+sep
+if access(reportdir,F_OK) == 0:
+    mkdir (reportdir)
+
+# User defined inputs
+report_title = 'Parameter change comparison for ANUGA: %s' %scenario_name.title()
+    
+# User defined inputs
+production_dirs = {'20060704_063005': 'June 2006', # HAT
+                   '20061106_223150': 'Nov 2006'} # HAT
+                   #'MOST': 'MOST'}
+
+gauge_map = 'onslow_dli_gauge.jpg'
+
+# Create sections and graphs for each designated production directory
+latex_output = []
+swwfiles = {}
+for label_id in production_dirs.keys():
+    
+    file_loc = project.outputdir + label_id + sep
+    swwfile = file_loc + project.basename + '.sww'
+    if label_id == 'MOST':
+        swwfile = project.boundarydir + project.boundary_basename + '.sww'
+    swwfiles[swwfile] = label_id
+
+print 'swwfiles', swwfiles
+
+texname, vec = sww2timeseries(swwfiles,
+                              project.gauge_comparison,
+                              production_dirs,
+                              report = True,
+                              reportname = 'latexoutputparameterchange',
+                              plot_quantity = ['stage', 'speed'],
+                              generate_fig = True,
+                              surface = False,
+                              time_min = None,
+                              time_max = None,
+                              title_on = False,
+                              verbose = True)
+
+latex_output.append(texname)
+
+# Start report generation
+report_name = reportdir + scenario + '_parameter_comparison_onslow.tex'
+fid = open(report_name, 'w')
+
+s = """
+% This is based on an automatically generated file (by make_report.py).
+%
+% Manual parts are:
+% * an abstract must be written in abstract.tex
+% * an introduction must be written in introduction.tex; a basic outline and
+%   some of the core inputs are already in place
+% * outline of the modelling methodology provided in modelling_methodology.tex
+% * the tsunami-genic event should be discussed in tsunami_scenario.tex
+% * an computational_setup.tex file needs to be written for the particular scenario
+% * the interpretation of the results needs to be written to interpretation.tex
+% * maximum inundation maps need to be included in HAT_map.tex and LAT_map.tex etc.
+% * damage modelling maps need to be included in HAT_damage and LAT_damage etc.
+% * a summary must be written into summary.tex
+% * metadata for the scenario data to be included in metadata.tex
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\include{appendix}
+\setstretch{1.25}
+\\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\\textwidth \paperwidth
+\\advance\\textwidth -2in
+
+"""
+fid.write(s)
+
+#s = '\\title{%s} \n' %report_title
+#fid.write(s)
+
+s = """
+\date{\\today}
+%\\author{Geoscience Australia}
+
+\\begin{document}
+\\title{
+\\begin{figure}[hbt]
+  \centerline{ \includegraphics[scale=0.4]{../report_figures/GAlogo.jpg}}
+\end{figure}
+"""
+fid.write(s)
+
+fid.write(s)
+s = '%s} '%report_title
+fid.write(s)
+
+s = '\maketitle'
+fid.write(s)
+
+s = '\\begin{figure}[hbt] \n \centerline{ \includegraphics[width=150mm, height=100mm]{../report_figures/%s}}' %gauge_map
+fid.write(s)
+
+s  = """
+\caption{Point locations used to compare ANUGA output for Onslow region.}  
+\label{fig:comparisonpoints}
+\end{figure}
+"""
+fid.write(s)
+    
+s = '\input{%s} \n \clearpage \n \n' %latex_output[0]
+fid.write(s)
+
+s = '\end{document}'
+fid.write(s)
+
Index: /anuga_work/production/wa/onslow_2006/compare_timeseries_data.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/compare_timeseries_data.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/compare_timeseries_data.py	(revision 7411)
@@ -0,0 +1,53 @@
+"""
+Generate latex output comparing time series of given sww files
+
+Inputs:
+
+output dirs: dictionary of output directories with a
+             association to simulation, eg 50m boundary, 100m boundary
+                    
+Outputs:
+
+* latex output to generate figures for report 
+* figures used for report stored in the report_figure directory
+NOTE, this directory will need to be committed, as well as
+the latex files.
+
+June 2006                    
+"""
+
+from os import sep
+import project
+from anuga.pyvolution.util import sww2timeseries, get_gauges_from_file
+
+# User defined inputs
+
+# for comparison between DTED and WA DLI data
+production_dirs = {'20060515_001733': 'DTED',
+                   '20060704_063234': 'WA DLI'}
+
+plot_quantity = ['stage', 'speed']
+
+# Create sections and graphs for each designated production directory
+latex_output = []
+swwfiles = {}
+for label_id in production_dirs.keys():
+    
+    file_loc = project.outputdir + label_id + sep
+    swwfile = file_loc + project.basename + '.sww'
+    swwfiles[swwfile] = label_id
+
+texname, vec = sww2timeseries(swwfiles,
+                              project.gauge_filename,
+                              production_dirs,
+                              report = True,
+                              reportname = 'compare_output_datasets',
+                              surface = False,
+                              plot_quantity = plot_quantity,
+                              generate_fig = True,
+                              time_min = None,
+                              time_max = None,
+                              title_on = False,
+                              verbose = True)
+
+latex_output.append(texname)
Index: /anuga_work/production/wa/onslow_2006/convert2latlon.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/convert2latlon.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/convert2latlon.py	(revision 7411)
@@ -0,0 +1,43 @@
+"""
+Convert Easting Northing to lon/lat for ultimately get kml file
+"""
+
+def alter_file(filename,filenameout):
+
+    from anuga.coordinate_transforms.lat_long_UTM_conversion import UTMtoLL
+    
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    fid_out = open(filenameout, 'w')
+    s = '%s,%s,%s\n' %('lon','lat','stage')
+    fid_out.write(s)
+    for line in lines[1:]:
+       fields = line.split(',')
+       easting = float(fields[0])
+       northing = float(fields[1])
+       stage = float(fields[3])
+       lat, lon = UTMtoLL(northing,easting, 50)
+       s = '%f,%f,%f\n' %(lon,lat,stage)
+       fid_out.write(s)
+
+    fid_out.close() 
+
+    return
+
+import project
+from os import sep
+
+#timedir = '20070608_060316_run_final_1.5_onslow_nbartzis' # HAT 1 in Onslow 10000 yr
+timedir = '20070613_034754_run_final_1.5_dampier_nbartzis'
+#timedir = '20070906_061418_run_final_1.5_jsexton_exmouth_original'
+filename = project.outputdir + timedir + sep + 'stage0_interp.csv'
+#filename = project.outputdir + timedir + sep + 'stage5_interp.csv'
+#filename = project.outputdir+ timedir + sep + 'stage20_interp.csv'
+#filename = project.outputdir+  timedir + sep + 'stage80_interp.csv'
+filename_out = project.outputdir + timedir + sep + 'stage0_convert.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage5_convert.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage20_convert.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage80_convert.csv'
+alter_file(filename,filename_out)
Index: /anuga_work/production/wa/onslow_2006/convert_db_points.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/convert_db_points.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/convert_db_points.py	(revision 7411)
@@ -0,0 +1,38 @@
+"""
+Convert DB's data from lat/long to easting/northing
+
+"""
+
+def alter_file(filename,filenameout):
+
+    from anuga.coordinate_transforms.redfearn import redfearn
+    
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    fid_out = open(filenameout, 'w')
+    s = '%s,%s,%s\n' %('easting','northing','zone')
+    fid_out.write(s)
+    for line in lines[1:]:
+       fields = line.split(',')
+       #x = float(fields[1])
+       #y = float(fields[0])
+       x = float(fields[0])
+       y = float(fields[1])
+       zone, easting, northing = redfearn(x,y)
+       s = '%f,%f,%f\n' %(easting,northing,zone)
+       fid_out.write(s)
+
+    fid_out.close() 
+
+    return
+
+import project
+
+#filename = project.gaugedir + 'db_points.txt'
+#filename_out = project.gaugedir + 'db_points_convert.txt'
+filename = project.gaugedir + 'aus_hazard_pts.txt'
+filename_out = project.gaugedir + 'aus_hazard_pts_en.txt'
+alter_file(filename,filename_out)
+
Index: /anuga_work/production/wa/onslow_2006/diagnostics.txt
===================================================================
--- /anuga_work/production/wa/onslow_2006/diagnostics.txt	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/diagnostics.txt	(revision 7411)
@@ -0,0 +1,65 @@
+
+ONSHORE DEM
++------------------------------------------------
+Least squares statistics
++------------------------------------------------
+points: 1673196 points
+    x in [3524.821537, 79985.305179]
+    y in [6.645381, 48974.715154]
+    z in [1.000000, 39.000000]
+
+Cropped points: 1094077 points
+    x in [3524.821537, 79985.305179]
+    y in [6.645381, 48974.715154]
+    z in [1.000000, 39.000000]
+
+Mesh: 4320 vertices
+    xi in [0.000000, 80000.000000]
+    eta in [0.000000, 55000.000000]
+    zeta in [-45.970201, 43.202756]
++------------------------------------------------
+
+
+OFFSHORE DEM
++------------------------------------------------
+Least squares statistics
++------------------------------------------------
+points: 536077 points
+    x in [239182.330000, 394600.680000]
+    y in [7567430.640000, 7865031.670000]
+    z in [-421.490000, -0.001000]
+
+Cropped points: 160187 points
+    x in [250138.990000, 327155.640000]
+    y in [7587393.550000, 7634999.630000]
+    z in [-57.490000, -0.001000]
+
+Mesh: 4320 vertices
+    xi in [0.000000, 80000.000000]
+    eta in [0.000000, 55000.000000]
+    zeta in [-63.717178, 35.661167]
++------------------------------------------------
+
+
+COMBINED DEM
++------------------------------------------------
+Least squares statistics
++------------------------------------------------
+points: 2209273 points
+    x in [3524.821537, 394600.680000]
+    y in [6.645381, 7865031.670000]
+    z in [-421.490000, 39.000000]
+
+Cropped points: 160187 points
+    x in [250138.990000, 327155.640000]
+    y in [7587393.550000, 7634999.630000]
+    z in [-57.490000, -0.001000]
+
+Mesh: 4320 vertices
+    xi in [0.000000, 80000.000000]
+    eta in [0.000000, 55000.000000]
+    zeta in [-63.717178, 35.661167]
++------------------------------------------------
+
+
+
Index: /anuga_work/production/wa/onslow_2006/export_results.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/export_results.py	(revision 7411)
@@ -0,0 +1,105 @@
+import project_grad, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+#time_dir = '20070613_034754_run_final_1.5_dampier_nbartzis' # HAT 1 in Dampier 10000 yr
+#time_dir = '20070518_021050_run_final_0.0_nbartzis' # MSL 1 in Dampier 10000 yr
+#time_dir = '' # HAT 1 in Broome 10000 yr
+#time_dir = '' # MSL 1 in Broome 10000 yr
+#time_dir = '' # HAT 1 in Pt Hedland 10000 yr
+#time_dir = '' # MSL 1 in Pt Hedland 10000 yr
+#time_dir = '20070608_060316_run_final_1.5_onslow_nbartzis' # HAT 1 in Onslow 10000 yr
+#time_dir = '20070531_002753_run_final_0.0_onslow_nbartzis' # MSL 1 in Onslow 10000 yr
+#time_dir = '20070608_062811_run_final_1.5_exmouth_nbartzis' # HAT 1 in Exmouth 10000 yr
+#time_dir = '20070605_234905_run_final_0.0_exmouth_nbartzis' # MSL 1 in Exmouth 10000 yr
+#time_dir = '20060704_063005' # 2006 simulation HAT Mw9
+#time_dir = '20070619_042140_run_final_1.5_exmouth_nbartzis' # exmouth HAT longer time
+#time_dir = '20070904_235118_run_final_1.5_jsexton_exmouth_original' # revised model original data
+#time_dir = '20070905_052311_run_final_1.5_jsexton_exmouth_revised' # revised model original + survey data
+#time_dir = '20070906_061418_run_final_1.5_jsexton_exmouth_original' # refined again
+#time_dir = '20070907_055936_run_final_1.5_jsexton_exmouth_revised' # refined again
+#time_dir = '20080526_043334_run_final_1.5_kvanputt_exmouth_revised' # New
+time_dir = '20080529_053834_run_final_1.5_kvanputt_exmouth_revised' # New
+
+
+cellsize = 25
+#cellsize = 150
+timestep = None
+directory = project_grad.output_dir
+#name = directory + time_dir + sep + project_grad.scenario_name
+name = directory+time_dir+sep+project_grad.scenario_name
+#name = directory+time_dir+sep+'onslow_time_35760_0'
+#name = directory+time_dir+sep+'source'
+
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+
+#elevgrid = directory+time_dir+sep+'onslow_elevation_town'
+
+#convert_dem_from_ascii2netcdf(elevgrid, use_cache=True, verbose=True)
+
+#dem2pts(elevgrid,run_up_elev=True,run_up_loc=True)
+
+is_parallel = False
+#is_parallel = True
+if is_parallel == True: nodes = 4
+print 'output dir:', name
+
+var = [2,3,4] # depth and speed
+#var = [2] # depth
+#var = [4]
+#var = [0]
+
+for which_var in var:
+    if which_var == 0:  # Stage
+        outname = name + '_stage'
+        quantityname = 'stage'
+
+    if which_var == 1:  # Absolute Momentum
+        outname = name + '_momentum'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+    if which_var == 2:  # Depth
+        outname = name + '_depth'
+        quantityname = 'stage-elevation'  
+
+    if which_var == 3:  # Speed
+        outname = name + '_speed'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+    if which_var == 4:  # Elevation
+        outname = name + '_elevation'
+        quantityname = 'elevation'  #Elevation
+
+    if is_parallel == True:
+    #    print 'is_parallel',is_parallel
+        for i in range(0,nodes):
+            namei = name + '_P%d_%d' %(i,nodes)
+            outnamei = outname + '_P%d_%d' %(i,nodes)
+            print 'start sww2dem for sww file %d' %(i)
+            sww2dem(namei, basename_out = outnamei,
+                        quantity = quantityname,
+                        timestep = timestep,
+                        cellsize = cellsize,      
+                        easting_min = project_grad.e_min_area,
+                        easting_max = project_grad.e_max_area,
+                        northing_min = project_grad.n_min_area,
+                        northing_max = project_grad.n_max_area,        
+                        reduction = max, 
+                        verbose = True,
+                        format = 'asc')
+    else:
+        print 'start sww2dem'
+        sww2dem(name, basename_out = outname,
+                    quantity = quantityname,
+                    timestep = timestep,
+                    cellsize = cellsize,      
+                    #easting_min = project_grad.e_min_area,
+                    #easting_max = project_grad.e_max_area,
+                    #northing_min = project_grad.n_min_area,
+                    #northing_max = project_grad.n_max_area,        
+                    reduction = max, 
+                    verbose = True,
+                    format = 'asc')
+
Index: /anuga_work/production/wa/onslow_2006/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/get_timeseries.py	(revision 7411)
@@ -0,0 +1,43 @@
+"""
+Generate images of "gauges" for production run
+
+Inputs:
+
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+Outputs:
+
+* figures used for report stored in the report_figure directory
+
+"""
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+import project_urs
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries
+
+# 
+production_dirs = {'20070608_062811_run_final_1.5_exmouth_nbartzis': ''}
+
+swwfiles = {}    
+for label_id in production_dirs.keys():
+    
+    file_loc = project.outputdir + label_id + sep
+    swwfile = file_loc + project_urs.scenario_name + '.sww'
+    swwfiles[swwfile] = label_id
+        
+    texname, elev_output = sww2timeseries(swwfiles,
+                                          project.td_gauges,
+                                          production_dirs,
+                                          report = False,
+                                          plot_quantity = ['stage', 'speed', 'momentum'],
+                                          generate_fig = True,
+                                          surface = False,
+                                          time_min = None,
+                                          time_max = None,
+                                          time_unit = 'hours',
+                                          title_on = False,
+                                          use_cache = True,
+                                          verbose = True)
+                                      
Index: /anuga_work/production/wa/onslow_2006/make_gauges.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/make_gauges.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/make_gauges.py	(revision 7411)
@@ -0,0 +1,98 @@
+""" Make a line of gauges from near the boundary to near centre polygon
+for Onslow study to look at MOST wave and compare to ANUGA output
+Output from here is used as the gauge file input in MOST_timeseries.py
+"""
+import project
+from pylab import plot, xlabel, ylabel, title, ion, axis, savefig, close, text
+from anuga.utilities.polygon import poly_xy, is_inside_polygon
+from Numeric import arange
+from anuga.pmesh.create_mesh import convert_from_latlon_to_utm
+
+x_bound, y_bound = poly_xy(project.polyAll)
+
+MOST_south = project.south
+MOST_north = project.north
+MOST_east = project.east
+MOST_west = project.west
+p0 = [MOST_south, MOST_west]
+p1 = [MOST_south, MOST_east]
+p2 = [MOST_north, MOST_east]
+p3 = [MOST_north, MOST_west]
+MOSTpoly, zone = convert_from_latlon_to_utm([p0, p1, p2, p3])
+
+MOSTymax = 0
+MOSTymin = 7800000.0
+MOSTxmax = 0
+MOSTxmin = 7800000.0
+for i, point in enumerate(MOSTpoly):
+    x = point[0]
+    y = point[1]
+    if y > MOSTymax: MOSTymax = y
+    if y < MOSTymin: MOSTymin = y
+    if x > MOSTxmax: MOSTxmax = x
+    if x < MOSTxmin: MOSTxmin = x
+
+MOSTymax = MOSTymax-3000.0
+# nominated point in centre region for Onslow
+x2 = 305000.0
+y2 = 7605000.0
+testy = 7625000.0
+
+d0 = project.d0
+d1 = project.d1
+d2 = project.d2
+d3 = project.d3
+
+d = [d0, d1, d2, d3]
+ion()
+fid = open(project.gauge_comparison,'w')
+s = 'Easting,Northing,Name,Elevation \n'
+fid.write(s)
+count = 0
+miny = 7580000.0
+maxy = 7800000.0
+xplot = []
+yplot = []
+names = []
+for i, point in enumerate(d):
+    x = point[0]
+    y = point[1]
+    m = (y-y2)/(x-x2)
+    c = y2-m*x2
+    if m > 0:
+        plotx = arange(MOSTxmin,MOSTxmax,1000.0)
+        for j, xpoint in enumerate(plotx):
+            ypoint = m*xpoint+c
+            test = is_inside_polygon([xpoint,ypoint],project.polyAll,closed=True)
+            if test == True:
+                if ypoint > testy and ypoint < MOSTymax:
+                    xplot.append(xpoint)
+                    yplot.append(ypoint)
+                    thisname = 'Point%d' %count
+                    names.append(thisname)
+                    count += 1
+                    s = '%.2f,%.2f,%s,%.2f \n' %(xpoint,ypoint,thisname,0.0)
+                    fid.write(s)
+    else:
+        plotx = arange(MOSTxmin,MOSTxmax,5000.0)
+        for j, xpoint in enumerate(plotx):
+            ypoint = m*xpoint+c
+            test = is_inside_polygon([xpoint,ypoint],project.polyAll,closed=True)
+            if test == True:
+                if ypoint > testy and ypoint < MOSTymax:
+                    xplot.append(xpoint)
+                    yplot.append(ypoint)
+                    thisname = 'Point%d' %count
+                    names.append(thisname)
+                    count += 1
+                    s = '%.2f,%.2f,%s,%.2f \n' %(xpoint,ypoint,thisname,0.0)
+                    fid.write(s)
+
+    plot(x_bound, y_bound, xplot, yplot,'b+')
+    for i, string in enumerate(names):
+        if xplot[i] > 240000 and xplot[i] < 340000:
+            text(xplot[i],yplot[i],string,fontsize=7)
+
+axis([240000,340000, miny, maxy])
+savefig('boundarycomparison')
+close('all')
Index: /anuga_work/production/wa/onslow_2006/make_report.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/make_report.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/make_report.py	(revision 7411)
@@ -0,0 +1,380 @@
+"""
+Generate report for production run
+
+Inputs:
+
+report_title:    title to be included in tex file
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+
+Outputs:
+
+* Report generated to scenario_report.tex where the scenario relates
+the name of the production directory this script is being run from.
+* figures used for report stored in the report_figure directory
+NOTE, this directory will need to be committed, as well as
+the latex files.
+
+The report structure is
+
+* Executive Summary
+* Introduction
+* Modelling Methodology
+* Tsunami scenario
+* Data sources
+* Inundation modelling results
+* Impact modelling
+* Summary
+* Acknowledgements
+* References
+* Appendix: Metadata
+* Appendix: Inundation model metadata
+* Appendix: Time series outputs
+
+Other files included in document which require manual intervention:
+
+* an abstract must be written in abstract.tex
+* an introduction must be written in introduction.tex; a basic outline and
+  some of the core inputs are already in place
+* the tsunami-genic event should be discussed in tsunami_scenario.tex
+* a discussion of the ANUGA model is required in anuga.tex
+* a computational_setup.tex file needs to be written for the particular scenario
+* the interpretation of the results needs to be written to interpretation.tex
+* maximum inundation map names need to be included in HAT_map and LAT_map etc.
+* damage modelling map names need to be included in HAT_damage and LAT_damage etc.
+* a summary must be written into summary.tex
+* metadata for the scenario data to be included in metadata.tex
+
+May, June 2006                    
+"""
+
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries, get_gauges_from_file
+
+# Derive scenario name
+p = getcwd().split(sep)
+scenario = p[-1] # Last element of absolute CWD path
+scenario_name = scenario.split('_2006')[0] # Strip any text past `_2006`
+test = scenario_name.split('_')
+if len(test) <> 1:
+    scenario_name = '%s %s' %(test[0], test[1])
+
+# Create report directory
+reportdir = getcwd()+sep+'report'+sep
+if access(reportdir,F_OK) == 0:
+    mkdir (reportdir)
+    
+# User defined inputs
+report_title = 'Tsunami impact modelling for the North West shelf: %s' %scenario_name.title()
+
+# DTED data
+#production_dirs = {'20060426_004129': '1.5 AHD',
+#                   '20060426_004237': '-1.5 AHD',
+#                   '20060515_001733': '0 AHD'}
+#damage_maps = {'1.5 AHD': 'HAT_damage',
+#               '-1.5 AHD': 'LAT_damage',
+#               '0 AHD': 'MSL_damage'}
+
+# WA DLI data
+production_dirs_test1 = {'20060704_063234': 'MSL',
+                         '20060704_063005': 'HAT',
+                         '20060706_235246': 'LAT'}
+
+production_dirs_test2 = production_dirs_test1
+
+return_periods = [1000, 1000000]
+
+all_prod_dirs = [production_dirs_test1, production_dirs_test2]
+#all_prod_dirs = [production_dirs_test1]
+
+is_parallel = False
+if is_parallel == True:
+    nodes = 8
+    
+max_maps1 = {'MSL': 'MSL_map',
+            'HAT': 'HAT_map',
+            'LAT': 'LAT_map'}
+
+max_maps2 = max_maps1
+
+all_maps = [max_maps1, max_maps2]
+
+gauge_map = 'onslow_dli_gauge.jpg'
+
+compare_output = 'compare_output_datasets'
+
+# Create sections and graphs for each designated production directory
+latex_output = []
+report_name = 'latexoutput'
+swwfiles = {}
+if is_parallel == True:
+
+    for j, production_dirs in enumerate(all_prod_dirs):
+        
+        for i in range(nodes):
+            print 'Sending node %d of %d' %(i,nodes)
+            swwfiles = {}
+            reportname = report_name + '%s' + 'rp%s' %(i,j)
+            
+            for label_id in production_dirs.keys():
+                file_loc = project.output_dir + label_id + sep
+                sww_extra = '_P%s_%s' %(i,nodes)
+                swwfile = file_loc + project.basename + sww_extra + '.sww'
+                #swwfile = file_loc + project.scenario_name + sww_extra + '.sww'
+                swwfiles[swwfile] = label_id
+
+                texname, elev_output = sww2timeseries(swwfiles,
+                                                      project.gauge_filename,
+                                                      production_dirs,
+                                                      report = True,
+                                                      reportname = reportname,
+                                                      plot_quantity = ['stage', 'momentum'],
+                                                      generate_fig = True,
+                                                      surface = False,
+                                                      time_min = None,
+                                                      time_max = None,
+                                                      title_on = False,
+                                                      verbose = True)
+                
+                latex_output.append(texname)
+    
+else:
+
+    for i, production_dirs in enumerate(all_prod_dirs):
+
+        swwfiles = {}
+        reportname = report_name + 'rp%s' %(i)
+        
+        for label_id in production_dirs.keys():
+
+            file_loc = project.outputdir + label_id + sep
+            swwfile = file_loc + project.basename + '.sww'
+            #swwfile = file_loc + project.scenario_name + sww_extra + '.sww'
+            swwfiles[swwfile] = label_id
+            
+        texname, elev_output = sww2timeseries(swwfiles,
+                                              project.gauge_filename,
+                                              production_dirs,
+                                              report = True,
+                                              reportname = reportname,
+                                              plot_quantity = ['stage', 'speed'],
+                                              generate_fig = True,
+                                              surface = False,
+                                              time_min = None,
+                                              time_max = None,
+                                              title_on = False,
+                                              verbose = True)
+        
+        latex_output.append(texname)
+    
+# Start report generation
+# Future: generate_report(reportdir, scenario, report_title, 
+# project.gauge_filename, max_maps, damage_maps, production_dirs, latex_output)
+report_name = reportdir + scenario + '_report.tex'
+fid = open(report_name, 'w')
+
+s = """
+% This is based on an automatically generated file (by make_report.py).
+%
+% Manual parts are:
+% * an abstract must be written in abstract.tex
+% * an introduction must be written in introduction.tex; a basic outline and
+%   some of the core inputs are already in place
+% * outline of the modelling methodology provided in modelling_methodology.tex
+% * the tsunami-genic event should be discussed in tsunami_scenario.tex
+% * an computational_setup.tex file needs to be written for the particular scenario
+% * the interpretation of the results needs to be written to interpretation.tex
+% * maximum inundation maps need to be included in HAT_map.tex and LAT_map.tex etc.
+% * damage modelling maps need to be included in HAT_damage and LAT_damage etc.
+% * a summary must be written into summary.tex
+% * metadata for the scenario data to be included in metadata.tex
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\usepackage{pdfpages}
+\include{appendix}
+\setstretch{1.25}
+\\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\\textwidth \paperwidth
+\\advance\\textwidth -2in
+
+"""
+fid.write(s)
+
+s = """
+\date{\\today}
+%\\author{Geoscience Australia}
+
+\\begin{document}
+\\title{
+\\begin{figure}[hbt]
+  \centerline{ \includegraphics[scale=0.4]{../report_figures/GAlogo.jpg}}
+\end{figure}
+"""
+fid.write(s)
+s = '%s} '%report_title
+fid.write(s)
+s = """
+  \maketitle
+
+    \section{Executive Summary}
+    \label{sec:execsum}
+  \input{execsum}
+
+\clearpage
+
+  \\tableofcontents
+  
+  \section{Introduction}
+    \label{sec:intro}
+  \input{introduction}
+
+   \section{Modelling methodology}
+    \label{sec:methodology}
+    \input{modelling_methodology}
+    
+  \section{Tsunami scenarios}
+    \label{sec:tsunamiscenario}
+    \input{tsunami_scenario}
+
+  \section{Data sources}
+    \label{sec:data}
+    \input{data}
+        
+  \section{Inundation modelling results}
+     \label{sec:results}
+         
+"""
+fid.write(s)
+    
+s = '\input{interpretation} \n'
+fid.write(s)
+
+# Assign titles to each production section 
+# Must specify one name per section
+for i, max_maps in enumerate(all_maps):
+
+    s = '\subsection{Return Period: %s years} \n \n' %return_periods[i]      
+    fid.write(s)
+
+    production_dirs = all_prod_dirs[i]
+    for i, name in enumerate(production_dirs.keys()):
+
+        s = '\input{%s} \n \clearpage \n \n' %max_maps[production_dirs[name]]
+        fid.write(s)
+
+# Generate latex output for location points
+s = '\\begin{table} \\begin{center} \n'
+fid.write(s)
+s = '\caption{Defined point locations for %s study area.}' %scenario_name.title()
+fid.write(s)
+s = """
+\label{table:locations}
+\\begin{tabular}{|l|l|l|l|}\hline
+\\bf{Point Name} & \\bf{Easting} & \\bf{Northing} & \\bf{Elevation (m)}\\\\ \hline
+"""
+fid.write(s)
+
+gauges, locations, elevation = get_gauges_from_file(project.gauge_filename)
+
+for name, gauges, elev in zip(locations, gauges, elevation):
+    east = gauges[0]
+    north = gauges[1]
+    s = '%s & %.2f & %.2f & %.2f \\\\ \hline \n' %(name.replace('_',' '), east, north, elev)
+    fid.write(s)
+
+s = '\\end{tabular} \n  \end{center} \n \end{table} \n \n'
+fid.write(s)
+
+#s = '\\begin{figure}[h] \n \centerline{ \includegraphics[width=\paperwidth]{../report_figures/%s}}' %gauge_map
+s = '\\begin{figure}[h] \n \centerline{ \includegraphics[scale=0.7]{../report_figures/%s}}' %gauge_map
+fid.write(s)
+
+s  = """
+\caption{Point locations used for Onslow study.}  
+\label{fig:points}
+\end{figure}
+
+\clearpage
+"""
+fid.write(s)
+
+# Closing
+
+s = """
+   \section{Impact modelling}
+    \label{sec:impact}
+     \input{damage}
+"""
+fid.write(s)
+
+s = """
+  % \section{Impact due to data accuracy}
+  %   \input{discussion}
+  %   \label{sec:issues}
+
+     \section{Summary}
+     \label{sec:summary}
+     \input{summary}
+
+     \section{Acknowledgements}
+     \input{acknowledgements}
+     
+    \input{references}
+
+\clearpage
+
+    \\appendix
+
+    \section{ANUGA modelling parameters}
+    \label{sec:anugasetup}
+    \input{anuga_setup}
+
+\clearpage
+
+   \section{Metadata}
+     \label{sec:metadata}
+     \input{metadata}
+
+\clearpage
+
+   \section{Time series}
+     \label{sec:timeseries}
+     \input{timeseriesdiscussion}
+     \clearpage
+"""
+fid.write(s)
+
+for i in range(len(latex_output)):
+    if latex_output[i] <> '':
+        s = '\subsection{Return Period: %s years} \n' %return_periods[i]
+        fid.write(s)
+        s = '\input{%s} \n \clearpage \n \n' %latex_output[i]   
+        fid.write(s)
+
+s="""
+
+   \section{Damage modelling inputs}
+     \label{sec:damageinputs}
+     \input{damage_inputs}
+
+\end{document}
+"""
+fid.write(s)
Index: /anuga_work/production/wa/onslow_2006/plot_contour_data.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/plot_contour_data.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/plot_contour_data.py	(revision 7411)
@@ -0,0 +1,64 @@
+"""Read in contour data file and plot max and min
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid
+from os import sep
+ 
+directory = project.outputdir
+timedir = '20070906_061418_run_final_1.5_jsexton_exmouth_original'
+#timedir = '20070608_060316_run_final_1.5_onslow_nbartzis'
+#timedir = '20070613_034754_run_final_1.5_dampier_nbartzis'
+
+def get_data(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[2]))
+    return max(stage), min(stage)
+
+files = ['stage0_convert.csv','stage5_convert.csv','stage20_convert.csv','stage80_convert.csv']
+depth = [0,5,20,80]
+stage_max = []
+stage_min = []
+
+for thefile in files:
+
+    filename = directory + timedir + sep + thefile
+    max_stage, min_stage = get_data(filename)
+    stage_max.append(max_stage)
+    stage_min.append(min_stage)
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 80.
+d2 = arange(d1,0.15,-0.1)
+h1 = max_stage
+#h1 = 4.0
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+    
+ion()
+plot(depth,stage_max,'ob',d2,green,'-g',depth,stage_max,'-b')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+Magnitude 9.3 event (Java) at Onslow')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.1 event (Sumba) at Onslow')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.0 event (Sumba) at Onslow')
+legend(['ANUGA','Green\'s law'])
+axis([-5,85,min(stage_max)*0.9,max(stage_max)*1.1])
+grid(True)
+#savefig('stratification_onslow_gun')
+savefig('stratification_exmouth_gun')
+#savefig('stratification_dampier_gun')
+
+close('all')
+
Index: /anuga_work/production/wa/onslow_2006/plot_data_extent.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/plot_data_extent.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/plot_data_extent.py	(revision 7411)
@@ -0,0 +1,139 @@
+from pylab import *
+from anuga.geospatial_data.geospatial_data import *
+from anuga.pmesh.create_mesh import convert_from_latlon_to_utm
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+from os import sep
+from anuga.utilities.polygon import inside_polygon
+import project
+from anuga.utilities.polygon import plot_polygons, poly_xy, polygon_area
+
+datadir = project.datadir
+ion()
+
+print 'Area of overall polygon: ', polygon_area(project.polyAll)
+
+plot_data = False
+plot_with_poly = True
+
+def read_community_file(filename1, filename2, polygon):
+    from anuga.coordinate_transforms.redfearn import redfearn
+    from anuga.utilities.polygon import inside_polygon
+    fid1 = open(filename1)
+    lines = fid1.readlines()
+    fid1.close()
+    xlocs = []
+    ylocs = []
+    community = []
+    population = []
+    line1 = lines[0]
+    line11 = line1.split(',')
+    fid2 = open(filename2,'w')
+    s = 'Easting, Northing, Community, Population\n'
+    fid2.write(s)
+    for i in range(len(line11)):
+        if line11[i].strip('\n').strip(' ') == 'LATITUDE': lat_index = i
+        if line11[i].strip('\n').strip(' ') == 'LONGITUDE': lon_index = i
+        if line11[i].strip('\n').strip(' ') == 'COMMUNITY': name_index = i
+        if line11[i].strip('\n').strip(' ') == 'POPULATION': pop_index = i
+    for line in lines[1:]:
+        fields = line.split(',')
+        lat = float(fields[lat_index])
+        lon = float(fields[lon_index])
+        z, easting, northing = redfearn(lat,lon)
+        v = inside_polygon([easting,northing],polygon)
+        if z == 50 and v == True:
+            xlocs.append(easting)
+            ylocs.append(northing)
+            community = fields[name_index]
+            population = fields[pop_index]
+            s = '%f, %f, %s, %s\n' %(easting, northing, community, population)
+            fid2.write(s)
+            print community, easting, northing
+    
+    return xlocs, ylocs, community, population
+
+def read_file(filename1):
+    fid1 = open(filename1)
+    lines = fid1.readlines()
+    fid1.close()
+    x = []
+    y = []
+    name = []
+    line1 = lines[0]
+    for line in lines[1:]:
+        fields = line.split(',')
+        x.append(float(fields[0]))
+        y.append(float(fields[1]))
+        if len(line) > 2: name.append(fields[2])
+    
+    return x, y, name
+
+if plot_data == True:
+    file1 = datadir+'onslow_onshore_30m_dted.pts'
+    file2 = datadir+'onslow_offshore_points.xya'
+
+    G1 = Geospatial_data(file_name = file1)
+    G2 = Geospatial_data(file_name = file2)
+
+    pts1 = G1.get_data_points(absolute = True)
+    pts2 = G2.get_data_points(absolute = True)
+
+    if plot_with_poly == True:
+        figname = 'onslow_data_poly'
+        x1, y1 = poly_xy(project.polyAll)
+        x2, y2 = poly_xy(project.poly_onslow)
+        x3, y3 = poly_xy(project.poly_coast)
+        x4, y4 = poly_xy(project.poly_region)
+        figure(1)
+        plot(pts1[:,0],pts1[:,1],'g.',
+             pts2[:,0],pts2[:,1],'b.',
+             x1,y1,'r-',x2,y2,'r-',x3,y3,'r-',x4,y4,'r-')
+        xlabel('Eastings')
+        ylabel('Northings')
+        savefig(figname)
+    else:
+        figure(2)
+        plot(pts1[:,0],pts1[:,1],'g.',
+             pts2[:,0],pts2[:,1],'b.')
+        xlabel('Eastings')
+        ylabel('Northings')
+        savefig('onslow_data_extent')
+else:
+    
+    figure(3)
+    figname = 'onslow_polys_test'
+    vec = plot_polygons([project.polyAll,
+                        project.poly_onslow, project.poly_coast],#, project.poly_region],
+                        figname,
+                        verbose = True)
+    figure(4)
+    x1, y1 = poly_xy(project.polyAll)
+    figname = 'onslow_communities'
+    x, y, community, population= \
+           read_community_file(project.community_filename, \
+                               project.community_scenario, project.polyAll)
+    #coastx, coasty = read_file(project.coast_filename)
+    #plot(x1,y1,'r-',x,y,'r+', coastx,coasty,'g.')
+    plot(x1,y1,'r-',x,y,'r+')
+    xlabel('Eastings')
+    ylabel('Northings')
+    savefig(figname)
+    figure(4)
+    figname = 'onslow_gauges'
+    x, y, name = read_file(project.gauge_filename)
+    plot(x1,y1,'r-',x,y,'r+')
+    savefig(figname)
+
+    figure(5)
+    figname = 'onslow_new_boundary_test'
+    gaugex, gaugey, name = read_file(project.gauges50)
+    x50, y50 = poly_xy(project.bounding_poly50)
+    x_onslow, y_onslow = poly_xy(project.poly_onslow)
+    x_coast, y_coast = poly_xy(project.poly_coast)
+    #x25, y25 = poly_xy(project.bounding_poly25)
+    #plot(x50,y50,'r-',x25,y25,'r-',x1,y1,'g-')
+    plot(x50,y50,'r-',x1,y1,'g-', gaugex, gaugey, 'b+', x_onslow, y_onslow,'r-', x_coast, y_coast,'r-')
+    for i, string in enumerate(name):
+        text(gaugex[i],gaugey[i],string,fontsize=7)
+    savefig(figname)
+close('all')
Index: /anuga_work/production/wa/onslow_2006/plot_for_ATWS_ppt.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/plot_for_ATWS_ppt.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/plot_for_ATWS_ppt.py	(revision 7411)
@@ -0,0 +1,164 @@
+"""Read in csv files and plot time series
+
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, hold, axis, close, figure
+from os import sep
+ 
+time_dir1 = '20070608_060316_run_final_1.5_onslow_nbartzis'# HAT onslow
+time_dir2 = '20070608_062811_run_final_1.5_exmouth_nbartzis'# HAT exmouth
+directory = project.outputdir
+filenames = [directory + time_dir1 + sep + 'gauges_time_series_100m.csv',
+            directory + time_dir2 + sep + 'gauges_time_series_100m.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_50m.csv',
+            directory + time_dir2 + sep + 'gauges_time_series_50m.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_20m.csv',
+            directory + time_dir2 + sep + 'gauges_time_series_20m.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_3.5m.csv',
+            directory + time_dir2 + sep + 'gauges_time_series_3.5m.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_closetown1.csv',
+            directory + time_dir2 + sep + 'gauges_time_series_closetown1.csv',
+            directory + time_dir1 + sep + 'gauges_time_series_closetown2.csv',   
+            directory + time_dir2 + sep + 'gauges_time_series_closetown2.csv']
+
+def get_time_series_from_file(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    t = []
+    stage = []
+    depth = []
+    speed = []
+    momentum = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        t.append((float(fields[0])/3600.0+5000./3600.))
+        stage.append(float(fields[1]))
+        depth.append(float(fields[1])-float(fields[4]))
+        speed.append(float(fields[3]))
+        momentum.append(float(fields[2]))        
+    return t, stage, depth, speed, momentum
+
+max_st = 0.
+max_sp = 0.
+max_mom = 0.
+min_st = 0.
+min_sp = 0.
+min_mom = 0.
+max_t = 0.0
+
+for filename in filenames:
+    t, stage, depth, speed, momentum = get_time_series_from_file(filename)
+    if max(t) > max_t: max_t = max(t)
+    if max(stage) > max_st: max_st = max(stage)
+    if max(speed) > max_sp: max_sp = max(speed)
+    if max(momentum) > max_mom: max_mom = max(momentum)
+    if min(stage) < min_st: min_st = min(stage)
+    if min(speed) < min_sp: min_sp = min(speed)
+    if min(momentum) < min_mom: min_mom = min(momentum)
+
+stage_axis = ([5000./3600.,max_t, min_st, max_st])
+speed_axis = ([5000/3600.,max_t, min_sp, max_sp])
+mom_axis = ([5000/3600.,max_t, min_mom, max_mom])
+
+ion()
+"""
+hold(False)
+
+for i, filename in enumerate(filenames):
+    t, stage, depth, speed, momentum = get_time_series_from_file(filename)
+
+    i1 = filename.rfind('gauges')
+    i2 = filename.rfind('csv')
+    name = filename[i1:i2-1]
+    loc = filename.rfind('1.5') + 4
+    if filename[loc] is 'o': community = 'onslow'
+    if filename[loc] is 'e': community = 'exmouth'
+
+    figure(1)
+    plot(t, stage, '-b', linewidth=1)
+    xlabel('time (hour)')
+    ylabel('wave height (m)')
+    axis(stage_axis)
+    figname = 'stage_%s_%s.png' %(name,community)
+    savefig(figname)
+
+    figure(2)
+    plot(t, speed, '-b', linewidth=1)
+    xlabel('time (hour)')
+    ylabel('speed (m/s)')
+    axis(speed_axis)
+    figname = 'speed_%s_%s.png' %(name,community)
+    savefig(figname)
+
+    figure(3)
+    plot(t, momentum, '-b', linewidth=1)
+    xlabel('time (hour)')
+    ylabel('momentum (m^2/sec)')
+    axis(mom_axis)
+    figname = 'mom_%s_%s.png' %(name,community)
+    savefig(figname)
+
+close('all')
+"""
+hold(True)
+count = 0
+figcount = 0
+cstr = ['b', 'r']
+
+filenames = [#directory + time_dir1 + sep + 'gauges_time_series_100m.csv',
+            #directory + time_dir2 + sep + 'gauges_time_series_100m.csv']
+            #directory + time_dir1 + sep + 'gauges_time_series_50m.csv',
+            #directory + time_dir2 + sep + 'gauges_time_series_50m.csv']
+            #directory + time_dir1 + sep + 'gauges_time_series_20m.csv',
+            #directory + time_dir2 + sep + 'gauges_time_series_20m.csv']
+            #directory + time_dir1 + sep + 'gauges_time_series_3.5m.csv',
+            #directory + time_dir2 + sep + 'gauges_time_series_3.5m.csv']
+            #directory + time_dir1 + sep + 'gauges_time_series_closetown1.csv',
+            #directory + time_dir2 + sep + 'gauges_time_series_closetown1.csv']
+            directory + time_dir1 + sep + 'gauges_time_series_closetown2.csv',   
+            directory + time_dir2 + sep + 'gauges_time_series_closetown2.csv']
+
+
+for i, filename in enumerate(filenames):
+    t, stage, depth, speed, momentum = get_time_series_from_file(filename)
+
+    i1 = filename.rfind('gauges')
+    i2 = filename.rfind('csv')
+    name = filename[i1:i2-1]
+    loc = filename.rfind('1.5') + 4
+    if filename[loc] is 'o': community = 'onslow'
+    if filename[loc] is 'e': community = 'exmouth'
+
+    figure(10+figcount)
+    plot(t, stage, c = cstr[i], linewidth=1)
+    xlabel('time (hour)')
+    ylabel('wave height (m)')
+    axis(stage_axis)
+    figname = 'stage_%s_both.png' %(name)
+    savefig(figname)
+
+    figure(20+figcount)
+    plot(t, speed, c = cstr[i], linewidth=1)
+    xlabel('time (hour)')
+    ylabel('speed (m/s)')
+    axis(speed_axis)
+    figname = 'speed_%s_both.png' %(name)
+    savefig(figname)
+
+    figure(30+figcount)
+    plot(t, momentum, c = cstr[i], linewidth=1)
+    xlabel('time (hour)')
+    ylabel('momentum (m^2/sec)')
+    axis(mom_axis)
+    figname = 'mom_%s_both.png' %(name)
+    savefig(figname)
+
+    count += 1
+    if int(count/2.) - count/2. is 0.0: figcount += 1
+    else:
+        figcount = 0
+  
+close('all')
Index: /anuga_work/production/wa/onslow_2006/plot_for_talk.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/plot_for_talk.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/plot_for_talk.py	(revision 7411)
@@ -0,0 +1,48 @@
+"""Read in sww file, interpolate at specified locations and plot time series
+
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion
+from os import sep
+ 
+#time_dir = '20060704_063234'# MSL
+time_dir = '20060704_063005'# HAT
+directory = project.outputdir
+filename = directory + time_dir + sep + 'gauges_time_series_Beadon Bay east.csv'
+#filename = directory + time_dir + sep + 'gauges_time_series_Bindi Bindi Community.csv'
+
+def get_time_series_from_file(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    t = []
+    stage = []
+    depth = []
+    elevation = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        t.append(float(fields[0])/3600.0)
+        stage.append(float(fields[1]))
+        depth.append(float(fields[1])-float(fields[4]))
+        elevation.append(float(fields[4]))        
+    return t, stage, depth, elevation
+
+t, stage, depth, elevation = get_time_series_from_file(filename)
+
+ion()
+# find index for t around 200 mins plot(t[x:], stage[x:])
+if elevation[0] < 0:
+     plot(t, stage, '-b')
+     xlabel('time (hour)') 
+     ylabel('wave height [m]')
+else:
+     plot(t, depth, '-b')
+     xlabel('time (hour)')
+     ylabel('water depth (m)')
+
+    
+savefig('test')
+
+
Index: /anuga_work/production/wa/onslow_2006/project.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/project.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/project.py	(revision 7411)
@@ -0,0 +1,247 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+Also includes origin for slump scenario.
+"""
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser
+from anuga.utilities.polygon import read_polygon, polygon_area
+import sys
+
+from anuga.coordinate_transforms.redfearn import convert_from_latlon_to_utm
+
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+
+from time import localtime, strftime, gmtime
+                
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_dir_name = 'onslow_tsunami_scenario_2006'
+scenario_name = 'onslow'
+
+# 250m data to be provided
+coarsename = 'onsl_bathydem250' # get from Neil/Ingo (DEM or topo data)
+
+# 30m data to be provided
+onshore_name_dted = 'onslow_onshore_30m_dted2' # get from Neil/Ingo (DEM or topo data)
+
+# 20m data to be provided
+onshore_name_dli = 'onslow_onshore_20m_dli' # get from Neil/Ingo (DEM or topo data) 
+
+coast_name = 'onslow_coast'
+islands_name = 'onslow_islands_dted2'
+offshore_name = 'onslow_offshore_points'
+
+boundary_basename = 'SU-AU_clip'
+
+#swollen/ all data output
+basename = 'source'
+
+codename = 'project.py'
+
+if sys.platform == 'win32':
+    home = getenv('INUNDATIONHOME')
+#    python_home = getenv('PWD')     
+#    home = environ['INUNDATIONHOME']     #Sandpit's parent dir
+    user = getenv('USERPROFILE')
+#    user = basename(user_path)
+    
+else:    
+    home = getenv('INUNDATIONHOME', sep+'d'+sep+'cit'+sep+'1'+sep+'cit'+sep+'risk_assessment_methods_project'+sep+'inundation')     
+    user = getenv('LOGNAME')
+    print 'USER:', user
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+home += sep +'data'
+
+#Derive subdirectories and filenames
+#time = strftime('%Y%m%d_%H%M%S',localtime()) #gets time for new dir
+local_time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+
+meshdir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'meshes'+sep
+datadir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'topographies'+sep
+gaugedir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'gauges'+sep
+polygondir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'polygons'+sep
+boundarydir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'boundaries'+sep
+#output dir without time
+outputdir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'outputs'+sep
+tidedir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'tide_data'+sep
+comparereportdir = '..'+sep+'..'+sep+'documentation'+sep+'experimentation'+sep+'boundary_ANUGA_MOST'+sep+'report'
+
+outputtimedir = outputdir + local_time + sep + scenario_name + sep +
+
+print'bound', boundarydir
+
+#gauge_filename = gaugedir + 'onslow_gauges.xya'
+#for MOST
+gauge_filename = gaugedir + 'gauge_location_onslow.csv'
+beach_gauges = gaugedir + 'beach_gauges.csv'
+boundary_gauges = gaugedir + 'boundary_gauges.csv'
+td_gauges = gaugedir + 'gauges_td.csv'
+db_point = gaugedir + 'db_points.csv'
+gauge_filename_bindi = gaugedir + 'gauge_location_bindi.csv'
+gauges50 = gaugedir + '50_gauges.xya'
+gauge_comparison = gaugedir + 'MOST_comparison_gauges.xya'
+gauge_comparison_3d = gaugedir + 'MOST_comparison_gauges_3d.xya'
+community_filename = gaugedir + 'CHINS_v2.csv'
+community_scenario = gaugedir + 'community_onslow.csv'
+buildings_filename = gaugedir + 'Onslow_res_Project.csv'
+buildings_filename_out = gaugedir + 'Onslow_res_Project.csv'
+
+
+gaugetimeseries = gaugedir + 'onslow'
+
+tidal_filename = tidedir + 'onsl.txt'
+tidal_outname = tidedir + 'max_min.txt'
+
+# boundary source data
+#MOST_dir = 'f:'+sep+'3'+sep+'ehn'+sep+'users'+sep+'davidb'+sep+'tsunami'+sep+'WA_project'+sep+'SU-AU_90'+sep+'most_2'+sep+'detailed'+sep
+
+codedir = getcwd()+sep
+                                
+codedirname = codedir + 'project.py'
+
+#meshname = meshdir + basename
+meshname = outputtimedir + 'mesh_' + basename
+print 'meshname',meshname
+coarsedemname = datadir + coarsename
+
+onshore_dem_name = datadir + onshore_name_dli
+
+offshore_dem_name = datadir + offshore_name
+coast_dem_name = datadir + coast_name
+islands_dem_name = datadir + islands_name
+combined_dem_name = datadir + 'onslow_combined_elevation'
+
+outputname = outputtimedir + basename  #Used by post processing
+
+#!gauge_filename = outputdir + 'onslow_gauges.xya'
+#!gauge_outname = outputdir + 'gauges_max_output.xya'
+
+# clipping region to make DEM (pts file) from fine elevation data
+eastingmin = 240000
+eastingmax = 340000
+northingmin = 7580000
+northingmax = 7700000
+
+south = degminsec2decimal_degrees(-22,15,0)
+north = degminsec2decimal_degrees(-20,30,0)
+west = degminsec2decimal_degrees(114,15,0)
+east = degminsec2decimal_degrees(115,50,0)
+'''
+# region for visualisation
+eminviz = 260000
+emaxviz = 320000
+nminviz = 7590000
+nmaxviz = 7630000
+'''
+# region to export
+
+e_min_area = 290500
+e_max_area = 321500
+n_min_area = 7601550
+n_max_area = 7620000
+
+# old onslow for Gordon Monday 27 July 2007
+e_min_area = 290828
+e_max_area = 301021
+n_min_area = 7596160
+n_max_area = 7603100
+
+# for test grid for ITEM ppt
+#e_min_area = 207600
+#e_max_area = 320000
+#n_min_area = 7600350
+#n_max_area = 7691200
+
+# region to export to make elevation map: JS 22/9/06 - NOTE, this won't
+# work as region needs to be inside bounding box (polyAll)!!
+
+#e_min_area = 240000
+#e_max_area = 340000
+#n_min_area = 7580000
+#n_max_area = 7690000
+export_region = [[e_min_area, n_min_area],
+                 [e_min_area, n_max_area],
+                 [e_max_area, n_max_area],
+                 [e_max_area, n_min_area]]
+#Georeferencing
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+
+refzone = 50
+
+#Updated Main Domain of Onslow: first run NB 6/4/06
+d0 = [310000, 7690000]
+d1 = [280000, 7690000]
+d2 = [270000, 7645000]
+d3 = [240000, 7625000]
+d4 = [270000, 7580000]
+d5 = [300000, 7590000]
+d6 = [340000, 7610000]
+
+polyAll = [d0, d1, d2, d3, d4, d5, d6]
+print 'bounding polygon area', polygon_area(polyAll)/1000000.0
+polygons = [polyAll, export_region]
+figname = 'checking.png'
+#Interior region - Onslow town
+
+#for visualisation
+#i0 = [304000, 7609000]
+#i1 = [301500, 7605000]
+#i2 = [304000, 7603000]
+#i3 = [307000, 7602000]
+#i4 = [309000, 7603000]
+#i5 = [311000, 7607000]
+
+#i0 = [304000, 7608000]
+i0 = [304000, 7607000]
+i1 = [302000, 7605000]
+#i2 = [303000, 7602000]
+i2 = [304000, 7603000]
+#i3 = [305000, 7601000]
+i3 = [307000, 7602000]
+i4 = [309000, 7603000]
+#i5 = [307000, 7606500]
+i5 = [307000, 7606000]
+
+
+poly_onslow = [i0, i1, i2, i3, i4, i5]
+print 'onslow polygon area', polygon_area(poly_onslow)/1000000.0
+#Thevenard Island
+j0 = [294000, 7629000]
+j1 = [285000, 7625000]
+j2 = [294000, 7621000]
+j3 = [299000, 7625000]
+
+poly_thevenard = [j0, j1, j2, j3]
+print 'thevenard polygon area', polygon_area(poly_thevenard)/1000000.0
+'''
+# Direction Is
+k0 = [309000, 7619000]
+k1 = [304000, 7619000]
+k2 = [304000, 7616500]
+k3 = [309000, 7616500]
+
+poly_direction = [k0, k1, k2, k3]
+'''
+
+#med res around onslow
+l0 = [300000, 7610000]
+l1 = [285000, 7600000]
+l2 = [300000, 7597500]
+l3 = [310000, 7600000]
+l4 = [315000, 7610000]
+#l5 = [310000, 7612500]
+
+#poly_coast = [l0, l1, l2, l3, l4, l5]
+poly_coast = [l0, l1, l2, l3, l4]
+print 'coast polygon area', polygon_area(poly_coast)/1000000.0
+#general coast and local area to onslow region
+m0 = [270000, 7581000]
+m1 = [300000, 7591000]
+m2 = [339000, 7610000]
+m3 = [330000, 7630000]
+m4 = [290000, 7640000]
+m5 = [260000, 7600000]
+
+poly_region = [m0, m1, m2, m3, m4, m5]
+print 'region polygon area', polygon_area(poly_region)/1000000.0
Index: /anuga_work/production/wa/onslow_2006/project_grad.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/project_grad.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/project_grad.py	(revision 7411)
@@ -0,0 +1,186 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+
+All filenames are given without extension
+"""
+
+from os import sep, environ, getenv, getcwd, umask
+from os.path import expanduser, basename, join
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon, number_mesh_triangles
+import sys
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+from time import localtime, strftime, gmtime
+from anuga.utilities.system_tools import get_user_name, get_host_name
+
+codename = 'project_grad.py' # FIXME can be obtained automatically as __file__
+
+home = join(getenv('INUNDATIONHOME'), 'data') # Location of Data   
+user = get_user_name()
+host = get_host_name()
+#needed when running using mpirun, mpirun doesn't inherit umask from .bashrc
+umask(002)
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'onslow'
+scenario = 'onslow_tsunami_scenario_2006'
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+
+#tide = 0.0 # MSL
+tide = 1.5 # HAT 
+#tide = -1.5 # LAT
+
+#Maybe will try to make project a class to allow these parameters to be passed in.
+alpha = 0.1
+friction = 0.01
+finaltime = 40000
+starttime = 3600 # Action starts around 9000
+setup='final'
+#setup = 'trial'
+#which_data = 'original'
+which_data = 'revised'
+boundary_event = 'onslow'
+
+boundary_event = 'exmouth'
+#boundary_event = 'onslow'
+#boundary_event = 'dampier'
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1.0
+    time_thinning=4
+    yieldstep=60
+
+anuga_dir = join(home, state, scenario, 'anuga')
+
+topographies_in_dir = join(anuga_dir, 'topographies')
+
+topographies_dir = join(anuga_dir, 'topographies') # Output dir for ANUGA
+
+if boundary_event =='dampier':
+    boundaries_name = 'onslow_3854_17042007' #Dampier gun
+    boundaries_in_dir = join(anuga_dir,'boundaries','urs','dampier','1_10000')
+
+if boundary_event=='onslow':
+    boundaries_name = 'onslow_3859_16052007' #onslow_hedland_broome gun
+    boundaries_in_dir = join(anuga_dir,'boundaries','urs','onslow_hedland_broome','1_10000')
+    
+if boundary_event=='exmouth':
+    boundaries_name = 'onslow_3103_18052007' #exmouth gun
+    boundaries_in_dir = join(anuga_dir,'boundaries','urs','exmouth','1_10000')
+
+dir_comment='_'+setup+'_'+str(tide)+'_'+\
+             str(user)+'_'+boundary_event+'_'+which_data
+
+
+# elevation data filenames
+
+if which_data == 'original':
+    ascii_grid_filenames = ['onslow_onshore_20m_dli', 'onslow_islands_dted2']
+    point_filenames = ['onslow_offshore_points', 'onslow_coast']
+
+if which_data == 'revised':
+    ascii_grid_filenames = ['revised_onshore_20m_dli', 'onslow_islands_dted2']
+    point_filenames = ['onslow_offshore_points', 'revised_coastline',
+                       'beach_survey', 'ONS16FINAL', 'ONS17FINAL', 'ONS18FINAL' ]
+
+# final topo name
+combined_name ='onslow_combined_elevation_grad_%s' %which_data
+combined_small_name = 'onslow_combined_elevation_grad'
+
+
+# Convert topo file locations into absolute pathnames
+for filename_list in [ascii_grid_filenames, point_filenames]:
+    for i, filename in enumerate(filename_list):
+        filename_list[i] = join(topographies_in_dir, filename)
+
+#final topo files
+combined_dir_name = join(topographies_dir, combined_name)
+combined_small_dir_name = join(topographies_dir, combined_small_name)
+
+mesh_dir = join(anuga_dir, 'meshes')
+mesh_name = join(mesh_dir, scenario_name)
+
+polygons_dir = join(anuga_dir, 'polygons') # Created with ArcGIS (csv files)
+tide_dir = join(anuga_dir, 'tide_data')
+
+#output locations
+output_dir = join(anuga_dir, 'outputs')+sep
+output_build_time_dir = output_dir+build_time+sep
+output_run_time_dir = output_dir +run_time+dir_comment+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+gauges_dir = join(anuga_dir,'gauges')
+gauge_name = 'gauge_location_onslow.csv'
+gauges_dir_name = gauges_dir + gauge_name
+
+#buildings_filename = gauges_dir + 'Onslow_res_Project.csv'
+#buildings_filename_out = 'Onslow_res_Project_modified.csv'
+
+# for ferret2sww
+south = degminsec2decimal_degrees(-20,30,0)
+north = degminsec2decimal_degrees(-17,10,0)
+west = degminsec2decimal_degrees(117,00,0)
+east = degminsec2decimal_degrees(120,00,0)
+
+# region to export (used from export_results.py)
+e_min_area = 300000   # Eastings min
+e_max_area = 310000
+n_min_area = 7600000
+n_max_area = 7610000
+# for old onslow town
+##e_min_area = 300000   # Eastings min
+##e_max_area = 310000
+##n_min_area = 7600000
+##n_max_area = 7610000
+                
+#FIXME (Ole): It is bad to read in polygons in project.py. If a file does not exist
+#project.py cannot be imported
+
+# Bounding polygon
+bounding_polygon = read_polygon(join(polygons_dir, 'domain.csv'))
+res_bounding_polygon = 500000*res_factor
+
+# Interior regions
+interior_regions_and_resolutions = {
+    'inner_region': 5000,
+    'region_50m': 50000,
+    'onslow_v2': 500,
+    'beach_left': 200,
+    'beach_right': 200}
+
+# Domain
+boundary_tags = {'back': [4, 5],   
+                 'side': [3, 6],
+                 'ocean': [0, 1, 2]}
+
+interior_regions = [] # Consider using dictionary for mesh interface.
+for area_name in interior_regions_and_resolutions.keys():
+    file_name = join(polygons_dir, area_name + '.csv')
+    
+    print 'Reading polygon from', file_name 
+    polygon = read_polygon(file_name)
+    base_resolution = interior_regions_and_resolutions[area_name]
+    
+    interior_regions.append([polygon, base_resolution*res_factor])
+
+trigs_min = number_mesh_triangles(interior_regions,
+                                  bounding_polygon,
+                                  res_bounding_polygon)
+
+onshore_polygon = read_polygon(join(home, state, scenario,'elevation_final','points',
+                                    'InitialCondition_points.csv'))
Index: /anuga_work/production/wa/onslow_2006/project_new.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/project_new.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/project_new.py	(revision 7411)
@@ -0,0 +1,127 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+Also includes origin for slump scenario.
+"""
+
+from os import sep, environ
+from os.path import expanduser
+from anuga.utilities.polygon import read_polygon
+import sys
+
+from anuga.pmesh.create_mesh import convert_from_latlon_to_utm
+
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+
+from time import localtime, strftime
+
+from os import getcwd
+                
+#Making assumptions about the location of scenario data
+scenario_dir_name = 'onslow_tsunami_scenario_2006'
+
+# 250m data to be provided
+coarsename = 'onsl_bathydem250' # get from Neil/Ingo (DEM or topo data)
+
+# 30m data to be provided
+onshore_name = 'onslow_onshore_30m_dted' # get from Neil/Ingo (DEM or topo data) 
+
+offshore_name = 'onslow_offshore_points'
+
+boundary_basename = 'SU-AU'
+
+#swollen/ all data output
+basename = 'source'
+
+codename = 'project.py'
+
+if sys.platform == 'win32':
+    home = environ['INUNDATIONHOME']     #Sandpit's parent dir
+else:    
+    home = expanduser('~')
+
+#Derive subdirectories and filenames
+timedir = strftime('%Y%m%d_%H%M%S',localtime()) #gets time for new dir
+outputdir = home+sep+scenario_dir_name+sep+'output'+sep+timedir+sep
+meshdir = home+sep+scenario_dir_name+sep+'meshes'+sep
+datadir = home+sep+scenario_dir_name+sep+'topographies'+sep
+
+polygondir = home+sep+scenario_dir_name+sep+'polygons'+sep
+boundarydir = home+sep+scenario_dir_name+sep+'boundaries'+sep
+
+codedir = getcwd()+sep
+                                
+codedirname = codedir + 'project.py'
+
+meshname = meshdir + basename
+
+coarsedemname = datadir + coarsename
+
+onshore_dem_name = datadir + onshore_name
+
+offshore_dem_name = datadir + offshore_name
+
+combined_dem_name = datadir + 'onslow_combined_elevation'
+
+outputname = outputdir + basename  #Used by post processing
+
+#!gauge_filename = outputdir + 'onslow_gauges.xya'
+#!gauge_outname = outputdir + 'gauges_max_output.xya'
+
+# clipping region for fine elevation data
+eastingmin = 250000
+eastingmax = 330000
+northingmin = 7580000
+northingmax = 7635000
+
+south = degminsec2decimal_degrees(-22,00,0)
+north = degminsec2decimal_degrees(-21,10,0)
+west = degminsec2decimal_degrees(114,30,0)
+east = degminsec2decimal_degrees(115,30,0)
+
+# region for visualisation
+eminviz = 260000
+emaxviz = 320000
+nminviz = 7590000
+nmaxviz = 7630000
+
+#Georeferencing
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+
+refzone = 50
+
+#Main Domain of Onslow: first run NB 21/2/06
+d0 = [305000, 7635000]
+d1 = [280000, 7635000]
+d2 = [250000, 7615000]
+d3 = [250000, 7590000]
+d4 = [310000, 7580000]
+d5 = [330000, 7610000]
+
+polyAll = [d0, d1, d2, d3, d4, d5]
+
+#Interior region - Onslow town
+
+i0 = [304000, 7608000]
+i1 = [302000, 7605000]
+i2 = [303000, 7602000]
+i3 = [305000, 7601000]
+i4 = [309000, 7603000]
+i5 = [307000, 7606500]
+
+poly_onslow = [i0, i1, i2, i3, i4, i5]
+
+#Thevenard Island
+j0 = [294000, 7629000]
+j1 = [285000, 7625000]
+j2 = [294000, 7621000]
+j3 = [299000, 7625000]
+
+poly_thevenard = [j0, j1, j2, j3]
+
+# Direction Is
+k0 = [309000, 7619000]
+k1 = [304000, 7619000]
+k2 = [304000, 7616500]
+k3 = [309000, 7616500]
+
+poly_direction = [k0, k1, k2, k3]
+
Index: /anuga_work/production/wa/onslow_2006/project_old.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/project_old.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/project_old.py	(revision 7411)
@@ -0,0 +1,129 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+Also includes origin for slump scenario.
+"""
+
+from os import sep, environ
+from os.path import expanduser
+from anuga.utilities.polygon import read_polygon
+import sys
+
+from anuga.pmesh.create_mesh import convert_from_latlon_to_utm
+
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+
+from time import localtime, strftime
+
+from os import getcwd
+
+                
+#Making assumptions about the location of scenario data
+scenario_dir_name = 'onslow_tsunami_scenario_2006'
+
+# 250m data to be provided
+coarsename = 'onsl_bathydem250' # get from Neil/Ingo (DEM or topo data)
+
+# 30m data to be provided
+onshore_name = 'onslow_onshore_30m_dted' # get from Neil/Ingo (DEM or topo data) 
+
+offshore_name = 'onslow_offshore_points'
+
+boundary_basename = 'SU-AU'
+
+#swollen/ all data output
+basename = 'source'
+
+codename = 'project.py'
+
+if sys.platform == 'win32':
+    home = environ['INUNDATIONHOME']     #Sandpit's parent dir
+else:    
+    home = expanduser('~')
+
+#Derive subdirectories and filenames
+
+
+meshdir = home+sep+scenario_dir_name+sep+'meshes'+sep
+datadir = home+sep+scenario_dir_name+sep+'topographies'+sep
+
+timedir = strftime('%Y%m%d_%H%M%S',localtime()) #gets time for new dir
+outputdir = home+sep+scenario_dir_name+sep+'output'+sep+timedir+sep
+polygondir = home+sep+scenario_dir_name+sep+'polygons'+sep
+boundarydir = home+sep+scenario_dir_name+sep+'boundaries'+sep
+
+codedir = getcwd()+sep
+codedirname = codedir + 'project.py'
+
+meshname = meshdir + basename
+
+coarsedemname = datadir + coarsename
+
+onshore_dem_name = datadir + onshore_name
+
+offshore_dem_name = datadir + offshore_name
+
+combined_dem_name = datadir + 'onslow_combined_elevation'
+
+outputname = outputdir + basename  #Used by post processing
+
+#!gauge_filename = outputdir + 'onslow_gauges.xya'
+#!gauge_outname = outputdir + 'gauges_max_output.xya'
+
+# clipping region for fine elevation data
+eastingmin = 250000
+eastingmax = 330000
+northingmin = 7580000
+northingmax = 7635000
+
+south = degminsec2decimal_degrees(-22,00,0)
+north = degminsec2decimal_degrees(-21,10,0)
+west = degminsec2decimal_degrees(114,30,0)
+east = degminsec2decimal_degrees(115,30,0)
+
+# region for visualisation
+eminviz = 260000
+emaxviz = 320000
+nminviz = 7590000
+nmaxviz = 7630000
+
+#Georeferencing
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+
+refzone = 50
+
+#Main Domain of Onslow: first run NB 21/2/06
+d0 = [305000, 7635000]
+d1 = [280000, 7635000]
+d2 = [250000, 7615000]
+d3 = [250000, 7590000]
+d4 = [310000, 7580000]
+d5 = [330000, 7610000]
+
+polyAll = [d0, d1, d2, d3, d4, d5]
+
+#Interior region - Onslow town
+
+i0 = [304000, 7608000]
+i1 = [302000, 7605000]
+i2 = [303000, 7602000]
+i3 = [305000, 7601000]
+i4 = [309000, 7603000]
+i5 = [307000, 7606500]
+
+poly_onslow = [i0, i1, i2, i3, i4, i5]
+
+#Thevenard Island
+j0 = [294000, 7629000]
+j1 = [285000, 7625000]
+j2 = [294000, 7621000]
+j3 = [299000, 7625000]
+
+poly_thevenard = [j0, j1, j2, j3]
+
+# Direction Is
+k0 = [309000, 7619000]
+k1 = [304000, 7619000]
+k2 = [304000, 7616500]
+k3 = [309000, 7616500]
+
+poly_direction = [k0, k1, k2, k3]
+
Index: /anuga_work/production/wa/onslow_2006/project_urs.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/project_urs.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/project_urs.py	(revision 7411)
@@ -0,0 +1,256 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+"""
+
+from os import sep, environ, getenv, getcwd,umask
+from os.path import expanduser
+import sys
+from time import localtime, strftime, gmtime
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon, number_mesh_triangles
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees, convert_from_latlon_to_utm
+from anuga.utilities.system_tools import get_user_name, get_host_name
+
+# file and system info
+#---------------------------------
+codename = 'project.py'
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent dir   
+user = get_user_name()
+host = get_host_name()
+#needed when running using mpirun, mpirun doesn't inherit umask from .bashrc
+umask(002)
+
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+#home += sep +'data'
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+
+#tide = -1.5
+#tide = 0.0
+tide = 1.5
+
+#Maybe will try to make project a class to allow these parameters to be passed in.
+alpha = 0.1
+friction=0.01
+starttime=3600
+finaltime=25000
+setup='final'
+#source='exmouth'
+source='onslow'
+#source='dampier'
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=1
+    yieldstep=60
+if setup =='store':
+    print'store'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240    
+
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(source)+'_'+str(user)
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'onslow'
+scenario = 'onslow_tsunami_scenario_2006'
+
+# onshore data provided by WA DLI
+onshore_name = 'onslow_onshore_30m_dted2' # original
+onshore_name1 = 'onslow_onshore_20m_dli' # original
+
+# AHO + DPI data + colin French coastline
+coast_name = 'onslow_coast'
+islands_name = 'onslow_islands_dted2'
+offshore_name = 'onslow_offshore_points'
+offshore1_name = '1'
+offshore2_name = '2'
+
+#final topo name
+combined_name ='onslow_combined_elevation'
+combined_smaller_name = 'onslow_combined_elevation_small'
+combined_smallest_name = 'onslow_combined_elevation_smallest'
+
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+#anuga_dir_name = temp_dir + temp_time+sep
+
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'070112'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+topographies_time_dir = topographies_dir+build_time+sep
+
+
+# input topo file location
+onshore_in_dir_name = topographies_in_dir + onshore_name
+coast_in_dir_name = topographies_in_dir + coast_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+offshore1_in_dir_name = topographies_in_dir + offshore1_name
+offshore2_in_dir_name = topographies_in_dir + offshore2_name
+
+onshore_dir_name = topographies_dir + onshore_name
+coast_dir_name = topographies_dir + coast_name
+offshore_dir_name = topographies_dir + offshore_name
+offshore1_dir_name = topographies_dir + offshore1_name
+offshore2_dir_name = topographies_dir + offshore2_name
+
+#final topo files
+combined_dir_name = topographies_dir + combined_name
+combined_time_dir_name = topographies_time_dir + combined_name
+#combined_smaller_dir_name = topographies_dir + combined_smaller_name
+#combined_smallest_dir_name = topographies_dir + combined_smallest_name
+#combined_time_dir_final_name = topographies_time_dir + combined_final_name
+
+meshes_dir = anuga_dir+'meshes'+sep
+meshes_dir_name = meshes_dir + scenario_name
+
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+
+
+if source =='dampier':
+    boundaries_name = 'onslow_3854_17042007' #Dampier gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'dampier'+sep+'1_10000'+sep
+
+if source=='onslow':
+    boundaries_name = 'onslow_3859_16052007' #onslow_hedland_broome gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'onslow_hedland_broome'+sep+'1_10000'+sep
+    
+if source=='exmouth':
+    boundaries_name = 'onslow_3103_18052007' #exmouth gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'exmouth'+sep+'1_10000'+sep
+
+#boundaries locations
+boundaries_source = ''
+#boundaries_in_dir = anuga_dir+'boundaries'+sep
+boundaries_in_dir_name = boundaries_in_dir + boundaries_name
+
+boundaries_dir = anuga_dir+'boundaries'+sep
+boundaries_dir_name = boundaries_dir + boundaries_name
+
+#output locations
+output_dir = anuga_dir+'outputs'+sep
+output_build_time_dir = output_dir+build_time+'_'+source+sep
+#output_run_time_dir = output_dir +run_time+dir_comment+sep
+output_run_time_dir = output_dir +'20070619_042140_run_final_0_onslow_nbartzis'+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+gauges_dir = anuga_dir+'gauges'+sep
+
+gauges_dir_name = gauges_dir + 'gauge_location_onslow.csv'
+gauges_dir_name_bindi = gauges_dir + 'gauge_location_bindi.csv'
+gauges_comparison_dir_name_50 = gauges_dir + '50_gauges.xya'
+gauges_comparison_dir_name = gauges_dir + 'MOST_comparison_gauges.xya'
+gauges_comparison_dir_name_3d = gauges_dir + 'MOST_comparison_gauges_3d.xya'
+
+community_filename = gauges_dir + 'CHINS_v2.csv'
+community_scenario = gauges_dir + 'community_onslow.csv'
+buildings_filename = gauges_dir + 'Onslow_res_Project.csv'
+buildings_filename_out =output_run_time_dir + 'Onslow_res_Project_modified.csv'
+###############################
+# Domain definitions
+###############################
+
+south_boundary = degminsec2decimal_degrees(-22,15,0)
+north_boundary = degminsec2decimal_degrees(-20,30,0)
+west_boundary = degminsec2decimal_degrees(114,15,0)
+east_boundary = degminsec2decimal_degrees(115,50,0)
+
+#Updated Main Domain of Onslow: first run NB 6/4/06
+d0 = [310000, 7690000]
+d1 = [280000, 7690000]
+d2 = [270000, 7645000]
+d3 = [240000, 7625000]
+d4 = [270000, 7580000]
+d5 = [300000, 7590000]
+d6 = [340000, 7610000]
+
+poly_all = [d0, d1, d2, d3, d4, d5, d6]
+res_poly_all = 100000*res_factor
+print 'bounding polygon area', polygon_area(poly_all)/1000000.0
+#Interior region - Onslow town
+
+#for visualisation
+#i0 = [304000, 7609000]
+#i1 = [301500, 7605000]
+#i2 = [304000, 7603000]
+#i3 = [307000, 7602000]
+#i4 = [309000, 7603000]
+#i5 = [311000, 7607000]
+
+i0 = [304000, 7607000]
+i1 = [302000, 7605000]
+i2 = [304000, 7603000]
+i3 = [307000, 7602000]
+i4 = [309000, 7603000]
+i5 = [307000, 7606000]
+poly_onslow = [i0, i1, i2, i3, i4, i5]
+res_onslow = 500*res_factor
+print 'onslow polygon area', polygon_area(poly_onslow)/1000000.0
+
+#Thevenard Island
+j0 = [294000, 7629000]
+j1 = [285000, 7625000]
+j2 = [294000, 7621000]
+j3 = [299000, 7625000]
+poly_thevenard = [j0, j1, j2, j3]
+res_thevenard = 2500*res_factor
+print 'thevenard polygon area', polygon_area(poly_thevenard)/1000000.0
+
+#med res around onslow
+l0 = [300000, 7610000]
+l1 = [285000, 7600000]
+l2 = [300000, 7597500]
+l3 = [310000, 7600000]
+l4 = [315000, 7610000]
+poly_coast = [l0, l1, l2, l3, l4]
+res_coast = 2500*res_factor
+print 'coast polygon area', polygon_area(poly_coast)/1000000.0
+
+#general coast and local area to onslow region
+m0 = [270000, 7581000]
+m1 = [300000, 7591000]
+m2 = [339000, 7610000]
+m3 = [330000, 7630000]
+m4 = [290000, 7640000]
+m5 = [260000, 7600000]
+poly_region = [m0, m1, m2, m3, m4, m5]
+res_region = 20000*res_factor
+print 'region polygon area', polygon_area(poly_region)/1000000.0
+
+interior_regions = [[poly_onslow,res_onslow],[poly_coast,res_coast],
+                    [poly_region,res_region]
+#                   ,[poly_thevenard,res_thevenard]
+                    ]
+
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+
+print 'min number triangles', trigs_min
+
+
+###################################################################
+# Clipping regions for export to asc and regions for clipping data
+###################################################################
+
+poly_mainland = read_polygon(polygons_dir+'InitialCondition_points.csv')
+
+# region to export
+eastingmin = 300000
+eastingmax = 310000
+northingmin = 7600000
+northingmax = 7610000
+
Index: /anuga_work/production/wa/onslow_2006/report/HAT_damage.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/HAT_damage.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/HAT_damage.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{figure}[hbt] 
+%\centerline{ \includegraphics[width=100mm, height=75mm]{../report_figures/.jpg}}  
+\caption{Damage modelling for the HAT scenario for Onslow region.}  
+\label{fig:HAT_damage}
+\end{figure}
Index: /anuga_work/production/wa/onslow_2006/report/HAT_map.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/HAT_map.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/HAT_map.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{sidewaysfigure}
+\centerline{ \includegraphics[width=\paperwidth]{../report_figures/high_tide_20060704_063005.jpg}} 
+\caption{Maximum inundation map for the HAT scenario for Onslow region. Data: WA DLI, DPI and AHO.}  
+\label{fig:HAT_max_inundation}
+\end{sidewaysfigure}
Index: /anuga_work/production/wa/onslow_2006/report/LAT_damage.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/LAT_damage.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/LAT_damage.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{figure}[hbt] 
+%\centerline{ \includegraphics[width=100mm, height=75mm]{../report_figures/.jpg}}  
+\caption{Damage modelling for the LAT scenario for Onslow region.}  
+\label{fig:LAT_damage}
+\end{figure}
Index: /anuga_work/production/wa/onslow_2006/report/LAT_map.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/LAT_map.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/LAT_map.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{sidewaysfigure}
+\centerline{ \includegraphics[width=\paperwidth]{../report_figures/low_tide_20060706_235246.jpg}}  
+\caption{Maximum inundation map for the LAT scenario for Onslow region.}  
+\label{fig:LAT_max_inundation}
+\end{sidewaysfigure}
Index: /anuga_work/production/wa/onslow_2006/report/MSL_damage.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/MSL_damage.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/MSL_damage.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{figure}[hbt] 
+%\centerline{ \includegraphics[width=100mm, height=75mm]{../report_figures/.jpg}}  
+\caption{Damage modelling for the MSL scenario for Onslow region.}  
+\label{fig:MSL_damage}
+\end{figure}
Index: /anuga_work/production/wa/onslow_2006/report/MSL_map.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/MSL_map.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/MSL_map.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{sidewaysfigure}
+\centerline{ \includegraphics[width=\paperwidth]{../report_figures/mid_tide_20060704_063234.jpg}}  
+\caption{Maximum inundation map for the MSL scenario for Onslow region. Data: WA DLI, DPI and AHO.}  
+\label{fig:MSL_max_inundation}
+\end{sidewaysfigure}
Index: /anuga_work/production/wa/onslow_2006/report/acknowledgements.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/acknowledgements.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/acknowledgements.tex	(revision 7411)
@@ -0,0 +1,25 @@
+
+The Inundation Modelling Team in 
+the Risk Research Group at GA would like to thank a number of organisations and groups
+in providing input in this study;
+
+\begin{itemize}
+\item The AHO for their assistance in supplying digitised fairsheet data for the priority areas
+along the NW Shelf. 
+\item The WA DPI in their assistance in supplying digitised state fairsheet data
+for nominated areas and ably assisting in queries regarding bathymetric data
+\item The WA DLI in their assistance in supplying the onshore 20m DEM for use in this project
+\item The National Mapping and Information Group, in particular Hamish Anderson, for sourcing onshore
+data for the FESA project and building a DEM
+suitable for purposes of inundation modelling
+\item The Petroleum and Marine Divison, in particular Kathryn Tobin, Mike Sexton, Phil O'Brien
+and Mark Alcock, for sourcing offshore data for the regions of interest and providing
+advice on bathymetric data issues, 
+\item The GIS team in the Risk Assessment Methods Project (RAMP) for developing the
+decision support tool and providing assistance to the inundation modellers on a frequent basis
+\item The exposure database development team in RAMP for providing the necessary information
+to undertake the damage modelling
+\item The engineering section in RAMP for calculating the damage estimates, 
+and finally
+\item FESA, for providing strong support to the project.
+\end{itemize}
Index: /anuga_work/production/wa/onslow_2006/report/anuga_setup.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/anuga_setup.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/anuga_setup.tex	(revision 7411)
@@ -0,0 +1,114 @@
+The following information is required to undertake the 
+inundation modelling;
+
+\begin{itemize}
+\item onshore and offshore elevation data (topographic and bathymetric data, 
+see Section \ref{sec:data}),
+\item initial conditions, such as initial water levels (e.g. determined by tides),
+\item boundary conditions (the tsunami source as described in 
+Section \ref{sec:methodology}), and
+\item computational requirements relating to the mesh construction.
+\end{itemize}
+ 
+The initial conditions used for this scenario are MSL, HAT and LAT which were
+defined in Section \ref{sec:data}. Figure \ref{fig:IC} shows the MSL, HAT and 
+LAT contours to illustrate the water level for each of these inial conditions.
+The dynamics of
+tidal effects (that is, the changes in water height over time for
+the entire study area) are not currently modelled.
+Sea floor friction will generally provide resistance to the water flow
+and thus reduce the impact somewhat. However, limited
+research has been carried out to determine 
+the friction coefficients, and 
+thus it has not been incorporated
+in the scenario. The 
+results are therefore likely to be over estimates.
+
+\begin{figure}[h]
+
+  \centerline{\includegraphics[width=\paperwidth]{../report_figures/onslow_dli_contour.jpg}}
+
+  \caption{Onslow region showing the initial conditions used for the study; 
+  -1.5m AHD (LAT), 0m AHD (MSL) and 1.5m AHD (HAT) contour lines.}
+  \label{fig:IC}
+\end{figure}
+
+
+To set up a model for the tsunami scenario, a study area is first 
+determined. Preliminary investigations have indicated that the
+output from MOST or URS should be input to ANUGA 
+at the 100m water depth. Historical run-up heights are 
+of the order of 10 m and we would expect that a tsunami wave
+would penetrate no higher for this scenario, hence we have
+bounded our study region at 10m elevation.
+Current computation requirements define a coastline
+extent of around 100 km. Therefore, the study area of around 6300 km$^2$ 
+covers approximately 100 km of
+coastline and extends offshore to the 100m contour line and inshore to 
+approximately 10m elevation. 
+
+The finite volume technique relies on the construction of a triangular mesh which covers the study region. 
+This mesh can be altered to suit the needs of the scenario in question. The mesh can be refined in areas of 
+interest, particularly in the coastal region where complex behaviour is likely to occur. 
+In setting up the model, the user defines the area of the triangular cells in each region of interest\footnote{Note that the cell 
+area will be the maximum cell area within the defined region and that each 
+cell in the region does not necessarily have the same area.}.
+The cell areas should not be too small as this will cause unrealisticly long computational time, 
+and not too great as this may inadequately capture important behaviour. 
+%There are no gains in choosing the area to be less than the supporting data.
+Figure \ref{fig:onslow_area} shows the study area with regions of difference cell areas. The total number
+of cells is 401939. 
+Lateral accuracy refers to the distance at which we are confident in stating a region is inundated. 
+Figure \ref{fig:onslow_area} shows the maximum triangular cell area and lateral accuracy for each region. 
+Therefore we can only be confident in the calculated inundation extent in the Onslow town centre to within 30 m.
+
+
+\begin{figure}[hbt]
+
+  \centerline{ \includegraphics[scale=0.125]{../report_figures/onslow_resolution_zones.jpg}}
+
+  \caption{Study area for Onslow scenario highlighting four regions of increased refinement.
+Region 1: Surrounds Onslow town centre with a cell area of 500 m$^2$ (lateral accuracy 30 m).
+Region 2: Surrounds the coastal region with a cell area of 2500 m$^2$ (lateral accuracy 70 m).
+Region 3: Water depths to the 50m contour line (approximately) with a cell area of 20000 m$^2$ (lateral accuracy 200 m).
+Region 4: Water depths to the boundary (approximately 100m contour line) with a cell area of 100000 m$^2$ (lateral accuracy 445 m).
+}
+  \label{fig:onslow_area}
+\end{figure}
+
+
+The final item to be addressed to complete the model setup is the 
+definition of the boundary condition. As 
+discussed in Section \ref{sec:methodology}, a series of events corresponding
+to a range of return periods are selected as the tsunami sources.
+The resultant tsunami wave is made up of a series
+of waves with different amplitudes which is affected by the energy
+and style of the event as well as the bathymetry whilst it travels
+from its source to Onslow. The amplitude and velocity of each of these
+waves are then provided to ANUGA as boundary conditions and propagated
+inshore.
+
+The tsunami generation and propagation modelling uses the URS paradigm.
+The URS output is saved every 2.5 seconds and with a spatial resolution
+of two arc minutes.
+
+Sea floor friction will generally provide resistance to the water flow
+and thus reduce the impact somewhat. Initial experimental results 
+indicate that the friction coefficient shoudl be 0.017.
+The following table summarises the modelling parameters;
+
+\begin{table}
+\begin{center}
+\caption{Parameters used in ANUGA for the Onslow scenario.}
+\begin{tabular}{|l|l|l|}\hline
+Mesh & & \\ \hline
+& resolution in Region 1 & 500 m$^2$ \\ \hline
+& resolution in Region 2 & 2500 m$^2$ \\ \hline
+& resolution in Region 3 & 20000 m$^2$ \\ \hline
+& remaining resolution & 100 000 m$^2$ \\ \hline
+Model parameters & & \\ \hline
+& friction & 0.017 \\ \hline
+& minimum stored height & 0.1 m \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
Index: /anuga_work/production/wa/onslow_2006/report/damage.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/damage.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/damage.tex	(revision 7411)
@@ -0,0 +1,108 @@
+In this report, impact modelling refers to casualties and
+damage to residential buildings as a result
+of the inundation described in Section \ref{sec:results}. It is assumed
+that the event occurs at night. 
+Exposure data are sourced from the National Building Exposure Database (NBED), 
+developed by GA\footnote{http://www.ga.gov.au/urban/projects/ramp/NBED.jsp}. 
+It contains information about residential buildings, people and the
+cost of replacing buildings and contents.
+
+To develop building damage and casuality estimates, 
+residential collapse vulnerability models and casualty models were developed.
+The vulnerability models have been developed for 
+framed residential construction based on limited data found in the literature
+as well as observations from the Indian Ocean tsunami event. 
+The models predict the collapse 
+probability for an exposed population and incorporates the following 
+parameters thought to influence building damage \cite{papathoma:vulnerability},
+
+\begin{itemize}
+\item	inundation depth at building	
+\item	distance from the coast	
+\item	building material (residential framed construction)	
+\item	inundation depth in house above floor level
+\end{itemize}	
+
+The collapse vulnerability models used are presented in Table \ref{table:collapse}. 
+%In applying the model, all structures in the inundation zone were 
+%spatially located and the local water depth and building row 
+%number from the exposed edge of the suburb were determined for each %structure.
+
+Casualty models were based on the
+storm surge models used for the Cairns Cyclone Scenario and 
+through consultation with Dr David Cooper of NSW Health, \cite{cooper:2005}. 
+The injury probabilities for exposed populations were determined 
+based on the nocturnal nature of the event, the collapse outcome 
+for the structure, the water depth with respect to 
+sleeping height (1.0 m) and the limited warning noise for people 
+in the first three city blocks (six house rows) that could potentially 
+awaken them. The three injury categories correspond with the 
+categories presented in HAZUS-MH \cite{NIBS:2003} for earthquake 
+related injury. The casualty model used is presented in Table
+\ref{table:casualty} 
+and the injury categories are presented in Table \ref{table:injury}. 
+Input data comprised of resident population data at census
+district level derived from the ABS 2001 Census. Given the exposure database is
+based on residential structures, we assume that the
+population are at home and sleeping when the event occurs and that there is no
+warning. Therefore, the casualty estimates would be significantly different
+if the event were to occur during the day when people are at work, travelling
+in a vehicle, spending time on the beach, for example, or if the event occurred
+during a major holiday season.
+
+There are an estimated
+325 residential structures and a population of approximately 770
+in Onslow\footnote{Population is determined by census data and the 1999
+ABS housing survey}. 
+The damage to the residential structures in the Onslow community
+is summarised in Table \ref{table:damageoutput}. As expected, the
+greatest impact is found for the high tide scenario. The percentage
+of repair cost to structural value shown is based on the total structural value
+of \$71M. Likewise, the percentage of contents loss shown is
+based on the total contents value of \$101M for
+the Onslow region\footnote{These values are based on 2003 figures.}. 
+The injuries sustained is summarised in Table \ref{table:injuries}. 
+The HAT scenario is the only scenario to cause damage 
+to Onslow with around 15-20\% of the population affected. 
+
+\begin{table}[h]
+\begin{center}
+\caption{Residential damage sustained for the MSL, HAT and LAT scenarios.}
+\label{table:damageoutput}
+\begin{tabular}{|l|l|l|l|l|l|l|}\hline
+&Houses  & Houses  & Structural & Repair Cost \% & Contents & Contents Loss \% \\ 
+&Inundated & Collapsed & Repair Cost 
+& of Total Value & Losses & of Total Value \\ \hline
+HAT & 100 &2&\$8M & 11\%&\$16M & 16 \% \\ \hline
+MSL & 0 & 0 & \$0 &   & \$0 &  \\ \hline
+LAT & 0 & 0 & \$0 &   & \$0 & \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+\begin{table}[h]
+\begin{center}
+\caption{Injuries sustained for the MSL, HAT and LAT scenarios.}
+\label{table:injuries}
+\begin{tabular}{|l|l|l|l|l|l|}\hline
+&Minor & Moderate & Serious & Fatal \\ \hline
+HAT & 10's & 10's & 10's & 10's \\ \hline
+MSL & 0& 0 & 0 &0 \\ \hline
+LAT & 0&0 & 0& 0\\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+Tsunami impact on indigeneous communities should be considered
+in the future as a number of communities exist in coastal regions of north west WA.
+These communities are typically not included in national residential databases 
+and would be therefore overlooked in damage model estimates
+We can confirm that Bindi Bindi is not contained in the NBED.
+There is one indigeneous community located in this study area as seen
+in Figure \ref{fig:points}. 
+The population of the Bindibindi community is 140 
+(18 \% of the Onslow population)
+and is situated close to the coast as seen in Figure \ref{fig:points}.
+During the HAT scenario, over 1 m of water will inundate parts of the community (Figure 
+\ref{fig:gaugeBindiBindiCommunity}) which would cause 
+significant impact.
Index: /anuga_work/production/wa/onslow_2006/report/damage_inputs.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/damage_inputs.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/damage_inputs.tex	(revision 7411)
@@ -0,0 +1,64 @@
+\begin{table}[h]
+\begin{center}
+\caption{Framed residential building collapse probability. $h$ is the
+inundation height (m) above ground where the ground floor height of 0.3m is
+assumed.}
+\label{table:collapse}
+\begin{tabular}{|l|l|l|l|l|l|}\hline
+Distance from coast ($d[m]$) & 
+$h$<1.0 &1.0<$h$<2.0&	2.0<$h$<3.0	&3.0<$h$<5.0	&$h$>5.0 \\ \hline
+$d < 125$	 &0.05	&0.6	&0.8	&0.95	&0.99 \\ \hline
+$125 < d < 200$ &0.02	&0.3	&0.4	&0.7	&0.9 \\ \hline
+$200 < d < 250$	&0.01	&0.1	&0.25	&0.5	&0.65 \\ \hline
+$200 < d$	&0.0	&0.05	&0.15	&0.3	&0.45 \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+\begin{table}[h]
+\begin{center}
+\caption{Mortality and injury state probability}
+\label{table:casualty} 
+\begin{tabular}{|l|l|l|l|l|l|l|}\hline
+Hazard Exposure	& depth above floor & Unharmed	&Minor
+	&Moderate 	&Serious	&Death \\ \hline
+Collapse	&<1.0	&0.3	&0.28	&0.08	&0.04	&0.30 \\ \hline
+	&>1.0	&0.01	&0.028	&0.008	&0.004	&0.95 \\ \hline
+No Collapse - $d < 250$	&<1.0	&0.35	&0.40	&0.1	&0.05	&0.10 
+\\ \hline
+	&>1.0	&0.1	&0.28	&0.08	&0.04	&0.50 \\ \hline
+No Collapse - $250 < d$	&<1.0	&0.4	&0.4	&0.1	&0.05	&0.05 \\ \hline
+	&>1.0	&0.12	&0.33	&0.1	&0.05	&0.40 \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+\begin{table}[h]
+\begin{center}
+\caption{Injury level classificationse. Floor height is assumed to be 30cm}
+\label{table:injury}
+\begin{tabular*}{\textwidth}{|l|p{.695\textwidth}|}\hline
+Injury Severity Level	&Injury Description \\ \hline
+Minor Injury
+Severity 1	&Injuries requiring basic medical aid without requiring 
+hospitalisation.
+These types of injuries would require bandages or observation. 
+Some examples are: a sprain, a severe cut requiring stitches, 
+a  bump on the head without loss of consciousness. \\ \hline
+Moderate Injury
+Severity 2	&Injuries requiring a greater degree of 
+medical care and use of medical technology such as x-rays or surgery, 
+but not expected to progress to a life threatening status.
+Some examples are: a bump on the head that causes loss of consciousness, 
+fractured bone, dehydration or exposure. \\ \hline
+Severe Injury
+Severity 3	&Injuries that pose an immediate life threatening 
+condition if not treated adequately and expeditiously. Some examples are: 
+uncontrolled bleeding, punctured organ, other internal injuries, 
+spinal column injuries, or crush syndrome. \\ \hline
+Fatal
+Severity 4	&Instantaneously killed or mortally injured. \\ \hline
+\end{tabular*}
+\end{center}
+\end{table}
+\clearpage
Index: /anuga_work/production/wa/onslow_2006/report/data.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/data.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/data.tex	(revision 7411)
@@ -0,0 +1,111 @@
+The calculated run-up height and resulting inundation ashore is controlled by
+the input topographic and bathymetric elevation, the
+initial and boundary conditions, as well as the cell area of the computational
+mesh. 
+Ideally, the topographic and bathymetric data
+should adequately capture all complex features
+of the underlying bathymetry and topography. Any limitations
+in the resolution and accuracy of the data will introduce 
+errors to the inundation maps, in addition to the range of approximations
+made within the model.
+
+In this study, we used the Australian Height Datum (AHD)
+as the vertical datum. Mean Sea Level (MSL) is approximately equal to
+0m AHD with the Highest Astronomical Tide (HAT) 
+and Lowest Astronomical Tide (LAT) defined as 1.5m AHD
+and -1.5m AHD respectively for Onslow \cite{antt:06}. 
+As an aside, current work at GA is
+extracting information from LANDSAT imagery to reconstruct the 
+tidal variations for various WA locations. Future modelling of
+these areas will incorporate this information.
+
+Data for this study have been sourced from a number of agencies. With
+respect to the onshore data, the Defence Imagery and Geospatial
+Organisation (DIGO) supplied the Digital Terrain Elevation
+Data Level 2 (DTED) which has been authorised for Australian Tsunami
+Warning System use only. The resolution of this data is 1 second
+(about 30 metres), and has been produced from 1:50 000 contours, elevations and
+drainage. In addition, the Department of Land Information (DLI) has provided a
+20m Digital Elevation Model (DEM) and orthophotography 
+covering the NW Shelf. The DTED Level 2 data is ``bare earth'' while the 
+DLI data is distorted by vegetation and buildings.  
+
+With respect to the offshore data, the Department of Planning and
+Infrastructure (DPI) have provided state digital fairsheet data around
+Onslow. This data covers a very small geographic area. 
+Similar data have been provided by DPI for Pt Hedland and Broome.
+The Australian Hydrographic Office (AHO) has supplied extensive
+fairsheet data which has also been utilised. In contrast to the onshore data, 
+the offshore data is a series of survey points which is typically 
+not supplied on a fixed grid. In addition, offshore data typically 
+does not have the coverage of the onshore data, and often the 
+offshore data will have gaps where surveys have not been conducted.
+The coastline has been generated by
+using the aerial photography, two detailed surveys provided
+by WA DPI and a number of total station surveys \footnote{Total station survey information
+has been used to verify the elevation data. A total station is an
+electronic device that combines the ability to measure a position 
+horizontally and vertically at the same time.} of Onslow. 
+The WA DLI data surrounding the coast are error prone and
+have been clipped at the derived coastline. 
+
+Figure \ref{fig:contours_compare}(a) shows the contour lines for
+HAT, MSL and LAT for Onslow using the DTED data where it is evident 
+that the extent of the tidal inundation is exaggerated. In particular,
+parts of Onslow town appears to be inundated at HAT before a tsunami has
+even been generated. This is due to
+shortcomings with the digital elevation model (DEM) created from 
+the DTED data. 
+Figure \ref{fig:contours_compare}(b) shows
+the contour lines for HAT, MSL and LAT for Onslow using the WA DLI data.
+It is obvious that there are significant differences in each DEM with
+the total station survey information and the knowledge
+of the HAT contour line pointing to increased confidence in the WA DLI
+data over the DTED data for use in the inundation modelling.
+Consequently the DLI data has been used in this study.
+
+
+\begin{figure}[p]
+\center{(a)}
+  \centerline{ \includegraphics[width=150mm, height=100mm]
+{../report_figures/onslow_dted_contour.jpg}}
+
+ % \caption{Onslow region showing the -1.5m AHD (LAT), 0m AHD (MSL)
+ %and -1.5m AHD (LAT) contour lines using the DTED Level 2 data.}
+ % \label{fig:contours_dted}
+%\end{figure}
+
+%\begin{figure}[hbt]
+\center{(b)}
+  \centerline{ \includegraphics[width=150mm, height=100mm]
+{../report_figures/onslow_dli_contour.jpg}}
+
+  \caption{Onslow region showing the -1.5m AHD (LAT), 0m AHD (MSL) 
+and 1.5m AHD (HAT) contour lines using the (a) DTED Level 2 data and
+the (b) WA DLI data.}
+ % \label{fig:contours_dli}
+ \label{fig:contours_compare}
+\end{figure}
+
+
+Appendix \ref{sec:metadata} provides more details and the supporting metadata 
+for this study, including images of the data extent.
+Table \ref{table:data} summarises the available data. 
+
+\begin{table}
+\caption{Available data for the North West shelf tsunami inundation studies.}
+\label{table:data}
+\begin{center}
+\begin{tabular}{|l|l|}\hline
+Data & Specifications \\ \hline 
+DIGO DTED Level 2  & Onshore, 1 second $\approx$ 30m \\ \hline 
+DLI & Onshore, 20m DEM and orthophotography \\ \hline
+DPI & Offshore, fairsheet data around Onslow \\ \hline
+AHO & Offshore, fairsheet data for North West Shelf region \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+
+\pagebreak
+
Index: /anuga_work/production/wa/onslow_2006/report/discussion.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/discussion.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/discussion.tex	(revision 7411)
@@ -0,0 +1,15 @@
+The purpose of this section is to show the differences of impact
+and the importance of using the
+best possible data set. Given that the 1.5m AHD contour
+line is further from the coast for the DTED data than the DLI data, we
+expect the inundation to extend further and thus be greater than
+that seen in Figure \ref{fig:MSL_max_inundation}. 
+Further, the impact modelling
+will result in inflated structural and contents loss figures as well as
+numbers of people affected.
+These results point to the need for the best 
+available data so that more accurate predictions regarding the 
+inundation can be made.
+
+
+
Index: /anuga_work/production/wa/onslow_2006/report/execsum.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/execsum.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/execsum.tex	(revision 7411)
@@ -0,0 +1,29 @@
+This report is being provided to the Fire and Emergency Services Authority
+(FESA) as part of the Collaborative Research Agreement (CRA) 
+with Geoscience Australia (GA), Tsunami Impact Modelling for WA.
+FESA has recognised the potential vulnerability of the Western Australia
+coastline to tsunami originating from earthquakes on
+the Sunda Arc subduction zone. 
+There is historic evidence of tsunami affecting the 
+Western Australia coastline, \cite{CB:ausgeo}, 
+and FESA has sought to assess
+the relative risk of its urban and regional communities to the tsunami
+threat and develop detailed response plans for a range of plausible events.
+
+This report describes the modelling methodology and results
+for a number of tsunami-genic events with varied return periods
+as they impact the Onslow region.
+In particular, maximum inundation maps are shown
+and discussed 
+for the event occurring at mean sea level as well as 
+highest and lowest astronomical tide. The inundation results allow
+estimation of the number of houses inundated and collapsed, as well as
+the numbers of persons affected. The Onslow township has approximately
+350 residential structures and a population of around 800.
+
+The results of this study will allow an assessment of the relative tsunami risk 
+to communities along the NW Shelf of WA. 
+This report and the decision support tool are the 
+June 2007 deliverables of the Collaborative Research Agreement
+between FESA and GA.
+
Index: /anuga_work/production/wa/onslow_2006/report/interpretation.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/interpretation.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/interpretation.tex	(revision 7411)
@@ -0,0 +1,65 @@
+The inundation extent calculated at Onslow will be described in this section with
+impact assessments following in Section \ref{sec:impact}.
+% there will need to be something in here for when doing a range of events for each return period.
+Figures \ref{fig:HAT_max_inundation}, \ref{fig:MSL_max_inundation} and 
+\ref{fig:LAT_max_inundation} illustrate the maximum inundation extent
+for the Mw 9 event occurring at HAT, MSL and LAT respectively. 
+As expected, there is greater inundation at HAT with increased
+extent. The major road
+into Onslow, the Onslow Mount Stuart Rd, remains free of inundation for
+all tidal scenarios with a small amount of inundation evident at HAT at
+the intersection with Beadon Creek Rd. Beadon Creek Rd services the wharf in the
+creek which becomes increasingly inundated as the tide height
+increases. The only road sufficiently inundated at LAT is Beadon
+Creek Rd near the entry to the wharf. This road during the HAT 
+scenario would be impassable as the water depths are consistently
+over 1 m with a maximum water depth of around 2 m found close to 
+the wharf. 
+
+There is significant inundation of at
+least 2 m on the foreshore of Onslow for MSL and HAT.
+The inundation extends further as the tidal heights increase.  
+At HAT, the inundation reaches the southern boundaries of 
+the road infrastructure in the Onslow town centre.  
+The airport remains
+free of inundation for each tidal scenario. Section \ref{sec:impact}
+details the impact estimates to the residential infrastructure.
+
+The geography of the Onslow area has played a role in offering
+some protection to the Onslow community. The tsunami wave is 
+travelling from the north west of the area. Most of
+the inundation along the coast is that which is open to this
+direction.  
+The sand dunes west of Onslow 
+appear to have halted this tsunami wave
+(see Figure \ref{fig:MSL_max_inundation}) with limited
+inundation found on the town's side of the dunes.
+The inundation within the community has occurred due to the
+wave reflecting from the beach area west of the creek and
+returning towards the Onslow town itself.  
+There are also sand dunes east of the creek which have also
+halted inundation beyond them. 
+Currently, we do not model changes 
+to the bathymetry or topography due to effects of the water flow. 
+Therefore, we do not know whether these sand dunes would withstand the
+transmitted energy of the tsunami wave. 
+Water features such as rivers, creeks and estuaries also play a role
+in the inundation extent.
+The tsunami wave penetrates the creek east of Onslow, however it
+is evident that the inundation is essentailly maintained in the
+large tidal flat region surrounding the southern parts of the creek.
+
+In addition to describing the maximum inundation extent,
+we have
+chosen a number of locations to illustrate the features
+of the tsunami as it approaches and impacts Onslow.
+These locations have been chosen as we believe they would 
+either be critical
+in an emergency situation, (e.g. the hospital and power station) or
+effect recovery efforts, (e.g. the airport and docks). These locations
+are described in Table \ref{table:locations} and shown in 
+Figure \ref{fig:points}. The water's stage and speed 
+at each of these locations are shown
+as a function of time in the series of graphs shown in
+Appendix \ref{sec:timeseries}. Discussion of the main features of the
+tsunami wave is also described in Appendix \ref{sec:timeseries}.
Index: /anuga_work/production/wa/onslow_2006/report/introduction.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/introduction.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/introduction.tex	(revision 7411)
@@ -0,0 +1,52 @@
+The Fire and Emergency Services Authority (FESA) of Western Australia  and 
+associated volunteers respond to a wide range of emergencies 
+as well as undertaking search and rescue operations on land and 
+water\footnote{http://www.fesa.wa.gov.au/internet/}. 
+FESA helps the West Australian 
+community prepare, prevent (where possible) and respond safely to disasters.
+FESA also aims to reduce injury, loss of life and destruction of property in 
+Western Australian communities through proactive measures. 
+These measures involve understanding the relative risk
+of the disaster so that resources can be directed to appropriate areas
+and corresponding evacuation plans put in place.  
+
+The key role of the Risk Research Group at Geoscience Australian 
+is to develop knowledge on the risk from natural and 
+human-caused hazards for input to policy and operational decision making on 
+the mitigation of risk to Australian communities. The Group achieves 
+this through the development of computational methods, models and decision 
+support tools that assess the hazard, vulnerability and risk posed by hazard
+events. To develop an understanding of the tsunami risk, GA has developed
+decision support tools, consisting of inundation
+maps overlaid on aerial photography of the region 
+detailing critical infrastructure as well as damage modelling estimates. 
+
+This report details the impact assessments for a range of tsunami events.
+These events are based on the probabilistic hazard assessment conducted
+for the Western Australian coastline. A number of events are selected for
+return periods of 500, 1000 and 2000 years, see Section \ref{sec:tsunamiscenario}.
+%This report is the first in a series of tsunami assessments 
+%of the North West Shelf. The scenario used for this study has
+%an unknown return period, but is considered a plausible event (see
+%Section \ref{sec:methodology}). 
+%Subsequent assessments will use refined hazard models with
+%associate return periods. A suite of assessments will be
+%made for Onslow and other localities, as advised by FESA.
+
+Onslow has a population of around 800 and
+is part of the Shire of Ashburton in the Pilbara region of 
+Western Autralia\footnote{http://www.pdc.wa.gov.au/region/political.htm}. 
+Onslow supports
+a variety of industries, including oil, gas, mining, cattle, 
+fishing and tourism.
+
+The modelling technique to simulate the 
+impact ashore is discussed in Section \ref{sec:methodology} with 
+event and data inputs
+discussed in Sections \ref{sec:tsunamiscenario} and \ref{sec:data} respectively. 
+The inundation results are presented and discussed in Section \ref{sec:results} 
+and the impact modelling results outlined in Section \ref{sec:impact}.
+A summary of the results detailing issues
+regarding underlying data and further model development, are discussed 
+in Section \ref{sec:summary}.
+
Index: /anuga_work/production/wa/onslow_2006/report/latexoutput.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/latexoutput.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/latexoutput.tex	(revision 7411)
@@ -0,0 +1,141 @@
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonPointLoadingBerthstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonPointLoadingBerthmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and momentum at Beadon Point Loading Berth location (elevation -8.70m)} 
+ \label{fig:gaugeBeadonPointLoadingBerth} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeHospitalstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeHospitalmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for depth and momentum at Hospital location (elevation 6.02m)} 
+ \label{fig:gaugeHospital} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBindiBindiCommunitystage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBindiBindiCommunitymomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for depth and momentum at Bindi Bindi Community location (elevation 4.08m)} 
+ \label{fig:gaugeBindiBindiCommunity} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePowerStationstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePowerStationmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for depth and momentum at Power Station location (elevation 5.81m)} 
+ \label{fig:gaugePowerStation} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeAirportRunwaystage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeAirportRunwaymomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for depth and momentum at Airport Runway location (elevation 5.49m)} 
+ \label{fig:gaugeAirportRunway} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreekDocksstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreekDocksmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for depth and momentum at Beadon Creek Docks location (elevation 1.65m)} 
+ \label{fig:gaugeBeadonCreekDocks} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeWestofGroynestage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeWestofGroynemomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and momentum at West of Groyne location (elevation -2.11m)} 
+ \label{fig:gaugeWestofGroyne} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreekmouthstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreekmouthmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and momentum at Beadon Creek mouth location (elevation -2.90m)} 
+ \label{fig:gaugeBeadonCreekmouth} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreeksouthofdockstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreeksouthofdockmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and momentum at Beadon Creek south of dock location (elevation -1.81m)} 
+ \label{fig:gaugeBeadonCreeksouthofdock} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeCentredamwallstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeCentredamwallmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for depth and momentum at Centre dam wall location (elevation 2.09m)} 
+ \label{fig:gaugeCentredamwall} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeDamoverflowstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeDamoverflowmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for depth and momentum at Dam overflow location (elevation 0.88m)} 
+ \label{fig:gaugeDamoverflow} 
+ \end{figure} 
+ 
+\clearpage 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeLightTowerstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeLightTowermomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for depth and momentum at Light Tower location (elevation 3.86m)} 
+ \label{fig:gaugeLightTower} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonBayweststage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonBaywestmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and momentum at Beadon Bay west location (elevation -4.62m)} 
+ \label{fig:gaugeBeadonBaywest} 
+ \end{figure} 
+ 
+\begin{figure}[ht] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonBayeaststage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonBayeastmomentum.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and momentum at Beadon Bay east location (elevation -3.56m)} 
+ \label{fig:gaugeBeadonBayeast} 
+ \end{figure} 
+ 
Index: /anuga_work/production/wa/onslow_2006/report/latexoutput20060515001733.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/latexoutput20060515001733.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/latexoutput20060515001733.tex	(revision 7411)
@@ -0,0 +1,140 @@
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonPointLoadingBerthstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonPointLoadingBerthspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Beadon Point Loading Berth location (elevation -8.69m)} 
+ \label{fig:20060515001733gaugeBeadonPointLoadingBerth} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeHospitalstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeHospitalspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Hospital location (elevation 7.56m)} 
+ \label{fig:20060515001733gaugeHospital} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBindiBindiCommunitystage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBindiBindiCommunityspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Bindi Bindi Community location (elevation 1.00m)} 
+ \label{fig:20060515001733gaugeBindiBindiCommunity} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePowerStationstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePowerStationspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Power Station location (elevation 5.17m)} 
+ \label{fig:20060515001733gaugePowerStation} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeAirportRunwaystage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeAirportRunwayspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Airport Runway location (elevation 3.00m)} 
+ \label{fig:20060515001733gaugeAirportRunway} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreekDocksstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreekDocksspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Beadon Creek Docks location (elevation 1.76m)} 
+ \label{fig:20060515001733gaugeBeadonCreekDocks} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeWestofGroynestage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeWestofGroynespeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at West of Groyne location (elevation -2.10m)} 
+ \label{fig:20060515001733gaugeWestofGroyne} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreekmouthstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreekmouthspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Beadon Creek mouth location (elevation -2.80m)} 
+ \label{fig:20060515001733gaugeBeadonCreekmouth} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreeksouthofdockstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonCreeksouthofdockspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Beadon Creek south of dock location (elevation -1.49m)} 
+ \label{fig:20060515001733gaugeBeadonCreeksouthofdock} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeCentredamwallstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeCentredamwallspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Centre dam wall location (elevation 3.00m)} 
+ \label{fig:20060515001733gaugeCentredamwall} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeDamoverflowstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeDamoverflowspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Dam overflow location (elevation 1.53m)} 
+ \label{fig:20060515001733gaugeDamoverflow} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeLightTowerstage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeLightTowerspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Light Tower location (elevation 1.47m)} 
+ \label{fig:20060515001733gaugeLightTower} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonBayweststage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonBaywestspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Beadon Bay west location (elevation -4.61m)} 
+ \label{fig:20060515001733gaugeBeadonBaywest} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonBayeaststage20060515001733.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeBeadonBayeastspeed20060515001733.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Beadon Bay east location (elevation -3.56m)} 
+ \label{fig:20060515001733gaugeBeadonBayeast} 
+ \end{figure} 
+ 
Index: /anuga_work/production/wa/onslow_2006/report/metadata.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/metadata.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/metadata.tex	(revision 7411)
@@ -0,0 +1,1 @@
+%\includepdf[pages={1-6}]{MetadataforATWSOnslowScenario}
Index: /anuga_work/production/wa/onslow_2006/report/modelling_methodology.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/modelling_methodology.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/modelling_methodology.tex	(revision 7411)
@@ -0,0 +1,120 @@
+Geoscience Australia aims to define the economic and social threat posed to urban communities 
+by a range of rapid onset natural hazards. Through the integration of natural hazard research, defining national exposure and 
+estimating socio-economic vulnerabilities, predictions of the likely impacts of events can be made. 
+By modelling the likely impacts on urban communities as accurately as possible and
+building these estimates into land use planning and emergency
+management, communities will be better prepared to respond to
+natural disasters when they occur.
+
+
+%GA bases its risk modelling on the process of understanding the hazard and a community's 
+%vulnerability in order to determine the impact of a particular hazard event. 
+%The resultant risk relies on an assessment of the likelihood of the event. 
+%An overall risk assessment for a particular hazard would then rely on scaling 
+%each event's impact by its likelihood.
+
+To develop a tsunami risk assessment, 
+the tsunami hazard itself must first be understood. These events are generally modelled by converting
+the energy released by a subduction earthquake into a vertical displacement of the ocean surface. 
+%Tsunami hazard models have been available for some time. 
+The resulting wave is
+then propagated across a sometimes vast stretch of ocean towards the
+area of interest. 
+%using a relatively coarse model 
+%based on bathymetries with a typical resolution of two arc minutes.
+The hazard itself is then reported as a maximum wave height at a fixed contour line near the coastline, 
+(e.g. 50m). This is how the preliminary tsunami hazard assessment was reported by GA 
+to FESA in September 2005 \cite{BC:FESA} for a suite of Mw 9 earthquakes
+evenly spaced along the Sunda Arc subduction zone. 
+The assessment used the Method of Splitting Tsunamis (MOST)
+\cite{VT:MOST} model. This preliminary hazard map had no probability attached to the event which is
+required to conduct a tsunami risk assessment. Using
+the Probabilistic Tsunami Hazard Analysis \cite{somerville:urs} paradigm
+used by the URS corporation, a detailed probabilistic hazard map has now been completed
+for the WA coastline \cite{prob:fesa}. 
+
+While MOST and URS are suitable for generating and propagating the tsunami wave from its source, 
+they are not adequate to
+model the wave's impact on communities ashore.  
+To capture the \emph{impact} of a tsunami to a coastal community, 
+the model must be capable of capturing more detail about the wave, 
+particularly how it is affected by the local bathymetry, as well as the 
+local topography as the wave moves onshore. 
+%the details of how waves are reflected and otherwise 
+%shaped by the local bathymetries as well as the dynamics of the 
+%runup process onto the topography in question.
+It is well known that local bathymetric and topographic effects are 
+critical in determining the severity of a hydrological disaster 
+\cite{matsuyama:1999}. To model the impact of the tsunami wave on the 
+coastal community, we use ANUGA \cite{ON:modsim}. In order to capture the 
+details of the wave and its interactions, a much finer resolution is 
+required than that of the hazard model. As a result, ANUGA simulations concentrate 
+on specific coastal communities. MOST and URS by contrast use a 
+coarser resolution and cover often vast areas. To develop the impact 
+from an earthquake event from a distant source, we adopt a hybrid approach of 
+modelling the event itself with MOST or URS and modelling the impact with ANUGA. 
+In this way, the output from MOST or URS serve as an input to ANUGA. 
+In modelling terms, the MOST or URS output is a boundary condition for ANUGA.
+Further details
+regarding the inundation modelling requirements for this study can be found in 
+Appendix \ref{sec:anugasetup}.
+
+The risk of a given tsunami scenario can only be determined when the likelihood
+of the event is known. The probabilistic hazard map for WA \cite{prob:fesa}
+calculates which events pose the most threat to an identified region. Figure
+\ref{fig:probonslow} describes the probability of each event generated along the Java trench
+impacting Onslow. For example, an event generated at point A end would have a
+smaller chance of impacting Onslow than an event generated at point B.
+
+\begin{figure}[h]
+
+%\centerline{ \includegraphics[width=140mm, height=100mm]{../report_figures/}}
+
+  \caption{}
+  \label{fig:probonslow}
+\end{figure}
+
+To prepare a tsunami risk assessment, a number of events will be chosen
+for a range of probabilities (or return periods). As Figure \ref{fig:probonslow}
+shows, for a given probability, a number of events are possible. The resulting
+impact to Onslow would then vary depending on the source of the event.  The
+tsunami scenarios selected for the tsunami risk assessment 
+are discussed in Section \ref{sec:tsunamiscenario}.
+
+% used for the 2005 report when looking at one event
+%\bigskip %FIXME (Ole): Should this be a subsection even? 
+%The risk of a given tsunami scenario cannot be determined until the 
+%likelihood of the tsunami is known. GA is currently building a 
+%complete probabilistic hazard map which is due for completion 
+%in late 2006. We therefore report on the impact of a single 
+%tsunami event only. When the hazard map is completed, the impact 
+%will be assessed for a range of events which will ultimately 
+%determine a tsunami risk assessment for the NW shelf.
+
+%FESA is interested in the ``most frequent worst case scenario''. Whilst
+%we currently cannot determine exactly what that event may be, the
+%preliminary hazard assessment suggested that the maximum
+%magnitude of earthquakes off Java was considered to be at 
+%least 8.5 and could potentially be as high as 9. Therefore, 
+%the Mw 9 event 
+%provides a plausible worst case scenario and is used as the tsunami
+%source in this report.
+%Figure \ref{fig:mw9} shows the maximum wave height of a tsunami initiated 
+%by a Mw 9 event off
+%the coast of Java. This event provides the source and
+%boundary condition to the
+%inundation model presented in Section \ref{sec:anuga}. 
+
+%\begin{figure}[h]
+
+%  \centerline{ \includegraphics[width=140mm, height=100mm]
+%{../report_figures/mw9.jpg}}
+
+%  \caption{Maximum wave height (in cms) for a Mw 9 event off the 
+%coast of Java}
+%  \label{fig:mw9}
+%\end{figure}
+
+
+
+ 
Index: /anuga_work/production/wa/onslow_2006/report/onslow_2006_report.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/onslow_2006_report.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/onslow_2006_report.tex	(revision 7411)
@@ -0,0 +1,184 @@
+
+% This is based on an automatically generated file (by make_report.py).
+%
+% Manual parts are:
+% * an abstract must be written in abstract.tex
+% * an introduction must be written in introduction.tex; a basic outline and
+%   some of the core inputs are already in place
+% * outline of the modelling methodology provided in modelling_methodology.tex
+% * the tsunami-genic event should be discussed in tsunami_scenario.tex
+% * an computational_setup.tex file needs to be written for the particular scenario
+% * the interpretation of the results needs to be written to interpretation.tex
+% * maximum inundation maps need to be included in HAT_map.tex and LAT_map.tex etc.
+% * damage modelling maps need to be included in HAT_damage and LAT_damage etc.
+% * a summary must be written into summary.tex
+% * metadata for the scenario data to be included in metadata.tex
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\usepackage{pdfpages}
+\include{appendix}
+\setstretch{1.25}
+\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\textwidth \paperwidth
+\advance\textwidth -2in
+
+
+\date{\today}
+%\author{Geoscience Australia}
+
+\begin{document}
+\title{
+\begin{figure}[hbt]
+  \centerline{ \includegraphics[scale=0.4]{../report_figures/GAlogo.jpg}}
+\end{figure}
+Tsunami impact modelling for the North West shelf: Onslow} 
+  \maketitle
+
+    \section{Executive Summary}
+    \label{sec:execsum}
+  \input{execsum}
+
+\clearpage
+
+  \tableofcontents
+  
+  \section{Introduction}
+    \label{sec:intro}
+  \input{introduction}
+
+   \section{Modelling methodology}
+    \label{sec:methodology}
+    \input{modelling_methodology}
+    
+  \section{Tsunami scenarios}
+    \label{sec:tsunamiscenario}
+    \input{tsunami_scenario}
+
+  \section{Data sources}
+    \label{sec:data}
+    \input{data}
+        
+  \section{Inundation modelling results}
+     \label{sec:results}
+         
+\input{interpretation} 
+\subsection{Return Period: 1000 years} 
+ 
+\input{HAT_map} 
+ \clearpage 
+ 
+\input{MSL_map} 
+ \clearpage 
+ 
+\input{LAT_map} 
+ \clearpage 
+ 
+\subsection{Return Period: 1000000 years} 
+ 
+\input{HAT_map} 
+ \clearpage 
+ 
+\input{MSL_map} 
+ \clearpage 
+ 
+\input{LAT_map} 
+ \clearpage 
+ 
+\begin{table} \begin{center} 
+\caption{Defined point locations for Onslow study area.}
+\label{table:locations}
+\begin{tabular}{|l|l|l|l|}\hline
+\bf{Point Name} & \bf{Easting} & \bf{Northing} & \bf{Elevation (m)}\\ \hline
+Beadon Point Loading Berth & 302986.51 & 7607334.65 & -8.70 \\ \hline 
+Hospital & 304973.04 & 7605500.42 & 6.02 \\ \hline 
+Bindi Bindi Community & 305430.37 & 7605586.65 & 4.08 \\ \hline 
+Power Station & 305687.62 & 7605062.62 & 5.81 \\ \hline 
+Airport Runway & 304471.19 & 7602750.41 & 5.49 \\ \hline 
+Beadon Creek Docks & 306622.77 & 7604706.10 & 1.65 \\ \hline 
+West of Groyne & 306556.76 & 7605791.87 & -2.11 \\ \hline 
+Beadon Creek mouth & 306626.50 & 7605532.27 & -2.90 \\ \hline 
+Beadon Creek south of dock & 306676.87 & 7604408.63 & -1.81 \\ \hline 
+Centre dam wall & 308516.86 & 7603955.82 & 2.09 \\ \hline 
+Dam overflow & 307913.42 & 7604034.90 & 0.88 \\ \hline 
+Light Tower & 304562.88 & 7606431.74 & 3.86 \\ \hline 
+Beadon Bay west & 305311.01 & 7606557.16 & -4.62 \\ \hline 
+Beadon Bay east & 307989.36 & 7606591.95 & -3.56 \\ \hline 
+\end{tabular} 
+  \end{center} 
+ \end{table} 
+ 
+\begin{figure}[h] 
+ \centerline{ \includegraphics[scale=0.7]{../report_figures/onslow_dli_gauge.jpg}}
+\caption{Point locations used for Onslow study.}  
+\label{fig:points}
+\end{figure}
+
+\clearpage
+
+   \section{Impact modelling}
+    \label{sec:impact}
+     \input{damage}
+
+  % \section{Impact due to data accuracy}
+  %   \input{discussion}
+  %   \label{sec:issues}
+
+     \section{Summary}
+     \label{sec:summary}
+     \input{summary}
+
+     \section{Acknowledgements}
+     \input{acknowledgements}
+     
+    \input{references}
+
+\clearpage
+
+    \appendix
+
+    \section{ANUGA modelling parameters}
+    \label{sec:anugasetup}
+    \input{anuga_setup}
+
+\clearpage
+
+   \section{Metadata}
+     \label{sec:metadata}
+     \input{metadata}
+
+\clearpage
+
+   \section{Time series}
+     \label{sec:timeseries}
+     \input{timeseriesdiscussion}
+     \clearpage
+\subsection{Return Period: 1000 years} 
+\input{latexoutputrp0} 
+ \clearpage 
+ 
+\subsection{Return Period: 1000000 years} 
+\input{latexoutputrp1} 
+ \clearpage 
+ 
+
+
+   \section{Damage modelling inputs}
+     \label{sec:damageinputs}
+     \input{damage_inputs}
+
+\end{document}
Index: /anuga_work/production/wa/onslow_2006/report/references.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/references.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/references.tex	(revision 7411)
@@ -0,0 +1,54 @@
+\begin{thebibliography}{99}
+
+\bibitem{CB:ausgeo} Cummins, P. and Burbidge, D. (2004) 
+Small threat, but warning sounded for tsunami research. AusGeo News 75, 4-7.
+
+\bibitem{BC:FESA} Burbidge, D. and Cummins, P. (2005) Preliminary Tsuanmi 
+Hazard Assesment of Western Australia. Report 
+to the Fire and Emergency Services Authority of Western Australia.
+
+\bibitem{VT:MOST} Titov, V.V., and F.I. Gonzalez (1997)
+Implementation and testing of the Method of Splitting 
+Tsunami (MOST) model, NOAA Technical Memorandum ERL PMEL-112.
+
+\bibitem{prob:fesa} Burbidge, D. and Cummins, P. (2006) Probabilistic
+Tsunami Hazard Assessment of Western Australia. Report to the 
+Fire and Emergency Services Authority of Western Australia.
+
+\bibitem{somerville:urs} Somerville, P., Thio, H.K. and Ichinose, G. (2005)
+Probabilistic Tsunami Hazard Analysis. Report delivered to Geoscience
+Australia 2005.
+
+\bibitem{matsuyama:1999}
+Matsuyama, M., Walsh, J.P. and Yeh, H. (1999) 
+The effect of bathymetry on tsunami characteristics at 
+Sisano Lagoon, Papua New Guinea. 
+Geophysical Research Letters, 26, 23, 3513-3516.
+
+\bibitem{ON:modsim} Nielsen, O., Roberts, Gray, D., McPherson, A. and 
+Hitchman, A (2005) 
+Hydrodynamic modelling of coastal inundation, MODSIM 2005 International 
+Congress on Modelling and Simulation.
+Modelling and Simulation Society of Australian and New Zealand, 518-523,
+URL: http://www.mssanz.org.au/modsim05/papers/nielsen.pdf
+
+\bibitem{antt:06} Australian National Tide Tables 2006:
+Australia, Papua New Guinea, Solomon Islands and Antarctica and East Timor.
+Australian Hydrographic Publication 11, Australian Hydrographic Service.
+
+\bibitem{papathoma:vulnerability} 
+Papathoma, M. and Dominey-Howes, D. (2003) 
+Tsunami vulnerability assessment and its implications for coastal hazard 
+analysis and disaster management planning, Gulf of Corinth, Greece, 
+Natural Hazards and Earth System Sciences, 3, 733-747.
+
+\bibitem{cooper:2005}
+Cooper, D. (2005) Risk Research Group Personal Communication at NSW Tsunami 
+Workshop 12th and 13th April, Masonic Centre, Goulburn St, Sydney.
+
+\bibitem{NIBS:2003} National Institute of Building Sciences (2003) 
+HAZUS-MH User Manual, Washington DC, USA.
+
+\bibitem{uq:friction} Duncan - do you have a reference for this?
+
+\end{thebibliography}
Index: /anuga_work/production/wa/onslow_2006/report/summary.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/summary.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/summary.tex	(revision 7411)
@@ -0,0 +1,39 @@
+This report has described the impact on Onslow from a tsunami
+generated by a Mw 9 earthquake on the Sunda Arc subduction zone 
+occurring at Highest Astronomical Tide, Lowest Astronomical Tide
+and Mean Sea Level. 
+As yet, there is no knowledge of the return period for this event. The
+modelling methodology, assumptions and data sources for the Onslow 
+scenario have also been described. 
+
+As shown in Section \ref{sec:data}, it is imperative
+that the best available data is used to increase confidence
+in the inundation maps. 
+Given that the Highest Astronomical Tide contour
+line is further from the coast for the DTED data than the DLI data, we
+expect the inundation to extend further and thus be greater than
+that seen in Figure \ref{fig:MSL_max_inundation}. 
+The impact modelling
+will result in significantly inflated structural and contents loss figures as well as
+numbers of people affected.
+These results strongly point to the need for the best 
+available data so that more accurate predictions regarding the 
+inundation can be made.
+An onshore grid resolution of the order
+of tens of metres is required, however, it is more important that the data
+are accurate (or at least well known).
+
+These scenarios will be revisited once the probabilistic models
+are complete so that a suite of tsunami impact assessments can be made.
+Future activities to support the impact studies on the North West Shelf
+include:
+
+\begin{itemize}
+\item Sourcing of data sets,
+\item Investigation of solution sensitivity to cell resolution,
+bathymetry and tsunami source uncertainties,
+\item Location of boundary for simulation study area, and
+\item Investigation of friction coefficients.
+\end{itemize}
+
+
Index: /anuga_work/production/wa/onslow_2006/report/timeseriesdiscussion.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/timeseriesdiscussion.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/timeseriesdiscussion.tex	(revision 7411)
@@ -0,0 +1,97 @@
+It is assumed that the earthquake is
+generated at the beginning of the simulation, i.e. time = 0 minutes.
+Stage is defined as the absolute
+water level (in metres) relative to AHD 
+\footnote{For an offshore location such as Beadon Bay West,
+the initial water level will be that of the tidal scenario. In the 
+case of MSL, this water level will be 0. As the tsunami wave moves
+through this point, the water height may grow and thus the stage will 
+represent the amplitude of the wave.} For an onshore location such as the 
+Light Tower, the actual water depth will be shown rather than the stage. 
+Both stage and speed 
+(in metres/second) for
+each scenario (HAT, MSL and LAT) are shown
+on consistent scales to allow comparison between point locations.
+As a useful benchmark, Table \ref{table:speedexamples}
+describes typical examples for a range of speeds found in the 
+simulations. 
+
+\begin{table}[h]
+\label{table:speedexamples}
+\caption{Examples of a range of velocities.}
+\begin{center}
+\begin{tabular}{|l|l|}\hline
+{\bf Velocity (m/s)} & {\bf Example} \\ \hline
+1 & leisurely stroll pace\\ \hline
+1.5 & average walking pace \\ \hline
+%2 & 100m Olympic male freestyle \\ \hline
+%3 & mackeral \\ \hline
+4 & average person can maintain running for 1000m \\ \hline
+%5 & blue whale \\ \hline
+10 & 100m Olympic male sprinter \\ \hline
+16 & car travelling in urban zones (60 km/hr) \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+A tsunami wave typically has a small amplitude and typically travels at 100's of kilometres per hour. 
+The low amplitude complicates the ability to detect
+the wave. As the water depth decreases, 
+the speed of the wave 
+decreases and the amplitude grows. Another important feature of tsunamis 
+is drawdown. This means that the water is seen to retreat from the beaches
+before a tsunami wave 
+impacts that location. Other features 
+include reflections (where the wave is redirected due to the 
+influence 
+of the coast) and shoaling (where the wave's amplitude is amplified
+close to the coast due to wave interactions).
+These features are seen in these scenarios, and are consistent
+for HAT, MSL and LAT. 
+There is a small wave, followed
+by a large drawdown and then a large secondary wave. 
+
+These 
+features are illustrated in Figure \ref{fig:gaugeBeadonBayeast}
+where a small wave can be seen at around 200 mins. For the HAT
+case (shown in blue), the amplitude
+of the wave at this location is around 0.8 m\footnote{In this
+scenario, the initial water level is 1.5 m, which means that
+the actual amplitude is the difference between the stage value
+and the initial water level; 2.3 - 1.5}.
+The drawdown of 4.05 m (i.e. 2.3 - -1.75) then occurs at around 230 mins
+(i.e. 3.8 hours after the event has been generated), before
+the second wave arrives 
+with an amplitude of around 3.6 m (i.e. 4.1 - 1.5). A further wave
+is then evident a short time later (around 255 mins) 
+which further increases the amplitude to around 5 m (i.e. 6.6 - 1.5).
+These features are replicated at each of the offshore points (those
+points with negative elevation as shown in Table \ref{table:locations}).
+
+The wave amplitude is typically greater
+for those locations which are in the shallowest water. For example,
+the maximum wave amplitude at the Beadon Bay East location 
+(Figure \ref{fig:gaugeBeadonBayeast}) is over
+4.5m where the water depth would normally be 3.56 m. In the 
+Beadon Bay West location (Figure \ref{fig:gaugeBeadonBaywest})
+where the water depth would normally be 4.62 m, 
+the maximum wave amplitude is much less (around 3 m). The wave amplitude
+at the West of Groyne location (Figure \ref{fig:gaugeWestofGroyne})
+is not greater than that seen
+at the Beadon Bay East location, even though the water depth is 
+much less, at 2.11m. This is probably due to its proximity
+to the groyne\footnote{A groyne is a man made structure to combat
+coastal erosion.}
+which has impeded the tsunami wave to some degree. However, the 
+maximum speed found amongst the locations is at the West of Groyne
+point which is in the shallowest water.
+
+The speed of the tsunami sharply increases as it moves onshore. There
+is minimal inundation found at the locations chosen, with the Bindi Bindi
+community receiving the greatest inundation for all tidal scenarios.
+At HAT, the community would receive over 1 m of inundation with 
+the water moving through the community at approximately 16 m/s. Referring
+to Table \ref{table:speedexamples}, a person in this location could
+not outrun this water movement. A small amount of water is found
+at the hospital (10 cm). Whilst this seems minimal, the water is moving 
+at around 6 m/s which could dislodge some items if the water was able to enter the hospital.
Index: /anuga_work/production/wa/onslow_2006/report/tsunami_scenario.tex
===================================================================
--- /anuga_work/production/wa/onslow_2006/report/tsunami_scenario.tex	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/report/tsunami_scenario.tex	(revision 7411)
@@ -0,0 +1,42 @@
+% for original scenario
+%The tsunamigenic event used in this report was developed for a 
+%preliminary tsunami hazard assessment study delivered by GA
+%to FESA in September 2005
+%\cite{BC:FESA}. In the assessment, a suite of Mw 9 earthquakes
+%were evenly spaced along the Sunda Arc subduction zone and there
+%was no consideration of the likelihood of each event. 
+%Other less likely sources were not considered, such
+%as intra-plate earthquakes near the WA coast, volcanoes, landslides
+%or asteroids. 
+%In the preliminary assessment,
+%the maximum magnitude of earthquakes off Java was considered to be
+%at least 8.5 and could potentially be as high as 9.
+
+%FESA is interested in the ``most frequent worst case scenario''. Whilst
+%we currently cannot determine exactly what that event may be, the Mw 9 event 
+%provides a plausible worst case scenario. To understand the 
+%frequency of these tsunami-genic events,
+%GA is building probabilistic
+%models to develop a more complete tsunami hazard assessment
+%for the Sunda Arc subduction zone,
+%due for completion in late 2006. In the preliminary assessment for
+%example, it was suggested that while Mw 7 and 8 earthquakes are expected
+%to occur with a greater frequency than Mw 9 events, 
+%they are likely to pose a comparatively low and more localised hazard to WA. 
+
+%Figure \ref{fig:mw9} shows the maximum wave height of a tsunami initiated 
+%by a Mw 9 event off
+%the coast of Java. This event provides the source and
+%boundary condition to the
+%inundation model presented in Section \ref{sec:anuga}. 
+
+
+%\begin{figure}[hbt]
+
+%  \centerline{ \includegraphics[width=140mm, height=100mm]
+%{../report_figures/mw9.jpg}}
+
+%  \caption{Maximum wave height (in cms) for a Mw 9 event off the 
+%coast of Java}
+%  \label{fig:mw9}
+%\end{figure}
Index: /anuga_work/production/wa/onslow_2006/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/run_boundary_points.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/run_boundary_points.py	(revision 7411)
@@ -0,0 +1,35 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+
+# # Related major packages
+# from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import URS_points_needed_to_file, \
+     urs_ungridded2sww
+import project                 # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+poly = project.polyAll
+print "poly", poly
+print "project.boundaries", project.boundarydir
+URS_points_needed_to_file(project.boundarydir,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True)
+#urs_ungridded2sww(project.boundaries_in_dir_name2, project.boundaries_dir_name5, mean_stage= project.tide,  verbose=True)
Index: /anuga_work/production/wa/onslow_2006/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,36 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+import project_urs
+
+# Inputs
+#timestampdir = '20070507_215717_run_final_1.5_nbartzis' # HAT
+timestampdir = '20070518_021050_run_final_0.0_nbartzis' # MSL
+file_loc = project_urs.output_dir + timestampdir + sep 
+swwfile = file_loc + project_urs.scenario_name #+ '.sww'
+buildings_filename = project_urs.buildings_filename
+buildings_filename_out = file_loc + project_urs.buildings_filename_out
+
+#add_depth_and_momentum2csv(swwfile, buildings_filename, buildings_filename_out)
+inundation_damage(swwfile, buildings_filename, buildings_filename_out)
+
+print '\n Augmented building file written to %s \n' \
+      %buildings_filename_out
Index: /anuga_work/production/wa/onslow_2006/run_onslow.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/run_onslow.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/run_onslow.py	(revision 7411)
@@ -0,0 +1,269 @@
+"""Script for running a tsunami inundation scenario for Onslow, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.outputtimedir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Nick Bartzis, GA - 2006
+"""
+
+
+#-------------------------------------------------------------------------------# Import necessary modules
+#-------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import time
+from shutil import copy
+from os import mkdir, access, F_OK
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain, Reflective_boundary, \
+                            Dirichlet_boundary, Time_boundary, File_boundary
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts, ferret2sww
+#from anuga.abstract_2d_finite_volumes.combine_pts import combine_rectangular_points_files 
+from anuga.geospatial_data.geospatial_data import *
+#from anuga.abstract_2d_finite_volumes.util import Screen_Catcher
+#from anuga.shallow_water.data_manager import start_screen_catcher
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#-------------------------------------------------------------------------------
+
+### creates copy of code in output dir if dir doesn't exist
+if access(project.outputtimedir,F_OK) == 0 :
+    mkdir (project.outputtimedir)
+copy (project.codedirname, project.outputtimedir + project.codename)
+copy (project.codedir + 'run_onslow.py', project.outputtimedir + 'run_onslow.py')
+print'output dir', project.outputtimedir
+
+###normal screen output is stored in 
+##screen_output_name = project.outputtimedir + "screen_output.txt"
+##screen_error_name = project.outputtimedir + "screen_error.txt"
+##
+###used to catch screen output to file
+##sys.stdout = Screen_Catcher(screen_output_name)
+###sys.stderr = Screen_Catcher(screen_output_name)
+##sys.stderr = Screen_Catcher(screen_error_name)
+##
+##print 'USER:    ', project.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+
+# filenames
+onshore_dem_name = project.onshore_dem_name
+islands_dem_name = project.islands_dem_name
+coast_points = project.coast_dem_name
+offshore_points = project.offshore_dem_name
+meshname = project.meshname+'.msh'
+source_dir = project.boundarydir
+
+copied_files = False
+
+# files to be used
+files_used = [onshore_dem_name, offshore_points, coast_points,]
+
+# fine data (clipping the points file to smaller area)
+# creates DEM from asc data
+convert_dem_from_ascii2netcdf(onshore_dem_name, use_cache=True, verbose=True)
+
+#creates pts file for onshore DEM
+dem2pts(onshore_dem_name,
+        easting_min=project.eastingmin,
+        easting_max=project.eastingmax,
+        northing_min=project.northingmin,
+        northing_max= project.northingmax,
+        use_cache=True, 
+        verbose=True)
+
+convert_dem_from_ascii2netcdf(islands_dem_name, use_cache=True, verbose=True)
+
+#creates pts file for islands DEM
+dem2pts(islands_dem_name, use_cache=True, verbose=True)
+
+print'create G1'
+G1 = Geospatial_data(file_name = project.offshore_dem_name + '.txt')
+print'create G2'
+G2 = Geospatial_data(file_name = project.onshore_dem_name + '.pts')
+print'create G3'
+G3 = Geospatial_data(file_name = project.coast_dem_name + '.txt')
+print'create G4'
+G4 = Geospatial_data(file_name = project.islands_dem_name + '.pts')
+print'add G1+G2+G3+G4'
+G = G1 + G2 + G3 + G4
+print'export G'
+G.export_points_file(project.combined_dem_name + '.pts')
+
+#-------------------------------------------------------------------------------                                 
+# Create the triangular mesh based on overall clipping polygon with a tagged
+# boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+
+#new
+region_res = 200000
+coast_res = 25000
+onslow_res = 5000
+interior_regions = [[project.poly_onslow, onslow_res],
+                    [project.poly_coast, coast_res],
+                    [project.poly_region, region_res]]
+
+print 'number of interior regions', len(interior_regions)
+
+from caching import cache
+_ = cache(create_mesh_from_regions,
+          project.polyAll,
+          {'boundary_tags': {'top': [0], 'topleft': [1],
+                             'topleft1': [2], 'bottomleft': [3],
+                             'bottom': [4], 'bottomright': [5],
+                             'topright':[6]},
+           'maximum_triangle_area': 100000,
+           'filename': meshname,           
+           'interior_regions': interior_regions},
+          verbose = True, evaluate=True)
+
+
+#-------------------------------------------------------------------------------                                 
+# Setup computational domain
+#-------------------------------------------------------------------------------                                 
+
+#domain = pmesh_to_domain_instance(meshname, Domain,
+#                                  use_cache = False,
+#                                  verbose = True)
+
+domain = Domain(meshname, use_cache = False, verbose = True)
+
+print 'Number of triangles = ', len(domain)
+print 'The extent is ', domain.get_extent()
+print domain.statistics()
+
+domain.set_name(project.basename)
+domain.set_datadir(project.outputtimedir)
+domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+
+
+#-------------------------------------------------------------------------------                                 
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+tide = 0.0
+
+domain.set_quantity('stage', tide)
+domain.set_quantity('friction', 0.0) 
+print 'hi and file',project.combined_dem_name + '.pts'
+
+domain.set_quantity('elevation', 
+#                    0.
+#                    filename = project.onshore_dem_name + '.pts',
+                    filename = project.combined_dem_name + '.pts',
+#                    filename = project.offshore_dem_name + '.pts',
+                    use_cache = True,
+                    verbose = True,
+                    alpha = 0.1
+                    )
+
+print 'hi1'
+
+#-------------------------------------------------------------------------------                                 
+# Setup boundary conditions (all reflective)
+#-------------------------------------------------------------------------------
+print 'start ferret2sww'
+
+
+south = project.south 
+north = project.north
+west = project.west
+east = project.east
+
+#note only need to do when an SWW file for the MOST boundary doesn't exist
+cache(ferret2sww,
+      (source_dir + project.boundary_basename,
+       source_dir + project.boundary_basename), 
+#      (project.MOST_dir + project.boundary_basename,
+#       source_dir + project.boundary_basename), 
+      {'verbose': True,
+# note didn't work with the below
+#       'minlat': south - 1,
+#       'maxlat': north + 1,
+#       'minlon': west - 1,
+#       'maxlon': east + 1,
+       'minlat': south,
+       'maxlat': north,
+       'minlon': west,
+       'maxlon': east,
+#       'origin': project.mesh_origin,
+       'origin': domain.geo_reference.get_origin(),
+       'mean_stage': tide,
+       'zscale': 1,                 #Enhance tsunami
+       'fail_on_NaN': False,
+       'inverted_bathymetry': True},
+      #evaluate = True,
+       verbose = True,
+       dependencies = source_dir + project.boundary_basename + '.sww')
+
+
+print 'Available boundary tags', domain.get_boundary_tags()
+
+Bf = File_boundary(source_dir + project.boundary_basename + '.sww', 
+                    domain, verbose = True)
+Br = Reflective_boundary(domain)
+Bd = Dirichlet_boundary([tide,0,0])
+
+
+# 7 min square wave starting at 1 min, 6m high
+Bw = Time_boundary(domain = domain,
+                   f=lambda t: [(60<t<480)*6, 0, 0])
+
+domain.set_boundary( {'top': Bf, 'topleft': Bf,
+                      'topleft1': Bf, 'bottomleft': Bd,
+                      'bottom': Br, 'bottomright': Br, 'topright': Bd} )
+
+#-------------------------------------------------------------------------------                                 
+# Evolve system through time
+#-------------------------------------------------------------------------------
+import time
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = 240, finaltime = 7200): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'top')     
+
+for t in domain.evolve(yieldstep = 120, finaltime = 12600
+                       ,skip_initial_step =True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'top')     
+
+for t in domain.evolve(yieldstep = 60, finaltime = 19800
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'top')     
+    
+for t in domain.evolve(yieldstep = 120, finaltime = 25200
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'top')     
+
+for t in domain.evolve(yieldstep = 240, finaltime = 36000
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'top')
+    
+print 'That took %.2f seconds' %(time.time()-t0)
+
+print 'finished'
Index: /anuga_work/production/wa/onslow_2006/run_onslow_grad.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/run_onslow_grad.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/run_onslow_grad.py	(revision 7411)
@@ -0,0 +1,247 @@
+"""Script for running tsunami inundation scenario for Onslow, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_grad_grad.py
+The output sww file is stored in project_grad_grad.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project_grad_grad.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep,umask
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+
+from anuga.shallow_water.data_manager import export_grid
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+
+# Application specific imports
+import project_grad                 # Definition of file names and polygons
+
+def run_model(**kwargs):
+    
+    tide = kwargs['tide']
+    alpha = kwargs['alpha']
+    friction = kwargs['friction']
+    time_thinning = kwargs['time_thinning']
+    scenario_name = kwargs['aa_scenario_name']
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+
+    #copy script must be before screen_catcher
+    print 'tide',tide
+    kwargs['est_num_trigs']=project_grad.trigs_min
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project_grad.host
+    kwargs['res_factor']=project_grad.res_factor
+    kwargs['starttime']=project_grad.starttime
+    kwargs['yieldstep']=project_grad.yieldstep
+    kwargs['finaltime']=project_grad.finaltime
+    
+    kwargs['output_dir']=project_grad.output_run_time_dir
+    kwargs['bathy_file']=project_grad.combined_dir_name + '.pts'
+    kwargs['boundary_file']=project_grad.boundaries_in_dir+sep+project_grad.boundaries_name+'_40000.sww'
+#    kwargs['Completed']=''
+
+    print 'output_dir',kwargs['output_dir']
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                        dirname(project_grad.__file__)+sep+project_grad.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print 'Processor Name:', get_processor_name()
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project_grad.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    #IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+
+    # FIXME (Ole): Move to build_shark_bay.py
+    if myid == 0:
+    
+        print 'start create mesh from regions'
+        
+        create_mesh_from_regions(project_grad.bounding_polygon,
+                                 boundary_tags=project_grad.boundary_tags,
+                                 maximum_triangle_area=project_grad.res_bounding_polygon,
+                                 interior_regions=project_grad.interior_regions,
+                                 filename=project_grad.mesh_name+'.msh',
+                                 use_cache=True,
+                                 verbose=True)
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    #domain = cache(Domain, (mesh_name), {'use_cache':True, 'verbose':True}, verbose=True)
+    #above don't work
+    domain = Domain(project_grad.mesh_name+'.msh',
+                    use_cache=True, verbose=True)
+     
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    if myid == 0:
+
+        IC = project_grad.tide
+        #if project_grad.tide == 0.0:
+        #    print 'Tide is MSL'
+        #    IC = 0.0
+        #else:    
+        #    print 'Create onshore polygon'
+        #    from polygon import Polygon_function
+        #    #following sets the stage/water to be offcoast only
+        #    IC = Polygon_function([(project_grad.onshore_polygon, -1.0)],
+        #                          default = tide,
+        #                          geo_reference = domain.geo_reference)
+            
+
+        print 'Set initial conditions'
+        domain.set_quantity('stage', IC)
+        domain.set_quantity('friction', friction)
+        print 'Set elevation'
+        domain.set_quantity('elevation', 
+                            filename = kwargs['bathy_file'],
+                            use_cache = True,
+                            verbose = True,
+                            alpha = project_grad.alpha)
+        
+
+    #------------------------------------------------------
+    # Distribute domain to implement parallelism !!!
+    #------------------------------------------------------
+    barrier()
+    if numprocs > 1:
+        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(scenario_name)
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2) # Apply second order scheme
+    domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+    print 'domain id', id(domain)
+
+    domain.tight_slope_limiters = 0
+    
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+    #print 'Reading Boundary file',project_grad.boundaries_dir_namea + '.sww'
+
+    Bf = Field_boundary(kwargs['boundary_file'],
+                        domain,
+                        time_thinning=time_thinning,
+                        mean_stage=tide,
+                        use_cache=True,
+                        verbose=True)
+                    
+    kwargs['input_start_time']=domain.starttime
+
+    print 'finished reading boundary file'
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([tide,0,0])
+
+    print'set_boundary'
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf})
+
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #----------------------------------------------------------------------------
+
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['starttime']): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+
+    for t in domain.evolve(yieldstep = kwargs['yieldstep'], finaltime = 21600
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+    
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')   
+
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'That took %.2f seconds' %(time.time()-t0)
+    
+    kwargs['completed']=str(time.time()-t0)
+    
+    store_parameters(**kwargs)
+
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+    run_model(file_name=project_grad.home+'detail.csv', aa_scenario_name=project_grad.scenario_name,
+              ab_time=project_grad.time, res_factor= project_grad.res_factor, tide=project_grad.tide, user=project_grad.user,
+              alpha = project_grad.alpha, friction=project_grad.friction,
+              time_thinning = project_grad.time_thinning,
+              dir_comment=project_grad.dir_comment)
+
+
Index: /anuga_work/production/wa/onslow_2006/run_onslow_new.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/run_onslow_new.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/run_onslow_new.py	(revision 7411)
@@ -0,0 +1,243 @@
+"""Script for running a tsunami inundation scenario for Onslow, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.outputdir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Nick Bartzis, GA - 2006
+"""
+
+
+#-------------------------------------------------------------------------------# Import necessary modules
+#-------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import time
+
+# Related major packages
+from anuga.pyvolution.shallow_water import Domain, Reflective_boundary, \
+                            Dirichlet_boundary, Time_boundary, File_boundary
+from anuga.pyvolution.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.pyvolution.combine_pts import combine_rectangular_points_files 
+from anuga.pyvolution.pmesh2domain import pmesh_to_domain_instance
+from anuga.geospatial_data.geospatial_data import add_points_files
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+from smf import slump_tsunami  # Function for submarine mudslide 
+
+from shutil import copy
+from os import mkdir, access, F_OK
+
+from anuga.geospatial_data.geospatial_data import *
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+
+# filenames
+coarsedemname = project.coarsedemname
+
+onshore_dem_name = project.onshore_dem_name
+
+offshore_points = project.offshore_dem_name
+
+meshname = project.meshname+'.msh'
+
+source_dir = project.boundarydir
+
+# creates copy of code in output dir
+if access(project.outputdir,F_OK) == 0 :
+    mkdir (project.outputdir)
+copy (project.codedirname, project.outputdir + project.codename)
+copy (project.codedir + 'run_onslow.py', project.outputdir + 'run_onslow.py')
+
+
+'''
+# coarse data
+convert_dem_from_ascii2netcdf(coarsedemname, use_cache=True, verbose=True)
+dem2pts(coarsedemname, use_cache=True, verbose=True)
+
+
+# fine data (clipping the points file to smaller area)
+convert_dem_from_ascii2netcdf(onshore_dem_name, use_cache=True, verbose=True)
+dem2pts(onshore_dem_name,
+        easting_min=project.eastingmin,
+        easting_max=project.eastingmax,
+        northing_min=project.northingmin,
+        northing_max= project.northingmax,
+        use_cache=True, 
+        verbose=True)
+
+        '''
+print'create G1'
+G1 = Geospatial_data(file_name = project.offshore_dem_name + '.xya')
+
+print'create G2'
+G2 = Geospatial_data(file_name = project.onshore_dem_name + '.pts')
+
+print'add G1+G2'
+G = G1 + G2
+
+print'export G'
+G.new_export_points_file(project.combined_dem_name + '.pts')
+
+'''
+add_points_files(
+                  project.offshore_dem_name + '.xya',
+                  project.onshore_dem_name + '.pts',
+                  project.combined_dem_name + '.pts')
+'''
+#-------------------------------------------------------------------------------                                 
+# Create the triangular mesh based on overall clipping polygon with a tagged
+# boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+
+# original
+interior_res = 5000
+interior_regions = [[project.poly_onslow, interior_res],
+                    [project.poly_thevenard, interior_res],
+                    [project.poly_direction, interior_res]]
+                    #[project.testpoly, interior_res]]
+print 'number of interior regions', len(interior_regions)
+
+from caching import cache
+_ = cache(create_mesh_from_regions,
+          project.polyAll,
+          {'boundary_tags': {'top': [0], 'topleft': [1],
+                             'left': [2], 'bottom': [3],
+                             'bottomright': [4], 'topright': [5]},
+           'maximum_triangle_area': 100000,
+           'filename': meshname,           
+           'interior_regions': interior_regions},
+          verbose = True)
+
+
+#-------------------------------------------------------------------------------                                 
+# Setup computational domain
+#-------------------------------------------------------------------------------                                 
+
+domain = pmesh_to_domain_instance(meshname, Domain,
+                                  use_cache = True,
+                                  verbose = True)
+
+print 'Number of triangles = ', len(domain)
+print 'The extent is ', domain.get_extent()
+print domain.statistics()
+
+domain.set_name(project.basename)
+domain.set_datadir(project.outputdir)
+domain.set_quantities_to_be_stored(['stage'])
+
+
+#-------------------------------------------------------------------------------
+# Set up scenario (tsunami_source is a callable object used with set_quantity)
+#-------------------------------------------------------------------------------
+'''
+tsunami_source = slump_tsunami(length=30000.0,
+                               depth=400.0,
+                               slope=6.0,
+                               thickness=176.0, 
+                               radius=3330,
+                               dphi=0.23,
+                               x0=project.slump_origin[0], 
+                               y0=project.slump_origin[1], 
+                               alpha=0.0, 
+                               domain=domain)
+
+'''
+#-------------------------------------------------------------------------------                                 
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+tide = 0.
+
+domain.set_quantity('stage', tide)
+domain.set_quantity('friction', 0.0) 
+print 'hi and file',project.combined_dem_name + '.pts'
+domain.set_quantity('elevation', 
+#                    0.
+#                    filename = project.onshore_dem_name + '.pts',
+                    filename = project.combined_dem_name + '.pts',
+#                    filename = project.offshore_dem_name + '.pts',
+                    use_cache = False,
+                    verbose = True,
+                    alpha = 0.1
+                    )
+print 'hi1'
+
+#-------------------------------------------------------------------------------                                 
+# Setup boundary conditions (all reflective)
+#-------------------------------------------------------------------------------
+
+from anuga.pyvolution.data_manager import ferret2sww
+
+south = project.south 
+north = project.north
+west = project.west
+east = project.east
+
+cache(ferret2sww,
+      (source_dir + project.boundary_basename,
+       source_dir + project.boundary_basename), 
+      {'verbose': True,
+# note didn't work with the below
+#       'minlat': south - 1,
+#       'maxlat': north + 1,
+#       'minlon': west - 1,
+#       'maxlon': east + 1,
+       'minlat': south,
+       'maxlat': north,
+       'minlon': west,
+       'maxlon': east,
+#       'origin': project.mesh_origin,
+       'origin': domain.geo_reference.get_origin(),
+       'mean_stage': tide,
+       'zscale': 1,                 #Enhance tsunami
+       'fail_on_NaN': False,
+       'inverted_bathymetry': True},
+      #evaluate = True,
+       verbose = True)
+
+
+print 'Available boundary tags', domain.get_boundary_tags()
+
+Bf = File_boundary(source_dir + project.boundary_basename + '.sww', 
+                    domain, verbose = True)
+Br = Reflective_boundary(domain)
+Bd = Dirichlet_boundary([tide,0,0])
+
+
+# 7 min square wave starting at 1 min, 6m high
+Bw = Time_boundary(domain = domain,
+                   f=lambda t: [(60<t<480)*6, 0, 0])
+
+domain.set_boundary( {'top': Bf, 'topleft': Bf,
+                             'left': Br, 'bottom': Br,
+                             'bottomright': Br, 'topright': Bf} )
+
+
+#-------------------------------------------------------------------------------                                 
+# Evolve system through time
+#-------------------------------------------------------------------------------
+import time
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = 50, finaltime = 100): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'top')     
+    
+print 'That took %.2f seconds' %(time.time()-t0)
+
+print 'finished'
Index: /anuga_work/production/wa/onslow_2006/run_onslow_old.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/run_onslow_old.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/run_onslow_old.py	(revision 7411)
@@ -0,0 +1,267 @@
+"""Script for running a tsunami inundation scenario for Onslow, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.outputdir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Nick Bartzis, GA - 2006
+"""
+
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import time
+
+# Related major packages
+from anuga.pyvolution.shallow_water import Domain, Reflective_boundary, \
+                            Dirichlet_boundary, Time_boundary, File_boundary
+from anuga.pyvolution.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.pyvolution.combine_pts import combine_rectangular_points_files 
+from anuga.pyvolution.pmesh2domain import pmesh_to_domain_instance
+#from anuga.geospatial_data.geospatial_data import *
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+from smf import slump_tsunami  # Function for submarine mudslide 
+
+from shutil import copy
+from os import mkdir, access, F_OK
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+# filenames
+coarsedemname = project.coarsedemname
+
+onshore_dem_name = project.onshore_dem_name
+
+meshname = project.meshname+'.msh'
+
+#############################################################
+# making a copy of project and run to a time stamped directory
+# with the ouput
+source_dir = project.boundarydir
+
+#if dir doesn't exists then makes dir
+if access(project.outputdir,F_OK) == 0 :
+    mkdir (project.outputdir)
+# creates copy of code in output dir
+copy (project.codedirname, project.outputdir + project.codename)
+copy (project.codedir + 'run_onslow.py', project.outputdir + 'run_onlsow.py')
+#print "copied to"+ project.outputdir + project.codename + 'and run_onlsow.py'
+#################################################################
+'''
+# coarse data
+convert_dem_from_ascii2netcdf(coarsedemname, use_cache=True, verbose=True)
+dem2pts(coarsedemname, use_cache=True, verbose=True)
+
+
+# fine data (clipping the points file to smaller area)
+convert_dem_from_ascii2netcdf(onshore_dem_name, use_cache=True, verbose=True)
+dem2pts(onshore_dem_name,
+        easting_min=project.eastingmin,
+        easting_max=project.eastingmax,
+        northing_min=project.northingmin,
+        northing_max= project.northingmax,
+        use_cache=True, 
+        verbose=True)
+
+print 'before off xya to object'
+offshore_pts = Geospatial_data(project.offshore_dem_name + '.xya')
+print 'before offshore to dict'
+offshore_dict = geospatial_data2points_dictionary(offshore_pts)
+
+print 'offshore to pts file'
+export_points_file(project.offshore_dem_name + '.pts', offshore_dict)
+'''
+# combining the coarse and fine data
+# NOTE MUST HAVE FINE FIRST!
+'''
+combine_rectangular_points_files(
+                                 project.onshore_dem_name + '.pts',
+                                 project.coarsedemname + '.pts',
+                                 project.combined_dem_name + '.pts')
+
+print 'create G1'
+G1 = Geospatial_data(project.onshore_dem_name + '.pts')
+print 'G1 dict'
+G1_points_dict = geospatial_data2points_dictionary(G1)
+print 'G1 xya file'
+export_points_file(project.datadir + 'offshore_dem.xya', G1_points_dict)
+print 'create G2'
+G2 = Geospatial_data(project.offshore_dem_name + '.xya')
+print 'G1+g2'
+G = G1 + G2
+print 'G dict'
+G_points_dict = geospatial_data2points_dictionary(G)
+print 'G to xya'
+export_points_file(project.combined_dem_name + '.xya', G_points_dict)
+
+
+add_points_files(project.onshore_dem_name + '.pts', 
+                  project.offshore_dem_name + '.xya',
+                  project.combined_dem_name + '.pts')
+
+print 'please'
+
+add_points_files(project.onshore_dem_name + '.pts', 
+                  project.offshore_dem_name + '.pts',
+                  project.combined_dem_name + '.pts')
+
+print ' finished with points'
+'''
+#-------------------------------------------------------------------------------                                 
+# Create the triangular mesh based on overall clipping polygon with a tagged
+# boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#------------------------------------------------------------------------------
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+
+# original
+interior_res = 50000
+interior_regions = [[project.poly_onslow, interior_res],
+                    [project.poly_thevenard, interior_res],
+                    [project.poly_direction, interior_res]]
+                    #[project.testpoly, interior_res]]
+print 'number of interior regions', len(interior_regions)
+
+from caching import cache
+_ = cache(create_mesh_from_regions,
+          project.polyAll,
+          {'boundary_tags': {'top': [0], 'topleft': [1],
+                             'left': [2], 'bottom': [3],
+                             'bottomright': [4], 'topright': [5]},
+           'maximum_triangle_area': 1000000,
+           'filename': meshname,           
+           'interior_regions': interior_regions},
+          verbose = True)
+
+
+#------------------------------------------------------------------------------
+# Setup computational domain
+#------------------------------------------------------------------------------
+
+domain = pmesh_to_domain_instance(meshname, Domain,
+                                  use_cache = True,
+                                  verbose = True)
+
+print 'Number of triangles = ', len(domain)
+print 'The extent is ', domain.get_extent()
+print domain.statistics()
+
+domain.set_name(project.basename)
+domain.set_datadir(project.outputdir)
+domain.set_quantities_to_be_stored(['stage'])
+
+print 'hi'
+#------------------------------------------------------------------------------
+# Set up scenario (tsunami_source is a callable object used with set_quantity)
+#------------------------------------------------------------------------------
+'''
+tsunami_source = slump_tsunami(length=30000.0,
+                               depth=400.0,
+                               slope=6.0,
+                               thickness=176.0, 
+                               radius=3330,
+                               dphi=0.23,
+                               x0=project.slump_origin[0], 
+                               y0=project.slump_origin[1], 
+                               alpha=0.0, 
+                               domain=domain)
+
+'''
+#------------------------------------------------------------------------------
+# Setup initial conditions
+#------------------------------------------------------------------------------
+
+tide = 0.
+
+domain.set_quantity('stage', tide)
+domain.set_quantity('friction', 0.0) 
+print 'hi1', project.combined_dem_name + '.pts'
+domain.set_quantity('elevation', 
+#                    0.
+#                    filename = project.onshore_dem_name + '.pts',
+                    filename = project.combined_dem_name + '.pts',
+#                    filename = project.coarsedemname + '.pts',
+                    use_cache = True,
+                    verbose = True
+                    )
+
+print 'hi2'
+#------------------------------------------------------------------------------
+# Setup boundary conditions (all reflective)
+#------------------------------------------------------------------------------
+'''
+from anuga.pyvolution.data_manager import ferret2sww
+
+south = project.south 
+north = project.north
+west = project.west
+east = project.east
+
+cache(ferret2sww,
+      (source_dir + project.boundary_basename,
+       source_dir + project.boundary_basename), 
+      {'verbose': True,
+# note didn't work with the below
+#       'minlat': south - 1,
+#       'maxlat': north + 1,
+#       'minlon': west - 1,
+#       'maxlon': east + 1,
+       'minlat': south,
+       'maxlat': north,
+       'minlon': west,
+       'maxlon': east,
+#       'origin': project.mesh_origin,
+       'origin': domain.geo_reference.get_origin(),
+       'mean_stage': tide,
+       'zscale': 1,                 #Enhance tsunami
+       'fail_on_NaN': False,
+       'inverted_bathymetry': True},
+      #evaluate = True,
+       verbose = True)
+'''
+
+print 'Available boundary tags', domain.get_boundary_tags()
+
+#Bf = File_boundary(source_dir + project.boundary_basename + '.sww', 
+#                    domain, verbose = True)
+Br = Reflective_boundary(domain)
+Bd = Dirichlet_boundary([tide,0,0])
+
+print 'hi3'
+# 7 min square wave starting at 1 min, 6m high
+Bw = Time_boundary(domain = domain,
+                   f=lambda t: [(60<t<480)*6, 0, 0])
+
+domain.set_boundary( {'top': Bw, 'topleft': Bw,
+                             'left': Br, 'bottom': Br,
+                             'bottomright': Br, 'topright': Br} )
+print 'hi4'
+
+#------------------------------------------------------------------------------
+# Evolve system through time
+#------------------------------------------------------------------------------
+
+import time
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = 50, finaltime = 50): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'top')     
+    
+print 'That took %.2f seconds' %(time.time()-t0)
+print 'hi5'
Index: /anuga_work/production/wa/onslow_2006/run_onslow_urs.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/run_onslow_urs.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/run_onslow_urs.py	(revision 7411)
@@ -0,0 +1,269 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project_urs.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid
+
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+
+# Application specific imports
+import project_urs                 # Definition of file names and polygons
+
+def run_model(**kwargs):
+    
+#    scenario_name = kwargs['aa_scenario_name']
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+
+    #copy script must be before screen_catcher
+    print 'tide',kwargs['tide']
+    kwargs['est_num_trigs']=project_urs.trigs_min
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project_urs.host
+    kwargs['res_factor']=project_urs.res_factor
+    kwargs['starttime']=project_urs.starttime
+    kwargs['yieldstep']=project_urs.yieldstep
+    kwargs['finaltime']=project_urs.finaltime
+    
+    kwargs['output_dir']=project_urs.output_run_time_dir
+    kwargs['bathy_file']=project_urs.combined_dir_name + '.pts'
+#    kwargs['bathy_file']=project_urs.combined_small_dir_name + '.txt'
+    kwargs['boundary_file']=project_urs.boundaries_in_dir_name + '.sww'
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+        
+    print 'output_dir',kwargs['output_dir']
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                 dirname(project_urs.__file__)+sep+ project_urs.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+
+    print "Processor Name:",get_processor_name()
+
+    # creates copy of code in output dir
+    print 'min triangles', project_urs.trigs_min,
+    print 'Note: This is generally about 20% less than the final amount'
+
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project_urs.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+    #IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+
+    if myid == 0:
+    
+        print 'start create mesh from regions'
+
+        create_mesh_from_regions(project_urs.poly_all,
+                             boundary_tags={'back': [4, 5], 'side': [3, 6],
+                                            'ocean': [0, 1, 2]},
+                             maximum_triangle_area=project_urs.res_poly_all,
+                             interior_regions=project_urs.interior_regions,
+                             filename=project_urs.meshes_dir_name+'.msh',
+                             use_cache=False,
+                             verbose=True)
+    barrier()
+    
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+    #from caching import cache
+
+    #domain = cache(Domain, (meshes_dir_name), {'use_cache':True, 'verbose':True}, verbose=True)
+    #above don't work
+    domain = Domain(project_urs.meshes_dir_name+'.msh', use_cache=False, verbose=True)
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    if myid == 0:
+
+        print 'Setup initial conditions'
+
+        from polygon import Polygon_function
+        #following sets the stage/water to be offcoast only
+        IC = Polygon_function( [(project_urs.poly_mainland, -1.0)], default = kwargs['tide'],
+                                 geo_reference = domain.geo_reference)
+        domain.set_quantity('stage', IC)
+        domain.set_quantity('friction', kwargs['friction']) 
+        
+        print 'Start Set quantity'
+
+        domain.set_quantity('elevation', 
+                            filename = kwargs['bathy_file'],
+                            use_cache = True,
+                            verbose = True,
+                            alpha = kwargs['alpha'])
+        print 'Finished Set quantity'
+    barrier()
+
+
+    #------------------------------------------------------
+    # Distribute domain to implement parallelism !!!
+    #------------------------------------------------------
+
+    if numprocs > 1:
+        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['aa_scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2) # Apply second order scheme
+    domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+    #print 'Reading Boundary file',project_urs.boundaries_dir_namea + '.sww'
+
+    Bf = Field_boundary(kwargs['boundary_file'],
+                    domain, time_thinning=kwargs['time_thinning'], mean_stage=kwargs['tide'], 
+                    use_cache=True, verbose=True)
+                    
+    kwargs['input_start_time']=domain.starttime
+
+    print 'finished reading boundary file'
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([kwargs['tide'],0,0])
+
+    print'set_boundary'
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf}) 
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #----------------------------------------------------------------------------
+
+    t0 = time.time()
+    
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['starttime']): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+
+    for t in domain.evolve(yieldstep = kwargs['yieldstep'], finaltime = 21600
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+    
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean') 
+
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'That took %.2f seconds' %(time.time()-t0)
+    
+    kwargs['completed']=str(time.time()-t0)
+    
+    if myid == 0:
+        #store_parameters(**kwargs)
+        
+        print 'memory usage before del domain',mem_usage()
+        #del domain
+        print 'memory usage after del domain',mem_usage()
+    
+    
+        swwfile = kwargs['output_dir']+kwargs['aa_scenario_name']
+        print 'swwfile',swwfile
+    
+        export_grid(swwfile, extra_name_out = 'town',
+                quantities = ['speed'], # '(xmomentum**2 + ymomentum**2)**0.5' defaults to elevation
+#                quantities = ['elevation','depth','stage','speed'], # '(xmomentum**2 + ymomentum**2)**0.5' defaults to elevation
+                timestep = None,
+                reduction = max,
+                cellsize = 25,
+                NODATA_value = -9999,
+                easting_min = project_urs.eastingmin,
+                easting_max = project_urs.eastingmax,
+                northing_min = project_urs.northingmin,
+                northing_max = project_urs.northingmax,
+                verbose = True,
+                origin = None,
+                datum = 'WGS84',
+                format = 'asc')
+    
+        buildings_filename = project_urs.buildings_filename
+        buildings_filename_out = project_urs.buildings_filename_out
+                
+        #inundation_damage(swwfile+'.sww', buildings_filename, buildings_filename_out)
+        print '\n Augmented building file written to %s \n' \
+           %buildings_filename_out
+    barrier()
+    
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+    run_model(file_name=project_urs.home+'detail.csv', aa_scenario_name=project_urs.scenario_name,
+              ab_time=project_urs.time, res_factor= project_urs.res_factor, tide=project_urs.tide, user=project_urs.user,
+              alpha = project_urs.alpha, friction=project_urs.friction,
+              time_thinning = project_urs.time_thinning,
+              dir_comment=project_urs.dir_comment)
+
+
Index: /anuga_work/production/wa/onslow_2006/run_timeseries.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/run_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/run_timeseries.py	(revision 7411)
@@ -0,0 +1,34 @@
+""" Script for generating figures, see sww2timeseries for documentation"""
+
+from anuga.pyvolution.util import sww2timeseries
+import project
+from os import sep
+
+# define directory location of sww and gauge data
+production_dirs = {'20060426_004129': '1.5 AHD',
+                   '20060426_004237': '-1.5 AHD',
+                   '20060515_001733': '0 AHD'}
+
+for label_id in production_dirs.keys():
+    
+    file_loc = project.outputdir + label_id + sep
+    swwfile = file_loc + project.basename + '.sww'
+    swwfiles[swwfile] = label_id
+    
+# generate figures - see sww2timeseries for documentation
+sww2timeseries(swwfiles,
+               project.gauge_filename,
+               production_dirs,
+               report = False,
+               plot_quantity = ['stage', 'speed'],
+               time_min = None,
+               time_max = None,
+               title_on = False,
+               verbose = True)
+
+print 'finished plotting time series'
+
+
+
+
+
Index: /anuga_work/production/wa/onslow_2006/test_export_results.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/test_export_results.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/test_export_results.py	(revision 7411)
@@ -0,0 +1,47 @@
+import project, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem, export_grid
+from os import sep
+
+# %This is the dir of the parallel results
+time_dir = '20070507_215717_run_final_1.5_nbartzis' # HAT 1 in Dampier 10000 yrr
+# This is the dir of the serial results
+time_dir = '20060704_063005'
+
+#time_dir = '' # HAT 1 in Broome 10000 yr
+#time_dir = '' # MSL 1 in Broome 10000 yr
+#time_dir = '' # HAT 1 in Pt Hedland 10000 yr
+#time_dir = '' # MSL 1 in Pt Hedland 10000 yr
+#time_dir = '' # HAT 1 in Onslow 10000 yr
+#time_dir = '' # MSL 1 in Onslow 10000 yr
+#time_dir = '' # HAT 1 in Exmouth 10000 yr
+#time_dir = '' # MSL 1 in Exmouth 10000 yr
+cellsize = 150
+timestep = None
+directory = project.outputdir
+#name = directory + time_dir + sep + project.scenario_name
+name = directory+time_dir+sep+'source'
+
+# export_grid(namei, basename_out = outnamei,
+#             quantity = quantityname,
+#             timestep = timestep,
+#             cellsize = cellsize,      
+#             easting_min = project.e_min_area,
+#             easting_max = project.e_max_area,
+#             northing_min = project.n_min_area,
+#             northing_max = project.n_max_area,        
+#             reduction = max, 
+#             verbose = True,
+#             format = 'asc')
+sww2dem(name, basename_out = 'dirty_monkey2',
+            quantity = 'elevation',
+            timestep = timestep,
+            cellsize = cellsize,      
+            #easting_min = project.e_min_area,
+            #easting_max = project.e_max_area,
+            #northing_min = project.n_min_area,
+            #northing_max = project.n_max_area,        
+            reduction = max, 
+            verbose = True,
+            format = 'asc')
Index: /anuga_work/production/wa/onslow_2006/ticket160_run.py
===================================================================
--- /anuga_work/production/wa/onslow_2006/ticket160_run.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2006/ticket160_run.py	(revision 7411)
@@ -0,0 +1,238 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project_urs.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+# Application specific imports
+import aticket160_project as project_urs
+
+def run_model(**kwargs):
+    
+    tide = kwargs['tide']
+    alpha = kwargs['alpha']
+    friction = kwargs['friction']
+    time_thinning = kwargs['time_thinning']
+    scenario_name = kwargs['aa_scenario_name']
+    
+    
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+
+    #copy script must be before screen_catcher
+    print 'tide',tide
+    kwargs['est_num_trigs']=project_urs.trigs_min
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project_urs.host
+    kwargs['res_factor']=project_urs.res_factor
+    kwargs['starttime']=project_urs.starttime    
+    kwargs['yieldstep']=project_urs.yieldstep
+    kwargs['finaltime']=project_urs.finaltime
+    
+    kwargs['output_dir']=project_urs.output_run_time_dir
+    kwargs['bathy_file']=project_urs.combined_dir_name + '.pts'
+    kwargs['boundary_file']=project_urs.boundaries_dir_name + '.sww'
+#    kwargs['Completed']=''
+
+    print 'output_dir',kwargs['output_dir']
+    
+    print 'myid',myid
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                 dirname(project_urs.__file__)+sep+ project_urs.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print "Processor Name:",get_processor_name()
+#    barrier()
+
+    # filenames
+    #boundaries_name = project_urs.boundaries_name
+    meshes_dir_name = project_urs.meshes_dir_name+'.msh'
+    #boundaries_dir_name = project_urs.boundaries_dir_name
+
+#    tide = project_urs.tide
+
+    # creates copy of code in output dir
+    print 'min triangles', project_urs.trigs_min,
+    print 'Note: This is generally about 20% less than the final amount'
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project_urs.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    if myid == 0:
+    
+        print 'start create mesh from regions'
+
+        create_mesh_from_regions(project_urs.poly_all,
+                             boundary_tags={'back': [4, 5], 'side': [3, 6],
+                                            'ocean': [0, 1, 2]},
+                             maximum_triangle_area=project_urs.res_poly_all,
+                             interior_regions=project_urs.interior_regions,
+                             filename=meshes_dir_name,
+                             use_cache=False,
+                             verbose=True)
+    barrier()
+    
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+    #from caching import cache
+
+    #domain = cache(Domain, (meshes_dir_name), {'use_cache':True, 'verbose':True}, verbose=True)
+    #above don't work
+    domain = Domain(meshes_dir_name, use_cache=False, verbose=True)
+#    print 'domain id', id(domain) 
+#    print 'myhash', myhash(domain)      
+       
+    print domain.statistics()
+#    domain.
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+#    print len(domain.mesh)
+
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    if myid == 0:
+
+        print 'Setup initial conditions'
+
+        from polygon import Polygon_function
+        #following sets the stage/water to be offcoast only
+        IC = Polygon_function( [(project_urs.poly_mainland, -1.0)], default = tide,
+                                 geo_reference = domain.geo_reference)
+        domain.set_quantity('stage', IC)
+        domain.set_quantity('friction', friction) 
+        
+        print 'Start Set quantity'
+
+        domain.set_quantity('elevation', 
+                            filename = kwargs['bathy_file'],
+                            use_cache = True,
+                            verbose = True,
+                            alpha = alpha)
+        print 'Finished Set quantity'
+    barrier()
+
+
+    #------------------------------------------------------
+    # Distribute domain to implement parallelism !!!
+    #------------------------------------------------------
+
+    if numprocs > 1:
+        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(scenario_name)
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2) # Apply second order scheme
+    domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+    domain.H0=0.01
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+    #print 'Reading Boundary file',project_urs.boundaries_dir_namea + '.sww'
+
+    #Bf = Field_boundary(kwargs['boundary_file'],
+     #               domain, time_thinning=time_thinning, mean_stage=tide, 
+      #              use_cache=True, verbose=True)
+                    
+    kwargs['input_start_time']=domain.starttime
+
+    print 'finished reading boundary file'
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([tide,0,0])
+    Bf = Dirichlet_boundary([5.,0,0])
+
+    print'set_boundary'
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf}) 
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #----------------------------------------------------------------------------
+
+    t0 = time.time()
+    print "in time"
+    for t in domain.evolve(yieldstep = 10, finaltime = 20):
+        print "yeah", 
+        domain.write_time()
+
+    if myid == 0:
+        store_parameters(**kwargs)
+    barrier()
+
+
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+    run_model(file_name=project_urs.home+'detail.csv',
+              aa_scenario_name=project_urs.scenario_name,
+              ab_time=project_urs.time,
+              res_factor= project_urs.res_factor,
+              tide=project_urs.tide, user=project_urs.user,
+              alpha = project_urs.alpha, friction=project_urs.friction,
+              time_thinning = project_urs.time_thinning,
+              dir_comment=project_urs.dir_comment)
+
+
Index: /anuga_work/production/wa/onslow_2009/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/onslow_2009/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2009/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,78 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\onslow_tsunami_scenario_2009\\"
+output_dir="anuga\\outputs\\"
+
+time_dir1 = '20090817_171542_run_final_0.0_27283_kvanputt'
+
+time_dirs = [time_dir1]
+
+for time_dir in time_dirs:
+    # Local variables...
+    folder = scenario_dir + output_dir +  time_dir +'\\'
+    raster_gbd = folder + 'raster.gdb'
+##    land = scenario_dir + "map_work\\\port_hedland.gdb\\outlines\\initial_condition"
+##    ocean = scenario_dir + "map_work\\\port_hedland.gdb\\outlines\\initial_conditions_ocean"
+
+    print 'Process: Create File GDB'
+    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    print gp.Workspace
+    
+    #replication dictionary
+    replicate = (('onslow', ''),('_', ''),('max','_M'),
+                 ('CBD', 'CDB'),
+                 ('depth','_depth'),('speed', '_speed'),
+                 ('elevation', '_ele'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection'
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+##        output_extract = output_DEM + 'E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+
Index: /anuga_work/production/wa/onslow_2009/build_elevation.py
===================================================================
--- /anuga_work/production/wa/onslow_2009/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2009/build_elevation.py	(revision 7411)
@@ -0,0 +1,100 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' # except', project.offshore_name5
+G = None
+for key in geospatial_data:
+    #if key == project.point_filenames[4] or key == project.ascii_filenames[1]:
+    #    # Skip these files for now
+    #    continue
+    
+    G += geospatial_data[key]
+        
+#print 'Clip combined geospatial data'
+##G_clip = G.clip_outside(project.poly_aoi1)
+##G_all = G_clip + geospatial_data[project.point_filenames[4]] 
+#G_clipped = G_all.clip(project.poly_all)
+#G_clip = G.clip(project.bounding_polygon)
+
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/onslow_2009/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/onslow_2009/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2009/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                central_meridian=project.central_meridian,
+                zone=project.zone,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                central_meridian=project.central_meridian,
+                zone=project.zone,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/onslow_2009/file_length.py
===================================================================
--- /anuga_work/production/wa/onslow_2009/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2009/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/onslow_2009/project.py
===================================================================
--- /anuga_work/production/wa/onslow_2009/project.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2009/project.py	(revision 7411)
@@ -0,0 +1,267 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'onslow'
+scenario_folder = 'onslow_tsunami_scenario_2009'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0.0              # 3.6 difference between MSL and HAT in metres
+zone= 50               # specify UTM zone of model
+central_meridian = None 
+event_number = 27283    # 27255,27283 the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=1000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+##mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+##multi_mux = False
+mux_input_filename = 'event.list'
+multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number]
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['revised_onshore_20m_dli',
+                        'onslow_islands_dted2']
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['onslow_offshore_points.txt',
+                   'beach_survey.txt',
+                   'ONS16FINAL.txt',
+                   'ONS17FINAL.txt',
+                   'ONS18FINAL.txt' ]
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# SIMPLE BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'bounding_polygon.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['sw_MH.csv', 3000],
+                         ['aos_MH.csv', 800],
+                         ['aoi_MH.csv', 500],
+                         ['island1_MH.csv', 3000],
+                         ['island2_MH.csv', 3000],
+                         ['island3_MH.csv', 3000],
+                         ['island4_MH.csv', 3000]]
+
+#Format for points easting,northing,id,value
+interior_regions_combined_filename = None
+    
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.
+# If a list format for points easting,northing (no header)
+
+##land_initial_conditions_filename = []
+
+#Format for points easting,northing,id,value
+land_initial_conditions_filename = 'initial_conditions_simple.csv'
+
+# MODEL BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'urs_order.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_boundary.csv'
+
+#-------------------------------------------------------------------------------
+# For output sww file
+#-------------------------------------------------------------------------------
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = ''
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = '' # from NEXIS
+
+# AREA OF IMAGES - Extent of each image to find out highest runup
+# Header - easting,northing,id,value
+# Used in get_runup.py
+images_filename = ''
+
+
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+
+# ASCII export grid for Onslow
+xminOnslow = 301200
+xmaxOnslow = 311500
+yminOnslow = 7601000
+ymaxOnslow = 7609200
+
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_2009_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# The absolute pathname for the image file
+# Used for get_runup.py
+if images_filename:
+    images = join(polygons_folder, images_filename)
+
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
+#Multiple polygons in one CSV file to make internal polygons
+if not interior_regions_combined_filename == None:
+    interior_regions_combined = join(polygons_folder, interior_regions_combined_filename)
+
+
Index: /anuga_work/production/wa/onslow_2009/run_model.py
===================================================================
--- /anuga_work/production/wa/onslow_2009/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2009/run_model.py	(revision 7411)
@@ -0,0 +1,163 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/onslow_2009/setup_model.py
===================================================================
--- /anuga_work/production/wa/onslow_2009/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/onslow_2009/setup_model.py	(revision 7411)
@@ -0,0 +1,198 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+from anuga.shallow_water.data_manager import csv2polygons
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+# if it's a list, then it's a list of land condition filenames
+# else it's a string - a single file, multiple land conditions
+if isinstance(project.land_initial_conditions_filename, list):
+    for filename, MSL in project.land_initial_conditions_filename:
+        polygon = read_polygon(join(project.polygons_folder, filename))
+        project.land_initial_conditions.append([polygon, MSL])
+elif isinstance(project.land_initial_conditions_filename, basestring):
+    polygons, MSL = csv2polygons(join(project.polygons_folder,
+                                      project.land_initial_conditions_filename))
+    for i, key in enumerate(polygons):
+        if i%100==0: print i
+        poly = polygons[key]
+        land = float(MSL[key])
+        project.land_initial_conditions.append([poly, land])
+else:
+    msg = ('project.land_initial_conditions_filename must be a list or '
+           'string, got %s'
+           % type(project.land_initial_conditions_filename))
+    raise Exception, msg
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+
+if project.interior_regions_combined_filename is not None:
+    polygons, maxareas = csv2polygons(project.PriorityAreas)
+    print 'Creating %d internal polygons' % len(polygons)
+    #def create_polygon_function(polygons, geo_reference=None):
+    project.interior_regions = []
+    for i, key in enumerate(polygons):
+        if i%100==0: print i
+        poly = polygons[key]
+        maxarea = float(maxareas[key])
+        project.interior_regions.append([poly,
+                                         maxarea*project.scale_factor])
+
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/perth/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/perth/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/perth/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,87 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\perth_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir1] #time_dir1, time_dir2, time_dir3, 
+ 
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    raster_gbd = folder + 'raster.gdb'
+    contour = raster_gbd + '\\contour_dep'
+    land = scenario_dir + "map_work\\Perth.gdb\\Outlines\\poly_all_cut"
+    ocean = scenario_dir + "map_work\\Perth.gdb\\Outlines\\initial_conditions_ocean1"
+    
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    #print gp.Workspace
+    
+    #replication dictionary
+    replicate = (('perth', ''),('time_39900_0', 'b'), ('time_79800_0', 'c'),
+                 ('_', ''),('Geordie', 'Geo'),('Sorrento', 'Sor'), ('max','M_'),
+                 ('Fremantle', 'Fre'),('Rockingham', 'Roc'),('depth','_dep_'),
+                 ('speed', '_spe_'), ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*ham_speed_max.asc')
+    print time_dir
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection' 
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+
+    
+##        output_extract = output_DEM + 'E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+       
Index: /anuga_work/production/wa/perth/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/perth/Arc_txt2feature_class_res.py	(revision 7411)
+++ /anuga_work/production/wa/perth/Arc_txt2feature_class_res.py	(revision 7411)
@@ -0,0 +1,64 @@
+# ---------------------------------------------------------------------------
+# txt2fc_res.py
+# Created on: Mon Dec 01 2008 11:36:17 AM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+from os.path import join
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\perth_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir3, time_dir4, time_dir5, time_dir6] 
+
+def replace_in_file(filename, instr, repstr):
+    '''Replace one string with another in a file.'''
+    
+    # get the file contents
+    fd = open(filename, 'r')
+    lines = fd.readlines()
+    fd.close()
+
+    # convert list to one string
+    newlines = ''.join(lines)
+    
+    # replace 'instr' with 'repstr'
+    newlines = newlines.replace(instr, repstr)
+    
+    # write changed lines back to file
+    fd = open(filename, 'w')
+    fd.write(newlines)
+    fd.close()
+
+for time_dir in time_dirs:
+    print 'time_dir = ', time_dir
+    
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'perth_res.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+
+    print 'replace _$ with nothing'
+    replace_in_file(input_dir_name, '_$', '')
+    
+##    print 'Process: Feature Class to Feature Class'
+##    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "perth_res", "", "OBJECTID OBJECTID true true false 4 Long 0 10 ,First,#,perth_res.csv_Features,OBJECTID,-1,-1;LONGITUDE LONGITUDE true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,LONGITUDE,-1,-1;LATITUDE LATITUDE true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,LATITUDE,-1,-1;STRUCT_INUNDATED STRUCT_INUNDATED true true false 4 Long 0 10 ,First,#,perth_res.csv_Features,STRUCT_INUNDATED,-1,-1;STRUCT_DAMAGE_fraction STRUCT_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,STRUCT_DAMAGE_fraction,-1,-1;COLLAPSE_CSV_INFO COLLAPSE_CSV_INFO true true false 255 Text 0 0 ,First,#,perth_res.csv_Features,COLLAPSE_CSV_INFO,-1,-1;MAX_DEPTH_m MAX_DEPTH_m true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,MAX_DEPTH_m,-1,-1;STRUCT_COLLAPSED STRUCT_COLLAPSED true true false 255 Text 0 0 ,First,#,perth_res.csv_Features,STRUCT_COLLAPSED,-1,-1;STRUCT_LOSS STRUCT_LOSS true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,STRUCT_LOSS,-1,-1;CONTENTS_DAMAGE_fraction CONTENTS_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,CONTENTS_DAMAGE_fraction,-1,-1;CONTENTS_LOSS CONTENTS_LOSS true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,CONTENTS_LOSS,-1,-1", "")
+##
Index: /anuga_work/production/wa/perth/Arc_txt2feature_class_runup.py
===================================================================
--- /anuga_work/production/wa/perth/Arc_txt2feature_class_runup.py	(revision 7411)
+++ /anuga_work/production/wa/perth/Arc_txt2feature_class_runup.py	(revision 7411)
@@ -0,0 +1,49 @@
+# ---------------------------------------------------------------------------
+# txt2fc_field.py
+# Created on: Thu Nov 27 2008 01:48:26 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\perth_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir4, time_dir5, time_dir6] #time_dir1, time_dir2, time_dir3] #, 
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'perth_runup.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+  
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "x", "y", layer, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM"
+                                   "['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT"
+                                   "['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting'"
+                                   ",500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER"
+                                   "['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "perth_runup", "", "area area true true false 255 Text 0 0 ,First,#,perth_runup.csv_Features,area,-1,-1;q q true true false 8 Double 0 0 ,First,#,perth_runup.csv_Features,q,-1,-1;x x true true false 8 Double 0 0 ,First,#,perth_runup.csv_Features,x,-1,-1;y y true true false 8 Double 0 0 ,First,#,perth_runup.csv_Features,y,-1,-1", "")
+
+
+  
Index: /anuga_work/production/wa/perth/README.txt
===================================================================
--- /anuga_work/production/wa/perth/README.txt	(revision 7411)
+++ /anuga_work/production/wa/perth/README.txt	(revision 7411)
@@ -0,0 +1,17 @@
+This area aims at collecting the best practices in setting up ANUGA models and
+show them as a running demo.
+
+The intent is to make setting up and running of models easier to do and more standardised (without compromising one bit of creativity, of course :-). One principle is that information should never have to be entered more than once.
+
+
+The ideas are:
+
+* Collect all elevation data files in lists for batch processing (as in Shark Bay 200&)
+
+* Roll all the urs2sts work into an ANUGA function (see ticket:317)
+ 
+* Get rid of kwargs and use project.* for all parameters and filenames.
+
+* Migrate towards unified anuga interface (as in the Patong scenario).
+
+*
Index: /anuga_work/production/wa/perth/build_elevation.py
===================================================================
--- /anuga_work/production/wa/perth/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/perth/build_elevation.py	(revision 7411)
@@ -0,0 +1,90 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' 
+G = None
+for key in geospatial_data:
+    G += geospatial_data[key]
+        
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/perth/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/perth/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/perth/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,167 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                zone=project.zone,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/perth/export_results_max.py
===================================================================
--- /anuga_work/production/wa/perth/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/perth/export_results_max.py	(revision 7411)
@@ -0,0 +1,121 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir4, time_dir5, time_dir6] #, time_dir4, time_dir5, time_dir6]
+  
+
+#cellsize = 250
+cellsize = 20
+
+timestep = None    # None means no timestep!
+#timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+area = ['Fremantle', 'Rockingham'] #['Geordie', 'Sorrento']  # strings must match keys in var_equations below
+#area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['depth', 'speed']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            name2 = join(directory, time_dir, project.scenario_name)+'_time_39900_0'
+            name3 = join(directory, time_dir, project.scenario_name)+'_time_79800_0'
+
+            names = [name1, name2, name3]
+      
+            asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+                asc_name.append(outname + '.asc')
+    
+            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+
+            print 'max asc outname ', maxasc_outname
+            print 'asc_name ', str(asc_name)
+            
+            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/perth/file_length.py
===================================================================
--- /anuga_work/production/wa/perth/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/perth/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/perth/get_runup.py
===================================================================
--- /anuga_work/production/wa/perth/get_runup.py	(revision 7411)
+++ /anuga_work/production/wa/perth/get_runup.py	(revision 7411)
@@ -0,0 +1,69 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from os.path import join
+from anuga.utilities.polygon import read_polygon
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+        
+# Application specific imports
+from setup_model import project  # Definition of file names and polygons
+import csv
+directory = project.output_folder
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir4, time_dir5, time_dir6] #[time_dir1, time_dir2, time_dir3] #, 
+
+interior_region = []
+for region in project.interior_regions_data[:5]:
+    polygon = read_polygon(join(project.polygons_folder,
+                                region[0]))
+    interior_region.append(polygon)
+
+area_dictionary = {'Fremantle' : interior_region[0],
+                  'Rockingham' : interior_region[1],
+                     'Geordie' : interior_region[3],
+                    'Sorrento' : interior_region[4]}
+
+area = ['Fremantle', 'Rockingham', 'Geordie', 'Sorrento'] 
+
+for time_dir in time_dirs:
+
+    basename = join(directory, time_dir, project.scenario_name)
+
+    out_file = basename+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+    print 'basename ',basename 
+
+    for which_area in area:
+        if which_area not in area_dictionary:
+            print 'Unrecognized variable name: %s' % which_area
+            break
+
+        polygon = area_dictionary[which_area]
+        
+        print 'Which area ',which_area
+
+        q, loc = get_maximum_inundation_data(basename+'.sww',
+                                             polygon=polygon, verbose=True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/perth/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/perth/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/perth/get_timeseries.py	(revision 7411)
@@ -0,0 +1,34 @@
+"""
+Generate time series of nominated "gauges".
+Input: sww file from run_perth.py
+       gauges project.gauge_filename
+Output: csv files stage,speed,depth,elevation over time
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+Can run different sww files at the same time
+make sure if there is a second sww file that it is placed into a folder called sww2
+Can run different gauges at the same time - ie testing boundary index point
+"""
+
+from os import sep, rename, listdir, system
+from os.path import join
+from anuga.abstract_2d_finite_volumes.util import sww2csv_gauges,csv2timeseries_graphs
+import project
+
+directory = project.output_folder
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+
+time_dirs = [time_dir1] #1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6]
+
+print 'time directories', time_dirs
+
+for time_dir in time_dirs:
+    name = join(directory,time_dir,project.scenario_name)
+    gauge = project.gauges
+    sww2csv_gauges(name+'.sww',gauge,
+                   quantities = ['stage','speed','depth','elevation'],
+                   verbose=True)
+  
+
Index: /anuga_work/production/wa/perth/perth_rerun/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,87 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\perth_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir1] #4, time_dir5, time_dir6] #time_dir1, time_dir2, time_dir3, 
+ 
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    raster_gbd = folder + 'raster.gdb'
+    contour = raster_gbd + '\\contour_dep'
+    land = scenario_dir + "map_work\\Perth.gdb\\Outlines\\poly_all_cut"
+    ocean = scenario_dir + "map_work\\Perth.gdb\\Outlines\\initial_conditions_ocean1"
+    
+##    print 'Process: Create File GDB'
+##    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    #print gp.Workspace
+    
+    #replication dictionary
+    replicate = (('perth', ''),('time_39900_0', 'b'), ('time_79800_0', 'c'),
+                 ('_', ''),('Geordie', 'Geo'),('Sorrento', 'Sor'), ('max','M_'),
+                 ('Fremantle', 'Fre'),('Rockingham', 'Roc'),('depth','_dep_'),
+                 ('speed', '_spe_'), ('elevation', '_ele_'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*elevation.asc')
+    print time_dir
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection' 
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+
+    
+##        output_extract = output_DEM + 'E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+       
Index: /anuga_work/production/wa/perth/perth_rerun/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/Arc_txt2feature_class_res.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/Arc_txt2feature_class_res.py	(revision 7411)
@@ -0,0 +1,64 @@
+# ---------------------------------------------------------------------------
+# txt2fc_res.py
+# Created on: Mon Dec 01 2008 11:36:17 AM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+from os.path import join
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\perth_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir3, time_dir4, time_dir5, time_dir6] 
+
+def replace_in_file(filename, instr, repstr):
+    '''Replace one string with another in a file.'''
+    
+    # get the file contents
+    fd = open(filename, 'r')
+    lines = fd.readlines()
+    fd.close()
+
+    # convert list to one string
+    newlines = ''.join(lines)
+    
+    # replace 'instr' with 'repstr'
+    newlines = newlines.replace(instr, repstr)
+    
+    # write changed lines back to file
+    fd = open(filename, 'w')
+    fd.write(newlines)
+    fd.close()
+
+for time_dir in time_dirs:
+    print 'time_dir = ', time_dir
+    
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'perth_res.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+
+    print 'replace _$ with nothing'
+    replace_in_file(input_dir_name, '_$', '')
+    
+##    print 'Process: Feature Class to Feature Class'
+##    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "perth_res", "", "OBJECTID OBJECTID true true false 4 Long 0 10 ,First,#,perth_res.csv_Features,OBJECTID,-1,-1;LONGITUDE LONGITUDE true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,LONGITUDE,-1,-1;LATITUDE LATITUDE true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,LATITUDE,-1,-1;STRUCT_INUNDATED STRUCT_INUNDATED true true false 4 Long 0 10 ,First,#,perth_res.csv_Features,STRUCT_INUNDATED,-1,-1;STRUCT_DAMAGE_fraction STRUCT_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,STRUCT_DAMAGE_fraction,-1,-1;COLLAPSE_CSV_INFO COLLAPSE_CSV_INFO true true false 255 Text 0 0 ,First,#,perth_res.csv_Features,COLLAPSE_CSV_INFO,-1,-1;MAX_DEPTH_m MAX_DEPTH_m true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,MAX_DEPTH_m,-1,-1;STRUCT_COLLAPSED STRUCT_COLLAPSED true true false 255 Text 0 0 ,First,#,perth_res.csv_Features,STRUCT_COLLAPSED,-1,-1;STRUCT_LOSS STRUCT_LOSS true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,STRUCT_LOSS,-1,-1;CONTENTS_DAMAGE_fraction CONTENTS_DAMAGE_fraction true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,CONTENTS_DAMAGE_fraction,-1,-1;CONTENTS_LOSS CONTENTS_LOSS true true false 8 Double 0 0 ,First,#,perth_res.csv_Features,CONTENTS_LOSS,-1,-1", "")
+##
Index: /anuga_work/production/wa/perth/perth_rerun/Arc_txt2feature_class_runup.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/Arc_txt2feature_class_runup.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/Arc_txt2feature_class_runup.py	(revision 7411)
@@ -0,0 +1,49 @@
+# ---------------------------------------------------------------------------
+# txt2fc_field.py
+# Created on: Thu Nov 27 2008 01:48:26 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir="\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\perth_tsunami_scenario\\"
+output_dir = "anuga\\outputs\\"
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir4, time_dir5, time_dir6] #time_dir1, time_dir2, time_dir3] #, 
+
+for time_dir in time_dirs:
+
+    # Local variables...
+    folder =  scenario_dir + output_dir + time_dir + '\\'
+    input_dir_name = folder+'perth_runup.csv'
+    raster_gdb = folder + "raster.gdb"
+    layer = 'layer'
+  
+    print 'Process: Make XY Event Layer'
+    gp.MakeXYEventLayer_management(input_dir_name, "x", "y", layer, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM"
+                                   "['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT"
+                                   "['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting'"
+                                   ",500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER"
+                                   "['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]];IsHighPrecision")
+
+    print 'Process: Feature Class to Feature Class'
+    gp.FeatureClassToFeatureClass_conversion(layer, raster_gdb, "perth_runup", "", "area area true true false 255 Text 0 0 ,First,#,perth_runup.csv_Features,area,-1,-1;q q true true false 8 Double 0 0 ,First,#,perth_runup.csv_Features,q,-1,-1;x x true true false 8 Double 0 0 ,First,#,perth_runup.csv_Features,x,-1,-1;y y true true false 8 Double 0 0 ,First,#,perth_runup.csv_Features,y,-1,-1", "")
+
+
+  
Index: /anuga_work/production/wa/perth/perth_rerun/Inundation_polygon.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/Inundation_polygon.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/Inundation_polygon.py	(revision 7411)
@@ -0,0 +1,103 @@
+# ---------------------------------------------------------------------------
+# Inundation_line.py
+# Created on: Tue May 12 2009 01:50:45 PM
+#   (generated by ArcGIS/ModelBuilder)
+# Usage: Inundation_line <Bun_depth_M_E> <Bus_depth_M_E> <bunbury_1km> <busselton_1km> 
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+gp.overwriteoutput = 1
+
+# Set the necessary product code
+gp.SetProduct("ArcInfo")
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Analysis Tools.tbx")
+
+# Script arguments...
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir1, time_dir2, time_dir3, time_dir4, time_dir5, time_dir6] 
+
+community = 'perth'
+scenario = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\" + community +"_tsunami_scenario\\"
+output_folder = scenario + "anuga\\outputs\\"
+locations = ['bunbury', 'busselton']
+
+locations = ['Fremantle', 'Rockingham', 'Geordie', 'Sorrento']
+
+for time_dir in time_dirs:
+
+    raster = output_folder + time_dir + "\\raster.gdb\\"
+    
+    for location in locations:
+
+        # Local variables...
+        if location == 'Fremantle':
+            # polygon clip
+            extent = scenario + "map_work\\Perth.gdb\\Internal_Polygons\\CBD_coastal_clip"
+            # name of rasters
+            depth = 'Fre_dep_M_E'
+           
+        elif location == 'Rockingham':
+            # polygon clip
+            extent = scenario + "map_work\\Perth.gdb\\Internal_Polygons\\rockingham_penguin_clip"
+            # name of rasters
+            depth = 'Roc_dep_M_E'
+            
+        elif location == 'Geordie':
+            # polygon clip
+            extent = scenario + "map_work\\Perth.gdb\\Internal_Polygons\\Geordie_Bay_clip"
+            # name of rasters
+            depth = 'Geo_dep_M_E'
+           
+        elif location == 'Sorrento':
+            # polygon clip
+            extent = scenario + "map_work\\Perth.gdb\\Internal_Polygons\\Sorrento_gauge_clip"
+            # name of rasters
+            depth = 'Sor_dep_M_E'
+            
+        else:
+            print 'No recognisable location entered'
+
+        print 'location', location
+        print 'extent', extent
+
+        depth_raster = depth
+
+        # Local variables...
+        Output_raster = raster +"Temp_raster_"+ location
+        Output_polygon_features = raster +"Temp_polygon_"+ location
+        Output_Feature_Class = raster +"Temp_line_"+ location
+        Reclassification = "0 0.05 NODATA;0.05 4.5840001106262207 1"
+        Inundation = raster + "Inundation_" + location + "_polygon"
+        Inundation_line = raster + "Inundation_line"
+        depth_loc = raster + depth
+        
+        print 'Process: Reclassify'
+        gp.Reclassify_sa(depth_loc, "Value", Reclassification, Output_raster, "DATA")
+        
+        print 'Process: Raster to Polygon'
+        gp.RasterToPolygon_conversion(Output_raster, Output_polygon_features, "SIMPLIFY", "VALUE")
+
+        print 'Process: Clip'
+        gp.Clip_analysis(Output_polygon_features, extent, Inundation, "")
+
+        print 'Process: Delete'
+        gp.Delete_management(Output_raster, "RasterDataset")
+        gp.Delete_management(Output_polygon_features, "FeatureClass")
Index: /anuga_work/production/wa/perth/perth_rerun/Perth4distribution.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/Perth4distribution.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/Perth4distribution.py	(revision 7411)
@@ -0,0 +1,152 @@
+# ---------------------------------------------------------------------------
+# Carnarvon4distribution.py
+# Created on: Thu Apr 30 2009 03:51:03 PM
+#   (generated by ArcGIS/ModelBuilder)
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+community = 'Perth'
+output_loc = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\FESA_outputs_Dec_08\\ARCgrids\\April_2009\\"
+input_scenario = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\perth_tsunami_scenario\\"
+input_output = input_scenario + "\\anuga\\outputs\\"
+
+locations = ['Fremantle', 'Rockingham', 'Geordie', 'Sorrento']
+
+in_Tsunami_1_HAT = input_output + "20090324_155028_run_final_0.6_27283_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_1_MSL = input_output + "20090327_155353_run_final_0_27283_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_2_HAT = input_output + "20090324_135427_run_final_0.6_27255_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_2_MSL = input_output + "20090327_155659_run_final_0_27255_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_3_HAT = input_output + "20090324_154957_run_final_0.6_68693_Bt_kvanputt\\raster.gdb\\"
+in_Tsunami_3_MSL = input_output + "20090327_155803_run_final_0_68693_Bt_kvanputt\\raster.gdb\\"
+
+Tsunami_1_HAT = output_loc + "Tsunami1-Exmouth\\" + community + "_HAT.gdb\\"
+Tsunami_1_MSL = output_loc + "Tsunami1-Exmouth\\" + community + "_MSL.gdb\\"
+Tsunami_2_HAT = output_loc + "Tsunami2-Perth\\" + community + "_HAT.gdb\\"
+Tsunami_2_MSL = output_loc + "Tsunami2-Perth\\" + community + "_MSL.gdb\\"
+Tsunami_3_HAT = output_loc + "Tsunami3-1833\\" + community + "_HAT.gdb\\"
+Tsunami_3_MSL = output_loc + "Tsunami3-1833\\" + community + "_MSL.gdb\\"
+
+hr = community + '_runup'
+
+for location in locations:
+
+    # Local variables...
+    if location == 'Fremantle':
+        # polygon clip
+        extent = input_scenario + "map_work\\Perth.gdb\\Internal_Polygons\\CBD_coastal"
+        # name of rasters
+        depth = 'Fre_dep_M_E'
+        speed = 'Fre_spe_M_'
+    elif location == 'Rockingham':
+        # polygon clip
+        extent = input_scenario + "map_work\\Perth.gdb\\Internal_Polygons\\rockingham_penguin"
+        # name of rasters
+        depth = 'Roc_dep_M_E'
+        speed = 'Roc_spe_M_'
+    elif location == 'Geordie':
+        # polygon clip
+        extent = input_scenario + "map_work\\Perth.gdb\\Internal_Polygons\\Geordie_Bay"
+        # name of rasters
+        depth = 'Geo_dep_M_E'
+        speed = 'Geo_spe_M_'
+    elif location == 'Sorrento':
+        # polygon clip
+        extent = input_scenario + "map_work\\Perth.gdb\\Internal_Polygons\\Sorrento_gauge"
+        # name of rasters
+        depth = 'Sor_dep_M_E'
+        speed = 'Sor_spe_M_'
+    else:
+        print 'No recognisable location entered'
+
+    print 'location', location
+    print 'extent', extent
+
+    # Output locations
+    
+    hr_1_HAT = Tsunami_1_HAT +"highest_runup"
+    hr_1_MSL = Tsunami_1_MSL +"highest_runup"
+    hr_2_HAT = Tsunami_2_HAT +"highest_runup"
+    hr_2_MSL = Tsunami_2_MSL +"highest_runup"
+    hr_3_HAT = Tsunami_3_HAT +"highest_runup"
+    hr_3_MSL = Tsunami_3_MSL +"highest_runup"
+
+    depth_1_HAT = Tsunami_1_HAT + location + "_depth"
+    depth_1_MSL = Tsunami_1_MSL + location + "_depth"
+    depth_2_HAT = Tsunami_2_HAT + location + "_depth"
+    depth_2_MSL = Tsunami_2_MSL + location + "_depth"
+    depth_3_HAT = Tsunami_3_HAT + location + "_depth"
+    depth_3_MSL = Tsunami_3_MSL + location + "_depth"
+
+    speed_1_HAT = Tsunami_1_HAT + location + "_speed"
+    speed_1_MSL = Tsunami_1_MSL + location + "_speed"
+    speed_2_HAT = Tsunami_2_HAT + location + "_speed"
+    speed_2_MSL = Tsunami_2_MSL + location + "_speed"
+    speed_3_HAT = Tsunami_3_HAT + location + "_speed"
+    speed_3_MSL = Tsunami_3_MSL + location + "_speed"
+
+
+    # Input locations
+
+    in_depth_1_HAT = in_Tsunami_1_HAT + depth
+    in_depth_1_MSL = in_Tsunami_1_MSL + depth
+    in_depth_2_HAT = in_Tsunami_2_HAT + depth
+    in_depth_2_MSL = in_Tsunami_2_MSL + depth
+    in_depth_3_HAT = in_Tsunami_3_HAT + depth
+    in_depth_3_MSL = in_Tsunami_3_MSL + depth
+
+    in_speed_1_HAT = in_Tsunami_1_HAT + speed
+    in_speed_1_MSL = in_Tsunami_1_MSL + speed
+    in_speed_2_HAT = in_Tsunami_2_HAT + speed
+    in_speed_2_MSL = in_Tsunami_2_MSL + speed
+    in_speed_3_HAT = in_Tsunami_3_HAT + speed
+    in_speed_3_MSL = in_Tsunami_3_MSL + speed
+
+    in_hr_1_HAT = in_Tsunami_1_HAT + hr
+    in_hr_1_MSL = in_Tsunami_1_MSL + hr
+    in_hr_2_HAT = in_Tsunami_2_HAT + hr
+    in_hr_2_MSL = in_Tsunami_2_MSL + hr
+    in_hr_3_HAT = in_Tsunami_3_HAT + hr
+    in_hr_3_MSL = in_Tsunami_3_MSL + hr
+
+
+# Process: Extract by Mask
+    print 'Extract by mask for depth'
+    gp.ExtractByMask_sa(in_depth_1_HAT, extent, depth_1_HAT)
+    gp.ExtractByMask_sa(in_depth_1_MSL, extent, depth_1_MSL)
+    gp.ExtractByMask_sa(in_depth_2_HAT, extent, depth_2_HAT)
+    gp.ExtractByMask_sa(in_depth_2_MSL, extent, depth_2_MSL)
+    gp.ExtractByMask_sa(in_depth_3_HAT, extent, depth_3_HAT)
+    gp.ExtractByMask_sa(in_depth_3_MSL, extent, depth_3_MSL)
+
+    print 'Extract by mask for speed'
+    gp.ExtractByMask_sa(in_speed_1_HAT, extent, speed_1_HAT)
+    gp.ExtractByMask_sa(in_speed_1_MSL, extent, speed_1_MSL)
+    gp.ExtractByMask_sa(in_speed_2_HAT, extent, speed_2_HAT)
+    gp.ExtractByMask_sa(in_speed_2_MSL, extent, speed_2_MSL)
+    gp.ExtractByMask_sa(in_speed_3_HAT, extent, speed_3_HAT)
+    gp.ExtractByMask_sa(in_speed_3_MSL, extent, speed_3_MSL)
+
+
+# Process: Copy Features...
+
+print 'Copy Highest Runup'
+gp.CopyFeatures_management(in_hr_1_HAT, hr_1_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_1_MSL, hr_1_MSL, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_2_HAT, hr_2_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_2_MSL, hr_2_MSL, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_3_HAT, hr_3_HAT, "", "0", "0", "0")
+gp.CopyFeatures_management(in_hr_3_MSL, hr_3_MSL, "", "0", "0", "0")
+
Index: /anuga_work/production/wa/perth/perth_rerun/build_elevation.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/build_elevation.py	(revision 7411)
@@ -0,0 +1,90 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' 
+G = None
+for key in geospatial_data:
+    G += geospatial_data[key]
+        
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/perth/perth_rerun/export_results_max.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/export_results_max.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/export_results_max.py	(revision 7411)
@@ -0,0 +1,121 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir1] #4, time_dir5, time_dir6] #, time_dir4, time_dir5, time_dir6]
+  
+
+#cellsize = 250
+cellsize = 20
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+area = ['Fremantle', 'Rockingham','Geordie', 'Sorrento']  # strings must match keys in var_equations below
+#area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            name2 = join(directory, time_dir, project.scenario_name)+'_time_39900_0'
+            name3 = join(directory, time_dir, project.scenario_name)+'_time_79800_0'
+
+            names = [name1] #, name2, name3]
+      
+            #asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/perth/perth_rerun/get_runup.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/get_runup.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/get_runup.py	(revision 7411)
@@ -0,0 +1,69 @@
+# Standard modules
+from os import sep
+import os
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from os.path import join
+from anuga.utilities.polygon import read_polygon
+from shutil import copy
+import time
+import sys
+# Related major packages
+from anuga.shallow_water.data_manager import get_maximum_inundation_data
+        
+# Application specific imports
+from setup_model import project  # Definition of file names and polygons
+import csv
+directory = project.output_folder
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir4, time_dir5, time_dir6] #[time_dir1, time_dir2, time_dir3] #, 
+
+interior_region = []
+for region in project.interior_regions_data[:5]:
+    polygon = read_polygon(join(project.polygons_folder,
+                                region[0]))
+    interior_region.append(polygon)
+
+area_dictionary = {'Fremantle' : interior_region[0],
+                  'Rockingham' : interior_region[1],
+                     'Geordie' : interior_region[3],
+                    'Sorrento' : interior_region[4]}
+
+area = ['Fremantle', 'Rockingham', 'Geordie', 'Sorrento'] 
+
+for time_dir in time_dirs:
+
+    basename = join(directory, time_dir, project.scenario_name)
+
+    out_file = basename+'_runup.csv'
+    output_file = open(out_file, 'w')
+    s = 'area,q,x,y\n' 
+    output_file.write(s)
+    print 'basename ',basename 
+
+    for which_area in area:
+        if which_area not in area_dictionary:
+            print 'Unrecognized variable name: %s' % which_area
+            break
+
+        polygon = area_dictionary[which_area]
+        
+        print 'Which area ',which_area
+
+        q, loc = get_maximum_inundation_data(basename+'.sww',
+                                             polygon=polygon, verbose=True)
+
+        print '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+        s = '%s, %.6f, %.6f, %.6f\n' %(str(which_area), q, loc[0],loc[1])
+
+        output_file.write(s)
+
+        print 'output file printed to: %s' %out_file
+    output_file.close()
Index: /anuga_work/production/wa/perth/perth_rerun/project.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/project.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/project.py	(revision 7411)
@@ -0,0 +1,283 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'perth'
+scenario_folder = 'perth_tsunami_scenario'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0                # difference between MSL and HAT in metres
+zone = 50               # specify zone of model
+event_number = 68693    # the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=80000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number, 'Bt']
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['perth_dli_ext',   # Topo
+                        'rott_dli_ext',
+                        'gard_dli_ext',
+                        'carnac_island_dli_ext',
+                        'penguin_dli_ext'] 
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['coastline_perthP.txt',    # Coastline
+                   'Perth.txt',         # Original
+                   'Perth_Chart.txt',   # Bathymetry Charts
+                   'Fremantle_north.txt',       # DPI data
+                   'port_swanriver.txt',]           
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'poly_all.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['CBD_coastal.csv', 500],
+                         ['rockingham_penguin.csv', 500],
+                         ['garden.csv', 500],
+                         ['geordie_bay.csv', 500],
+                         ['sorrento_gauge.csv', 500],
+                         ['garden_rockingham.csv', 1000],
+                         ['rottnest_external.csv', 1000],
+                         ['DredgeArea.csv', 1000],
+                         ['internal_h20mORd3km.csv', 25000],
+                         ['rottnest_internal.csv', 100000]]
+
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing (no header)
+land_initial_conditions_filename = [['initial_conditions_N.csv', 0],
+                                    ['initial_conditions_S.csv', 0],
+                                    ['initial_conditions_rottnest.csv',0],
+                                    ['initial_conditions_garden.csv',0]]
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = 'MH_gauges2.csv'
+
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = 'perth_res_combined.csv' # from NEXIS
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'thinned_boundary_ordering.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_bounding_polygon.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+##mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+##multi_mux = False
+mux_input_filename = 'event.list'
+multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+#Geordie Bay extract ascii grid
+xminGeordie = 358000
+xmaxGeordie = 362000
+yminGeordie = 6458500
+ymaxGeordie = 6461000
+
+#Sorrento extract ascii grid
+xminSorrento = 379000
+xmaxSorrento = 382500
+yminSorrento = 6477000
+ymaxSorrento = 6480000
+
+#Fremantle extract ascii grid
+xminFremantle = 376000
+xmaxFremantle = 388000
+yminFremantle = 6449000
+ymaxFremantle = 6461000
+
+#Rockingham extract ascii grid
+xminRockingham = 373500
+xmaxRockingham = 385500
+yminRockingham = 6424000
+ymaxRockingham = 6433000
+
+#Fremantle and Perth extract ascii grid
+xminPerth = 376000
+xmaxPerth = 396000
+yminPerth = 6449000
+ymaxPerth = 6467000
+
+#Rottnest
+xminRottnest = 352700
+xmaxRottnest = 364800
+yminRottnest = 6455000
+ymaxRottnest = 6460500
+
+
+
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
Index: /anuga_work/production/wa/perth/perth_rerun/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,72 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from os.path import join
+from setup_model import project
+import csv
+
+directory = project.output_folder + sep
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir6] #, time_dir5, time_dir6] #time_dir1, time_dir2, time_dir3] #, 
+  
+buildings = project.building_exposure
+
+for time_dir in time_dirs:
+    
+    time_dir_name = time_dir[-20:][:-12]
+    print time_dir_name
+       
+    building_marker = '_m_'+ time_dir_name
+    basename = join(directory, time_dir, project.scenario_name) #basename for the sww files 
+    
+    inundation_damage(basename, buildings, building_marker)
+    #add_depth_and_momentum2csv(name, buildings, building_marker)
+    
+    building_marker_dir_name = join(project.gauges_folder,
+                                    project.building_exposure_filename[:-4]) + building_marker + '.csv'
+    out_file = basename + '_res.csv'
+    print 'out file %s' %out_file
+    print 'building_marker_dir_name %s' %building_marker_dir_name
+    csv_fd = open(building_marker_dir_name, 'r')
+    output_file = open(out_file, 'w')
+
+    reader = csv.reader(csv_fd)
+    writer = csv.writer(output_file, lineterminator='\n')
+
+    for record in reader:
+       newline = record[-8:]
+       newline.insert(0,record[0])
+       newline.insert(1,record[1])
+       newline.insert(2,record[2])
+       writer.writerow(newline)
+       
+    print 'output file printed to: %s' %out_file
+    csv_fd.close()
+    output_file.close()
+
+    
Index: /anuga_work/production/wa/perth/perth_rerun/run_model.py
===================================================================
--- /anuga_work/production/wa/perth/perth_rerun/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/perth/perth_rerun/run_model.py	(revision 7411)
@@ -0,0 +1,163 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/perth/project.py
===================================================================
--- /anuga_work/production/wa/perth/project.py	(revision 7411)
+++ /anuga_work/production/wa/perth/project.py	(revision 7411)
@@ -0,0 +1,247 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'onslow'
+scenario_folder = 'onslow_tsunami_scenario_2008'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0                # difference between MSL and HAT in metres
+zone = 50               # specify zone of model
+#event_number = 68693    # the event number or the mux file name
+event_number = 'wa04_val'   # the event number or the mux file name
+
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=80000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number, 'Bt']
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+# Format for ascii grids, as produced in ArcGIS + a projection file
+ascii_grid_filenames = ['revised_onshore_20m_dli',
+                        'onslow_islands_dted2']
+
+# Format for point is x,y,elevation (with header)
+point_filenames = ['onslow_offshore_points.txt',
+                   'revised_coastline.txt',
+                   'beach_survey.txt',
+                   'ONS16FINAL.txt',
+                   'ONS17FINAL.txt',
+                   'ONS18FINAL.txt' ]
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'bounding_polygon.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['aoi.csv', 500],
+                         ['aos1.csv', 800],
+                         ['sw.csv', 1500]]
+
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing (no header)
+land_initial_conditions_filename = [['initial_condition_mainland.csv', 0]]
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = ''
+
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = '' # from NEXIS
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'urs_order.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_boundary.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+multi_mux = False
+##mux_input_filename = 'event.list'
+##multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# region to export (used from export_results.py)
+e_min_area = 300000   # Eastings min
+e_max_area = 310000
+n_min_area = 7600000
+n_max_area = 7610000
+
+
+
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_2009_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
Index: /anuga_work/production/wa/perth/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/perth/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/perth/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,72 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from os.path import join
+from setup_model import project
+import csv
+
+directory = project.output_folder + sep
+
+time_dir1 = '20090324_135427_run_final_0.6_27255_Bt_kvanputt'
+time_dir2 = '20090324_154957_run_final_0.6_68693_Bt_kvanputt'
+time_dir3 = '20090324_155028_run_final_0.6_27283_Bt_kvanputt'
+time_dir4 = '20090327_155353_run_final_0_27283_Bt_kvanputt'
+time_dir5 = '20090327_155659_run_final_0_27255_Bt_kvanputt'
+time_dir6 = '20090327_155803_run_final_0_68693_Bt_kvanputt'
+
+time_dirs = [time_dir6] #, time_dir5, time_dir6] #time_dir1, time_dir2, time_dir3] #, 
+  
+buildings = project.building_exposure
+
+for time_dir in time_dirs:
+    
+    time_dir_name = time_dir[-20:][:-12]
+    print time_dir_name
+       
+    building_marker = '_m_'+ time_dir_name
+    basename = join(directory, time_dir, project.scenario_name) #basename for the sww files 
+    
+    inundation_damage(basename, buildings, building_marker)
+    #add_depth_and_momentum2csv(name, buildings, building_marker)
+    
+    building_marker_dir_name = join(project.gauges_folder,
+                                    project.building_exposure_filename[:-4]) + building_marker + '.csv'
+    out_file = basename + '_res.csv'
+    print 'out file %s' %out_file
+    print 'building_marker_dir_name %s' %building_marker_dir_name
+    csv_fd = open(building_marker_dir_name, 'r')
+    output_file = open(out_file, 'w')
+
+    reader = csv.reader(csv_fd)
+    writer = csv.writer(output_file, lineterminator='\n')
+
+    for record in reader:
+       newline = record[-8:]
+       newline.insert(0,record[0])
+       newline.insert(1,record[1])
+       newline.insert(2,record[2])
+       writer.writerow(newline)
+       
+    print 'output file printed to: %s' %out_file
+    csv_fd.close()
+    output_file.close()
+
+    
Index: /anuga_work/production/wa/perth/run_model.py
===================================================================
--- /anuga_work/production/wa/perth/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/perth/run_model.py	(revision 7411)
@@ -0,0 +1,163 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/perth/setup_model.py
===================================================================
--- /anuga_work/production/wa/perth/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/perth/setup_model.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+for filename, MSL in project.land_initial_conditions_filename:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.land_initial_conditions.append([polygon, MSL])
+
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/pt_hedland_2006/build_pt_hedland.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/build_pt_hedland.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/build_pt_hedland.py	(revision 7411)
@@ -0,0 +1,128 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project_urs.output_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts,urs_ungridded2sww
+from anuga.geospatial_data.geospatial_data import *
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files
+from anuga_parallel.parallel_abstraction import get_processor_name
+
+# Application specific imports
+import project_urs   # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project_urs.output_build_time_dir,__file__, 
+               dirname(project_urs.__file__)+sep+ project_urs.__name__+'.py' )
+
+start_screen_catcher(project_urs.output_build_time_dir)
+
+print "Processor Name:",get_processor_name()
+print 'USER: ', project_urs.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+print"project_urs.combined_dir_name",project_urs.combined_dir_name
+
+# topography directory filenames
+onshore_in_dir_name = project_urs.onshore_in_dir_name
+coast_in_dir_name = project_urs.coast_in_dir_name
+offshore_in_dir_name = project_urs.offshore_in_dir_name
+offshore1_in_dir_name = project_urs.offshore1_in_dir_name
+offshore2_in_dir_name = project_urs.offshore2_in_dir_name
+
+onshore_dir_name = project_urs.onshore_dir_name
+coast_dir_name = project_urs.coast_dir_name
+offshore_dir_name = project_urs.offshore_dir_name
+offshore1_dir_name = project_urs.offshore1_dir_name
+offshore2_dir_name = project_urs.offshore2_dir_name
+'''
+## creates DEM from asc data
+#print "creates DEMs from asc data"
+#convert_dem_from_ascii2netcdf(onshore_in_dir_name,
+#                              basename_out=onshore_dir_name,
+#                              use_cache=True, verbose=True)
+##creates pts file for onshore DEM
+#print "creates pts file for onshore DEM"
+#dem2pts(onshore_dir_name, use_cache=True, verbose=True)
+
+print'create Geospatial onshore objects from topographies'
+G = Geospatial_data(file_name = onshore_dir_name + '.pts') +\
+    Geospatial_data(file_name = coast_in_dir_name + '.txt') +\
+    Geospatial_data(file_name = offshore_in_dir_name + '.txt') 
+     
+
+print'clip combined geospatial object by bounding polygon'
+G_clipped = G.clip(project_urs.poly_all)
+
+print'export combined DEM file'
+if access(project_urs.topographies_dir,F_OK) == 0:
+    mkdir (project_urs.topographies_dir)
+G.export_points_file(project_urs.combined_dir_name + '.txt')
+
+print'split combined data set'
+G_small, G_other = G_clipped.split(0.1, True)
+
+print'export split DEM file'
+G_small.export_points_file(project_urs.combined_dir_name + '_small' + '.txt')
+#G_other.export_points_file(project_urs.combined_dir_name + '_other' + '.pts')
+
+'''
+print 'start reading:',project_urs.combined_dir_name + '.txt'
+G = Geospatial_data(file_name = (project_urs.combined_dir_name + '.txt'))
+print 'start writing',project_urs.combined_dir_name + '.pts'
+G.export_points_file(project_urs.combined_dir_name + '.pts')
+'''
+G_clipped = G.clip(project_urs.poly_topo_clip)
+
+print 'start split'
+#G_smallest, G_other = G.split(0.1,True)
+
+print 'start export',project_urs.combined_smallest_dir_name + '.txt'
+#G.export_points_file(project_urs.combined_smaller_dir_name + '.txt')
+G_clipped.export_points_file(project_urs.combined_smallest_dir_name + '.txt')
+
+#-------------------------------------------------------------------------
+# Convert URS to SWW file for boundary conditions 
+#-------------------------------------------------------------------------
+print 'starting to create boundary conditions'
+     
+print 'boundaries_in_dir_name',project_urs.boundaries_in_dir_name
+
+urs_ungridded2sww(project_urs.boundaries_in_dir_name, project_urs.boundaries_in_dir_name,
+                  verbose=True, mint=5000, maxt=35000, zscale=1)
+
+'''
+
+
+
Index: /anuga_work/production/wa/pt_hedland_2006/compare_timeseries.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/compare_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/compare_timeseries.py	(revision 7411)
@@ -0,0 +1,98 @@
+"""
+Generate latex output comparing time series of given sww files
+
+Inputs:
+
+output dirs: dictionary of output directories with a
+             association to simulation, eg 50m boundary, 100m boundary
+                    
+Outputs:
+
+* latex output to generate figures for report 
+* figures used for report stored in the report_figure directory
+NOTE, this directory will need to be committed, as well as
+the latex files.
+
+June 2006                    
+"""
+
+from os import sep
+import project
+from anuga.pyvolution.util import sww2timeseries, get_gauges_from_file
+
+# User defined inputs
+production_dirs = {'': '100m boundary',
+                   '': '50m boundary'}
+
+gauge_map = 'pt_hedland_boundary_gauges.png'
+
+plot_quantity = ['stage', 'speed']
+
+# Create sections and graphs for each designated production directory
+latex_output = []
+swwfiles = {}
+for label_id in production_dirs.keys():
+    
+    file_loc = project.outputdir + label_id + sep
+    swwfile = file_loc + project.basename + '.sww'
+    swwfiles[swwfile] = label_id
+
+texname, vec = sww2timeseries(swwfiles,
+                              project.gauges50,
+                              production_dirs,
+                              report = True,
+                              reportname = 'latexoutput_compare_pt_hedland',
+                              plot_quantity = plot_quantity,
+                              generate_fig = True,
+                              time_min = None,
+                              time_max = None,
+                              title_on = False,
+                              verbose = True)
+
+latex_output.append(texname)
+
+from shutil import copy, move
+copy ('report' + sep + texname + '.tex', project.comparereportdir + sep + texname + '.tex')
+
+
+# Start report generation
+input_name = project.comparereportdir + sep + 'comparison_pt_hedland.tex'
+fid = open(input_name, 'w')
+
+# Generate latex output for location points
+s = '\\begin{table} \label{table:locationspthedland} \n'
+fid.write(s)
+s = '\caption{Defined point locations for comparison study for Pt Hedland region.}' 
+fid.write(s)
+s = """
+\\begin{center}
+\\begin{tabular}{|l|l|l|l|}\hline
+\\bf{Point Name} & \\bf{Easting} & \\bf{Northing} & \\bf{Elevation (m)}\\\\ \hline
+"""
+fid.write(s)
+
+for i, thisvec in enumerate(vec):
+    name = thisvec[0]
+    east = thisvec[1]
+    north = thisvec[2]
+    elev = thisvec[3]
+    s = '%s & %.2f & %.2f & %.2f \\\\ \hline \n' %(name, east, north, elev)
+    fid.write(s)
+    for which_one in plot_quantity:
+        move ('report_figures' + sep + 'gauge'+name.replace(' ','')+which_one+'.png', project.comparereportfigdir)
+
+s = '\\end{tabular} \n  \end{center} \n \end{table} \n \n'
+fid.write(s)
+
+s = '\\begin{figure}[hbt] \n \centerline{ \includegraphics[width=150mm, height=100mm]{../report_figures/%s}}' %gauge_map
+fid.write(s)
+
+s  = """
+\caption{Point locations used for comparison between boundary at 50m and 100m contour for Onslow region.}  
+\label{fig:points}
+\end{figure}
+"""
+fid.write(s)
+    
+s = '\input{%s} \n \clearpage \n \n' %latex_output[0]
+fid.write(s)
Index: /anuga_work/production/wa/pt_hedland_2006/convert2latlon.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/convert2latlon.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/convert2latlon.py	(revision 7411)
@@ -0,0 +1,43 @@
+"""
+Convert Easting Northing to lon/lat for ultimately get kml file
+"""
+
+def alter_file(filename,filenameout):
+
+    from anuga.coordinate_transforms.lat_long_UTM_conversion import UTMtoLL
+    
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    
+    fid_out = open(filenameout, 'w')
+    s = '%s,%s,%s\n' %('lon','lat','stage')
+    fid_out.write(s)
+    for line in lines[1:]:
+       fields = line.split(',')
+       easting = float(fields[0])
+       northing = float(fields[1])
+       stage = float(fields[3])
+       lat, lon = UTMtoLL(northing,easting, 50)
+       s = '%f,%f,%f\n' %(lon,lat,stage)
+       fid_out.write(s)
+
+    fid_out.close() 
+
+    return
+
+import project
+from os import sep
+
+timedir='20070613_044204_run_final_3.6_exmouth_nbartzis'
+#timedir='20070613_061053_run_final_3.6_onslow_nbartzis'
+
+#filename = project.outputdir + timedir + sep + 'stage0_interp.csv'
+filename = project.outputdir + timedir + sep + 'stage5_interp.csv'
+#filename = project.outputdir+ timedir + sep + 'stage20_interp.csv'
+#filename = project.outputdir+  timedir + sep + 'stage50_interp.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage0_convert.csv'
+filename_out = project.outputdir + timedir + sep + 'stage5_convert.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage20_convert.csv'
+#filename_out = project.outputdir + timedir + sep + 'stage50_convert.csv'
+alter_file(filename,filename_out)
Index: /anuga_work/production/wa/pt_hedland_2006/export_results.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/export_results.py	(revision 7411)
@@ -0,0 +1,76 @@
+import project_urs, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+#time_dir = '20070518_020117_run_final_3.6_nbartzis' # HAT 1 in Dampier 10000 yr
+#time_dir = '20070520_225029_run_final_0.0_nbartzis' # MSL 1 in Dampier 10000 yr
+time_dir = '20070613_061053_run_final_3.6_onslow_nbartzis' # HAT 1 in Onslow 10000 yr
+#time_dir = '20070613_061125_run_final_0.0_onslow_nbartzis' # MSL 1 in Onslow 10000 yr
+#time_dir = '20070613_044204_run_final_3.6_exmouth_nbartzis' # HAT 1 in Exmouth 10000 yr
+#time_dir = '20070613_225854_run_final_0.0_exmouth_nbartzis' # MSL 1 in Exmouth 10000 yr
+
+cellsize = 25
+timestep = None
+directory = project_urs.output_dir
+
+name = directory+time_dir+sep+project_urs.scenario_name
+
+is_parallel = False
+if is_parallel == True: nodes = 4
+print 'output dir:', name
+
+var = [0,2,3,4] # depth and speed
+
+for which_var in var:
+    if which_var == 0:  # Stage
+        outname = name + '_stage'
+        quantityname = 'stage'
+
+    if which_var == 1:  # Absolute Momentum
+        outname = name + '_momentum_i1'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+    if which_var == 2:  # Depth
+        outname = name + '_depth_facility'
+        quantityname = 'stage-elevation'  
+
+    if which_var == 3:  # Speed
+        outname = name + '_speed_facility'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+    if which_var == 4:  # Elevation
+        outname = name + '_elevation'
+        quantityname = 'elevation'  #Elevation
+
+    if is_parallel == True:
+    #    print 'is_parallel',is_parallel
+        for i in range(0,nodes):
+            namei = name + '_P%d_%d' %(i,nodes)
+            outnamei = outname + '_P%d_%d' %(i,nodes)
+            print 'start sww2dem for sww file %d' %(i)
+            sww2dem(namei, basename_out = outnamei,
+                        quantity = quantityname,
+                        timestep = timestep,
+                        cellsize = cellsize,      
+                        easting_min = project_urs.e_min_area,
+                        easting_max = project_urs.e_max_area,
+                        northing_min = project_urs.n_min_area,
+                        northing_max = project_urs.n_max_area,        
+                        reduction = max, 
+                        verbose = True,
+                        format = 'asc')
+    else:
+        print 'start sww2dem'
+        sww2dem(name, basename_out = outname,
+                    quantity = quantityname,
+                    timestep = timestep,
+                    cellsize = cellsize,      
+                    easting_min = project_urs.e_min_area,
+                    easting_max = project_urs.e_max_area,
+                    northing_min = project_urs.n_min_area,
+                    northing_max = project_urs.n_max_area,        
+                    reduction = max, 
+                    verbose = True,
+                    format = 'asc')
Index: /anuga_work/production/wa/pt_hedland_2006/locate_indigeneous.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/locate_indigeneous.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/locate_indigeneous.py	(revision 7411)
@@ -0,0 +1,41 @@
+#
+# script to determine which communities are located in study region
+# 31 October 2006
+#
+
+def community_in_extent(filename,extent,zone,fid_out):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+
+    line1 = lines[0]
+    line11 = line1.split(',')
+    for i in range(len(line11)):
+        if line11[i].strip('\n').strip(' ') == 'LATITUDE': lat_index = i
+        if line11[i].strip('\n').strip(' ') == 'LONGITUDE': lon_index = i
+        if line11[i].strip('\n').strip(' ') == 'COMMUNITY': name_index = i
+
+    from anuga.coordinate_transforms.redfearn import convert_from_latlon_to_utm
+    from anuga.utilities.polygon import plot_polygons, is_inside_polygon
+    
+    for line in lines[1:]:
+        fields = line.split(',')
+        point, zone1 = convert_from_latlon_to_utm(latitudes=[fields[lat_index]],\
+                                                 longitudes=[fields[lon_index]])
+        if zone1 == zone:
+            v = is_inside_polygon(point,extent,verbose=False)
+            if v == True:
+                p = point[0]
+                s = '%s, %.2f, %.2f\n' %(fields[name_index], p[0], p[1])
+                fid_out.write(s)
+    return
+
+import project
+
+filename = project.community_filename
+filename_out = project.community_pt_hedland
+fid_out = open(filename_out, 'w')
+extent = project.polyAll
+zone = 50
+
+community_in_extent(filename,extent,zone,fid_out)
Index: /anuga_work/production/wa/pt_hedland_2006/make_report.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/make_report.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/make_report.py	(revision 7411)
@@ -0,0 +1,364 @@
+"""
+Generate report for production run
+
+Inputs:
+
+report_title:    title to be included in tex file
+production dirs: dictionary of production directories with a
+                 association to that simulation run, eg high tide,
+                 low tide and MSL.
+                    
+
+Outputs:
+
+* Report generated to scenario_report.tex where the scenario relates
+the name of the production directory this script is being run from.
+* figures used for report stored in the report_figure directory
+NOTE, this directory will need to be committed, as well as
+the latex files.
+
+The report structure is
+
+* Executive Summary
+* Introduction
+* Modelling Methodology
+* Tsunami scenario
+* Data sources
+* Inundation model
+* Inundation modelling results
+* Impact modelling
+* Summary
+* References
+* Appendix: Metadata
+* Appendix: Time series outputs
+
+Other files included in document which require manual intervention:
+
+* an abstract must be written in abstract.tex
+* an introduction must be written in introduction.tex; a basic outline and
+  some of the core inputs are already in place
+* the tsunami-genic event should be discussed in tsunami_scenario.tex
+* a discussion of the ANUGA model is required in anuga.tex
+* a computational_setup.tex file needs to be written for the particular scenario
+* the interpretation of the results needs to be written to interpretation.tex
+* maximum inundation map names need to be included in HAT_map and LAT_map etc.
+* damage modelling map names need to be included in HAT_damage and LAT_damage etc.
+* a summary must be written into summary.tex
+* metadata for the scenario data to be included in metadata.tex
+
+May, June 2006                    
+"""
+
+from os import getcwd, sep, altsep, mkdir, access, F_OK
+import project
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries, get_gauges_from_file
+
+# Derive scenario name
+p = getcwd().split(sep)
+scenario = p[-1] # Last element of absolute CWD path
+scenario_name = scenario.split('_2006')[0] # Strip any text past `_2006`
+test = scenario_name.split('_')
+if len(test) <> 1:
+    scenario_name = '%s %s' %(test[0], test[1])
+
+# Create report directory
+reportdir = getcwd()+sep+'report'+sep
+if access(reportdir,F_OK) == 0:
+    mkdir (reportdir)
+    
+# User defined inputs
+report_title = 'Tsunami impact modelling for the North West shelf: %s' %scenario_name.title()
+
+is_parallel = False
+if is_parallel == True:
+    nodes = 8
+    
+# WA DLI data
+production_dirs = {'20060707_001859': 'MSL',
+                   '20060707_003301': 'HAT',
+                   '20060707_003424': 'LAT'}
+
+all_prod_dirs = [production_dirs]
+
+max_maps = {'MSL': 'MSL_map',
+            'HAT': 'HAT_map',
+            'LAT': 'LAT_map'}
+
+gauge_map = 'pt_hedland_gauge.jpg'
+
+# Create sections and graphs for each designated production directory
+latex_output = []
+report_name = 'latexoutput'
+swwfiles = {}
+if is_parallel == True:
+
+    for j, production_dirs in enumerate(all_prod_dirs):
+        
+        for i in range(nodes):
+            print 'Sending node %d of %d' %(i,nodes)
+            swwfiles = {}
+            reportname = report_name + '%s' + 'rp%s' %(i,j)
+            
+            for label_id in production_dirs.keys():
+                file_loc = project.output_dir + label_id + sep
+                sww_extra = '_P%s_%s' %(i,nodes)
+                swwfile = file_loc + project.basename + sww_extra + '.sww'
+                #swwfile = file_loc + project.scenario_name + sww_extra + '.sww'
+                swwfiles[swwfile] = label_id
+
+                texname, elev_output = sww2timeseries(swwfiles,
+                                                      project.gauge_filename,
+                                                      production_dirs,
+                                                      report = True,
+                                                      reportname = reportname,
+                                                      plot_quantity = ['stage', 'speed'],
+                                                      generate_fig = True,
+                                                      surface = False,
+                                                      time_min = None,
+                                                      time_max = None,
+                                                      time_unit = 'hours',
+                                                      title_on = False,
+                                                      use_cache = True,
+                                                      verbose = True)
+                
+                latex_output.append(texname)
+    
+else:
+
+    for i, production_dirs in enumerate(all_prod_dirs):
+
+        swwfiles = {}
+        reportname = report_name + 'rp%s' %(i)
+        
+        for label_id in production_dirs.keys():
+
+            file_loc = project.outputdir + label_id + sep
+            swwfile = file_loc + project.basename + '.sww'
+            #swwfile = file_loc + project.scenario_name + sww_extra + '.sww'
+            swwfiles[swwfile] = label_id
+            
+        texname, elev_output = sww2timeseries(swwfiles,
+                                              project.gauge_filename,
+                                              production_dirs,
+                                              report = True,
+                                              reportname = reportname,
+                                              plot_quantity = ['stage', 'speed'],
+                                              generate_fig = True,
+                                              surface = False,
+                                              time_min = None,
+                                              time_max = None,
+                                              time_unit = 'hours',
+                                              title_on = False,
+                                              use_cache = True,
+                                              verbose = True)
+        
+        latex_output.append(texname)
+    
+# Start report generation
+# Future: generate_report(reportdir, scenario, report_title, 
+# project.gauge_filename, max_maps, damage_maps, production_dirs, latex_output)
+report_name = reportdir + scenario + '_report.tex'
+fid = open(report_name, 'w')
+
+s = """
+% This is based on an automatically generated file (by make_report.py).
+%
+% Manual parts are:
+% * an abstract must be written in abstract.tex
+% * an introduction must be written in introduction.tex; a basic outline and
+%   some of the core inputs are already in place
+% * outline of the modelling methodology provided in modelling_methodology.tex
+% * the tsunami-genic event should be discussed in tsunami_scenario.tex
+% * an computational_setup.tex file needs to be written for the particular scenario
+% * the interpretation of the results needs to be written to interpretation.tex
+% * maximum inundation maps need to be included in HAT_map.tex and LAT_map.tex etc.
+% * damage modelling maps need to be included in HAT_damage and LAT_damage etc.
+% * a summary must be written into summary.tex
+% * metadata for the scenario data to be included in metadata.tex
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\usepackage{pdfpages}
+\include{appendix}
+\setstretch{1.25}
+\\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\\textwidth \paperwidth
+\\advance\\textwidth -2in
+
+"""
+fid.write(s)
+
+s = """
+\date{\\today}
+%\\author{Geoscience Australia}
+
+\\begin{document}
+\\title{
+\\begin{figure}[hbt]
+  \centerline{ \includegraphics[scale=0.4]{../report_figures/GAlogo.jpg}}
+\end{figure}
+"""
+fid.write(s)
+s = '%s} '%report_title
+fid.write(s)
+s = """
+  \maketitle
+
+    \section{Executive Summary}
+    \label{sec:execsum}
+  \input{execsum}
+
+\clearpage
+
+  \\tableofcontents
+  
+  \section{Introduction}
+    \label{sec:intro}
+  \input{introduction}
+
+   \section{Modelling methodology}
+    \label{sec:methodology}
+    \input{modelling_methodology}
+    
+  \section{Tsunami scenarios}
+    \label{sec:tsunamiscenario}
+    \input{tsunami_scenario}
+
+  \section{Data sources}
+    \label{sec:data}
+    \input{data}
+        
+  \section{Inundation modelling results}
+     \label{sec:results}
+         
+"""
+fid.write(s)
+    
+s = '\input{interpretation} \n'
+fid.write(s)
+
+# Assign titles to each production section 
+# Must specify one name per section
+for i, max_maps in enumerate(all_maps):
+
+    s = '\subsection{Return Period: %s years} \n \n' %return_periods[i]      
+    fid.write(s)
+
+    production_dirs = all_prod_dirs[i]
+    for i, name in enumerate(production_dirs.keys()):
+
+        s = '\input{%s} \n \clearpage \n \n' %max_maps[production_dirs[name]]
+        fid.write(s)
+
+# Generate latex output for location points
+s = '\\begin{table} \\begin{center} \n'
+fid.write(s)
+s = '\caption{Defined point locations for %s study area.}' %scenario_name.title()
+fid.write(s)
+s = """
+\label{table:locations}
+\\begin{tabular}{|l|l|l|l|}\hline
+\\bf{Point Name} & \\bf{Easting} & \\bf{Northing} & \\bf{Elevation (m)}\\\\ \hline
+"""
+fid.write(s)
+
+gauges, locations, elevation = get_gauges_from_file(project.gauge_filename)
+
+for name, gauges, elev in zip(locations, gauges, elevation):
+    east = gauges[0]
+    north = gauges[1]
+    s = '%s & %.2f & %.2f & %.2f \\\\ \hline \n' %(name.replace('_',' '), east, north, elev)
+    fid.write(s)
+
+s = '\\end{tabular} \n  \end{center} \n \end{table} \n \n'
+fid.write(s)
+
+#s = '\\begin{figure}[h] \n \centerline{ \includegraphics[width=\paperwidth]{../report_figures/%s}}' %gauge_map
+s = '\\begin{figure}[h] \n \centerline{ \includegraphics[scale=0.7]{../report_figures/%s}}' %gauge_map
+fid.write(s)
+
+s  = """
+\caption{Point locations used for Port Hedland study.}  
+\label{fig:points}
+\end{figure}
+
+\clearpage
+"""
+fid.write(s)
+
+# Closing
+
+s = """
+   \section{Impact modelling}
+    \label{sec:impact}
+     \input{damage}
+"""
+fid.write(s)
+
+s = """
+  % \section{Impact due to data accuracy}
+  %   \input{discussion}
+  %   \label{sec:issues}
+
+     \section{Summary}
+     \label{sec:summary}
+     \input{summary}
+
+     \section{Acknowledgements}
+     \input{acknowledgements}
+     
+    \input{references}
+
+\clearpage
+
+    \\appendix
+
+    \section{ANUGA modelling parameters}
+    \label{sec:anugasetup}
+    \input{anuga_setup}
+
+\clearpage
+
+   \section{Metadata}
+     \label{sec:metadata}
+     \input{metadata}
+
+\clearpage
+
+   \section{Time series}
+     \label{sec:timeseries}
+     \input{timeseriesdiscussion}
+     \clearpage
+"""
+fid.write(s)
+
+for i in range(len(latex_output)):
+    if latex_output[i] <> '':
+        s = '\subsection{Return Period: %s years} \n' %return_periods[i]
+        fid.write(s)
+        s = '\input{%s} \n \clearpage \n \n' %latex_output[i]   
+        fid.write(s)
+
+s="""
+
+   \section{Damage modelling inputs}
+     \label{sec:damageinputs}
+     \input{damage_inputs}
+
+\end{document}
+"""
+fid.write(s)
Index: /anuga_work/production/wa/pt_hedland_2006/plot_contour_data.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/plot_contour_data.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/plot_contour_data.py	(revision 7411)
@@ -0,0 +1,65 @@
+"""Read in contour data file and plot max and min
+"""
+
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, close, axis, title, legend, grid
+from os import sep
+ 
+directory = project.outputdir
+timedir='20070613_044204_run_final_3.6_exmouth_nbartzis'
+#timedir='20070613_061053_run_final_3.6_onslow_nbartzis'
+
+def get_data(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    stage = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        stage.append(float(fields[2]))
+    return max(stage), min(stage)
+
+files = ['stage0_convert.csv','stage5_convert.csv','stage20_convert.csv','stage50_convert.csv']
+#files = ['stage0_convert.csv','stage20_convert.csv','stage50_convert.csv']
+depth = [0,5,20,50]
+#depth = [0,20,50]
+stage_max = []
+stage_min = []
+
+for thefile in files:
+
+    filename = directory + timedir + sep + thefile
+    max_stage, min_stage = get_data(filename)
+    stage_max.append(max_stage)
+    stage_min.append(min_stage)
+
+from anuga.abstract_2d_finite_volumes.util import greens_law
+from Numeric import arange
+d1 = 50.
+d2 = arange(d1,0.15,-0.1)
+h1 = max_stage
+#h1 = 4.0
+green = []
+for d in d2:
+    h2 = greens_law(d1,d,h1)
+    green.append(h2)
+    
+ion()
+plot(depth,stage_max,'ob',d2,green,'-g',depth,stage_max,'-b')
+xlabel('depth (m)') 
+ylabel('stage (m)')
+title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+Magnitude 9.3 event (Java) at Pt Hedland')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.1 event (Sumba) at Pt Hedland')
+#title('ANUGA modelled maximum stage versus Green\'s approximation \n \
+#Magnitude 9.0 event (Sumba) at Pt Hedland')
+legend(['ANUGA','Green\'s law'])
+axis([-5,55,min(stage_max)*0.9,max(stage_max)*1.1])
+grid(True)
+#savefig('stratification_onslow_gun')
+savefig('stratification_exmouth_gun')
+#savefig('stratification_dampier_gun')
+
+close('all')
+
Index: /anuga_work/production/wa/pt_hedland_2006/project.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/project.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/project.py	(revision 7411)
@@ -0,0 +1,289 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+Also includes origin for slump scenario.
+"""
+
+from os import sep, environ, getenv, getcwd
+from os.path import expanduser, basename
+#from anuga.utilities.polygon import read_polygon
+import sys
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+from time import localtime, strftime
+from anuga.geospatial_data.geospatial_data import *
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_dir_name = 'pt_hedland_tsunami_scenario_2006'
+
+# onshore data from 30m DTED level 2
+onshore_name_dted = 'pt_hedland_onshore_30m_dted' # get from Neil/Ingo (DEM or topo data)
+onshore_name_dli = 'pt_hedland_onshore_20m_dli' # get from Neil/Ingo (DEM or topo data)
+
+# offshore data from GA digitised charts
+offshore_name1 = 'pt_hedland_offshore_points_orig'
+
+# offshore data from AHO fairsheets
+offshore_name2 = 'pt_hedland_offshore_points_fairsheet_orig'
+
+# reissued offshore data from PMD and NM&I Nov 2006
+offshore_name0 = 'hydrographic_charts'
+offshore_name1 = 'xy100003817'
+offshore_name2 = 'xy100003819'
+offshore_name3 = 'xy100003822'
+offshore_name4 = 'xy100003824'
+offshore_name5 = 'xy100003825'
+offshore_name6 = 'xy100003826'
+offshore_name7 = 'xy100003827'
+offshore_name8 = 'xy100003828'
+offshore_name9 = 'xy100003829'
+offshore_name10 = 'xy100003830'
+offshore_name11 = 'xy100003831'
+offshore_name12 = 'xy100003832'
+offshore_name13 = 'xy100003837'
+offshore_name14 = 'xy100003838'
+offshore_name15 = 'xy100003840'
+offshore_name16 = 'xy100003841'
+offshore_name17 = 'xy100003843'
+offshore_name18 = 'xy100003845'
+offshore_name19 = 'xy100003846'
+offshore_name20 = 'xy100003847'
+offshore_name21 = 'xy100003945'
+offshore_name22 = 'xy100003946'
+offshore_name23 = 'xy100003947'
+offshore_name24 = 'xy100003948'
+offshore_name25 = 'xy100004071'
+offshore_name26 = 'xy100004072'
+offshore_name27 = 'xy100004074'
+offshore_name28 = 'xy100004078'
+offshore_name29 = 'xy100004079'
+offshore_name30 = 'xy100004080'
+offshore_name31 = 'xy100004081'
+offshore_name32 = 'xy100004082'
+offshore_name33 = 'xy100004083'
+offshore_name34 = 'xy100004084'
+offshore_name35 = 'xy100004085'
+offshore_name36 = 'xy100004086'
+offshore_name37 = 'xy100004087'
+offshore_name38 = 'xy100004088'
+offshore_name39 = 'xy100004089'
+offshore_name40 = 'xy100004090'
+offshore_name41 = 'xy100011753'
+offshore_name42 = 'xy100014967'
+offshore_name43 = 'xy100014968'
+offshore_name44 = 'xy100014969'
+offshore_name45 = 'xy100021030'
+offshore_name46 = 'xy100021031'
+offshore_name47 = 'xy100021032'
+offshore_name48 = 'xy100021033'
+offshore_name49 = 'xy100021035'
+offshore_name50 = 'xy100022767'
+
+# coastline developed from aerial photography and 1.5m DLI contour
+#coast_name = 'pt_hedland_coastline_points_dted2_new'
+coast_name = 'coast_with_extracted_z'
+
+
+boundary_basename = 'SU-AU_clip'
+
+#swollen/ all data output
+basename = 'source'
+
+codename = 'project.py'
+
+if sys.platform == 'win32':
+    home = getenv('INUNDATIONHOME') #Sandpit's parent dir
+#    python_home = getenv('PWD')     
+    user = getenv('USERPROFILE')
+    #print 'USER:', user
+else:
+    # original
+    #home = getenv('INUNDATIONHOME', sep+'d'+sep+'cit'+sep+'1'+sep+'cit'+sep+'risk_assessment_methods_project'+sep+'inundation')
+    # update to perlite 2
+    home = getenv('INUNDATIONHOME', sep+'d'+sep+'cit'+sep+'2'+sep+'cit'+sep+'inundation'+sep+'data')     
+    user = getenv('LOGNAME')
+
+# INUNDATIONHOME is the inundation directory, not the data directory.
+home += sep +'data'
+
+#Derive subdirectories and filenames
+time = strftime('%Y%m%d_%H%M%S',localtime()) #gets time for new dir
+outputtimedir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'outputs'+sep+time+sep
+
+#print 'outputtimedir', outputtimedir
+#meshdir = home+sep+scenario_dir_name+sep+'meshes'+sep
+#datadir = home+sep+scenario_dir_name+sep+'topographies'+sep
+#gaugedir = home+sep+scenario_dir_name+sep+'gauges'+sep
+#polygondir = home+sep+scenario_dir_name+sep+'polygons'+sep
+#boundarydir = home+sep+scenario_dir_name+sep+'boundaries'+sep
+#outputdir = home+sep+scenario_dir_name+sep+'outputs'+sep
+#tidedir = home+sep+scenario_dir_name+sep+'tide_data'+sep
+
+meshdir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'meshes'+sep
+datadir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'topographies'+sep
+gaugedir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'gauges'+sep
+polygondir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'polygons'+sep
+boundarydir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'boundaries'+sep
+outputdir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'outputs'+sep
+tidedir = home+sep+state+sep+scenario_dir_name+sep+'anuga'+sep+'tide_data'+sep
+
+gauge_filename = gaugedir + 'gauge_location_port_hedland.csv'
+beach_gauges = gaugedir + 'beach_gauges.csv'
+gauge_checking = gaugedir + 'gauge_checking_test.csv'
+buildings_filename = gaugedir + 'Port_Hedland_res_Project.csv'
+buildings_filename_out = 'Port_Hedland_res_Project_modified.csv'
+community_filename = gaugedir + 'CHINS_v2.csv'
+community_scenario = gaugedir + 'community_pt_hedland.csv'
+tidal_filename = tidedir + 'pt_hedland_tide.txt'
+
+meshname = meshdir + basename
+#onshore_dem_name = datadir + onshore_name_dted
+onshore_dem_name = datadir + onshore_name_dli
+offshore_dem_name0 = datadir + offshore_name0
+offshore_dem_name1 = datadir + offshore_name1
+offshore_dem_name2 = datadir + offshore_name2
+offshore_dem_name3 = datadir + offshore_name3
+offshore_dem_name4 = datadir + offshore_name4
+offshore_dem_name5 = datadir + offshore_name5
+offshore_dem_name6 = datadir + offshore_name6
+offshore_dem_name7 = datadir + offshore_name7
+offshore_dem_name8 = datadir + offshore_name8
+offshore_dem_name9 = datadir + offshore_name9
+offshore_dem_name10 = datadir + offshore_name10
+offshore_dem_name11 = datadir + offshore_name11
+offshore_dem_name12 = datadir + offshore_name12
+offshore_dem_name13 = datadir + offshore_name13
+offshore_dem_name14 = datadir + offshore_name14
+offshore_dem_name15 = datadir + offshore_name15
+offshore_dem_name16 = datadir + offshore_name16
+offshore_dem_name17 = datadir + offshore_name17
+offshore_dem_name18 = datadir + offshore_name18
+offshore_dem_name19 = datadir + offshore_name19
+offshore_dem_name20 = datadir + offshore_name20
+offshore_dem_name21 = datadir + offshore_name21
+offshore_dem_name22 = datadir + offshore_name22
+offshore_dem_name23 = datadir + offshore_name23
+offshore_dem_name24 = datadir + offshore_name24
+offshore_dem_name25 = datadir + offshore_name25
+offshore_dem_name26 = datadir + offshore_name26
+offshore_dem_name27 = datadir + offshore_name27
+offshore_dem_name28 = datadir + offshore_name28
+offshore_dem_name29 = datadir + offshore_name29
+offshore_dem_name30 = datadir + offshore_name30
+offshore_dem_name31 = datadir + offshore_name31
+offshore_dem_name32 = datadir + offshore_name32
+offshore_dem_name33 = datadir + offshore_name33
+offshore_dem_name34 = datadir + offshore_name34
+offshore_dem_name35 = datadir + offshore_name35
+offshore_dem_name36 = datadir + offshore_name36
+offshore_dem_name37 = datadir + offshore_name37
+offshore_dem_name38 = datadir + offshore_name38
+offshore_dem_name39 = datadir + offshore_name39
+offshore_dem_name40 = datadir + offshore_name40
+offshore_dem_name41 = datadir + offshore_name41
+offshore_dem_name42 = datadir + offshore_name42
+offshore_dem_name43 = datadir + offshore_name43
+offshore_dem_name44 = datadir + offshore_name44
+offshore_dem_name45 = datadir + offshore_name45
+offshore_dem_name46 = datadir + offshore_name46
+offshore_dem_name47 = datadir + offshore_name47
+offshore_dem_name48 = datadir + offshore_name48
+offshore_dem_name49 = datadir + offshore_name49
+offshore_dem_name50 = datadir + offshore_name50
+
+coast_dem_name = datadir + coast_name
+combined_dem_name = datadir + 'pt_hedland_combined_elevation'
+outputname = outputtimedir + basename  #Used by post processing
+
+community_filename = gaugedir + 'CHINS_v2.csv'
+community_pt_hedland = gaugedir + 'community_pt_hedland.csv'
+
+# clipping region to make DEM (pts file) from onshore data
+eastingmin = 594000
+eastingmax = 715000
+northingmin = 7720000
+northingmax = 7880000
+
+# for ferret2sww
+south = degminsec2decimal_degrees(-20,30,0)
+north = degminsec2decimal_degrees(-17,10,0)
+west = degminsec2decimal_degrees(117,00,0)
+east = degminsec2decimal_degrees(120,00,0)
+
+# region to export (used from export_results.py)
+e_min_area = 648000
+e_max_area = 675000
+n_min_area = 7745000
+n_max_area = 7761000
+
+export_region = [[e_min_area,n_min_area],[e_min_area,n_max_area],[e_max_area,n_max_area],[e_max_area,n_min_area]]
+                 
+refzone = 50 
+
+from anuga.coordinate_transforms.redfearn import redfearn
+# boundary up to 50 m contour
+lat1_50 = degminsec2decimal_degrees(-19,20,0)
+lat2_50 = degminsec2decimal_degrees(-19,30,0)
+lat3_50 = degminsec2decimal_degrees(-19,45,0)
+lon1_50 = degminsec2decimal_degrees(119,05,0)
+lon2_50 = degminsec2decimal_degrees(118,20,0)
+lon3_50 = degminsec2decimal_degrees(117,45,0)
+z, easting, northing = redfearn(lat1_50, lon1_50)
+d0_50 = [easting, northing]
+z, easting, northing = redfearn(lat2_50, lon2_50)
+d1_50 = [easting, northing]
+z, easting, northing= redfearn(lat3_50, lon3_50)
+d2_50 = [easting, northing]
+
+d4_50 = [285000, 7585000]
+d6_50 = [330000, 7605000]
+#bounding_poly50 = [p0_50, p1_50, p2_50, d6_50, d5, d4_50]
+
+d0 = [763852.0, 7934358.0]
+d1 = [710987.0, 7925797.0]
+d2 = [658264.0, 7926314.0]
+d3 = [552686.0, 7871580.0]
+#d4 = [604415.81, 7733013.56]
+d4 = [638000.0, 7733013.56]
+#d5 = [656561.15, 7732615.11]
+d5 = [662000.0, 7732615.11]
+#d6 = [708940.32, 7750510.33]
+d6 = [690000.0, 7740510.33]
+#polyAll = [d0, d1, d2, d3, d4, d5, d6]
+#polyAll = [d0_50, d1_50, d2_50, d4, d5, d6]
+# from Hamish
+h0=[629262.17, 7747205.47]
+h1=[552686.00, 7871579.99] #d3
+h2=[658264.00, 7926314.00] #d2
+h3=[710986.99, 7925796.99] #d1
+h4=[763851.99, 7934357.99] #d0
+h5=[701485.21, 7770656.86]
+h6=[698273.75, 7762227.38]
+h7=[698194.23, 7762018.65]
+h8=[691627.41, 7744781.98]
+h9=[679220.75, 7743604.59]
+h10=[653512.59, 7740528.56]
+h11=[634777.71, 7738247.17]
+h12=[629443.86, 7746910.37]
+h13=[629396.84, 7746986.75]
+h14=[629352.32, 7747059.06]
+h15=[629276.24, 7747182.63]
+h16=[629262.17, 7747205.47] #repeat of h0
+# using Hamish's new bounding polygon
+#polyAll = [d0_50, d1_50, d2_50, h16,h15,h14,h13,h12,h11,h10,h9,h8,h7,h6,h5]
+polyAll = [d0_50, d1_50, d2_50, h16,h11,h8,h6, h5]
+
+#Interior region - Pt Hedland town
+i0 = [668000, 7757000]
+i1 = [659000, 7755000]
+i2 = [660000, 7749000]
+i3 = [667000, 7746000]
+i4 = [678000, 7751000]
+
+poly_pt_hedland = [i0, i1, i2, i3, i4]
+
+#Are there other significant features?
+j0 = [670000, 7760000]
+j1 = [633000, 7745000]
+j2 = [665000, 7743000]
+j3 = [690000, 7755000]
+
+poly_region = [j0, j1, j2, j3]
Index: /anuga_work/production/wa/pt_hedland_2006/project_urs.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/project_urs.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/project_urs.py	(revision 7411)
@@ -0,0 +1,257 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+Also includes origin for slump scenario.
+"""
+
+from os import sep, environ, getenv, getcwd,umask
+from os.path import expanduser, basename
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon, number_mesh_triangles
+import sys
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+from time import localtime, strftime, gmtime
+from anuga.utilities.system_tools import get_user_name, get_host_name
+
+
+home = getenv('INUNDATIONHOME') + sep +'data'+sep #Sandpit's parent dir   
+user = get_user_name()
+host = get_host_name()
+#needed when running using mpirun, mpirun doesn't inherit umask from .bashrc
+umask(002)
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'pt_hedland'
+scenario = 'pt_hedland_tsunami_scenario_2006'
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+
+#tide = -3.9
+#tide = 0.0
+tide = 3.6
+
+#Maybe will try to make project a class to allow these parameters to be passed in.
+alpha = 0.1
+friction=0.01
+starttime=3600
+finaltime=25000
+setup='final'
+source='onslow'
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1
+    time_thinning=1
+    yieldstep=60
+if setup =='store':
+    print'store'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240    
+
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(source)+'_'+str(user)
+
+# onshore data from 30m DTED level 2
+onshore_name = 'dli_dem' # get from Neil/Ingo (DEM or topo data)
+offshore_name = 'pthedland_0607'
+offshore1_name = '1'
+offshore2_name = '2'
+coast_name = 'Coastline'
+
+#final topo name
+combined_name ='pt_hedland_combined_elevation_test'
+combined_small_name = 'pt_hedland_combined_elevation_small'
+combined_smallest_name = 'pt_hedland_export'
+
+anuga_dir = home+state+sep+scenario+sep+'anuga'+sep
+
+topographies_in_dir = home+state+sep+scenario+sep+'elevation_final'+sep+'20070416_updated'+sep+'points'+sep
+topographies_dir = anuga_dir+'topographies'+sep
+
+# input topo file location
+onshore_in_dir_name = topographies_in_dir + onshore_name
+coast_in_dir_name = topographies_in_dir + coast_name
+offshore_in_dir_name = topographies_in_dir + offshore_name
+offshore1_in_dir_name = topographies_in_dir + offshore1_name
+offshore2_in_dir_name = topographies_in_dir + offshore2_name
+
+onshore_dir_name = topographies_dir + onshore_name
+coast_dir_name = topographies_dir + coast_name
+offshore_dir_name = topographies_dir + offshore_name
+offshore1_dir_name = topographies_dir + offshore1_name
+offshore2_dir_name = topographies_dir + offshore2_name
+
+#final topo files
+combined_dir_name = topographies_dir + combined_name
+#combined_time_dir_name = topographies_time_dir + combined_name
+combined_small_dir_name = topographies_dir + combined_small_name
+combined_smallest_dir_name = topographies_dir + combined_smallest_name
+
+meshes_dir = anuga_dir+'meshes'+sep
+meshes_dir_name = meshes_dir + scenario_name
+
+polygons_dir = anuga_dir+'polygons'+sep
+tide_dir = anuga_dir+'tide_data'+sep
+
+#boundaries locations
+
+if source =='dampier':
+    boundaries_name = 'pt_hedland_3854_17042007' #Dampier gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'dampier'+sep+'1_10000'+sep
+
+if source=='onslow':
+    boundaries_name = 'pt_hedland_3859_16052007' #onslow_hedland_broome gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'onslow_hedland_broome'+sep+'1_10000'+sep
+    
+if source=='exmouth':
+    boundaries_name = 'pt_hedland_3103_18052007' #exmouth gun
+    boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'exmouth'+sep+'1_10000'+sep
+    
+#boundaries_in_dir = anuga_dir+'boundaries'+sep+'urs'+sep+'1_10000'+sep
+boundaries_in_dir_name = boundaries_in_dir + boundaries_name
+boundaries_dir = anuga_dir+'boundaries'+sep
+boundaries_dir_name = boundaries_dir + boundaries_name
+
+#output locations
+output_dir = anuga_dir+'outputs'+sep
+output_build_time_dir = output_dir+build_time+'_'+source+sep
+output_run_time_dir = output_dir +run_time+dir_comment+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+gauge_name = 'gauge_location_port_hedland.csv'
+gauge_name_test = 'gauge_checking_test.csv' 
+gauges_dir = anuga_dir+'gauges'+sep
+gauges_dir_name = gauges_dir + gauge_name
+gauges_dir_name_test = gauges_dir + gauge_name_test
+beach_gauges = gauges_dir + 'beach_gauges.csv'
+
+tide_dir = anuga_dir+'tide_data'+sep
+
+buildings_filename = gauges_dir + 'Port_Hedland_res_Project.csv'
+buildings_filename_out = 'Port_Hedland_res_Project_modified.csv'
+tidal_filename = tide_dir + 'pt_hedland_tide.txt'
+community_filename = gauges_dir + 'CHINS_v2.csv'
+community_scenario = gauges_dir + 'community_pt_hedland.csv'
+
+# clipping region to make DEM (pts file) from onshore data
+eastingmin = 594000
+eastingmax = 715000
+northingmin = 7720000
+northingmax = 7880000
+
+# for ferret2sww
+south = degminsec2decimal_degrees(-20,30,0)
+north = degminsec2decimal_degrees(-17,10,0)
+west = degminsec2decimal_degrees(117,00,0)
+east = degminsec2decimal_degrees(120,00,0)
+
+# region to export (used from export_results.py)
+eastingmin = 648000
+eastingmax = 675000
+northingmin = 7745000
+northingmax = 7761000
+
+#export_region = [[e_min_area,n_min_area],[e_min_area,n_max_area],
+#                 [e_max_area,n_max_area],[e_max_area,n_min_area]]
+                 
+#refzone = 50 
+
+from anuga.coordinate_transforms.redfearn import redfearn
+# boundary up to 50 m contour
+lat1_50 = degminsec2decimal_degrees(-19,20,0)
+lat2_50 = degminsec2decimal_degrees(-19,30,0)
+lat3_50 = degminsec2decimal_degrees(-19,45,0)
+lon1_50 = degminsec2decimal_degrees(119,05,0)
+lon2_50 = degminsec2decimal_degrees(118,20,0)
+lon3_50 = degminsec2decimal_degrees(117,45,0)
+z, easting, northing = redfearn(lat1_50, lon1_50)
+d0_50 = [easting, northing]
+z, easting, northing = redfearn(lat2_50, lon2_50)
+d1_50 = [easting, northing]
+z, easting, northing= redfearn(lat3_50, lon3_50)
+d2_50 = [easting, northing]
+
+d4_50 = [285000, 7585000]
+d6_50 = [330000, 7605000]
+#bounding_poly50 = [p0_50, p1_50, p2_50, d6_50, d5, d4_50]
+
+d0 = [763852.0, 7934358.0]
+d1 = [710987.0, 7925797.0]
+d2 = [658264.0, 7926314.0]
+d3 = [552686.0, 7871580.0]
+#d4 = [604415.81, 7733013.56]
+d4 = [638000.0, 7733013.56]
+#d5 = [656561.15, 7732615.11]
+d5 = [662000.0, 7732615.11]
+#d6 = [708940.32, 7750510.33]
+d6 = [690000.0, 7740510.33]
+#polyAll = [d0, d1, d2, d3, d4, d5, d6]
+#polyAll = [d0_50, d1_50, d2_50, d4, d5, d6]
+# from Hamish
+h0=[629262.17, 7747205.47]
+h1=[552686.00, 7871579.99] #d3
+h2=[658264.00, 7926314.00] #d2
+h3=[710986.99, 7925796.99] #d1
+h4=[763851.99, 7934357.99] #d0
+h5=[701485.21, 7770656.86]
+h6=[698273.75, 7762227.38]
+h7=[698194.23, 7762018.65]
+h8=[691627.41, 7744781.98]
+h9=[679220.75, 7743604.59]
+h10=[653512.59, 7740528.56]
+h11=[634777.71, 7738247.17]
+h12=[629443.86, 7746910.37]
+h13=[629396.84, 7746986.75]
+h14=[629352.32, 7747059.06]
+h15=[629276.24, 7747182.63]
+h16=[629262.17, 7747205.47] #repeat of h0
+# using Hamish's new bounding polygon
+#polyAll = [d0_50, d1_50, d2_50, h16,h15,h14,h13,h12,h11,h10,h9,h8,h7,h6,h5]
+poly_all = [d0_50, d1_50, d2_50, h16,h11,h8,h6, h5]
+res_poly_all = 250000*res_factor
+
+#Interior region - Pt Hedland town
+i0 = [668000, 7757000]
+i1 = [659000, 7755000]
+i2 = [660000, 7749000]
+i3 = [667000, 7746000]
+i4 = [678000, 7751000]
+
+poly_pt_hedland = [i0, i1, i2, i3, i4]
+res_pt_hedland=500*res_factor
+
+#Are there other significant features?
+j0 = [670000, 7760000]
+j1 = [633000, 7745000]
+j2 = [665000, 7743000]
+j3 = [690000, 7755000]
+
+poly_region = [j0, j1, j2, j3]
+res_region = 60000*res_factor
+
+poly_mainland = read_polygon(polygons_dir+'Initial_Condition.csv')
+
+poly_topo_clip = [[664000,7752000],[664000,7754000],
+                  [666000,7754000],[666000,7752000]]
+
+interior_regions = [[poly_pt_hedland,res_pt_hedland],[poly_region,res_region]
+#                    ,[poly_region,res_region]
+                    ]
+
+trigs_min = number_mesh_triangles(interior_regions, poly_all, res_poly_all)
+
+print 'min number triangles', trigs_min
+
+
Index: /anuga_work/production/wa/pt_hedland_2006/report/HAT_damage.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/HAT_damage.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/HAT_damage.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{figure}[hbt] 
+%\centerline{ \includegraphics[width=100mm, height=75mm]{../report_figures/.jpg}}  
+\caption{Damage modelling for highest astronomical tide for Pt Hedland region (in m).}  
+\label{fig:HAT_damage}
+\end{figure}
Index: /anuga_work/production/wa/pt_hedland_2006/report/HAT_map.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/HAT_map.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/HAT_map.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{sidewaysfigure}
+\centerline{ \includegraphics[width=\paperwidth]{../report_figures/pt_hedland_high_tide.jpg}}  
+\caption{Maximum inundation map for HAT scenario for Pt Hedland region (in m). Data: WA DLI, DPI and AHO.}  
+\label{fig:HAT_max_inundation}
+\end{sidewaysfigure}
Index: /anuga_work/production/wa/pt_hedland_2006/report/LAT_damage.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/LAT_damage.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/LAT_damage.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{figure}[hbt] 
+%\centerline{ \includegraphics[width=100mm, height=75mm]{../report_figures/.jpg}}  
+\caption{Damage modelling for lowest astronomical tide for Pt Hedland region (in m).}  
+\label{fig:LAT_damage}
+\end{figure}
Index: /anuga_work/production/wa/pt_hedland_2006/report/LAT_map.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/LAT_map.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/LAT_map.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{sidewaysfigure}
+\centerline{ \includegraphics[width=\paperwidth]{../report_figures/pt_hedland_low_tide.jpg}}  
+\caption{Maximum inundation map for LAT scenario for Port Hedland region (in m). Data: WA DLI, DPI and AHO.}  
+\label{fig:LAT_max_inundation}
+\end{sidewaysfigure}
Index: /anuga_work/production/wa/pt_hedland_2006/report/MSL_damage.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/MSL_damage.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/MSL_damage.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{figure}[hbt] 
+%\centerline{ \includegraphics[width=100mm, height=75mm]{../report_figures/.jpg}}  
+\caption{Damage modelling for mean sea level for Pt Hedland region (in m).}  
+\label{fig:MSL_damage}
+\end{figure}
Index: /anuga_work/production/wa/pt_hedland_2006/report/MSL_map.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/MSL_map.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/MSL_map.tex	(revision 7411)
@@ -0,0 +1,5 @@
+\begin{sidewaysfigure}[hbt] 
+\centerline{ \includegraphics[width=\paperwidth]{../report_figures/pt_hedland_mid_tide.jpg}}  
+\caption{Maximum inundation map for MSL scenario for Port Hedland region (in m). Data: WA DLI, DPI and AHO.}  
+\label{fig:MSL_max_inundation}
+\end{sidewaysfigure}
Index: /anuga_work/production/wa/pt_hedland_2006/report/acknowledgements.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/acknowledgements.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/acknowledgements.tex	(revision 7411)
@@ -0,0 +1,25 @@
+
+The Inundation Modelling Team in 
+the Risk Research Group at GA would like to thank a number of organisations and groups
+in providing input in this study;
+
+\begin{itemize}
+\item The AHO for their assistance in supplying digitised fairsheet data for the priority areas
+along the NW Shelf. 
+\item The WA DPI in their assistance in supplying digitised state fairsheet data
+for nominated areas and ably assisting in queries regarding bathymetric data
+\item The WA DLI in their assistance in supplying the onshore 20m DEM for use in this project
+\item The National Mapping Division, in particular Hamish Anderson, for sourcing onshore
+data for the FESA project and building a DEM
+suitable for purposes of inundation modelling
+\item The Petroleum and Marine Divison, in particular Kathryn Tobin, Mike Sexton, Phil O'Brien
+and Mark Alcock, for sourcing offshore data for the regions of interest and providing
+advice on bathymetric data issues, 
+\item The GIS team in the Risk Assessment Methods Project (RAMP) for developing the
+decision support tool and providing assistance to the inundation modellers on a frequent basis
+\item The exposure database development team in RAMP for providing the necessary information
+to undertake the damage modelling
+\item The engineering section in RAMP for calculating the damage estimates, 
+and finally
+\item FESA, for providing a range of support to the project.
+\end{itemize}
Index: /anuga_work/production/wa/pt_hedland_2006/report/anuga_setup.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/anuga_setup.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/anuga_setup.tex	(revision 7411)
@@ -0,0 +1,112 @@
+The following information is required to undertake the 
+inundation modelling;
+
+\begin{itemize}
+\item onshore and offshore elevation data (topographic and bathymetric data, 
+see Section \ref{sec:data}),
+\item initial conditions, such as initial water levels (e.g. determined by tides),
+\item boundary conditions (the tsunami source as described in 
+Section \ref{sec:methodology}), and
+\item computational requirements relating to the mesh construction.
+\end{itemize}
+ 
+The initial conditions used for this scenario are MSL, HAT and LAT which were
+defined in Section \ref{sec:data}. Figure \ref{fig:IC} shows the MSL, HAT and 
+LAT contours to illustrate the water level for each of these inial conditions.
+The dynamics of
+tidal effects (that is, the changes in water height over time for
+the entire study area) are not currently modelled.
+Sea floor friction will generally provide resistance to the water flow
+and thus reduce the impact somewhat. However, limited
+research has been carried out to determine 
+the friction coefficients, and 
+thus it has not been incorporated
+in the scenario. The 
+results are therefore likely to be over estimates.
+
+\begin{figure}[h]
+
+  \centerline{\includegraphics[width=\paperwidth]{../report_figures/port_hedland_dli_contour.jpg}}
+
+  \caption{Port Hedland region showing the initial conditions used for the study; 
+  -3.9m AHD (LAT), 0m AHD (MSL) and 3.6m AHD (HAT) contour lines.}
+  \label{fig:IC}
+\end{figure}
+
+To set up a model for the tsunami scenario, a study area is first 
+determined. Preliminary investigations have indicated the point
+at which the output from MOST is the input to ANUGA is
+sufficient at between the 50m and 100m bathymetric contour line.
+In constrast to the Onslow study,
+we choose the 50m contour line as the seaward boundary due primarily
+to computational constraints\footnote{ 
+Preliminary investigations indicate that MOST and ANUGA compare
+well at the 50m and 100m contour line. In addition, the resolution for
+the MOST modelling indicate that it can theoretically model 
+tsunamis with a wavelength of 20-30km, and the wavelength of
+the tsunami wave at the boundary is approximately 20km. A much
+higher model resolution will be used in developing the probabilistic
+models for further studies.}  Historical run-up heights are 
+of the order of 10m and we would expect that a tsunami wave
+would penetrate no higher for this scenario.
+Therefore, the study area of around ? km$^2$ 
+covers approximately 100km of
+coastline and extends offshore to the 50m contour line and inshore to 
+approximately 10m elevation. 
+
+The finite volume technique relies on the construction of a triangular mesh which covers the study region. This mesh can be altered to suit the needs of the scenario in question. The mesh can be refined in areas of interest, particularly in the coastal region where complex behaviour is likely to occur. In setting up the model, the user defines the area of the triangular cells in each region of interest\footnote{Note that the cell 
+area will be the maximum cell area within the defined region and that each 
+cell in the region does not necessarily have the same area.}.
+The area should not be too small as to exceed realistic computational time, and not too great as to inadequately capture important behaviour. There are no gains in choosing the area to be less than the supporting data.
+Figure \ref{fig:pt_hedland_area} shows the study area and where further mesh refinement has been made. For each region, a maximum triangular cell area is defined and its associated lateral accuracy.
+With these cell areas, the study area consists of 401939 triangles
+in which water levels and momentums are tracked through time. The lateral accuracy refers to the distance at which we are confident in stating a region is inundated. Therefore we can only be confident in the calculated inundation extent in the Port Hedland town centre to within 30m.
+
+\begin{figure}[hbt]
+
+  \centerline{ \includegraphics[scale=0.4]
+             {../report_figures/pt_hedland_resolution_zones.jpg}}
+
+  \caption{Study area for the Port Hedland scenario highlighting four regions of increased refinement. 
+Region 1: Surrounds Port Hedland town centre with a cell area of 500 m$^2$ (lateral accuracy 30m).
+Region 2: Surrounds the coastal region with a cell area of 50000 m$^2$ (lateral accuracy 220m).
+Region 3: Water depths to the 50m contour line (approximately) with a cell area of 250000 m$^2$ (lateral accuracy 700m).
+}
+  \label{fig:pt_hedland_area}
+\end{figure}
+
+
+The final item to be addressed to complete the model setup is the 
+definition of the boundary condition. As 
+discussed in Section \ref{sec:methodology}, a series of events corresponding
+to a range of return periods are selected as the tsunami sources.
+The resultant tsunami wave is made up of a series
+of waves with different amplitudes which is affected by the energy
+and style of the event as well as the bathymetry whilst it travels
+from its source to Port Hedland. The amplitude and velocity of each of these
+waves are then provided to ANUGA as boundary conditions and propagated
+inshore.
+
+The tsunami generation and propagation modelling uses the URS paradigm.
+The URS output is saved every 2.5 seconds and with a spatial resolution
+of two arc minutes.
+
+Sea floor friction will generally provide resistance to the water flow
+and thus reduce the impact somewhat. Initial experimental results 
+indicate that the friction coefficient shoudl be 0.017.
+The following table summarises the modelling parameters;
+
+\begin{table}
+\begin{center}
+\caption{Parameters used in ANUGA for the Port Hedland scenario.}
+\begin{tabular}{|l|l|l|}\hline
+Mesh & & \\ \hline
+& resolution in Region 1 & 500 m$^2$ \\ \hline
+& resolution in Region 2 & 50 000 m$^2$ \\ \hline
+& remaining resolution & 250 000 m$^2$ \\ \hline
+Model parameters & & \\ \hline
+& friction & 0.017 \\ \hline
+& minimum stored height & 0.1 m \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
Index: /anuga_work/production/wa/pt_hedland_2006/report/checking.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/checking.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/checking.tex	(revision 7411)
@@ -0,0 +1,31 @@
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\include{appendix}
+\setstretch{1.25}
+\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\textwidth \paperwidth
+\advance\textwidth -2in
+
+\begin{figure}[hbt] 
+ \centerline{ \includegraphics[width=150mm, height=100mm]{../report_figures/gauges_checking.png}}
+\caption{Point locations used to compare MOST and ANUGA for Onslow region.}  
+\label{fig:comparisonpoints}
+\end{figure}
+\input{latexoutput_checking} 
+ \clearpage 
+ \end{document}
Index: /anuga_work/production/wa/pt_hedland_2006/report/damage.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/damage.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/damage.tex	(revision 7411)
@@ -0,0 +1,85 @@
+In this report, impact modelling refers to casualties and
+damage to residential buildings as a result
+of the inundation described in Section \ref{sec:results}. It is assumed
+that the event occurs at night. 
+Exposure data are sourced from the National Building Exposure Database (NBED), 
+developed by GA\footnote{http://www.ga.gov.au/urban/projects/ramp/NBED.jsp}. 
+It contains information about residential buildings, people and the
+cost of replacing buildings and contents.
+
+To develop building damage and casuality estimates, 
+residential collapse vulnerability models and casualty models were developed.
+The vulnerability models have been developed for 
+framed residential construction based on limited data found in the literature
+as well as observations from the Indian Ocean tsunami event. 
+The models predict the collapse 
+probability for an exposed population and incorporates the following 
+parameters known to influence building damage \cite{papathoma:vulnerability},
+
+\begin{itemize}
+\item	inundation depth at building	
+\item	distance from the coast	
+\item	building material (residential framed construction)	
+\item	inundation depth in house above floor level
+\end{itemize}	
+
+The collapse vulnerability models used are presented in Table \ref{table:collapse}. 
+%In applying the model, all structures in the inundation zone were 
+%spatially located and the local water depth and building row 
+%number from the exposed edge of the suburb were determined for each %structure.
+
+Casualty models were based on the
+storm surge models used for the Cairns Cyclone Scenario and 
+through consultation with Dr David Cooper of NSW Health, \cite{cooper:2005}. 
+The injury probabilities for exposed populations were determined 
+based on the nocturnal nature of the event, the collapse outcome 
+for the structure, the water depth with respect to 
+sleeping height (1.0 m) and the limited warning noise for people 
+in the first three city blocks (six house rows) that could potentially 
+awaken them. The three injury categories correspond with the 
+categories presented in HAZUS-MH \cite{NIBS:2003} for earthquake 
+related injury. The casualty model used is presented in Table
+\ref{table:casualty} 
+and the injury categories are presented in Table \ref{table:injury}. 
+Input data comprised of resident population data at census
+district level derived from the ABS 2001 Census. Given the exposure database is
+based on residential structures, we assume that the
+population are at home and sleeping when the event occurs and that there is no
+warning. Therefore, the casualty estimates would be significantly different
+if the event were to occur during the day when people are at work, travelling
+in a vehicle, spending time on the beach, for example, or if the event occurred
+during a major holiday season.
+
+South Hedland is not exposed to inundation in this
+scenario, therefore we restrict the damage modelling to a smaller section of the NBED.
+For the damage modellin, there
+are an estimated 3700 residential structures and a population of approximately
+11500\footnote{Population is determined by census data and the 1999
+ABS housing survey}. 
+HAT is the only scenario in which damage occurs, and it is restricted to one residential 
+structure\footnote{The structure is classed as agricultural.} with no injuries sustained.  
+
+Tsunami impact on indigeneous communities should be considered
+in the future as a number of communities exist in coastal regions of north west WA.
+These communities are typically not included in national residential databases 
+and would therefore be overlooked in damage model estimates.
+There are four indigeneous communities located in this study area; Tjalkli Warra, Jinparinya,
+Punju Ngarugundi Njamal and Tjalka Boorda\footnote{get a reference from Anita}.
+Tjalka Boorda is located the closest to the headland and remains free of inundation
+for each scenario.
+
+%The community is not affected for any of the scenarios (see Figure 
+%\ref{fig:gaugeTjalkaBoordaAboriginalReserve}).
+
+%\begin{center}
+%\begin{tabular}{|l|l|l|l|}\hline
+%Easting	 & Northing	& Community	& Population \\ \hline
+%677055.85&	7742819.31&	 Tjalkli Warra&	100 \\ \hline
+%690756.92&	7746148.99&	 Jinparinya&	30 \\ \hline
+%691091.39&	7747119.61&	 Punju Ngarugundi Njamal&	22 \\ \hline
+%669526.15&    7752820.51& Tjalka Boorda	& 0 \\ \hline
+%\end{tabular}
+%\end{center}
+
+
+
Index: /anuga_work/production/wa/pt_hedland_2006/report/damage_inputs.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/damage_inputs.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/damage_inputs.tex	(revision 7411)
@@ -0,0 +1,65 @@
+\begin{table}[h]
+\begin{center}
+\caption{Framed residential building collapse probability. $h$ is the
+inundation height (m) above ground where the ground floor height of 0.3m is
+assumed.}
+\label{table:collapse}
+\begin{tabular}{|l|l|l|l|l|l|}\hline
+Distance from coast ($d[m]$) & 
+$h$<1.0 &1.0<$h$<2.0&	2.0<$h$<3.0	&3.0<$h$<5.0	&$h$>5.0 \\ \hline
+$d < 125$	 &0.05	&0.6	&0.8	&0.95	&0.99 \\ \hline
+$125 < d < 200$ &0.02	&0.3	&0.4	&0.7	&0.9 \\ \hline
+$200 < d < 250$	&0.01	&0.1	&0.25	&0.5	&0.65 \\ \hline
+$200 < d$	&0.0	&0.05	&0.15	&0.3	&0.45 \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+\begin{table}[h]
+\begin{center}
+\caption{Mortality and injury state probability}
+\label{table:casualty} 
+\begin{tabular}{|l|l|l|l|l|l|l|}\hline
+Hazard Exposure	& depth above floor & Unharmed	&Minor
+	&Moderate 	&Serious	&Death \\ \hline
+Collapse	&<1.0	&0.3	&0.28	&0.08	&0.04	&0.30 \\ \hline
+	&>1.0	&0.01	&0.028	&0.008	&0.004	&0.95 \\ \hline
+No Collapse - $d < 250$	&<1.0	&0.35	&0.40	&0.1	&0.05	&0.10 
+\\ \hline
+	&>1.0	&0.1	&0.28	&0.08	&0.04	&0.50 \\ \hline
+No Collapse - $250 < d$	&<1.0	&0.4	&0.4	&0.1	&0.05	&0.05 \\ \hline
+	&>1.0	&0.12	&0.33	&0.1	&0.05	&0.40 \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+\begin{table}[h]
+\begin{center}
+\caption{Injury level classificationse. Floor height is assumed to be 30cm}
+\label{table:injury}
+\begin{tabular*}{\textwidth}{|l|p{.695\textwidth}|}\hline
+Injury Severity Level	&Injury Description \\ \hline
+Minor Injury
+Severity 1	&Injuries requiring basic medical aid without requiring 
+hospitalisation.
+These types of injuries would require bandages or observation. 
+Some examples are: a sprain, a severe cut requiring stitches, 
+a  bump on the head without loss of consciousness. \\ \hline
+Moderate Injury
+Severity 2	&Injuries requiring a greater degree of 
+medical care and use of medical technology such as x-rays or surgery, 
+but not expected to progress to a life threatening status.
+Some examples are: a bump on the head that causes loss of consciousness, 
+fractured bone, dehydration or exposure. \\ \hline
+Severe Injury
+Severity 3	&Injuries that pose an immediate life threatening 
+condition if not treated adequately and expeditiously. Some examples are: 
+uncontrolled bleeding, punctured organ, other internal injuries, 
+spinal column injuries, or crush syndrome. \\ \hline
+Fatal
+Severity 4	&Instantaneously killed or mortally injured, \\ \hline
+\end{tabular*}
+\end{center}
+\end{table}
+\clearpage
+
Index: /anuga_work/production/wa/pt_hedland_2006/report/data.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/data.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/data.tex	(revision 7411)
@@ -0,0 +1,110 @@
+The calculated run-up height and resulting inundation ashore is controlled by
+the input topographic and bathymetric elevation, the
+initial and boundary conditions, as well as the cell area of the computational
+mesh. 
+Ideally, the data should adequately capture all complex features
+of the underlying bathymetry and topography. Any limitations
+in the resolution and accuracy of the data will introduce 
+errors to the inundation maps, in addition to the range of approximations
+made within the model.
+
+In this study, we used the Australian Height Datum (AHD)
+as the vertical datum. Mean Sea Level (MSL) is approximately equal to
+0m AHD with the Highest Astronomical Tide (HAT) 
+and Lowest Astronomical Tide (LAT) defined as 3.6 m AHD
+and -3.9 m AHD respectively for Port Hedland \cite{antt:06}. 
+As an aside, current work at GA is
+extracting information from LANDSAT imagery to reconstruct the 
+tidal variations for various WA locations. Future modelling of
+these areas will incorporate this information.
+
+Data for this study have been sourced from a number of agencies. With
+respect to the onshore data, the Defence Imagery and Geospatial
+Organisation (DIGO) supplied the Digital Terrain Elevation
+Data Level 2 (DTED) which has been authorised for Australian Tsunami
+Warning System use only. The resolution of this data is 1 second
+(about 30 metres), and has been produced from 1:50 000 contours, elevations and
+drainage. In addition, the Department of Land Information (DLI) has provided a
+20m Digital Elevation Model (DEM) and orthophotography 
+covering the NW Shelf. The DTED Level 2 data is ``bare earth'' and
+the DLI data is distorted by vegetation and buildings.  
+
+With respect to the offshore data, the Department of Planning and
+Infrastructure (DPI) have provided state digital fairsheet data around
+Onslow. This data covers a very small geographic area. 
+Similar data have been provided by DPI for Pt Hedland and Broome.
+The Australian Hydrographic Office (AHO) has supplied extensive
+fairsheet data which has also been utilised. In contrast to the onshore data, 
+the offshore data is a series of survey points which is typically 
+not supplied on a fixed grid. In addition, offshore data typically 
+does not have the coverage of the onshore data, and often the 
+offshore data will have gaps where surveys have not been conducted.
+The coastline has been generated by
+using the aerial photography, two detailed surveys provided
+by WA DPI and a number of total station surveys \footnote{Total station survey information
+has been used to verify the elevation data. A total station is an
+electronic device that combines the ability to measure a position 
+horizontally and vertically at the same time.} of Onslow. 
+The WA DLI data surrounding the coast are error prone and
+have been clipped at the derived coastline. 
+
+Figure \ref{fig:contours_compare}(a) shows the contour lines for
+HAT, MSL and LAT for Port Hedland using the DTED data where it is evident 
+that the extent of the tidal inundation is exaggerated. In particular,
+parts of Port Hedland appears to be inundated at HAT before a tsunami has
+even been generated. This is due to
+shortcomings with the digital elevation model (DEM) created from 
+the DTED data. 
+Figure \ref{fig:contours_compare}(b) shows
+the contour lines for HAT, MSL and LAT for Port Hedland using the WA DLI data.
+It is obvious that there are significant differences in each DEM with
+the knowledge
+of the HAT contour line pointing to increased confidence in the WA DLI
+data over the DTED data for use in the inundation modelling.
+Consequently the DLI data has been used in this study.
+
+
+\begin{figure}[p]
+\center{(a)}
+  \centerline{ \includegraphics[width=150mm, height=100mm]
+{../report_figures/port_hedland_dted_contour.jpg}}
+
+ % \caption{Port Hedland region showing the -3.9m AHD (LAT), 0m AHD (MSL)
+ %and -3.6m AHD (LAT) contour lines using the DTED Level 2 data.}
+ % \label{fig:contours_dted}
+%\end{figure}
+
+%\begin{figure}[hbt]
+\center{(b)}
+  \centerline{ \includegraphics[width=150mm, height=100mm]
+{../report_figures/port_hedland_dli_contour.jpg}}
+
+  \caption{Port Hedland region showing the -3.9m AHD (LAT), 0m AHD (MSL) 
+and 3.6m AHD (HAT) contour lines using the (a) DTED Level 2 data and
+the (b) WA DLI data.}
+ % \label{fig:contours_dli}
+ \label{fig:contours_compare}
+\end{figure}
+
+
+Appendix \ref{sec:metadata} provides more details and the supporting metadata 
+for this study, including images of the data extent.
+Table \ref{table:data} summarises the available data.
+
+\begin{table}
+\caption{Available data for the North West shelf tsunami inundation studies.}
+\label{table:data}
+\begin{center}
+\begin{tabular}{|l|l|}\hline
+Data & Detail \\ \hline 
+DIGO DTED Level 2  & Onshore, 1 second $\approx$ 30m \\ \hline 
+DLI & Onshore, 20m DEM and orthophotography \\ \hline
+DPI & Offshore, fairsheet data around Port Hedland \\ \hline
+AHO & Offshore, fairsheet data for North West Shelf region \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+
+\pagebreak
+
Index: /anuga_work/production/wa/pt_hedland_2006/report/discussion.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/discussion.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/discussion.tex	(revision 7411)
@@ -0,0 +1,15 @@
+The purpose of this section is to show the differences of impact
+and the importance of using the
+best possible data set. Given that the 1.5m AHD contour
+line is further from the coast for the DTED data than the DLI data, we
+expect the inundation to extend further and thus be greater than
+that seen in Figure \ref{fig:MSL_max_inundation}. 
+Further, the impact modelling
+will result in inflated structural and contents loss figures as well as
+numbers of people affected.
+These results point to the need for the best 
+available data so that more accurate predictions regarding the 
+inundation can be made.
+
+
+
Index: /anuga_work/production/wa/pt_hedland_2006/report/execsum.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/execsum.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/execsum.tex	(revision 7411)
@@ -0,0 +1,30 @@
+This report is being provided to the Fire and Emergency Services Authority
+(FESA) as part of the Collaborative Research Agreement (CRA) 
+with Geoscience Australia (GA), Tsunami Impact Modelling for WA.
+FESA has recognised the potential vulnerability of the Western Australia
+coastline to tsunami originating from earthquakes on
+the Sunda Arc subduction zone. 
+There is historic evidence of tsunami affecting the 
+Western Australia coastline, \cite{CB:ausgeo}, 
+and FESA has sought to assess
+the relative risk of its urban and regional communities to the tsunami
+threat and develop detailed response plans for a range of plausible events.
+
+This report describes the modelling methodology and results
+for a number of tsunami-genic events with varied return periods
+as they impact the Port Hedland region.
+In particular, maximum inundation maps are shown
+and discussed 
+for the event occurring at mean sea level as well as 
+highest and lowest astronomical tide. The inundation results allow
+estimation of the number of houses inundated and collapsed, as well as
+the numbers of persons affected. 
+
+The results of this study will allow an assessment of the relative tsunami risk 
+to communities along the NW Shelf of WA. 
+This report and the decision support tool are the 
+June 2007 deliverables of the Collaborative Research Agreement
+between FESA and GA.
+
+
+
Index: /anuga_work/production/wa/pt_hedland_2006/report/interpretation.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/interpretation.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/interpretation.tex	(revision 7411)
@@ -0,0 +1,50 @@
+The inundation extent calculated at Port Hedland will be described in this section with
+impact assessments following in Section \ref{sec:impact}.
+% there will need to be something in here for when doing a range of events for each return period.
+Figures \ref{fig:HAT_max_inundation}, \ref{fig:MSL_max_inundation} and 
+\ref{fig:LAT_max_inundation} illustrate the maximum inundation extent
+for the Mw 9 event occurring at HAT, MSL and LAT respectively. 
+As expected, there is greater inundation for the HAT scenario with increased
+extent. The major road from the south, 
+the Great Northern Highway, remains free of inundation for all tidal
+scenarios. At HAT, the road feeding off the highway, Anderson Street,
+suffers inundation in the tidal flat region. The inundation would
+be enough to halt usage of the road.
+The road servicing Finucane Station remains
+free of inundation, however there is a small section of the railway which
+receives under 0.2 m of water. Likewise, there
+is inundation on a section of the railway which services Port Hedland Station.
+There is not enough information regarding 
+the railway structure to determine whether it would halt its usage (i.e. how
+high has it been built). The airport remains
+free of inundation for each tidal scenario. 
+
+The geography of the Port Hedland area has played a role in offering
+some protection to the Port Hedland community. The tsunami wave is 
+travelling from the north west of the area. The opening of the channel faces
+northeast and it is
+offered some protection from the headland to its west. The tsunami wave impacts
+the headland east of the channel, with the north facing finger playing a role
+in the behaviour of the tsunami wave. There are a number of reflections
+occurring around the headland to the east of the channel, with the reflections
+not able to breach the finger. Inundation is evident on the finger which has
+resulted from reflections from the headland rather than the incoming tsunami
+wave.
+Shoaling is also observed in this region
+as a result of subsequent waves and reflections resulting from impact in 
+the region past the east of the headland.
+
+In addition to describing the maximum inundation extent,
+we have
+chosen a number of locations to illustrate the features
+of the tsunami as it approaches and impacts Port Hedland.
+These locations have been chosen as we believe they would 
+either be critical
+in an emergency situation, (e.g. the hospital) or
+effect recovery efforts, (e.g. the airport and wharfs). These locations
+are described in Table \ref{table:locations} and shown in 
+Figure \ref{fig:points}. The water's stage and speed 
+at each of these locations are shown
+as a function of time in the series of graphs shown in
+Appendix \ref{sec:timeseries}. Discussion of the main features of the
+tsunami wave is also described in Appendix \ref{sec:timeseries}.
Index: /anuga_work/production/wa/pt_hedland_2006/report/introduction.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/introduction.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/introduction.tex	(revision 7411)
@@ -0,0 +1,47 @@
+The Fire and Emergency Services Authority of Western Australia (FESA) and 
+associated volunteers respond to a wide range of emergencies 
+as well as undertaking search and rescue operations on land and 
+water\footnote{http://www.fesa.wa.gov.au/internet/}. 
+FESA also aims to reduce injury, loss of life and destruction of property in 
+Western Australian communities through proactive measures. 
+FESA helps the West Australian 
+community prepare, prevent (where possible) and respond safely to disasters.
+These risk mitigation activities involve understanding the relative risk
+of the disaster so that resources can be directed to appropriate areas
+and corresponding evacuation plans put in place.  
+
+The key role of the Risk Research Group at Geoscience Australian 
+is to develop knowledge on the risk from natural and 
+human-caused hazards for input to policy and operational decision making 
+on the mitigation of risk to Australian communities. The Group achieves 
+this through the development of computational methods, models and decision 
+support tools that assess the hazard, vulnerability and risk posed by hazard
+events.
+To develop an understanding of the tsunami risk, GA has developed
+decision support tools, consisting of inundation
+maps overlaid on aerial photography of the region 
+detailing critical infrastructure as well as damage modelling estimates. 
+
+This report details the impact assessments for a range of tsunami events.
+These events are based on the probabilistic hazard assessment conducted
+for the Western Australian coastline. A number of events are selected for
+return periods of 500, 1000 and 2000 years, see Section \ref{sec:tsunamiscenario}.
+
+Port Hedland has a population of around 42000 (including South Hedland) and
+is part of the Pilbara region of Western Autralia
+\footnote{http://www.porthedland.wa.gov.au/}. Pt Hedland itself has a 
+population of around 15000 and supports
+a variety of industries, including iron ore export, salt, tourism, 
+pastoral and light industrial.
+
+The modelling technique to simulate the 
+impact ashore will be discussed in Section \ref{sec:methodology} and 
+event and data inputs
+discussed in Sections \ref{sec:tsunamiscenario} and \ref{sec:data} respectively. 
+The inundation results are presented and discussed in Section \ref{sec:results} 
+and the impact modelling results outlined in Section \ref{sec:impact}.
+A summary of the results detailing issues
+regarding underlying data and further model development, are discussed 
+in Section \ref{sec:summary}.
+
+
Index: /anuga_work/production/wa/pt_hedland_2006/report/latexoutput.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/latexoutput.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/latexoutput.tex	(revision 7411)
@@ -0,0 +1,202 @@
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeHospitalstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeHospitalspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Hospital location (elevation 14.56m)} 
+ \label{fig:gaugeHospital} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeEffluentWaterPondsstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeEffluentWaterPondsspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Effluent Water Ponds location (elevation 5.13m)} 
+ \label{fig:gaugeEffluentWaterPonds} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeTjalkaBoordaAboriginalReservestage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeTjalkaBoordaAboriginalReservespeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Tjalka Boorda Aboriginal Reserve location (elevation 5.79m)} 
+ \label{fig:gaugeTjalkaBoordaAboriginalReserve} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeWaterTanksstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeWaterTanksspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Water Tanks location (elevation 5.65m)} 
+ \label{fig:gaugeWaterTanks} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePrimarySchoolstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePrimarySchoolspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Primary School location (elevation 11.59m)} 
+ \label{fig:gaugePrimarySchool} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeLaceyStreetstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeLaceyStreetspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Lacey Street location (elevation 11.26m)} 
+ \label{fig:gaugeLaceyStreet} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeCouncilOfficesstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeCouncilOfficesspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Council Offices location (elevation 13.81m)} 
+ \label{fig:gaugeCouncilOffices} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeRichardsonStreetstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeRichardsonStreetspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Richardson Street location (elevation 8.94m)} 
+ \label{fig:gaugeRichardsonStreet} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeTugHarbourstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeTugHarbourspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Tug Harbour location (elevation -16.01m)} 
+ \label{fig:gaugeTugHarbour} 
+ \end{figure} 
+ 
+\clearpage 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeNo1Warfstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeNo1Warfspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at No 1 Warf location (elevation 6.63m)} 
+ \label{fig:gaugeNo1Warf} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeNo3Warfstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeNo3Warfspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at No 3 Warf location (elevation 7.84m)} 
+ \label{fig:gaugeNo3Warf} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeNelsonPointWarfstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeNelsonPointWarfspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Nelson Point Warf location (elevation 8.55m)} 
+ \label{fig:gaugeNelsonPointWarf} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeHelipadstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeHelipadspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Helipad location (elevation 6.83m)} 
+ \label{fig:gaugeHelipad} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeMtGoldworthyWharf-Berthstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeMtGoldworthyWharf-Berthspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Mt Goldworthy Wharf - Berth location (elevation -10.62m)} 
+ \label{fig:gaugeMtGoldworthyWharf-Berth} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeIronOreHoldingsstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeIronOreHoldingsspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Iron Ore Holdings location (elevation 8.93m)} 
+ \label{fig:gaugeIronOreHoldings} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeMiddleChannelstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeMiddleChannelspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Middle Channel location (elevation -8.76m)} 
+ \label{fig:gaugeMiddleChannel} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeGreatNorthernHwy-SolarSaltFarmstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeGreatNorthernHwy-SolarSaltFarmspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Great Northern Hwy - Solar Salt Farm location (elevation 5.32m)} 
+ \label{fig:gaugeGreatNorthernHwy-SolarSaltFarm} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeEstsideSolarSaltFarmstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeEstsideSolarSaltFarmspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Est side Solar Salt Farm location (elevation 4.18m)} 
+ \label{fig:gaugeEstsideSolarSaltFarm} 
+ \end{figure} 
+ 
+\clearpage 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeAirportstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeAirportspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Airport location (elevation 9.26m)} 
+ \label{fig:gaugeAirport} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeLeeheyStreetstage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugeLeeheyStreetspeed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Leehey Street location (elevation 5.90m)} 
+ \label{fig:gaugeLeeheyStreet} 
+ \end{figure} 
+ 
Index: /anuga_work/production/wa/pt_hedland_2006/report/latexoutput_checking.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/latexoutput_checking.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/latexoutput_checking.tex	(revision 7411)
@@ -0,0 +1,384 @@
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint0stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint0speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point0 location (elevation 10.94m)} 
+ \label{fig:gaugePoint0} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint1stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint1speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point1 location (elevation 2.83m)} 
+ \label{fig:gaugePoint1} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint2stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint2speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point2 location (elevation -7.94m)} 
+ \label{fig:gaugePoint2} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint3stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint3speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point3 location (elevation -11.65m)} 
+ \label{fig:gaugePoint3} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint4stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint4speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point4 location (elevation -11.96m)} 
+ \label{fig:gaugePoint4} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint5stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint5speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point5 location (elevation -14.18m)} 
+ \label{fig:gaugePoint5} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint6stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint6speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point6 location (elevation -17.15m)} 
+ \label{fig:gaugePoint6} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint7stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint7speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point7 location (elevation -14.55m)} 
+ \label{fig:gaugePoint7} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint8stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint8speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point8 location (elevation -17.91m)} 
+ \label{fig:gaugePoint8} 
+ \end{figure} 
+ 
+\clearpage 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint9stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint9speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point9 location (elevation -21.80m)} 
+ \label{fig:gaugePoint9} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint10stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint10speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point10 location (elevation -27.49m)} 
+ \label{fig:gaugePoint10} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint11stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint11speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point11 location (elevation -31.82m)} 
+ \label{fig:gaugePoint11} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint12stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint12speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point12 location (elevation -37.31m)} 
+ \label{fig:gaugePoint12} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint13stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint13speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point13 location (elevation -42.23m)} 
+ \label{fig:gaugePoint13} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint14stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint14speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point14 location (elevation -48.99m)} 
+ \label{fig:gaugePoint14} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint15stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint15speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point15 location (elevation -55.14m)} 
+ \label{fig:gaugePoint15} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint16stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint16speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point16 location (elevation -40.02m)} 
+ \label{fig:gaugePoint16} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint17stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint17speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point17 location (elevation -33.67m)} 
+ \label{fig:gaugePoint17} 
+ \end{figure} 
+ 
+\clearpage 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint18stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint18speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point18 location (elevation -21.52m)} 
+ \label{fig:gaugePoint18} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint19stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint19speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point19 location (elevation -20.13m)} 
+ \label{fig:gaugePoint19} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint20stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint20speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point20 location (elevation -4.67m)} 
+ \label{fig:gaugePoint20} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint21stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint21speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point21 location (elevation -44.99m)} 
+ \label{fig:gaugePoint21} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint22stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint22speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point22 location (elevation -39.23m)} 
+ \label{fig:gaugePoint22} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint23stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint23speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point23 location (elevation -36.54m)} 
+ \label{fig:gaugePoint23} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint24stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint24speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point24 location (elevation -31.18m)} 
+ \label{fig:gaugePoint24} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint25stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint25speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point25 location (elevation -27.35m)} 
+ \label{fig:gaugePoint25} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint26stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint26speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point26 location (elevation -25.02m)} 
+ \label{fig:gaugePoint26} 
+ \end{figure} 
+ 
+\clearpage 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint27stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint27speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point27 location (elevation -20.69m)} 
+ \label{fig:gaugePoint27} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint28stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint28speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point28 location (elevation -11.90m)} 
+ \label{fig:gaugePoint28} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint29stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint29speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point29 location (elevation -8.76m)} 
+ \label{fig:gaugePoint29} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint30stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint30speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point30 location (elevation -5.13m)} 
+ \label{fig:gaugePoint30} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint31stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint31speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point31 location (elevation 3.63m)} 
+ \label{fig:gaugePoint31} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint32stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint32speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point32 location (elevation 10.13m)} 
+ \label{fig:gaugePoint32} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint33stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint33speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point33 location (elevation -54.45m)} 
+ \label{fig:gaugePoint33} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint34stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint34speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point34 location (elevation 5.27m)} 
+ \label{fig:gaugePoint34} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint35stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint35speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point35 location (elevation 4.39m)} 
+ \label{fig:gaugePoint35} 
+ \end{figure} 
+ 
+\clearpage 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint36stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint36speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point36 location (elevation 5.19m)} 
+ \label{fig:gaugePoint36} 
+ \end{figure} 
+ 
+\begin{figure}[hbt] 
+ \centering 
+ \begin{tabular}{cc} 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint37stage.png}& 
+\includegraphics[width=0.49\linewidth, height=50mm]{../report_figures/gaugePoint37speed.png}\\ 
+\end{tabular} 
+ \caption{Time series for stage and speed at Point37 location (elevation 9.96m)} 
+ \label{fig:gaugePoint37} 
+ \end{figure} 
+ 
Index: /anuga_work/production/wa/pt_hedland_2006/report/metadata.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/metadata.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/metadata.tex	(revision 7411)
@@ -0,0 +1,1 @@
+%\includepdf[pages={1-6}]{MetadataforATWSPortHedlandScenario}
Index: /anuga_work/production/wa/pt_hedland_2006/report/modelling_methodology.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/modelling_methodology.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/modelling_methodology.tex	(revision 7411)
@@ -0,0 +1,115 @@
+Geoscience Australia aims to define the economic and social threat posed to urban communities 
+by a range of rapid onset natural hazards. Through the integration of natural hazard research, defining national exposure and 
+estimating socio-economic vulnerabilities, predictions of the likely impacts of events can be made. 
+Hazards include earthquakes, landslides, tsunami, severe winds and cyclones.
+
+By modelling the likely impacts on urban communities as accurately as possible and
+building these estimates into land use planning and emergency
+management, communities will be better prepared to respond to
+natural disasters when they occur.
+
+
+%GA bases its risk modelling on the process of understanding the hazard and a community's 
+%vulnerability in order to determine the impact of a particular hazard event. 
+%The resultant risk relies on an assessment of the likelihood of the event. 
+%An overall risk assessment for a particular hazard would then rely on scaling 
+%each event's impact by its likelihood.
+
+To develop a tsunami risk assessment, 
+the tsunami hazard itself must first be understood. These events are generally modelled by converting
+the energy released by a subduction earthquake into a vertical displacement of the ocean surface. 
+%Tsunami hazard models have been available for some time. 
+The resulting wave is
+then propagated across a sometimes vast stretch of ocean towards the
+area of interest. 
+%using a relatively coarse model 
+%based on bathymetries with a typical resolution of two arc minutes.
+The hazard itself is then reported as a maximum wave height at a fixed contour line near the coastline, 
+(e.g. 50m). This is how the preliminary tsunami hazard assessment was reported by GA 
+to FESA in September 2005 \cite{BC:FESA}. The assessment used the Method of Splitting Tsunamis (MOST)
+\cite{VT:MOST} model. 
+%The maximal wave height at a fixed contour line near the coastline
+%(e.g. 50m) is then reported as the hazard to communities ashore. 
+%Models such as Method of Splitting Tsunamis (MOST) \cite{VT:MOST} and the 
+%URS Corporation's
+%Probabilistic Tsunami Hazard Analysis  
+%\cite{somerville:urs} follow this paradigm.
+
+While MOST is suitable for generating and propagating the tsunami wave from its source, it is not adequate to
+model the wave's impact on communities ashore.  
+To capture the \emph{impact} of a tsunami to a coastal community, 
+the model must be capable of capturing more detail about the wave, 
+particularly how it is affected by the local bathymetry, as well as the 
+local topography as the wave moves onshore. 
+%the details of how waves are reflected and otherwise 
+%shaped by the local bathymetries as well as the dynamics of the 
+%runup process onto the topography in question.
+It is well known that local bathymetric and topographic effects are 
+critical in determining the severity of a hydrological disaster 
+\cite{matsuyama:1999}. To model the impact of the tsunami wave on the 
+coastal community, we use ANUGA \cite{ON:modsim}. In order to capture the 
+details of the wave and its interactions, a much finer resolution is 
+required than that of the hazard model. As a result, ANUGA simulations concentrate 
+on specific coastal communities. MOST by contrast uses a 
+coarser resolution and covers often vast areas. To develop the impact 
+from an earthquake event from a distant source, we adopt a hybrid approach of 
+modelling the event itself with MOST and modelling the impact with ANUGA. 
+In this way, the output from MOST serves as an input to ANUGA. 
+In modelling terms, the MOST output is a boundary condition for ANUGA.
+
+\bigskip %FIXME (Ole): Should this be a subsection even? 
+The risk of the scenario tsunami event cannot be determined until the 
+likelihood of the event is known. GA is currently building a 
+complete probabilistic hazard map which is due for completion 
+in late 2006. We therefore report on the impact of a single 
+tsunami event only. When the hazard map is completed, the impact 
+will be assessed for a range of events which will ultimately 
+determine a tsunami risk assessment for the NW shelf.
+%To model the
+%details of tsunami inundation of a community one must therefore capture %what is 
+%known as non-linear effects and use a much higher resolution for the 
+%elevation data. 
+%Linear models typically use data resolutions of the order
+%of hundreds of metres, which is sufficient to model the tsunami waves
+%in deeper water where the wavelength is longer. 
+%Non-linear models however require much finer resolution in order to %capture
+%the complexity associated with the water flow from offshore 
+%to onshore. By contrast, the data
+%resolution required is typically of the order of tens of metres.
+%The model ANUGA \cite{ON:modsim} is suitable for this type of non-linear
+%modelling.
+%Using a non-linear model capable of resolving local bathymetric effects 
+%and runup using detailed elevation data will require more computational 
+%resources than the typical hazard model making it infeasible to use it 
+%for the entire, end-to-end, modelling. 
+
+%We have adopted a hybrid approach whereby the output from the  
+%hazard model MOST is used as input to ANUGA at the seaward boundary of its %study area. 
+%In other words, the output of MOST serves as boundary condition for the 
+%ANUGA model. In this way, we restrict the computationally intensive part %only to 
+%regions where we are interested in the detailed inundation process.  
+
+%Furthermore, to avoid unnecessary computations ANUGA works with an 
+%unstructured triangular mesh rather than the rectangular grids 
+%used by e.g.\ MOST. The advantage of an unstructured mesh 
+%is that different regions can have different resolutions allowing 
+%computational resources to be directed where they are most needed. 
+%For example, one might use very high resolution near a community 
+%or in an estuary, whereas a coarser resolution may be sufficient 
+%in deeper water where the bathymetric effects are less pronounced. 
+%Figure \ref{fig:refinedmesh} shows a mesh of variable resolution.
+
+%\begin{figure}[hbt]
+%
+%  \centerline{ \includegraphics[width=100mm, height=75mm]
+%             {../report_figures/refined_mesh.jpg}}
+%
+%  \caption{Unstructured mesh with variable resolution.}
+%  \label{fig:refinedmesh}
+%\end{figure}
+   
+
+
+
+ 
+
Index: /anuga_work/production/wa/pt_hedland_2006/report/pt_hedland_2006_report.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/pt_hedland_2006_report.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/pt_hedland_2006_report.tex	(revision 7411)
@@ -0,0 +1,157 @@
+
+% This is based on an automatically generated file (by make_report.py).
+%
+% Manual parts are:
+% * an abstract must be written in abstract.tex
+% * an introduction must be written in introduction.tex; a basic outline and
+%   some of the core inputs are already in place
+% * outline of the modelling methodology provided in modelling_methodology.tex
+% * the tsunami-genic event should be discussed in tsunami_scenario.tex
+% * an computational_setup.tex file needs to be written for the particular scenario
+% * the interpretation of the results needs to be written to interpretation.tex
+% * maximum inundation maps need to be included in HAT_map.tex and LAT_map.tex etc.
+% * damage modelling maps need to be included in HAT_damage and LAT_damage etc.
+% * a summary must be written into summary.tex
+% * metadata for the scenario data to be included in metadata.tex
+
+\documentclass{article}
+
+\usepackage{ae} % or {zefonts}
+\usepackage[T1]{fontenc}
+\usepackage[ansinew]{inputenc}
+\usepackage{amsmath}
+\usepackage{amssymb}
+\usepackage{graphicx}
+\usepackage{color}
+\usepackage[colorlinks]{hyperref}
+\usepackage{lscape} %landcape pages support
+\usepackage{setspace}
+\usepackage{rotating}
+\include{appendix}
+\setstretch{1.25}
+\topmargin 0pt
+\oddsidemargin 0pt
+\evensidemargin 0pt
+\marginparwidth 0.5pt
+\textwidth \paperwidth
+\advance\textwidth -2in
+
+
+\date{\today}
+%\author{Geoscience Australia}
+
+\begin{document}
+\title{
+\begin{figure}[hbt]
+  \centerline{ \includegraphics[scale=0.4]{../report_figures/GAlogo.jpg}}
+\end{figure}
+Tsunami impact modelling for the North West shelf: Pt Hedland} 
+  \maketitle
+
+    \section{Executive Summary}
+    \label{sec:execsum}
+  \input{execsum}
+
+  \tableofcontents
+  
+  \section{Introduction}
+    \label{sec:intro}
+  \input{introduction}
+
+   \section{Modelling methodology}
+    \label{sec:methodology}
+    \input{modelling_methodology}
+    
+  \section{Tsunami scenarios}
+    \label{sec:tsunamiscenario}
+    \input{tsunami_scenario}
+
+  \section{Data sources}
+    \label{sec:data}
+    \input{data}
+    
+   \section{Inundation model}
+    \label{sec:anuga}
+    \input{anuga}
+    \input{computational_setup}
+        
+  \section{Inundation modelling results}
+     \label{sec:results}
+         
+\begin{table} \begin{center} 
+\caption{Defined point locations for pt hedland study area.}
+\label{table:locations}
+\begin{tabular}{|l|l|l|l|}\hline
+\bf{Point Name} & \bf{Easting} & \bf{Northing} & \bf{Elevation}\\ \hline
+Hospital & 665984.49 & 7753480.95 & 14.56 \\ \hline 
+Effluent Water Ponds & 669402.20 & 7753721.98 & 5.13 \\ \hline 
+Tjalka Boorda Aboriginal Reserve & 669503.41 & 7753060.33 & 5.79 \\ \hline 
+Water Tanks & 669192.19 & 7752993.28 & 5.65 \\ \hline 
+Primary School & 670569.79 & 7754095.55 & 11.59 \\ \hline 
+Lacey Street & 670001.65 & 7754381.77 & 11.26 \\ \hline 
+Council Offices & 668403.96 & 7753665.67 & 13.81 \\ \hline 
+Richardson Street & 664865.60 & 7753496.96 & 8.94 \\ \hline 
+Tug Harbour & 664235.06 & 7753146.51 & -16.01 \\ \hline 
+No 1 Warf & 664223.98 & 7752869.02 & 6.63 \\ \hline 
+No 3 Warf & 664404.42 & 7752566.13 & 7.84 \\ \hline 
+Nelson Point Warf & 664801.12 & 7752365.82 & 8.55 \\ \hline 
+Helipad & 664518.41 & 7752877.95 & 6.83 \\ \hline 
+Mt Goldworthy Wharf - Berth & 664009.66 & 7753659.72 & -10.62 \\ \hline 
+Iron Ore Holdings & 662935.31 & 7754244.86 & 8.93 \\ \hline 
+Middle Channel & 665022.31 & 7754470.36 & -8.76 \\ \hline 
+Great Northern Hwy - Solar Salt Farm & 670773.09 & 7751099.43 & 5.32 \\ \hline 
+Est side Solar Salt Farm & 673193.31 & 7751012.09 & 4.18 \\ \hline 
+Airport & 670188.16 & 7745738.57 & 9.26 \\ \hline 
+Leehey Street & 665530.50 & 7747096.77 & 5.90 \\ \hline 
+\end{tabular} 
+  \end{center} 
+ \end{table} 
+ 
+\begin{sidewaysfigure} 
+ \centerline{ \includegraphics[width=\paperwidth]{../report_figures/pt_hedland_gauge.jpg}}
+\caption{Point locations used for Port Hedland study.}  
+\label{fig:points}
+\end{sidewaysfigure}
+\input{interpretation} 
+\input{LAT_map} 
+ \clearpage 
+ 
+\input{MSL_map} 
+ \clearpage 
+ 
+\input{HAT_map} 
+ \clearpage 
+ 
+
+   \section{Impact modelling}
+    \label{sec:impact}
+     \input{damage}
+
+     \section{Summary}
+     \label{sec:summary}
+     \input{summary}
+     
+    \input{references}
+
+    \appendix
+    
+   \section{Metadata}
+     \label{sec:metadata}
+     \input{metadata}
+
+\pagebreak
+
+   \section{Time series}
+     \label{sec:timeseries}
+\input{latexoutput} 
+ \clearpage 
+ 
+
+
+\pagebreak
+
+   \section{Damage modelling inputs}
+     \label{sec:damageinputs}
+     \input{damage_inputs}
+
+\end{document}
Index: /anuga_work/production/wa/pt_hedland_2006/report/references.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/references.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/references.tex	(revision 7411)
@@ -0,0 +1,54 @@
+\begin{thebibliography}{99}
+
+\bibitem{CB:ausgeo} Cummins, P. and Burbidge, D. (2004) 
+Small threat, but warning sounded for tsunami research. AusGeo News 75, 4-7.
+
+\bibitem{BC:FESA} Burbidge, D. and Cummins, P. (2005) Preliminary Tsuanmi 
+Hazard Assesment of Western Australia. Report 
+to the Fire and Emergency Services Authority of Western Australia.
+
+\bibitem{VT:MOST} Titov, V.V., and F.I. Gonzalez (1997)
+Implementation and testing of the Method of Splitting 
+Tsunami (MOST) model, NOAA Technical Memorandum ERL PMEL-112.
+
+\bibitem{prob:fesa} Burbidge, D. and Cummins, P. (2006) Probabilistic
+Tsunami Hazard Assessment of Western Australia. Report to the 
+Fire and Emergency Services Authority of Western Australia.
+
+\bibitem{somerville:urs} Somerville, P., Thio, H.K. and Ichinose, G. (2005)
+Probabilistic Tsunami Hazard Analysis. Report delivered to Geoscience
+Australia 2005.
+
+\bibitem{matsuyama:1999}
+Matsuyama, M., Walsh, J.P. and Yeh, H. (1999) 
+The effect of bathymetry on tsunami characteristics at 
+Sisano Lagoon, Papua New Guinea. 
+Geophysical Research Letters, 26, 23, 3513-3516.
+
+\bibitem{ON:modsim} Nielsen, O., Roberts, Gray, D., McPherson, A. and 
+Hitchman, A (2005) 
+Hydrodynamic modelling of coastal inundation, MODSIM 2005 International 
+Congress on Modelling and Simulation.
+Modelling and Simulation Society of Australian and New Zealand, 518-523,
+URL: http://www.mssanz.org.au/modsim05/papers/nielsen.pdf
+
+\bibitem{antt:06} Australian National Tide Tables 2006:
+Australia, Papua New Guinea, Solomon Islands and Antarctica and East Timor.
+Australian Hydrographic Publication 11, Australian Hydrographic Service.
+
+\bibitem{papathoma:vulnerability} 
+Papathoma, M. and Dominey-Howes, D. (2003) 
+Tsunami vulnerability assessment and its implications for coastal hazard 
+analysis and disaster management planning, Gulf of Corinth, Greece, 
+Natural Hazards and Earth System Sciences, 3, 733-747.
+
+\bibitem{cooper:2005}
+Cooper, D. (2005) Risk Research Group Personal Communication at NSW Tsunami 
+Workshop 12th and 13th April, Masonic Centre, Goulburn St, Sydney.
+
+\bibitem{NIBS:2003} National Institute of Building Sciences (2003) 
+HAZUS-MH User Manual, Washington DC, USA.
+
+\bibitem{uq:friction} Duncan - do you have a reference for this?
+
+\end{thebibliography}
Index: /anuga_work/production/wa/pt_hedland_2006/report/summary.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/summary.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/summary.tex	(revision 7411)
@@ -0,0 +1,37 @@
+This report has described the impact to Port Hedland from a tsunami
+generated by a Mw 9 earthquake on the Sunda Arc subduction zone 
+occurring at Highest Astronomical Tide, Lowest Astronomical Tide
+and Mean Sea Level. 
+As yet, there is no knowledge of the return period for this event. The
+modelling methodology, assumptions and data sources for the Port Hedland 
+scenario have also been described. 
+
+As shown in Section \ref{sec:data}, it is imperative
+that the best available data is used to increase confidence
+in the inundation maps. 
+Given that the Highest Astronomical Tide contour
+line is further from the coast for the DTED data than the DLI data, we
+expect the inundation to extend further and thus be greater than
+that seen in Figure \ref{fig:MSL_max_inundation}. 
+The impact modelling
+will result in significantly inflated structural and contents loss figures as well as
+numbers of people affected.
+These results strongly point to the need for the best 
+available data so that more accurate predictions regarding the 
+inundation can be made.
+An onshore grid resolution of the order
+of tens of metres is required, however, it is more important that the data
+are accurate (or at least well known).
+
+These scenarios will be revisited once the probabilistic models
+are complete so that a suite of tsunami impact assessments can be made.
+Future activities to support the impact studies on the North West Shelf
+include:
+
+\begin{itemize}
+\item Sourcing of data sets,
+\item Investigation of solution sensitivity to cell resolution,
+bathymetry and tsunami source uncertainties,
+\item Location of boundary for simulation study area, and
+\item Investigation of friction coefficients.
+\end{itemize}
Index: /anuga_work/production/wa/pt_hedland_2006/report/timeseriesdiscussion.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/timeseriesdiscussion.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/timeseriesdiscussion.tex	(revision 7411)
@@ -0,0 +1,92 @@
+It is assumed that the earthquake is
+generated at the beginning of the simulation, i.e. time = 0 minutes.
+Stage is defined as the absolute
+water level (in metres) relative to AHD 
+\footnote{For an offshore location such as Middle Channel,
+the initial water level will be that of the tidal scenario. In the 
+case of MSL, this water level will be 0. As the tsunami wave moves
+through this point, the water height may grow and thus the stage will 
+represent the amplitude of the wave.} For an onshore location such as the 
+Hospital, the actual water depth will be shown rather than the stage. 
+Both stage and speed (in metres/second) for
+each scenario (HAT, MSL and LAT) are shown
+on consistent scales to allow comparison between point locations.
+As a useful benchmark, Table \ref{table:speedexamples}
+describes typical examples for a range of speeds found in the 
+simulations. 
+
+\begin{table}[h]
+\label{table:speedexamples}
+\caption{Examples of a range of velocities.}
+\begin{center}
+\begin{tabular}{|l|l|}\hline
+{\bf Velocity (m/s)} & {\bf Example} \\ \hline
+1 & leisurely stroll pace\\ \hline
+1.5 & average walking pace \\ \hline
+%2 & 100m Olympic male freestyle \\ \hline
+%3 & mackeral \\ \hline
+4 & average person can maintain running for 1000m \\ \hline
+%5 & blue whale \\ \hline
+10 & 100m Olympic male sprinter \\ \hline
+16 & car travelling in urban zones (60 km/hr) \\ \hline
+\end{tabular}
+\end{center}
+\end{table}
+
+A tsunami wave typically has a small amplitude and typically travels at 
+100's of kilometres per hour. 
+The low amplitude complicates the ability to detect
+the wave. As the water depth decreases, 
+the speed of the wave 
+decreases and the amplitude grows. Another important feature of tsunamis 
+is drawdown. This means that the water is seen to retreat from the beaches
+before a tsunami wave 
+impacts that location. Other features 
+include reflections (where the wave is redirected due to the 
+influence 
+of the coast) and shoaling (where the wave's amplitude is amplified
+close to the coast due to wave interactions).
+These features are seen in the MSL scenario; 
+there is a small wave, followed
+by a large drawdown and then a large secondary wave.
+There are variations in the behaviour for the
+HAT and LAT scenarios, and these will be explained below.
+ 
+The features described above will be 
+illustrated for the MSL case by the Middel Channel location,
+Figure \ref{fig:gaugeMiddleChannel}.
+The first, small wave can be seen at around 230 mins (shown in red),
+with an amplitude of around 0.3 m\footnote{In this
+scenario, the initial water level is 0 m, which means that
+the actual amplitude is the difference between the stage value
+and the initial water level; 0.3 - 0}.
+The drawdown of around 2.6 m (i.e. 0.27 - -2.37) then occurs at around 270 mins
+(i.e. 4.5 hours after the event has been generated), before
+the second wave arrives at around 280 mins
+with an amplitude of around 1.8 m (i.e. 1.8 - 0). Subsequent waves
+are evident with decreased amplitudes.
+These features are replicated at each of the offshore points (those
+points with negative elevation as shown in Table \ref{table:locations}).
+The speed of the tsunami wave is greatest for those locations
+in shallowest water. Middle Channel is in shallower water
+than Mt Goldworthy Wharf - Berth
+and the maximum speeds measured are 1.93 m/s and 2.9 m/s respectively.
+
+There are variations in these behaviours for the HAT and LAT scenarios.
+Referring again to the Middle Channel location (Figure 
+\ref{fig:gaugeMiddleChannel}),
+
+{\bf stuff to write in here about the HAT, LAT scenarios }
+
+
+The tsunami wave has an amplitude of around 0.3 m for the MSL
+scenario as it enters the 
+channel (Figure \ref{fig:gaugeMiddleChannel}. There seems to be
+limited or no amplification of the tsunami wave as it moves into
+the channel. The amplitude of the first tsunami wave is around 0.3 m at
+the Mt Goldworthy Wharf - Berth location (shown in red in Figure 
+\ref{fig:gaugeMtGoldworthyWharf-Berth} and the maximum amplitude
+is around 1.7 m. At MSL and LAT, there is limited inundation in the
+areas surrounding the channel. At HAT, significantly increased
+inundation is evident surrounding the channel, however, this inundation
+is essentially caught in the tidal flat regions.
Index: /anuga_work/production/wa/pt_hedland_2006/report/tsunami_scenario.tex
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/report/tsunami_scenario.tex	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/report/tsunami_scenario.tex	(revision 7411)
@@ -0,0 +1,1 @@
+
Index: /anuga_work/production/wa/pt_hedland_2006/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/run_boundary_points.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/run_boundary_points.py	(revision 7411)
@@ -0,0 +1,35 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+
+# # Related major packages
+# from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import URS_points_needed_to_file, \
+     urs_ungridded2sww
+import project                 # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+poly = project.polyAll
+print "poly", poly
+print "project.boundaries",project.boundarydir
+URS_points_needed_to_file(project.boundarydir,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True, zone=50)
+#URS_points_needed_to_file(project.boundaries_dir_name5,poly, export_csv=True)
+#urs_ungridded2sww(project.boundaries_in_dir_name2, project.boundaries_dir_name5, mean_stage= project.tide,  verbose=True)
Index: /anuga_work/production/wa/pt_hedland_2006/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/run_building_inundation.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/run_building_inundation.py	(revision 7411)
@@ -0,0 +1,42 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+import project_urs
+
+# Inputs
+
+#timestamp_dir = '20070518_020117_run_final_3.6_nbartzis' # HAT 1 in Dampier 10000 yr
+#timestamp_dir = '20070520_225029_run_final_0.0_nbartzis' # MSL 1 in Dampier 10000 yr
+timestamp_dir = '20070613_061053_run_final_3.6_onslow_nbartzis' # HAT 1 in Onslow 10000 yr
+#timestamp_dir = '20070613_061125_run_final_0.0_onslow_nbartzis' # MSL 1 in Onslow 10000 yr
+#timestamp_dir = '20070613_044204_run_final_3.6_exmouth_nbartzis' # HAT 1 in Exmouth 10000 yr
+#timestamp_dir = '20070613_225854_run_final_0.0_exmouth_nbartzis' # MSL 1 in Exmouth 10000 yr
+
+file_loc = project_urs.output_dir + timestamp_dir + sep 
+swwfile = file_loc + project_urs.scenario_name #+ '.sww'
+buildings_filename = project_urs.buildings_filename
+buildings_filename_out = file_loc + project_urs.buildings_filename_out
+
+#add_depth_and_momentum2csv(swwfile, buildings_filename, buildings_filename_out)
+inundation_damage(swwfile, buildings_filename, buildings_filename_out)
+
+print '\n Augmented building file written to %s \n' \
+      %buildings_filename_out
Index: /anuga_work/production/wa/pt_hedland_2006/run_damage.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/run_damage.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/run_damage.py	(revision 7411)
@@ -0,0 +1,37 @@
+""" Script for calculating maximum inundation at building locations
+
+    Inputs:
+
+    swwfile             - name of sww file
+                        - assume that all conserved quantities have been stored
+                    
+    buildings_filename  - name of file containing building data, sourced
+                          from NBED
+
+    Output:
+    
+    - building_filename (.csv) augmented to include maximum depth, momentum and
+      velocity and stored in same location as swwfile
+      Name = augmented_buildings.csv
+      
+    """
+
+from os import sep
+
+from damage.inundation_damage import inundation_damage
+import project
+
+# Inputs
+timestampdir = '20060707_003301' # HAT
+#timestampdir = '20060704_063112' # LAT
+#timestampdir = '20060704_063234' # MSL
+file_loc = project.outputdir + timestampdir + sep 
+swwfile = file_loc + project.basename + '.sww'
+buildings_filename = project.buildings_filename
+buildings_filename_out = file_loc + project.buildings_filename_damage_out
+
+inundation_damage(swwfile, buildings_filename, timestampdir+"_damage.csv")
+
+
+print '\n Augmented building file written to %s \n' \
+      %buildings_filename_out
Index: /anuga_work/production/wa/pt_hedland_2006/run_pt_hedland.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/run_pt_hedland.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/run_pt_hedland.py	(revision 7411)
@@ -0,0 +1,280 @@
+"""Script for running a tsunami inundation scenario for Onslow, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.outputtimedir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a tsunami generated by a subduction zone earthquake.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Nick Bartzis, GA - 2006
+"""
+#-------------------------------------------------------------------------------# Import necessary modules
+#-------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+import time
+
+# Related major packages
+from anuga.shallow_water import Domain, Reflective_boundary, \
+                            Dirichlet_boundary, Time_boundary, File_boundary
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, \
+     dem2pts
+from anuga.abstract_2d_finite_volumes.combine_pts import combine_rectangular_points_files 
+from shutil import copy
+from os import mkdir, access, F_OK
+from anuga.geospatial_data.geospatial_data import *
+import sys
+from anuga.abstract_2d_finite_volumes.util import start_screen_catcher, copy_code_files
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.outputtimedir,__file__,dirname(project.__file__)+sep+ project.__name__+'.py' )
+myid = 0
+numprocs = 1
+start_screen_catcher(project.outputtimedir, myid, numprocs)
+
+print 'USER:    ', project.user
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+
+# filenames
+meshname = project.meshname+'.msh'
+source_dir = project.boundarydir
+
+# fine data (clipping the points file to smaller area)
+# creates DEM from asc data 
+convert_dem_from_ascii2netcdf(project.onshore_dem_name, use_cache=True, verbose=True)
+
+#creates pts file from DEM
+dem2pts(project.onshore_dem_name,
+        easting_min=project.eastingmin,
+        easting_max=project.eastingmax,
+        northing_min=project.northingmin,
+        northing_max= project.northingmax,
+        use_cache=True,
+        verbose=True)
+
+print 'create offshore'
+G11= Geospatial_data(file_name = project.offshore_dem_name0 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name1 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name2 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name3 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name4 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name5 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name6 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name7 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name8 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name9 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name10 + '.xya')
+G12= Geospatial_data(file_name = project.offshore_dem_name11 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name12 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name13 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name14 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name15 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name16 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name17 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name18 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name19 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name20 + '.xya')
+G13= Geospatial_data(file_name = project.offshore_dem_name21 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name22 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name23 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name24 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name25 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name26 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name27 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name28 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name29 + '.xya')
+G14= Geospatial_data(file_name = project.offshore_dem_name30 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name31 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name32 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name33 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name34 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name35 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name36 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name37 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name38 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name39 + '.xya')
+G15= Geospatial_data(file_name = project.offshore_dem_name40 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name41 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name42 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name43 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name44 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name45 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name46 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name47 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name48 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name49 + '.xya')+\
+     Geospatial_data(file_name = project.offshore_dem_name50 + '.xya')
+   
+print 'create onshore'
+G2 = Geospatial_data(file_name = project.onshore_dem_name + '.pts')
+print 'create coast'
+G3 = Geospatial_data(file_name = project.coast_dem_name + '.xya')
+print 'add'
+G = G11 + G12 + G13 + G14 + G15 + G2 + G3
+print 'export G'
+G.export_points_file(project.combined_dem_name + '.pts')
+
+#-------------------------------------------------------------------------------                                 
+# Create the triangular mesh based on overall clipping polygon with a tagged
+# boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+
+region_res = 500000
+coast_res = 500
+pt_hedland_res = 5000
+interior_regions = [[project.poly_pt_hedland, pt_hedland_res],
+                    [project.poly_region, region_res]]
+
+print 'number of interior regions', len(interior_regions)
+
+from anuga.utilities.polygon import plot_polygons
+if sys.platform == 'win32':
+    #figname = project.outputtimedir + 'pt_hedland_polys'
+    figname = 'pt_hedland_polys_test'
+    plot_polygons([project.polyAll,project.poly_pt_hedland,project.poly_region],
+              figname,
+              verbose = True)    
+
+print 'start create mesh from regions'
+from caching import cache
+_ = cache(create_mesh_from_regions,
+          project.polyAll,
+          {'boundary_tags': {'topright': [0], 'topleft': [1],
+                             'left': [2], 'bottom0': [3],
+                             'bottom1': [4], 'bottom2': [5],
+			     'bottom3': [6], 'right': [7]},
+           'maximum_triangle_area': 250000,
+           'filename': meshname,           
+           'interior_regions': interior_regions},
+          verbose = True, evaluate=True)
+
+#-------------------------------------------------------------------------------                                 
+# Setup computational domain
+#-------------------------------------------------------------------------------                                 
+domain = Domain(meshname, use_cache = False, verbose = True)
+
+print domain.statistics()
+print 'Number of triangles = ', len(domain)
+print 'The extent is ', domain.get_extent()
+print domain.statistics()
+
+domain.set_name(project.basename)
+domain.set_datadir(project.outputtimedir)
+domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+
+#-------------------------------------------------------------------------------                                 
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+tide = 0.
+#high
+#tide = 3.6
+#low
+#tide = -3.9
+
+domain.set_quantity('stage', tide)
+domain.set_quantity('friction', 0.0) 
+print 'hi and file',project.combined_dem_name + '.pts'
+
+domain.set_quantity('elevation', 
+                    filename = project.combined_dem_name + '.pts',
+                    use_cache = True,
+                    verbose = True,
+                    alpha = 0.1
+                    )
+
+#-------------------------------------------------------------------------------                                 
+# Setup boundary conditions (all reflective)
+#-------------------------------------------------------------------------------
+print 'start ferret2sww'
+# skipped as results in file SU-AU_clipped is correct for all WA
+
+from anuga.pyvolution.data_manager import ferret2sww
+
+south = project.south 
+north = project.north
+west = project.west
+east = project.east
+
+#note only need to do when an SWW file for the MOST boundary doesn't exist
+cache(ferret2sww,
+      (source_dir + project.boundary_basename,
+       source_dir + project.boundary_basename+'_'+project.basename), 
+      {'verbose': True,
+       'minlat': south,
+       'maxlat': north,
+       'minlon': west,
+       'maxlon': east,
+#       'origin': project.mesh_origin,
+       'origin': domain.geo_reference.get_origin(),
+       'mean_stage': tide,
+       'zscale': 1,                 #Enhance tsunami
+       'fail_on_NaN': False,
+       'inverted_bathymetry': True},
+       evaluate = True,
+       verbose = True,
+      dependencies = source_dir + project.boundary_basename + '.sww')
+
+print 'Available boundary tags', domain.get_boundary_tags()
+
+Bf = File_boundary(source_dir + project.boundary_basename + '.sww', 
+                    domain, verbose = True)
+Br = Reflective_boundary(domain)
+Bd = Dirichlet_boundary([tide,0,0])
+domain.set_boundary( {'topright': Bf,'topleft': Bf, 'left':  Bd, 'bottom0': Bd,
+                      'bottom1': Bd, 'bottom2': Bd, 'bottom3': Bd, 
+			'right': Bd})
+
+#-------------------------------------------------------------------------------                                 
+# Evolve system through time
+#-------------------------------------------------------------------------------
+import time
+t0 = time.time()
+
+for t in domain.evolve(yieldstep = 240, finaltime = 10800): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'topright')     
+
+for t in domain.evolve(yieldstep = 120, finaltime = 16200
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'topright')     
+
+for t in domain.evolve(yieldstep = 60, finaltime = 21600
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'topright')     
+    
+for t in domain.evolve(yieldstep = 120, finaltime = 27000
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'topright')     
+
+for t in domain.evolve(yieldstep = 240, finaltime = 36000
+                       ,skip_initial_step = True): 
+    domain.write_time()
+    domain.write_boundary_statistics(tags = 'topright')   
+  
+print 'That took %.2f seconds' %(time.time()-t0)
+
+print 'finished'
Index: /anuga_work/production/wa/pt_hedland_2006/run_pt_hedland_urs.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/run_pt_hedland_urs.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/run_pt_hedland_urs.py	(revision 7411)
@@ -0,0 +1,287 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project_urs.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep,umask
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+from anuga.shallow_water.data_manager import export_grid
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher, copy_code_files,store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+from anuga.damage_modelling.inundation_damage import add_depth_and_momentum2csv, inundation_damage
+from anuga.fit_interpolate.benchmark_least_squares import mem_usage 
+# Application specific imports
+import project_urs                 # Definition of file names and polygons
+
+def run_model(**kwargs):
+    
+    print 'tide',kwargs['tide']
+#    kwargs['est_num_trigs']=project_urs.trigs_min
+#    kwargs['num_cpu']=numprocs
+#    kwargs['host']=project_urs.host
+#    kwargs['res_factor']=project_urs.res_factor
+#    kwargs['starttime']=project_urs.starttime
+#    kwargs['yieldstep']=project_urs.yieldstep
+#    kwargs['finaltime']=project_urs.finaltime
+#    
+#    kwargs['output_dir']=project_urs.output_run_time_dir
+#    kwargs['bathy_file']=project_urs.combined_dir_name + '.pts'
+#    kwargs['boundary_file']=project_urs.boundaries_in_dir_name + '.sww'
+
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+
+    print 'output_dir',kwargs['output_dir']
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                 dirname(project_urs.__file__)+sep+ project_urs.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+    
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+    
+
+    print "Processor Name:",get_processor_name()
+
+    # creates copy of code in output dir
+    print 'min triangles', project_urs.trigs_min,
+    print 'Note: This is generally about 20% less than the final amount'
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project_urs.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    #IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+    if myid == 0:
+    
+        print 'start create mesh from regions'
+
+        create_mesh_from_regions(project_urs.poly_all,
+                             boundary_tags={'back': [3, 4, 5, 6], 'side': [2, 7],
+                                            'ocean': [0, 1]},
+                             maximum_triangle_area=project_urs.res_poly_all,
+                             interior_regions=project_urs.interior_regions,
+                             filename=project_urs.meshes_dir_name+'.msh',
+                             use_cache=False,
+                             verbose=True)
+    barrier()
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    #domain = cache(Domain, (meshes_dir_name), {'use_cache':True, 'verbose':True}, verbose=True)
+    #above don't work
+    domain = Domain(project_urs.meshes_dir_name+'.msh', use_cache=False, verbose=True)
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    if myid == 0:
+
+        print 'Setup initial conditions'
+
+        from polygon import Polygon_function
+        #following sets the stage/water to be offcoast only
+        #IC = Polygon_function( [(project_urs.poly_mainland, -50.0)], default = kwargs['tide'],
+        #                         geo_reference = domain.geo_reference)
+        #domain.set_quantity('stage', IC)
+        domain.set_quantity('stage', kwargs['tide'])
+        domain.set_quantity('friction', kwargs['friction']) 
+        
+        print 'Start Set quantity', kwargs['bathy_file'],kwargs['alpha']
+        
+        domain.set_quantity('elevation', 
+                            filename = kwargs['bathy_file'],
+                            use_cache = True,
+                            verbose = True,
+                            alpha = kwargs['alpha'])
+        print 'Finished Set quantity'
+    barrier()
+
+    #------------------------------------------------------
+    # Distribute domain to implement parallelism !!!
+    #------------------------------------------------------
+
+    if numprocs > 1:
+        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(kwargs['aa_scenario_name'])
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2) # Apply second order scheme
+    domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+    #print 'Reading Boundary file',project_urs.boundaries_dir_namea + '.sww'
+
+    Bf = Field_boundary(kwargs['boundary_file'],
+                    domain, time_thinning=kwargs['time_thinning'], mean_stage=kwargs['tide'], 
+                    use_cache=True, verbose=True)
+                    
+    kwargs['input_start_time']=domain.starttime
+
+    print 'finished reading boundary file'
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([kwargs['tide'],0,0])
+
+    print'set_boundary'
+
+    domain.set_boundary({'back': Br,
+                         'side': Bd,
+                         'ocean': Bf}) 
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #----------------------------------------------------------------------------
+
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['starttime']): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+
+    for t in domain.evolve(yieldstep = kwargs['yieldstep'], finaltime = 21600
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+    
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')   
+
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'That took %.2f seconds' %(time.time()-t0)
+    
+    kwargs['completed']=str(time.time()-t0)
+    
+    if myid == 0:
+        store_parameters(**kwargs)
+        
+        print 'memory usage before del domain',mem_usage()
+        del domain
+        print 'memory usage after del domain',mem_usage()
+    
+        swwfile = kwargs['output_dir']+kwargs['aa_scenario_name']
+        print'swwfile',swwfile
+
+        export_grid(swwfile, extra_name_out = 'town',
+                    quantities = ['speed','depth','stage','elevation'], # '(xmomentum**2 + ymomentum**2)**0.5' defaults to elevation
+                    timestep = None,
+                    reduction = max,
+                    cellsize = 25,
+                    NODATA_value = -9999,
+                    easting_min = project_urs.eastingmin,
+                    easting_max = project_urs.eastingmax,
+                    northing_min = project_urs.northingmin,
+                    northing_max = project_urs.northingmax,
+                    verbose = True,
+                    origin = None,
+                    datum = 'WGS84',
+                    format = 'asc')
+        
+        buildings_filename = project_urs.buildings_filename
+        buildings_filename_out = project_urs.buildings_filename_out
+                    
+        inundation_damage(swwfile+'.sww', buildings_filename, buildings_filename_out)
+        print '\n Augmented building file written to %s \n' %buildings_filename_out
+    
+    barrier()
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+#    run_model(file_name=project_urs.home+'detail.csv', aa_scenario_name=project_urs.scenario_name,
+#              ab_time=project_urs.time, res_factor= project_urs.res_factor, tide=project_urs.tide, user=project_urs.user,
+#              alpha = project_urs.alpha, friction=project_urs.friction,
+#              time_thinning = project_urs.time_thinning,
+#              dir_comment=project_urs.dir_comment)
+    kwargs={}
+    kwargs['est_num_trigs']=project_urs.trigs_min
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project_urs.host
+    kwargs['res_factor']=project_urs.res_factor
+    kwargs['starttime']=project_urs.starttime
+    kwargs['yieldstep']=project_urs.yieldstep
+    kwargs['finaltime']=project_urs.finaltime
+    
+    kwargs['output_dir']=project_urs.output_run_time_dir
+#    kwargs['bathy_file']=project_urs.combined_dir_name+'.txt'
+    kwargs['bathy_file']=project_urs.combined_dir_name + '.pts'
+    kwargs['boundary_file']=project_urs.boundaries_in_dir_name + '.sww'
+    kwargs['file_name']=project_urs.home+'detail.csv'
+    kwargs['aa_scenario_name']=project_urs.scenario_name
+    kwargs['ab_time']=project_urs.time
+    kwargs['res_factor']= project_urs.res_factor
+    kwargs['tide']=project_urs.tide
+    kwargs['user']=project_urs.user
+    kwargs['alpha'] = project_urs.alpha
+    kwargs['friction']=project_urs.friction
+    kwargs['time_thinning'] = project_urs.time_thinning
+    kwargs['dir_comment']=project_urs.dir_comment
+
+    run_model(**kwargs)
+      
+    if myid==0:
+        export_model(**kwargs)
+    barrier
+
+
Index: /anuga_work/production/wa/pt_hedland_2006/run_timeseries.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2006/run_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2006/run_timeseries.py	(revision 7411)
@@ -0,0 +1,29 @@
+""" Script for generating figures, see sww2timeseries for documentation"""
+
+from anuga.pyvolution.util import sww2timeseries
+import project
+from os import sep
+
+# define directory location of sww and gauge data
+timestampdir = ''
+file_loc = project.outputdir + timestampdir + sep #project.outputtimedir
+swwfile = file_loc + project.basename + '.sww'
+label_id = timestampdir
+
+# generate figures - see sww2timeseries for documentation
+texname = sww2timeseries(swwfile,
+                         project.beach_gauges,
+                         label_id,
+                         report = False,
+                         plot_quantity = ['stage', 'speed'],
+                         time_min = None,
+                         time_max = None,
+                         title_on = True,   
+                         verbose = True)
+
+print 'finished plotting time series'
+
+
+
+
+
Index: /anuga_work/production/wa/pt_hedland_2009/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2009/Arc_asc2raster_GDA94z50.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2009/Arc_asc2raster_GDA94z50.py	(revision 7411)
@@ -0,0 +1,78 @@
+# ---------------------------------------------------------------------------
+# This python script is an ArcGIS script that can only be run on a computer
+# with and ArcGIS licence and version 2.4.1 python.
+# This script is designed to read in .asc files and deliever rasters with
+# projection (GDA94z50) held in a file geodatabase (called raster)
+# written by Kristy Van Putten and Ross Wilson
+# ---------------------------------------------------------------------------
+
+# Import system modules
+import sys, string, os, arcgisscripting, glob, os.path
+
+# Create the Geoprocessor object
+gp = arcgisscripting.create()
+
+# Check out any necessary licenses
+gp.CheckOutExtension("spatial")
+
+# Load required toolboxes...
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx")
+gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")
+gp.overwriteoutput = 1
+
+scenario_dir = "\\\\nas2\\gemd\\georisk_models\\inundation\\data\\western_australia\\pt_hedland_tsunami_scenario_2009\\"
+output_dir="anuga\\outputs\\"
+
+time_dir1 = '20090818_133107_run_final_0.0_27283_kvanputt'
+
+time_dirs = [time_dir1]
+
+for time_dir in time_dirs:
+    # Local variables...
+    folder = scenario_dir + output_dir +  time_dir +'\\'
+    raster_gbd = folder + 'raster.gdb'
+##    land = scenario_dir + "map_work\\\port_hedland.gdb\\outlines\\initial_condition"
+##    ocean = scenario_dir + "map_work\\\port_hedland.gdb\\outlines\\initial_conditions_ocean"
+
+    print 'Process: Create File GDB'
+    gp.CreateFileGDB_management(folder, "raster")
+
+    gp.Workspace = raster_gbd
+
+    print gp.Workspace
+    
+    #replication dictionary
+    replicate = (('pt_hedland', ''),('_', ''),('max','_M'),
+                 ('CBD', 'CDB'), ('PtHedland', 'PH'),
+                 ('depth','_depth'),('speed', '_speed'),
+                 ('elevation', '_ele'), ('stage','_stage'))
+
+    generate_filename = []
+    input_ascii = glob.glob(folder + '*.asc')
+
+    for infile in input_ascii:
+        output_DEM = os.path.basename(infile)[:-4]
+        for (key, rep) in replicate:
+            output_DEM = output_DEM.replace(key,rep)
+        output_DEM = output_DEM[:10]
+        if output_DEM in generate_filename:
+            print 'Output_DEM filename (%s) already in use' % output_DEM
+            sys.exit(10)
+        generate_filename.append(output_DEM)
+
+        print 'Output DEM ',output_DEM
+        
+        print 'Process: ASCII to Raster'
+        gp.ASCIIToRaster_conversion(infile, output_DEM, "FLOAT")
+
+        print 'Process: Define Projection'
+        gp.DefineProjection_management(output_DEM, "PROJCS['GDA_1994_MGA_Zone_50',GEOGCS['GCS_GDA_1994',DATUM['D_GDA_1994',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
+                                                   ",PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',10000000.0],PARAMETER['Central_Meridian',117.0],PARAMETER['Scale_Factor',0.9996]"
+                                                   ",PARAMETER['Latitude_Of_Origin',0.0],UNIT['Meter',1.0]]")
+##        output_extract = output_DEM + 'E'
+##        print 'Output Extract ',output_extract
+##        print 'Process: Extract by Mask'
+##        gp.ExtractByMask_sa(output_DEM, land, output_extract)
+
+
Index: /anuga_work/production/wa/pt_hedland_2009/build_elevation.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2009/build_elevation.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2009/build_elevation.py	(revision 7411)
@@ -0,0 +1,100 @@
+"""Build the elevation data to run a tsunami inundation scenario 
+for Busselton, WA, Australia.
+
+Input: elevation data from project.py
+Output: pts file stored in project.topographies_dir 
+The run_model.py is reliant on the output of this script.
+
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+from os.path import join
+
+# Related major packages
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+
+# Application specific imports
+from setup_model import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+copy_code_files(project.output_build,__file__, 
+                os.path.dirname(project.__file__)+os.sep+\
+                project.__name__+'.py' )
+start_screen_catcher(project.output_build)
+
+
+#------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#------------------------------------------------------------------------------
+
+print 'project.bounding_polygon', project.bounding_polygon
+print 'project.combined_elevation_basename', project.combined_elevation_basename
+
+# Create Geospatial data from ASCII files
+geospatial_data = {}
+if not project.ascii_grid_filenames == []:
+    for filename in project.ascii_grid_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        convert_dem_from_ascii2netcdf(absolute_filename,
+                                      basename_out=absolute_filename,
+                                      use_cache=True,
+                                      verbose=True)
+        dem2pts(absolute_filename, use_cache=True, verbose=True)
+
+        G_grid = Geospatial_data(file_name=absolute_filename+'.pts',
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_grid.clip(project.bounding_polygon)
+
+# Create Geospatial data from TXT files
+if not project.point_filenames == []:
+    for filename in project.point_filenames:
+        absolute_filename = join(project.topographies_folder, filename)
+        G_points = Geospatial_data(file_name=absolute_filename,
+                                                    verbose=True)
+        print 'Clip geospatial object'
+        geospatial_data[filename] = G_points.clip(project.bounding_polygon)
+
+#-------------------------------------------------------------------------------
+# Combine, clip and export dataset 
+#-------------------------------------------------------------------------------
+
+print 'Add geospatial objects' # except', project.offshore_name5
+G = None
+for key in geospatial_data:
+    #if key == project.point_filenames[4] or key == project.ascii_filenames[1]:
+    #    # Skip these files for now
+    #    continue
+    
+    G += geospatial_data[key]
+        
+#print 'Clip combined geospatial data'
+##G_clip = G.clip_outside(project.poly_aoi1)
+##G_all = G_clip + geospatial_data[project.point_filenames[4]] 
+#G_clipped = G_all.clip(project.poly_all)
+#G_clip = G.clip(project.bounding_polygon)
+
+
+print 'Export combined DEM file'
+G.export_points_file(project.combined_elevation + '.pts')
+print 'Do txt version too'
+# Use for comparision in ARC
+G.export_points_file(project.combined_elevation + '.txt')
+
Index: /anuga_work/production/wa/pt_hedland_2009/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2009/build_urs_boundary.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2009/build_urs_boundary.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""
+Replacement function that wraps the legacy function urs2sts()
+and passes in the data from the EventSelection <event>.list file.
+"""
+
+import os
+import os.path
+from time import localtime, strftime, gmtime
+
+import project
+
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.shallow_water.data_manager import urs2sts
+
+import Numeric as num
+
+
+#-------------------------------------------------------------------------------
+# Get gauges (timeseries of index points)
+#-------------------------------------------------------------------------------
+def get_sts_gauge_data(filename, verbose=False):
+    print 'get_sts_gauge_data: filename=%s' % filename
+    fid = NetCDFFile(filename+'.sts', 'r')      #Open existing file for read
+    permutation = fid.variables['permutation'][:]
+    x = fid.variables['x'][:] + fid.xllcorner   #x-coordinates of vertices
+    y = fid.variables['y'][:] + fid.yllcorner   #y-coordinates of vertices
+    points = num.transpose(num.asarray([x.tolist(), y.tolist()]))
+    time = fid.variables['time'][:] + fid.starttime
+    elevation = fid.variables['elevation'][:]
+       
+    basename = 'sts_gauge'
+    quantity_names = ['stage', 'xmomentum', 'ymomentum']
+    quantities = {}
+    for i, name in enumerate(quantity_names):
+        quantities[name] = fid.variables[name][:]
+
+    #---------------------------------------------------------------------------
+    # Get maximum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+     
+    maxname = 'max_sts_stage.csv'
+    print 'get_sts_gauge_data: maxname=%s' % maxname
+    fid_max = open(os.path.join(project.event_folder, maxname), 'w')
+    fid_max.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_max.write('%d, %.6f, %.6f, %.6f\n' % (index, x[j], y[j], max(stage)))
+      
+    #---------------------------------------------------------------------------
+    # Get minimum wave height throughout timeseries at each index point
+    #---------------------------------------------------------------------------
+
+    minname = 'min_sts_stage.csv'
+    fid_min = open(os.path.join(project.event_folder, minname), 'w')
+    fid_min.write('index, x, y, max_stage \n')    
+    for j in range(len(x)):
+        index = permutation[j]
+        stage = quantities['stage'][:,j]
+        xmomentum = quantities['xmomentum'][:,j]
+        ymomentum = quantities['ymomentum'][:,j]
+
+        fid_min.write('%d, %.6f, %.6f, %.6f\n' %(index, x[j], y[j], min(stage)))
+
+        out_file = os.path.join(project.event_folder,
+                                basename+'_'+str(index)+'.csv')
+        fid_sts = open(out_file, 'w')
+        fid_sts.write('time, stage, xmomentum, ymomentum \n')
+
+        #-----------------------------------------------------------------------
+        # End of the get gauges
+        #-----------------------------------------------------------------------
+        for k in range(len(time)-1):
+            fid_sts.write('%.6f, %.6f, %.6f, %.6f\n'
+                          % (time[k], stage[k], xmomentum[k], ymomentum[k]))
+
+        fid_sts.close()      
+
+    fid.close()
+
+    return quantities,elevation,time
+
+
+##
+# @brief Build boundary STS files from one or more MUX files.
+# @param event_file Name of mux meta-file or single mux stem.
+# @param output_dir Directory to write STS data to.
+# @note 'event_file' is produced by EventSelection.
+def build_urs_boundary(event_file, output_dir):
+    '''Build a boundary STS file from a set of MUX files.'''
+
+    # if we are using an EventSelection multi-mux file
+    if project.multi_mux:
+        # get the mux+weight data from the meta-file (in <boundaries>)
+        mux_event_file = os.path.join(project.event_folder, event_file)
+        print 'using multi-mux file', mux_event_file
+        try:
+            fd = open(mux_event_file, 'r')
+            mux_data = fd.readlines()
+            fd.close()
+        except IOError, e:
+            msg = 'File %s cannot be read: %s' % (mux_event_file, str(e))
+            raise Exception, msg
+        except:
+            raise
+
+        # first line of file is # filenames+weight in rest of file
+        num_lines = int(mux_data[0].strip())
+        mux_data = mux_data[1:]
+        print 'number of sources %d' % num_lines
+
+        # quick sanity check on input mux meta-file
+        if num_lines != len(mux_data):
+            msg = ('Bad file %s: %d data lines, but line 1 count is %d'
+                   % (event_file, len(mux_data), num_lines))
+            raise Exception, msg
+
+        # Create filename and weights lists.
+        # Must chop GRD filename just after '*.grd'.
+        mux_filenames = []
+        for line in mux_data:
+            muxname = line.strip().split()[0]
+            split_index = muxname.index('.grd')
+            muxname = muxname[:split_index+len('.grd')]
+            muxname = os.path.join(project.mux_data_folder, muxname)
+            mux_filenames.append(muxname)
+        
+        mux_weights = [float(line.strip().split()[1]) for line in mux_data]
+
+        # Call legacy function to create STS file.
+        print 'creating sts file'
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=project.urs_order,
+                weights=mux_weights,
+                central_meridian=project.central_meridian,
+                zone=project.zone,
+                verbose=True)
+    else:                           # a single mux stem file, assume 1.0 weight
+        mux_file = os.path.join(project.event_folder, event_file)
+        mux_filenames = [mux_file]
+        print 'using single-mux file', mux_file
+
+        weight_factor = 1.0
+        mux_weights = weight_factor*num.ones(len(mux_filenames), num.Float)
+            
+        order_filename = project.urs_order
+
+        print 'reading', order_filename
+        # Create ordered sts file
+        urs2sts(mux_filenames,
+                basename_out=output_dir,
+                ordering_filename=order_filename,
+                weights=mux_weights,
+                central_meridian=project.central_meridian,
+                zone=project.zone,
+                verbose=True)
+
+    # report on progress so far
+    sts_file = os.path.join(project.event_folder, project.scenario_name)
+    quantities, elevation, time = get_sts_gauge_data(sts_file, verbose=False)
+    print len(elevation), len(quantities['stage'][0,:])
+
+    
+
Index: /anuga_work/production/wa/pt_hedland_2009/export_results.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2009/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2009/export_results.py	(revision 7411)
@@ -0,0 +1,121 @@
+"""
+Generates ascii grids of nominated areas -
+Input: sww file from run_perth.py
+       boundaries for grids from project.py
+Outputs: ascii grids of specified variables
+Stored in the 'outputs_dir' folder for respective .sww file
+
+Note:
+If producing a grid for the enitre extent cellsize should be greater than 30m
+If producing grids for inundation area resolution should be greater than mesh (ie ~22m)
+"""
+
+import project, os
+import sys
+from os.path import join
+from anuga.lib.maxasc.maxasc import MaxAsc
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf, dem2pts
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+
+directory = project.output_folder
+
+time_dir1 = '20090615_151314_run_final_0.0_27283_mhingee'
+##time_dir2 = '20090421_164728_run_final_0_64449_1699_Tb_internal_mhingee'
+##time_dir3 = ''
+##time_dir4 = ''
+##time_dir5 = ''
+##time_dir6 = ''
+##
+time_dirs = [time_dir1]#, time_dir2]# , time_dir4, time_dir5, time_dir6]
+  
+
+##cellsize = 250
+cellsize = 20
+
+#timestep = None    # None means no timestep!
+timestep = 0
+
+######
+# Set the special areas of interest.  If none, do: area='All'
+######
+
+area = ['Town']  # strings must match keys in var_equations below
+##area = ['All']      # 'All' means no special areas - the whole thing
+
+######
+# Define allowed variable names and associated equations to generate values.
+# This would not normally change.
+######
+var_equations = {'stage':     'stage',
+                 'momentum':  '(xmomentum**2 + ymomentum**2)**0.5',
+                 'depth':     'stage-elevation',
+                 'speed':     '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6)',
+                 'elevation': 'elevation' }
+
+# one or more key strings from var_equations above
+var = ['elevation','stage']
+
+######
+# Start running the various conversions we require.
+######
+
+for which_var in var:
+    if which_var not in var_equations:
+        print 'Unrecognized variable name: %s' % which_var
+        break
+
+    for which_area in area:
+        if which_area == 'All':
+            easting_min = None
+            easting_max = None
+            northing_min = None
+            northing_max = None
+        else:
+            try:
+                easting_min = eval('project.xmin%s' % which_area)
+                easting_max = eval('project.xmax%s' % which_area)
+                northing_min = eval('project.ymin%s' % which_area)
+                northing_max = eval('project.ymax%s' % which_area)
+            except AttributeError:
+                print 'Unrecognized area name: %s' % which_area
+                break
+
+        for time_dir in time_dirs:
+
+            name1 = join(directory, time_dir, project.scenario_name)
+            #name2 = join(directory, time_dir, project.scenario_name)+'_time_39600_0'
+            #name3 = join(directory, time_dir, project.scenario_name)+'_time_79200_0'
+
+            names = [name1] #, name2]#, name3]
+      
+           # asc_name = []   
+               
+            for name in names:
+                         
+                outname = name + '_' + which_area + '_' + which_var
+                quantityname = var_equations[which_var]
+
+                print 'start sww2dem: time_dir=%s' % time_dir
+                
+                sww2dem(name, basename_out = outname,
+                            quantity = quantityname,
+                            timestep = timestep,
+                            cellsize = cellsize,      
+                            easting_min = easting_min,
+                            easting_max = easting_max,
+                            northing_min = northing_min,
+                            northing_max = northing_max,        
+                            reduction = max, 
+                            verbose = True,
+                            format = 'asc')
+
+##                asc_name.append(outname + '.asc')
+##    
+##            maxasc_outname = join(directory, time_dir, project.scenario_name)+'_'+which_area+'_'+which_var+'_max.asc'
+##
+##            print 'max asc outname ', maxasc_outname
+##            print 'asc_name ', str(asc_name)
+##            
+##            MaxAsc(maxasc_outname, asc_name)
Index: /anuga_work/production/wa/pt_hedland_2009/file_length.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2009/file_length.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2009/file_length.py	(revision 7411)
@@ -0,0 +1,22 @@
+"""Function to return the length of a file.
+
+Intended to be used for simplfying the creation of boundary_tags in
+run_model.py
+
+Input: filename
+Returns: number of lines in file
+"""
+
+def file_length(in_file):
+    '''Function to return the number of lines in a file.
+
+    in_file: Path to the file to get number of lines in.
+    
+    Returns: number of lines in file
+    '''
+    
+    fid = open(in_file)
+    data = fid.readlines()
+    fid.close()
+    return len(data)
+
Index: /anuga_work/production/wa/pt_hedland_2009/project.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2009/project.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2009/project.py	(revision 7411)
@@ -0,0 +1,246 @@
+"""
+This file contains all your file and directory definitions 
+for elevation, meshes and outputs.
+"""
+
+import os
+from anuga.utilities.system_tools import get_user_name, get_host_name
+from time import localtime, strftime, gmtime
+from os.path import join, exists
+
+#-------------------------------------------------------------------------------
+# Directory setup
+#-------------------------------------------------------------------------------
+
+# this section needs to be updated to reflect the modelled community.
+# Note, the user needs to set up the directory system accordingly
+state = 'western_australia'
+scenario_name = 'pt_hedland'
+scenario_folder = 'pt_hedland_tsunami_scenario_2009'
+
+#-------------------------------------------------------------------------------
+# Initial Conditions
+#-------------------------------------------------------------------------------
+
+# Model specific parameters.
+# One or all can be changed each time the run_model script is executed
+tide = 0.0              # 3.6 difference between MSL and HAT in metres
+zone = 50               # specify UTM zone of model
+central_meridian = None 
+event_number = 27283    # 27255,27283 the event number or the mux file name
+alpha = 0.1             # smoothing parameter for mesh
+friction=0.01           # manning's friction coefficient
+starttime=0             # start time for simulation
+finaltime=1000         # final time for simulation
+
+setup = 'final'         # This can be one of three values
+                        #    trial - coarsest mesh, fast
+                        #    basic - coarse mesh
+                        #    final - fine mesh, slowest
+
+#-------------------------------------------------------------------------------
+# Output filename
+#
+# Your output filename should be unique between different runs on different data.
+# The list of items below will be used to create a file in your output directory.
+# Your user name and time+date will be automatically added.  For example,
+#     [setup, tide, event_number]
+# will result in a filename like
+#     20090212_091046_run_final_0_27283_rwilson
+#-------------------------------------------------------------------------------
+
+output_comment = [setup, tide, event_number]
+
+#-------------------------------------------------------------------------------
+# Input Data
+#-------------------------------------------------------------------------------
+
+# ELEVATION DATA
+# Used in build_elevation.py
+ascii_grid_filenames = ['dli_dem_clip']
+point_filenames = ['coastline.txt','port_hedland_new2.txt']
+
+### Add csv header list to all files in point_filenames
+##headerlist = ['x', 'y', 'elevation'] 
+##for f in point_filenames:
+##    add_csv_header(join(topographies_folder, f), headerlist)
+
+# BOUNDING POLYGON - for data clipping and estimate of triangles in mesh
+# Used in build_elevation.py
+# Format for points easting,northing (no header)
+bounding_polygon_filename = 'poly_all.csv'
+bounding_polygon_maxarea = 100000
+
+# INTERIOR REGIONS -  for designing the mesh
+# Used in run_model.py
+# Format for points easting,northing (no header)                    
+interior_regions_data = [['shallow_water.csv', 5000],
+                         ['area_of_significance.csv', 1500],
+                         ['area_of_interest.csv', 800]]
+
+PriorityArea_filename = None
+    
+# LAND - used to set the initial stage/water to be offcoast only
+# Used in run_model.py.  Format for points easting,northing,id,value
+land_initial_conditions_filename = 'initial_conditions_simple.csv'
+
+# GAUGES - for creating timeseries at a specific point
+# Used in get_timeseries.py.  
+# Format easting,northing,name,elevation (with header)
+gauges_filename = ''
+# BUILDINGS EXPOSURE - for identifying inundated houses
+# Used in run_building_inundation.py
+# Format latitude,longitude etc (geographic)
+building_exposure_filename = '' # from NEXIS
+
+# AREA OF IMAGES - Extent of each image to find out highest runup
+# Header - easting,northing,id,value
+# Used in get_runup.py
+images_filename = ''
+
+# BOUNDING POLYGON - used in build_boundary.py and run_model.py respectively
+# NOTE: when files are put together the points must be in sequence
+# For ease go clockwise!
+# Check the run_model.py for boundary_tags
+
+# Thinned ordering file from Hazard Map (geographic)
+# Format is index,latitude,longitude (with header)
+urs_order_filename = 'thinned_boundary_ordering.csv'
+
+# Landward bounding points
+# Format easting,northing (no header)
+landward_boundary_filename = 'landward_bounding_polygon.csv'
+
+# MUX input filename.
+# If a meta-file from EventSelection is used, set 'multi-mux' to True.
+# If a single MUX stem filename (*.grd) is used, set 'multi-mux' to False.
+##mux_input_filename = event_number # to be found in event_folder
+                                    # (ie boundaries/event_number/)
+##multi_mux = False
+mux_input_filename = 'event.list'
+multi_mux = True
+
+#-------------------------------------------------------------------------------
+# Clipping regions for export to asc and regions for clipping data
+# Final inundation maps should only be created in regions of the finest mesh
+#-------------------------------------------------------------------------------
+
+# ASCII export grid for Pt Hedland
+xminPtHedland = 659400
+xmaxPtHedland = 676600
+yminPtHedland = 7744000
+ymaxPtHedland = 7757300
+
+
+################################################################################
+################################################################################
+####         NOTE: NOTHING WOULD NORMALLY CHANGE BELOW THIS POINT.          ####
+################################################################################
+################################################################################
+
+# Get system user and host names.
+# These values can be used to distinguish between two similar runs by two
+# different users or runs by the same user on two different machines.
+user = get_user_name()
+host = get_host_name()
+
+# Environment variable names.
+# The inundation directory, not the data directory.
+ENV_INUNDATIONHOME = 'INUNDATIONHOME'
+
+# Path to MUX data
+ENV_MUXHOME = 'MUXHOME'
+
+#-------------------------------------------------------------------------------
+# Output Elevation Data
+#-------------------------------------------------------------------------------
+
+# Output filename for elevation
+# this is a combination of all the data generated in build_elevation.py
+combined_elevation_basename = scenario_name + '_combined_elevation'
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# determines time for setting up output directories
+time = strftime('%Y%m%d_%H%M%S', localtime()) 
+gtime = strftime('%Y%m%d_%H%M%S', gmtime()) 
+build_time = time + '_build'
+run_time = time + '_run_'
+
+# create paths generated from environment variables.
+home = join(os.getenv(ENV_INUNDATIONHOME), 'data') # Absolute path for data folder
+muxhome = os.getenv(ENV_MUXHOME)
+    
+# check various directories/files that must exist
+anuga_folder = join(home, state, scenario_folder, 'anuga')
+topographies_folder = join(anuga_folder, 'topographies')
+polygons_folder = join(anuga_folder, 'polygons')
+boundaries_folder = join(anuga_folder, 'boundaries')
+output_folder = join(anuga_folder, 'outputs')
+gauges_folder = join(anuga_folder, 'gauges')
+event_folder = join(boundaries_folder, str(event_number))
+
+# MUX data files
+# Directory containing the MUX data files to be used with EventSelection.
+mux_data_folder = join(muxhome, 'mux')
+
+#-------------------------------------------------------------------------------
+# Location of input and output data
+#-------------------------------------------------------------------------------
+
+# Convert the user output_comment to a string for run_model.py
+output_comment = ('_'.join([str(x) for x in output_comment if x != user])
+                  + '_' + user)
+
+# The absolute pathname of the all elevation, generated in build_elevation.py
+combined_elevation = join(topographies_folder, combined_elevation_basename)
+
+# The pathname for the urs order points, used within build_urs_boundary.py
+if urs_order_filename:
+    urs_order = join(boundaries_folder, urs_order_filename)
+
+# The absolute pathname for the landward points of the bounding polygon,
+# Used within run_model.py)
+if landward_boundary_filename:
+    landward_boundary = join(boundaries_folder, landward_boundary_filename)
+
+# The absolute pathname for the .sts file, generated in build_boundary.py
+event_sts = join(event_folder, scenario_name)
+
+# The absolute pathname for the output folder names
+# Used for build_elevation.py
+output_build = join(output_folder, build_time) + '_' + str(user) 
+# Used for run_model.py
+output_run = join(output_folder, run_time) + output_comment 
+# Used by post processing
+output_run_time = join(output_run, scenario_name) 
+
+# The absolute pathname of the mesh, generated in run_model.py
+meshes = join(output_run, scenario_name) + '.msh'
+
+# The absolute pathname for the gauges file
+# Used for get_timeseries.py
+if gauges_filename:
+    gauges = join(gauges_folder, gauges_filename)       
+
+# The absolute pathname for the building file
+# Used for run_building_inundation.py
+if building_exposure_filename:
+    building_exposure = join(gauges_folder, building_exposure_filename)
+
+# The absolute pathname for the image file
+# Used for get_runup.py
+if images_filename:
+    images = join(polygons_folder, images_filename)
+
+
+# full path to where MUX files (or meta-files) live
+mux_input = join(event_folder, mux_input_filename)
+
+#Multiple polygons in one CSV file to make internal polygons
+if not PriorityArea_filename == None:
+    PriorityAreas = join(polygons_folder, PriorityArea_filename)
+
+
Index: /anuga_work/production/wa/pt_hedland_2009/run_model.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2009/run_model.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2009/run_model.py	(revision 7411)
@@ -0,0 +1,163 @@
+"""Run a tsunami inundation scenario for Busselton, WA, Australia.
+
+The scenario is defined by a triangular mesh created from project.polygon, the
+elevation data is compiled into a pts file through build_elevation.py and a
+simulated tsunami is generated through an sts file from build_boundary.py.
+
+Input: sts file (build_boundary.py for respective event)
+       pts file (build_elevation.py)
+       information from project file
+Outputs: sww file stored in project.output_run_time_dir 
+The export_results_all.py and get_timeseries.py is reliant
+on the outputs of this script
+
+Ole Nielsen and Duncan Gray, GA - 2005, Jane Sexton, Nick Bartzis, GA - 2006
+Ole Nielsen, Jane Sexton and Kristy Van Putten - 2008
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+import os
+import os.path
+import time
+from time import localtime, strftime, gmtime
+
+# Related major packages
+from Scientific.IO.NetCDF import NetCDFFile
+import Numeric as num
+
+from anuga.interface import create_domain_from_regions
+from anuga.interface import Transmissive_stage_zero_momentum_boundary
+from anuga.interface import Dirichlet_boundary
+from anuga.interface import Reflective_boundary
+from anuga.interface import Field_boundary
+from anuga.interface import create_sts_boundary
+from anuga.interface import csv2building_polygons
+from file_length import file_length
+
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs2sts
+from anuga.utilities.polygon import read_polygon, Polygon_function
+
+# Application specific imports
+from setup_model import project
+import build_urs_boundary as bub
+
+#-------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file. Copy script must be before screen_catcher
+#-------------------------------------------------------------------------------
+
+copy_code_files(project.output_run, __file__, 
+                os.path.join(os.path.dirname(project.__file__),
+                             project.__name__+'.py'))
+start_screen_catcher(project.output_run, 0, 1)
+
+#-------------------------------------------------------------------------------
+# Create the computational domain based on overall clipping polygon with
+# a tagged boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#-------------------------------------------------------------------------------
+
+print 'Create computational domain'
+
+# Create the STS file
+print 'project.mux_data_folder=%s' % project.mux_data_folder
+if not os.path.exists(project.event_sts + '.sts'):
+    bub.build_urs_boundary(project.mux_input_filename, project.event_sts)
+
+# Read in boundary from ordered sts file
+event_sts = create_sts_boundary(project.event_sts)
+
+# Reading the landward defined points, this incorporates the original clipping
+# polygon minus the 100m contour
+landward_boundary = read_polygon(project.landward_boundary)
+
+# Combine sts polyline with landward points
+bounding_polygon_sts = event_sts + landward_boundary
+
+# Number of boundary segments
+num_ocean_segments = len(event_sts) - 1
+# Number of landward_boundary points
+num_land_points = file_length(project.landward_boundary)
+
+# Boundary tags refer to project.landward_boundary
+# 4 points equals 5 segments start at N
+boundary_tags={'back': range(num_ocean_segments+1,
+                             num_ocean_segments+num_land_points),
+               'side': [num_ocean_segments,
+                        num_ocean_segments+num_land_points],
+               'ocean': range(num_ocean_segments)}
+
+# Build mesh and domain
+domain = create_domain_from_regions(bounding_polygon_sts,
+                                    boundary_tags=boundary_tags,
+                                    maximum_triangle_area=project.bounding_maxarea,
+                                    interior_regions=project.interior_regions,
+                                    mesh_filename=project.meshes,
+                                    use_cache=True,
+                                    verbose=True)
+print domain.statistics()
+
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run) 
+domain.set_minimum_storable_height(0.01)    # Don't store depth less than 1cm
+
+#-------------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------------
+
+print 'Setup initial conditions'
+
+# Set the initial stage in the offcoast region only
+if project.land_initial_conditions:
+    IC = Polygon_function(project.land_initial_conditions,
+                          default=project.tide,
+                          geo_reference=domain.geo_reference)
+else:
+    IC = 0
+domain.set_quantity('stage', IC, use_cache=True, verbose=True)
+domain.set_quantity('friction', project.friction) 
+domain.set_quantity('elevation', 
+                    filename=project.combined_elevation+'.pts',
+                    use_cache=True,
+                    verbose=True,
+                    alpha=project.alpha)
+
+#-------------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------------
+
+print 'Set boundary - available tags:', domain.get_boundary_tags()
+
+Br = Reflective_boundary(domain)
+Bt = Transmissive_stage_zero_momentum_boundary(domain)
+Bd = Dirichlet_boundary([project.tide, 0, 0])
+Bf = Field_boundary(project.event_sts+'.sts',
+                    domain, mean_stage=project.tide,
+                    time_thinning=1,
+                    default_boundary=Dirichlet_boundary([0, 0, 0]),
+                    boundary_polygon=bounding_polygon_sts,                    
+                    use_cache=True,
+                    verbose=True)
+
+domain.set_boundary({'back': Br,
+                     'side': Bt,
+                     'ocean': Bf}) 
+
+#-------------------------------------------------------------------------------
+# Evolve system through time
+#-------------------------------------------------------------------------------
+
+t0 = time.time()
+for t in domain.evolve(yieldstep=project.yieldstep, 
+                       finaltime=project.finaltime,
+                       skip_initial_step=False): 
+    print domain.timestepping_statistics()
+    print domain.boundary_statistics(tags='ocean')
+
+print 'Simulation took %.2f seconds' % (time.time()-t0)
Index: /anuga_work/production/wa/pt_hedland_2009/setup_model.py
===================================================================
--- /anuga_work/production/wa/pt_hedland_2009/setup_model.py	(revision 7411)
+++ /anuga_work/production/wa/pt_hedland_2009/setup_model.py	(revision 7411)
@@ -0,0 +1,198 @@
+"""
+Module to import the project.py 'configuration' file and perform
+sanity checks plus a quick check on mesh generation.
+
+Also callable as a stand-alone program, mainly to view the results
+of the mesh generation.
+"""
+
+import os
+
+from os.path import join, exists
+from anuga.utilities.polygon import read_polygon, number_mesh_triangles
+from anuga.shallow_water.data_manager import csv2polygons
+import project
+
+
+#-------------------------------------------------------------------------------
+# Sanity checks - check that required files/directories, etc, exist.
+#-------------------------------------------------------------------------------
+
+# flag - we check many things and then don't proceed if anything wrong
+sanity_error = False               # checked at bottom of this file
+
+# Test that environment variables are defined.
+if os.getenv(project.ENV_INUNDATIONHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_INUNDATIONHOME
+    sanity_error = True
+
+if os.getenv(project.ENV_MUXHOME) is None:
+    print "Environment variable '%s' is not set" % project.ENV_MUXHOME
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check filename strings that MUST be set
+#-------------------------------------------------------------------------------
+
+if not project.urs_order_filename:
+    print ("Sorry, thinned ordering file parameter 'urs_order_filename' "
+           "isn't set")
+    sanity_error = True
+
+if not project.landward_boundary_filename:
+    print ("Sorry, landward bounding points parameter "
+           "'landward_boundary_filename' isn't set")
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Directory Structure
+#-------------------------------------------------------------------------------
+
+# check folders generated from environment variables.
+if not exists(project.home):
+    print "Sorry, data directory '%s' doesn't exist" % project.home
+    sanity_error = True
+    
+if not exists(project.muxhome):
+    print "Sorry, MUX directory '%s' doesn't exist" % project.muxhome
+    sanity_error = True
+    
+if not exists(project.anuga_folder):
+    print "Sorry, ANUGA directory '%s' doesn't exist" % project.anuga_folder
+    sanity_error = True
+
+if not exists(project.topographies_folder):
+    print ("Sorry, topo directory '%s' doesn't exist"
+           % project.topographies_folder)
+    sanity_error = True
+
+if not exists(project.polygons_folder):
+    print ("Sorry, polygon directory '%s' doesn't exist"
+           % project.polygons_folder)
+    sanity_error = True
+
+if not exists(project.boundaries_folder):
+    print ("Sorry, boundaries directory '%s' doesn't exist"
+           % project.boundaries_folder)
+    sanity_error = True
+
+if not exists(project.output_folder):
+    print "Sorry, outputs directory '%s' doesn't exist" % project.output_folder
+    sanity_error = True
+
+if not exists(project.gauges_folder):
+    print "Sorry, gauges directory '%s' doesn't exist" % project.gauges_folder
+    sanity_error = True
+
+if not exists(project.mux_data_folder):
+    print "Sorry, mux data directory '%s' doesn't exist" % project.mux_data_folder
+    sanity_error = True
+
+# if multi_mux is True, check if multi-mux file exists
+if project.multi_mux:
+    if not exists(project.mux_input):
+        print ("Sorry, MUX input file '%s' doesn't exist"
+               % project.mux_input)
+        sanity_error = True
+
+#-----
+# If this directory don't exist, EventSelection hasn't been run.
+#-----
+
+if not exists(project.event_folder):
+    print ("Sorry, you must generate event %s with EventSelection."
+           % project.event_number)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Determine type of run
+#-------------------------------------------------------------------------------
+
+if project.setup == 'trial':
+    print 'trial'
+    project.scale_factor = 100
+    project.time_thinning = 96
+    project.yieldstep = 240
+elif project.setup == 'basic': 
+    print 'basic'
+    project.scale_factor = 4
+    project.time_thinning = 12
+    project.yieldstep = 120
+elif project.setup == 'final': 
+    print 'final'
+    project.scale_factor = 1
+    project.time_thinning = 4
+    project.yieldstep = 60
+else:
+    print ("Sorry, you must set the 'setup' variable to one of:"
+           '   trial - coarsest mesh, fast\n'
+           '   basic - coarse mesh\n'
+           '   final - fine mesh, slowest\n'
+           '\n'
+           "'setup' was set to '%s'" % project.setup)
+    sanity_error = True
+
+#-------------------------------------------------------------------------------
+# Check for errors detected above.
+#-------------------------------------------------------------------------------
+
+if sanity_error:
+    msg = 'You must fix the above errors before continuing.'
+    raise Exception, msg
+
+#-------------------------------------------------------------------------------
+# Reading polygons and creating interior regions
+#-------------------------------------------------------------------------------
+
+# Create list of land polygons with initial conditions
+project.land_initial_conditions = []
+# if it's a list, then it's a list of land condition filenames
+# else it's a string - a single file, multiple land conditions
+if isinstance(project.land_initial_conditions_filename, list):
+    for filename, MSL in project.land_initial_conditions_filename:
+        polygon = read_polygon(join(project.polygons_folder, filename))
+        project.land_initial_conditions.append([polygon, MSL])
+elif isinstance(project.land_initial_conditions_filename, basestring):
+    polygons, MSL = csv2polygons(join(project.polygons_folder,
+                                      project.land_initial_conditions_filename))
+    for i, key in enumerate(polygons):
+        if i%100==0: print i
+        poly = polygons[key]
+        land = float(MSL[key])
+        project.land_initial_conditions.append([poly, land])
+else:
+    msg = ('project.land_initial_conditions_filename must be a list or '
+           'string, got %s'
+           % type(project.land_initial_conditions_filename))
+    raise Exception, msg
+# Create list of interior polygons with scaling factor
+project.interior_regions = []
+
+if project.PriorityArea_filename is not None:
+    polygons, maxareas = csv2polygons(project.PriorityAreas)
+    print 'Creating %d internal polygons' % len(polygons)
+    #def create_polygon_function(polygons, geo_reference=None):
+    project.interior_regions = []
+    for i, key in enumerate(polygons):
+        if i%100==0: print i
+        poly = polygons[key]
+        maxarea = float(maxareas[key])
+        project.interior_regions.append([poly,
+                                         maxarea*project.scale_factor])
+
+for filename, maxarea in project.interior_regions_data:
+    polygon = read_polygon(join(project.polygons_folder, filename))
+    project.interior_regions.append([polygon,
+                                     maxarea*project.scale_factor])
+
+# Initial bounding polygon for data clipping 
+project.bounding_polygon = read_polygon(join(project.polygons_folder,
+                                             project.bounding_polygon_filename))
+project.bounding_maxarea = project.bounding_polygon_maxarea*project.scale_factor
+
+# Estimate the number of triangles                     
+trigs_min = number_mesh_triangles(project.interior_regions,
+                                  project.bounding_polygon,
+                                  project.bounding_maxarea)
+
+print 'min estimated number of triangles', trigs_min
Index: /anuga_work/production/wa/shark_bay_2007/build_shark_bay.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/build_shark_bay.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/build_shark_bay.py	(revision 7411)
@@ -0,0 +1,122 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project.output_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated submarine landslide.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water.data_manager import convert_dem_from_ascii2netcdf
+from anuga.shallow_water.data_manager import dem2pts
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.geospatial_data.geospatial_data import Geospatial_data
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import urs_ungridded2sww
+from anuga_parallel.parallel_abstraction import get_processor_name
+
+# Application specific imports
+import project   # Definition of file names and polygons
+
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+
+copy_code_files(project.output_build_time_dir,__file__, 
+               dirname(project.__file__)+sep+ project.__name__+'.py' )#
+
+start_screen_catcher(project.output_build_time_dir)
+
+print 'Processor Name:', get_processor_name()
+print 'User: ', project.user
+
+
+#-------------------------------------------------------------------------------
+# Preparation of topographic data
+#
+# Convert ASC 2 DEM 2 PTS using source data and store result in source data
+# Do for coarse and fine data
+# Fine pts file to be clipped to area of interest
+#-------------------------------------------------------------------------------
+
+print 'project.combined_dir_name', project.combined_dir_name
+
+
+geospatial_data = None
+# create DEMs from asc data
+
+# FIXME (Ole): Clip data by interior regions if possible
+
+print 'creating geospatial data objects from asc data (via dem and pts formats)'
+for filename in project.ascii_grid_filenames:
+    convert_dem_from_ascii2netcdf(filename,
+                                  basename_out=filename,
+                                  use_cache=True, verbose=True)
+    dem2pts(filename, use_cache=True, verbose=True)
+
+    geospatial_data += Geospatial_data(file_name=filename + '.pts',
+                                       verbose=True)
+
+
+print 'creating geospatial data objects from txt data'
+for filename in project.point_filenames:
+    geospatial_data += Geospatial_data(file_name=filename + '.txt',
+                                       verbose=True)
+
+
+print 'clip combined geospatial object by bounding polygon'
+G = geospatial_data.clip(project.bounding_polygon)
+
+
+print 'export combined geospatial data'
+if access(project.topographies_dir, F_OK) == 0:
+    mkdir (project.topographies_dir)
+G.export_points_file(project.combined_dir_name + '.pts')
+
+
+#print 'split combined data set'
+#G_small, _ = G.split(0.1, True)
+#
+#print 'export sub sampled DEM file'
+#G_small.export_points_file(project.combined_dir_name + '_small' + '.txt')
+
+
+ 
+#-------------------------------------------------------------------------
+# Convert URS to SWW file for boundary conditions 
+#-------------------------------------------------------------------------
+print 'converting boundary conditions to sww format'
+
+print 'boundary_dir', project.boundary_dir
+print 'project.boundary_name', project.boundary_name
+
+urs_ungridded2sww(project.boundary_name, verbose=True,
+                  mint=0, maxt=40000, zscale=1)
+
+
+print 'Finished building the %s scenario' %project.scenario_name
+
+
Index: /anuga_work/production/wa/shark_bay_2007/convert_shapefiles_to_csv.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/convert_shapefiles_to_csv.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/convert_shapefiles_to_csv.py	(revision 7411)
@@ -0,0 +1,44 @@
+"""
+
+This uses ogr2ogr to convert shapefiles to gml and then 'manually' to csv
+It is assumed that the shapefile is in UTM coordinates
+"""
+
+import os
+import project
+
+os.chdir(project.polygons_dir)
+for file in os.listdir('.'):
+    root, extension = os.path.splitext(file)
+    if extension == '.shp':
+        s = 'ogr2ogr -f "GML" %s.gml %s.shp' %(root, root)
+        print s
+        os.system(s)
+
+        # Convert gml to csv
+        absolute_root = os.path.join(project.polygons_dir, root)
+        
+        infile = open(absolute_root + '.gml')
+        outfile = open(absolute_root + '.csv', 'w')
+
+        # Search for start of coordinate info
+        gml_code = infile.read()
+        infile.close()
+        
+        i = gml_code.find('<gml:coordinates>')
+        if i >= 0:
+            first = i + 17
+
+        # Search for end of coordinate info
+        i = gml_code.find('</gml:coordinates>')            
+        last = i
+
+        #print dir(outfile)
+        print 'Writing coordinates to', outfile.name
+        coordinates = gml_code[first:last]
+        for line in coordinates.split():
+            outfile.write(line + '\n')
+        outfile.close()
+
+print 'Done'
+        
Index: /anuga_work/production/wa/shark_bay_2007/export_results.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/export_results.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/export_results.py	(revision 7411)
@@ -0,0 +1,73 @@
+import project, os
+import sys
+
+from anuga.shallow_water.data_manager import sww2dem
+from os import sep
+
+#time_dir = '20070711_034317_run_final_0.0_shark_bay_onielsen_10000_tide0.0_coastpolys' # July 2006 event; small domain
+#time_dir = '20070710_023824_run_final_-0.85_shark_bay_onielsen_july2006_tide-0.85_coastpolys' # July 2006; larger domain
+time_dir = '20070717_021240_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T1200'
+cellsize = 10
+timestep = None
+directory = project.output_dir
+
+name = directory+time_dir+sep+project.scenario_name
+
+is_parallel = False
+if is_parallel == True: nodes = 4
+print 'output dir:', name
+
+#var = [0,2,3] # stage, depth and speed
+var = [4]
+
+for which_var in var:
+    if which_var == 0:  # Stage
+        outname = name + '_stage'
+        quantityname = 'stage'
+
+    if which_var == 1:  # Absolute Momentum
+        outname = name + '_momentum_i1'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5'  
+
+    if which_var == 2:  # Depth
+        outname = name + '_depth'
+        quantityname = 'stage-elevation'  
+
+    if which_var == 3:  # Speed
+        outname = name + '_speed'
+        quantityname = '(xmomentum**2 + ymomentum**2)**0.5/(stage-elevation+1.e-6/(stage-elevation))'  #Speed
+
+    if which_var == 4:  # Elevation
+        outname = name + '_elevation'
+        quantityname = 'elevation'  #Elevation
+
+    if is_parallel == True:
+    #    print 'is_parallel',is_parallel
+        for i in range(0,nodes):
+            namei = name + '_P%d_%d' %(i,nodes)
+            outnamei = outname + '_P%d_%d' %(i,nodes)
+            print 'start sww2dem for sww file %d' %(i)
+            sww2dem(namei, basename_out = outnamei,
+                        quantity = quantityname,
+                        timestep = timestep,
+                        cellsize = cellsize,      
+                        easting_min = project.e_min_area,
+                        easting_max = project.e_max_area,
+                        northing_min = project.n_min_area,
+                        northing_max = project.n_max_area,        
+                        reduction = max, 
+                        verbose = True,
+                        format = 'asc')
+    else:
+        print 'start sww2dem'
+        sww2dem(name, basename_out = outname,
+                    quantity = quantityname,
+                    timestep = timestep,
+                    cellsize = cellsize,      
+                    easting_min = project.e_min_area,
+                    easting_max = project.e_max_area,
+                    northing_min = project.n_min_area,
+                    northing_max = project.n_max_area,        
+                    reduction = max, 
+                    verbose = True,
+                    format = 'txt')
Index: /anuga_work/production/wa/shark_bay_2007/extract_boundary_timeseries.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/extract_boundary_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/extract_boundary_timeseries.py	(revision 7411)
@@ -0,0 +1,29 @@
+""" Script for generating timeseries from the sww file representing
+the boundary condition for this location.
+
+This to check that arrival times and amplitudes etc are sane at the boundary.
+see sww2timeseries for documentation
+"""
+
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries
+import project
+from os import sep
+
+# generate figures - see sww2timeseries for documentation
+texname = sww2timeseries({project.boundary_name + '.sww': ''},
+                         project.polygons_dir + sep + 'boundary_extent_small.csv',
+                         #project.polygons_dir + sep + 'boundary_points.csv',
+                         project.anuga_dir,
+                         report = False,
+                         #reportname = 'Boundary_gauges',
+                         plot_quantity = ['stage', 'speed'],
+                         generate_fig = True, 
+                         time_min = None,
+                         time_max = None,
+                         time_thinning = 1,                         
+                         title_on = True,
+                         use_cache = True,
+                         verbose = True)
+
+print 'finished plotting time series'
+
Index: /anuga_work/production/wa/shark_bay_2007/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/get_timeseries.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/get_timeseries.py	(revision 7411)
@@ -0,0 +1,75 @@
+""" Script for generating timeseries from the sww file representing
+the boundary condition for this location.
+
+This to check that arrival times and amplitudes etc are sane at the boundary.
+see sww2timeseries for documentation
+"""
+
+from anuga.abstract_2d_finite_volumes.util import sww2timeseries
+import project
+from os import sep
+
+production_dirs = {#'20070710_023849_run_final_-0.85_shark_bay_onielsen_10000_tide-0.85_coastpolys': 'LAT10000',
+                   #'20070710_001018_run_final_0.85_shark_bay_onielsen_10000_tide0.85_coastpolys': 'HAT10000'}
+                   #'20070710_001110_run_final_0.85_shark_bay_onielsen_july2006_tide0.85_coastpolys': 'HAT06',
+                   # 20070710_023824_run_final_-0.85_shark_bay_onielsen_july2006_tide-0.85_coastpolys': 'LAT06',
+                    #'20070712_001432_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T100': 'T100'}
+                    #'20070712_002232_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T200': 'T200'}
+                    #'20070712_002254_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T400': 'T400'}
+                    #'20070712_002317_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T800': 'T800'}
+                    #'20070712_002331_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T900': 'T900'}
+                    #'20070712_002526_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1800': 'T1800'}
+                    #'20070712_002604_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T3600': 'T3600'}
+                    #'20070712_002625_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T7200': 'T7200'}
+                    #'20070712_003334_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T300': 'T300'}
+                    #'20070712_003400_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T500': 'T500'}
+                    #'20070712_003410_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T600': 'T600'}
+                    #'20070712_003421_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T700': 'T700'}
+                    #'20070712_003433_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1000': 'T1000'}
+                    #'20070712_003443_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1100': 'T1100'}
+                    #'20070712_003453_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1200': 'T1200'}
+                    #'20070712_003527_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1300': 'T1300'}
+                    #'20070712_003606_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T50': 'T50'}
+                    #'20070712_003616_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T25': 'T25'}
+                    #'20070712_003626_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T12': 'T12'}
+                    #'20070712_003638_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T6': 'T6'}
+                    #'20070717_021240_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T1200': 'T1200new'}
+                    #'20070717_021545_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T1300': 'T1300new'}
+                    #'20070717_021601_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T1400': 'T1400new'}
+                    #'20070717_021615_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T1500': 'T1500new'}
+                    #'20070717_021646_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T1100': 'T1100new'}
+                    #'20070717_021656_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T1000': 'T1000new'}
+                    #'20070717_021707_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T900': 'T900new'}
+                    #'20070717_021717_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T800': 'T800new'}
+                    #'20070717_021750_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T700': 'T700new'}
+                    #'20070717_021801_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T600': 'T600new'}
+                    #'20070717_021814_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T300': 'T300new'}
+                    #'20070717_021831_run_final_0.79_shark_bay_onielsen_experimental_A0.5_T3000': 'T3000new'}
+                    #'20070716_025846_run_final_0.79_shark_bay_onielsen_july2006_X1_fixedbathy': '2006new'}
+                    #'20070713_033049_run_final_0.0_shark_bay_onielsen_july2006_X10_fixedbathy': '2006new10'}
+                    #'20070716_011226_run_final_0.0_shark_bay_onielsen_july2006_X50_fixedbathy': '2006new50'}
+                    '20070716_024711_run_final_0.79_shark_bay_onielsen_10000_X1_fixedbathy': '10000new'}
+                    #'': ''}
+
+swwfiles = {}    
+for label_id in production_dirs.keys():
+    
+    file_loc = project.output_dir + label_id + sep
+    swwfile = file_loc + project.scenario_name + '.sww'
+    swwfiles[swwfile] = label_id
+    
+    # generate figures - see sww2timeseries for documentation
+    texname = sww2timeseries(swwfiles,
+                             project.gauges_dir_name,
+                             production_dirs,
+                             report = False,
+                             plot_quantity = ['stage', 'speed'],
+                             generate_fig = False, 
+                             time_min = None,
+                             time_max = None,
+                             title_on = True,
+                             use_cache = True,
+                             verbose = True)
+
+print 'finished plotting time series'
+
Index: /anuga_work/production/wa/shark_bay_2007/plot_gauges.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/plot_gauges.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/plot_gauges.py	(revision 7411)
@@ -0,0 +1,119 @@
+"""Read in csv files and plot time series
+
+"""
+import project
+from pylab import plot, xlabel, ylabel, savefig, ion, hold, axis, close, figure, legend, title
+from os import sep
+
+directory = project.output_dir
+dirnames = [
+#'20070710_023849_run_final_-0.85_shark_bay_onielsen_10000_tide-0.85_coastpolys',
+#'20070710_001018_run_final_0.85_shark_bay_onielsen_10000_tide0.85_coastpolys',
+#'20070710_001110_run_final_0.85_shark_bay_onielsen_july2006_tide0.85_coastpolys',
+#'20070710_023824_run_final_-0.85_shark_bay_onielsen_july2006_tide-0.85_coastpolys',
+'20070712_003638_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T6',
+'20070712_003626_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T12',
+'20070712_003616_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T25',
+'20070712_003606_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T50',
+'20070712_001432_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T100',
+'20070712_002232_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T200',
+'20070712_003334_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T300',
+'20070712_002254_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T400',
+'20070712_003400_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T500',
+'20070712_003410_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T600',
+'20070712_003421_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T700',
+'20070712_002317_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T800',
+'20070712_002331_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T900',
+'20070712_003433_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1000',
+'20070712_003443_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1100',
+'20070712_003453_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1200',
+'20070712_003527_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1300',
+'20070712_002526_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T1800',
+'20070712_002604_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T3600',
+'20070712_002625_run_final_0.0_shark_bay_onielsen_experimental_A0.5_T7200'
+]
+
+period = [6,12,15,50,100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1800,3600,7200]
+
+def get_time_series_from_file(filename):
+    fid = open(filename)
+    lines = fid.readlines()
+    fid.close()
+    t = []
+    stage = []
+    #depth = []
+    speed = []
+    #momentum = []
+    for line in lines[1:]:
+        fields = line.split(',')
+        t.append((float(fields[0])/3600.0))
+        stage.append(float(fields[1]))
+        #depth.append(float(fields[1])-float(fields[4]))
+        speed.append(float(fields[3]))
+        #momentum.append(float(fields[2]))
+    return stage, speed
+    
+from Numeric import zeros, Float, size
+gauges = range(3,80)
+plot_gauges = range(77)
+max_st = max_sp = min_st = min_sp = max_m = min_m = zeros((len(gauges),len(dirnames)), Float)
+max_t = []
+
+for j, dirname in enumerate(dirnames):
+    for i, gauge in enumerate(gauges):  #could alter get_all_swwfiles to get all file extension and get csv files??
+        extra = 'gauges_time_series_%d.csv' %(gauge)
+        filename = directory + dirname + sep + extra
+        stage, speed = get_time_series_from_file(filename)
+        #max_t.append(max(t))
+        max_st[i,j] = max(stage)
+        max_sp[i,j] = max(speed)
+        min_st[i,j] = min(stage)
+        min_sp[i,j] = min(speed)
+        #min_m[i,j] = min(mom)
+        #max_m[i,j] = max(mom)
+
+#find maximums for axis for plots
+#stage_axis = ([5000./3600.,max(max_t), min(min(min_st)), max(max(max_st))])
+#speed_axis = ([5000/3600.,max(max_t), min(min(min_sp)), max(max(max_sp))])
+#mom_axis = ([5000/3600.,max(max_t), min(min(min_m)), max(max(max_m))])
+
+ion()
+hold(False)
+
+for i in plot_gauges:
+    plot(period,min_st[i,:],'+',period,max_st[i,:],'+',period,min_st[i,:],period,max_st[i,:])
+    #plot(period,max_st[i,:],'+',period,max_st[i,:])
+    xlabel('Period')
+    ylabel('Stage (m)')
+    axis(stage_axis)
+    name = 'stage_period_%d' %(i+3)
+    savefig(name)
+    plot(period,min_sp[i,:],'+',period,max_sp[i,:],'+',period,min_sp[i,:],period,max_sp[i,:])
+    #plot(period,max_sp[i,:],'+',period,max_sp[i,:])
+    xlabel('Period')
+    ylabel('Speed (m/s)')
+    axis(speed_axis)
+    name = 'speed_period_%d' %(i)
+    savefig(name)
+
+for i, dirname in enumerate(dirnames):
+    plot(gauges,min_st[:,i],'+',gauges,max_st[:,i],'+',gauges,min_st[:,i],gauges,max_st[:,i])
+    #plot(gauges,max_st[:,i],'+',gauges,max_st[:,i])
+    xlabel('Gauge number')
+    ylabel('Stage (m)')
+    axis(stage_axis)
+    title(dirname)
+    j = dirname.rfind('_')
+    name = 'stage_%s' %(dirname[j+1:])
+    savefig(name)
+    plot(gauges,min_sp[:,i],'+',gauges,max_sp[:,i],'+',gauges,min_sp[:,i],gauges,max_sp[:,i])
+    #plot(gauges,max_sp[:,i],'+',gauges,max_sp[:,i])
+    xlabel('Gauge number')
+    ylabel('Speed (m/s)')
+    axis(speed_axis)
+    title(dirname)
+    name = 'speed_%s' %(dirname[j+1:])
+    savefig(name)
+
+close('all')
+
Index: /anuga_work/production/wa/shark_bay_2007/project.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/project.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/project.py	(revision 7411)
@@ -0,0 +1,272 @@
+"""Common filenames and locations for topographic data, meshes and outputs.
+Also includes origin for slump scenario.
+
+All filenames are given without extension
+"""
+
+from os import sep, environ, getenv, getcwd, umask
+from os.path import expanduser, basename, join
+from anuga.utilities.polygon import read_polygon, plot_polygons, polygon_area, is_inside_polygon, number_mesh_triangles
+import sys
+from anuga.coordinate_transforms.redfearn import degminsec2decimal_degrees
+from time import localtime, strftime, gmtime
+from anuga.utilities.system_tools import get_user_name, get_host_name
+
+#codename = 'project.py' # FIXME can be obtained automatically as __file__
+
+home = join(getenv('INUNDATIONHOME'), 'data') # Location of Data   
+user = get_user_name()
+host = get_host_name()
+
+#needed when running using mpirun, mpirun doesn't inherit umask from .bashrc
+umask(002)
+
+#Making assumptions about the location of scenario data
+state = 'western_australia'
+scenario_name = 'shark_bay'
+scenario = 'shark_bay_tsunami_scenario'
+
+#time stuff
+time = strftime('%Y%m%d_%H%M%S',gmtime()) #gets time for new dir
+build_time = time+'_build'
+run_time = time+'_run'
+
+#tide = 0.0 # MSL
+tide = 0.79 # HAT average between Denham and Canarvon
+#tide = -0.80 # Estimated LAT
+
+# For frequency response study
+amplitude = 0.5
+period = 1800
+
+#momentum_scale=50 # Experiment
+momentum_scale=1 # Experiment                        
+
+#Maybe will try to make project a class to allow these parameters to be passed in.
+alpha = 0.1
+friction = 0.01
+finaltime = 40000
+starttime = 8000 # Action starts around 9000
+setup='final'
+#setup='trial'
+source='shark_bay'
+
+#boundary_event = 'july2006'
+#boundary_event = '10000'
+boundary_event = 'experimental'
+
+if setup =='trial':
+    print'trial'
+    res_factor=10
+    time_thinning=48
+    yieldstep=240
+if setup =='basic': 
+    print'basic'
+    res_factor=4
+    time_thinning=12
+    yieldstep=120
+if setup =='final': 
+    print'final'
+    res_factor=1.0
+    time_thinning=1
+    yieldstep=10
+
+
+
+#dir_comment='_'+setup+'_'+str(tide)+'_'+str(source)+'_'+\
+#             str(user)+'_'+boundary_event+'_X'+str(momentum_scale)+'_fixedbathy'
+
+dir_comment='_'+setup+'_'+str(tide)+'_'+str(source)+'_'+\
+             str(user)+'_'+boundary_event
+
+
+if boundary_event == 'experimental':
+    dir_comment += '_A'+str(amplitude)+'_T'+str(period)
+    
+
+# elevation data filenames
+ascii_grid_filenames = ['10m_dem_without_survey', '50m_dem_without_10m_dem',
+                        'bathysteeppt', 'bathyleft', 'bathyright']
+point_filenames = ['field_survey_north', 'field_survey_south',
+                   'clipped_bathymetry_final', 'coast_points_final']
+
+# final topo name
+combined_name ='shark_bay_combined_elevation'
+combined_small_name = 'shark_bay_combined_elevation_small'
+
+
+anuga_dir = join(home, state, scenario, 'anuga')
+
+topographies_in_dir = join(home, state, scenario,
+                           'elevation_final', 'test_area')
+
+topographies_dir = join(anuga_dir, 'topographies') # Output dir for ANUGA
+
+# Convert topo file locations into absolute pathnames
+for filename_list in [ascii_grid_filenames, point_filenames]:
+    for i, filename in enumerate(filename_list):
+        filename_list[i] = join(topographies_in_dir, filename)
+
+#final topo files
+combined_dir_name = join(topographies_dir, combined_name)
+combined_small_dir_name = join(topographies_dir, combined_small_name)
+
+
+mesh_dir = join(anuga_dir, 'meshes')
+mesh_name = join(mesh_dir, scenario_name)
+
+
+polygons_dir = join(anuga_dir, 'polygons') # Created with ArcGIS (csv files)
+tide_dir = join(anuga_dir, 'tide_data')
+
+
+# locations for boundary conditions
+if source=='shark_bay':
+    if boundary_event == '10000':
+        boundary_file_name = 'shark_bay_3867_18052007'
+        boundary_dir = join(anuga_dir, 'boundaries', 'shark_bay', '1_10000')
+    elif boundary_event == 'july2006':
+        boundary_file_name = 'july2006'    
+        boundary_dir = join(anuga_dir, 'boundaries',
+                            'shark_bay', 'july_2006_event')
+    else:
+        pass
+        #raise Exception, 'Unknown boundary event specified'
+        
+if boundary_event != 'experimental':
+    boundary_name = join(boundary_dir, boundary_file_name)
+else:
+    boundary_name = 'nil'
+
+#output locations
+output_dir = join(anuga_dir, 'outputs')+sep
+output_build_time_dir = output_dir+build_time+sep
+output_run_time_dir = output_dir +run_time+dir_comment+sep
+output_run_time_dir_name = output_run_time_dir + scenario_name  #Used by post processing
+
+#gauges
+gauge_name = 'gaugesv3.csv' 
+#gauge_name_test = 'gauge_checking_test.csv' 
+gauges_dir = anuga_dir+sep+'gauges'+sep
+gauges_dir_name = gauges_dir + gauge_name
+#gauges_dir_name_test = gauges_dir + gauge_name_test
+
+#tide_dir = anuga_dir+'tide_data'+sep
+
+#buildings_filename = gauges_dir + 'pt_hedland_res.csv'
+#buildings_filename_out = 'pt_hedland_res_modified.csv'
+#buildings_filename_damage_out = 'pt_hedland_res_modified_damage.csv'
+#tidal_filename = tide_dir + 'pt_hedland_tide.txt'
+#community_filename = gauges_dir + 'CHINS_v2.csv'
+#community_scenario = gauges_dir + 'community_pt_hedland.csv'
+
+# clipping region to make DEM (pts file) from onshore data
+#eastingmin = 594000
+#eastingmax = 715000
+#northingmin = 7720000
+#northingmax = 7880000
+
+# for ferret2sww
+south = degminsec2decimal_degrees(-20,30,0)
+north = degminsec2decimal_degrees(-17,10,0)
+west = degminsec2decimal_degrees(117,00,0)
+east = degminsec2decimal_degrees(120,00,0)
+
+# region to export (used from export_results.py)
+e_min_area = 713500   # Eastings min
+e_max_area = 726350
+n_min_area = 7100890
+n_max_area = 7111250
+
+#export_region = [[e_min_area,n_min_area],[e_min_area,n_max_area],
+#                 [e_max_area,n_max_area],[e_max_area,n_min_area]]
+                 
+#FIXME (Ole): It is bad to read in polygons in project.py. If a file does not exist
+#project.py cannot be imported
+
+# Bounding polygon
+bounding_polygon = read_polygon(join(polygons_dir, 'boundary_extent_small.csv'))
+res_bounding_polygon = 500000*res_factor
+
+# This is a restricted boundary used for experiments.
+# Cannot use URS boundary on this!
+small_bounding_polygon = read_polygon(join(polygons_dir, 'small_boundary.csv'))
+res_bounding_polygon = 500000*res_factor
+
+
+# Interior regions
+interior_regions_and_resolutions = {
+    'study_area': 300000,
+    'bernier_dorre_islands': 250000,
+    'map_area': 10000,
+    'bay_area': 4000,
+    'south_bank_buffer': 2000,
+    'south_coast_polygon_1': 1000,
+    'south_coast_polygon_2': 1000,
+    'north_bay_coastline': 1000,
+    'tsunami_approach_area': 50,
+    'inundated_area': 10,
+    'exclusion_1': 10000000,
+    'exclusion_2': 10000000,
+    'exclusion_3': 10000000}
+
+
+#poly_exclusion_area1 = read_polygon(join(polygons_dir, 'exclusion_area1.csv'))
+#res_exclusion_area1 = 2000000*res_factor
+#
+#interior_regions = [[poly_inundated_area, res_inundated_area],
+#                    [poly_tsunami_approach_area, res_tsunami_approach_area],
+#                    [poly_bay_area, res_bay_area],                    
+#                    [poly_map_area, res_map_area]]
+                    #[poly_model_area, res_model_area],
+                    #[poly_exclusion_area1, res_exclusion_area1]]                                        
+
+# FIXME (Ole): What if tags are wrong?
+
+#Large bounding poly
+#boundary_tags = {'back': [1, 2, 3, 4, 5],   
+#                 'side': [0, 6],
+#                 'ocean': [7, 8, 9, 10, 11]}
+
+
+#Small bounding poly
+#(counter clockwise starting in upper right corner)
+boundary_tags = {'tide': [0, 1, 2],
+                 'ocean': [3, 4, 5, 6]}
+
+#Very small bounding poly (experimental boundary)
+boundary_tags_small = {'tide': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13],
+                       'ocean': [11]}
+
+
+
+# Read filenames etc (FIXME: move this to new file: read_structures)
+
+interior_regions = [] # Consider using dictionary for mesh interface.
+for area_name in interior_regions_and_resolutions.keys():
+    file_name = join(polygons_dir, area_name + '.csv')
+    
+    print 'Reading polygon from', file_name 
+    polygon = read_polygon(file_name)
+    base_resolution = interior_regions_and_resolutions[area_name]
+    
+    interior_regions.append([polygon, base_resolution*res_factor])
+
+
+
+
+trigs_min = number_mesh_triangles(interior_regions,
+                                  bounding_polygon,
+                                  res_bounding_polygon)
+
+
+
+# For use with resetting IC (This is temporary)
+poly_tsunami_approach_area = read_polygon(
+    join(polygons_dir, 'tsunami_approach_area.csv'))
+
+
+
+onshore_polygon = read_polygon(join(topographies_in_dir,
+                                    'initial_condition.txt'))
+
Index: /anuga_work/production/wa/shark_bay_2007/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/run_boundary_points.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/run_boundary_points.py	(revision 7411)
@@ -0,0 +1,32 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+The output sww file is stored in project.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+
+# # Related major packages
+# from anuga.shallow_water import Domain
+from anuga.shallow_water.data_manager import URS_points_needed_to_file, \
+     urs_ungridded2sww
+import project                 # Definition of file names and polygons
+
+#------------------------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#------------------------------------------------------------------------------
+poly = project.poly_all
+print "poly", poly
+print "project.boundaries",project.boundaries_dir
+URS_points_needed_to_file(project.boundaries_dir_name,poly, export_csv=True, zone=49)
Index: /anuga_work/production/wa/shark_bay_2007/run_shark_bay.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/run_shark_bay.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/run_shark_bay.py	(revision 7411)
@@ -0,0 +1,252 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project_urs.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep,umask
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from Numeric import allclose
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+def run_model(**kwargs):
+    
+    tide = kwargs['tide']
+    alpha = kwargs['alpha']
+    friction = kwargs['friction']
+    time_thinning = kwargs['time_thinning']
+    scenario_name = kwargs['aa_scenario_name']
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+
+    #copy script must be before screen_catcher
+    print 'tide',tide
+    kwargs['est_num_trigs']=project.trigs_min
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project.host
+    kwargs['res_factor']=project.res_factor
+    kwargs['starttime']=project.starttime
+    kwargs['yieldstep']=project.yieldstep
+    kwargs['finaltime']=project.finaltime
+    
+    kwargs['output_dir']=project.output_run_time_dir
+    kwargs['bathy_file']=project.combined_dir_name + '.pts'
+#    kwargs['bathy_file']=project.combined_small_dir_name + '.pts'
+    kwargs['boundary_file']=project.boundary_name + '.sww'
+#    kwargs['Completed']=''
+
+    print 'output_dir',kwargs['output_dir']
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                        dirname(project.__file__)+sep+project.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print 'Processor Name:', get_processor_name()
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    #IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+
+    # FIXME (Ole): Move to build_shark_bay.py
+    if myid == 0:
+    
+        print 'start create mesh from regions'
+        
+        create_mesh_from_regions(project.bounding_polygon,
+                                 boundary_tags=project.boundary_tags,
+                                 maximum_triangle_area=project.res_bounding_polygon,
+                                 interior_regions=project.interior_regions,
+                                 filename=project.mesh_name+'.msh',
+                                 use_cache=False,
+                                 verbose=True)
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    #domain = cache(Domain, (mesh_name), {'use_cache':True, 'verbose':True}, verbose=True)
+    #above don't work
+    domain = Domain(project.mesh_name+'.msh',
+                    use_cache=False, verbose=True)
+     
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    if myid == 0:
+
+        IC = project.tide
+        #if project.tide == 0.0:
+        #    print 'Tide is MSL'
+        #    IC = 0.0
+        #else:    
+        #    print 'Create onshore polygon'
+        #    from polygon import Polygon_function
+        #    #following sets the stage/water to be offcoast only
+        #    IC = Polygon_function([(project.onshore_polygon, -1.0)],
+        #                          default = tide,
+        #                          geo_reference = domain.geo_reference)
+            
+
+        print 'Set initial conditions'
+        domain.set_quantity('stage', IC)
+        domain.set_quantity('friction', friction)
+        print 'Set elevation'
+        domain.set_quantity('elevation', 
+                            filename = kwargs['bathy_file'],
+                            use_cache = True,
+                            verbose = True,
+                            alpha = alpha)
+        
+
+    #------------------------------------------------------
+    # Distribute domain to implement parallelism !!!
+    #------------------------------------------------------
+    barrier()
+    if numprocs > 1:
+        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(scenario_name)
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2) # Apply second order scheme
+    domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+    print 'domain id', id(domain)
+    
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+    #print 'Reading Boundary file',project.boundaries_dir_namea + '.sww'
+
+    Bf = Field_boundary(kwargs['boundary_file'],
+                        domain,
+                        time_thinning=time_thinning,
+                        mean_stage=tide,
+                        momentum_scale=project.momentum_scale,                        
+                        use_cache=False,
+                        verbose=True)
+                    
+    kwargs['input_start_time']=domain.starttime
+
+    print 'finished reading boundary file'
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([tide,0,0])
+
+    print'set_boundary'
+
+    #domain.set_boundary({'back': Br,
+    #                     'side': Bd,
+    #                     'ocean': Bf})
+    domain.set_boundary({'tide': Bd,
+    #                     'ocean': Dirichlet_boundary([3,0,0])})
+                         'ocean': Bf})     
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #----------------------------------------------------------------------------
+
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['starttime']): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+
+
+    # Reset stage in study area
+    print 'Reset initial condition in study area'
+    domain.set_quantity('stage', project.tide,
+                        polygon=project.poly_tsunami_approach_area)
+    
+
+    for t in domain.evolve(yieldstep = kwargs['yieldstep'], finaltime = 18000
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+    
+    for t in domain.evolve(yieldstep = 240, finaltime = kwargs['finaltime']
+                       ,skip_initial_step = True): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')   
+
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'That took %.2f seconds' %(time.time()-t0)
+    
+    kwargs['completed']=str(time.time()-t0)
+    
+    store_parameters(**kwargs)
+
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+    run_model(file_name=project.home+'detail.csv', aa_scenario_name=project.scenario_name,
+              ab_time=project.time, res_factor= project.res_factor, tide=project.tide, user=project.user,
+              alpha = project.alpha, friction=project.friction,
+              time_thinning = project.time_thinning,
+              dir_comment=project.dir_comment)
+
+
Index: /anuga_work/production/wa/shark_bay_2007/run_shark_bay_embayment_study.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/run_shark_bay_embayment_study.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/run_shark_bay_embayment_study.py	(revision 7411)
@@ -0,0 +1,170 @@
+"""Script for running embayment study for Steep Point, WA, Australia.
+
+Title: Embayment study for Steep Point
+
+Description:
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project.py
+
+This script is designed to run a series of idealised incident waveforms
+at different frequencies.
+
+
+Author:  Ole Nielsen (Ole.Nielsen@ga.gov.au)
+
+CreationDate: 2007
+
+
+ModifiedBy:
+    $Author: ole $
+    $Date: 2007-11-30 11:47:13 +1100 (Fri, 30 Nov 2007) $
+    $LastChangedRevision: 4867 $    
+
+"""
+
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep
+from os.path import dirname
+from math import sin, pi
+import time
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Transmissive_Momentum_Set_Stage_boundary
+from Numeric import allclose
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import store_parameters
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+
+    
+    
+#-----------------------------------------------------------------
+# Copy scripts to time stamped output directory and capture screen
+# output to file
+#-----------------------------------------------------------------
+
+copy_code_files(project.output_run_time_dir,
+                __file__, 
+                dirname(project.__file__)+sep+project.__name__+'.py' )
+
+
+start_screen_catcher(project.output_run_time_dir)
+
+
+#--------------------------------------------------------------------------
+# Create the triangular mesh based on overall clipping polygon with a
+# tagged
+# boundary and interior regions defined in project.py along with
+# resolutions (maximal area of per triangle) for each polygon
+#--------------------------------------------------------------------------
+
+print 'Create mesh from regions'
+create_mesh_from_regions(project.small_bounding_polygon,
+                         boundary_tags=project.boundary_tags_small,
+                         maximum_triangle_area=project.res_bounding_polygon,
+                         interior_regions=project.interior_regions,
+                         filename=project.mesh_name+'.msh',
+                         fail_if_polygons_outside=False,
+                         use_cache=False,
+                         verbose=True)
+
+#-------------------------------------------------------------------------
+# Setup computational domain
+#-------------------------------------------------------------------------
+print 'Setup computational domain'
+domain = Domain(project.mesh_name+'.msh',
+                use_cache=False, verbose=True)
+
+print domain.statistics()
+    
+
+#-------------------------------------------------------------------------
+# Setup initial conditions
+#-------------------------------------------------------------------------
+
+print 'Set initial conditions'
+domain.set_quantity('stage', project.tide)
+domain.set_quantity('friction', project.friction)
+domain.set_quantity('elevation', 
+                    filename = project.combined_dir_name + '.pts',
+                    use_cache = True,
+                    verbose = True,
+                    alpha = project.alpha)
+        
+
+#------------------------------------------------------
+# Set domain parameters
+#------------------------------------------------------
+domain.set_name(project.scenario_name)
+domain.set_datadir(project.output_run_time_dir)
+domain.set_default_order(2)              # Apply second order scheme
+domain.set_minimum_storable_height(0.01) # Don't store anything < 1cm
+domain.set_store_vertices_uniquely(False)
+domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+
+domain.tight_slope_limiters = True
+    
+
+#-------------------------------------------------------------------------
+# Setup boundary conditions 
+#-------------------------------------------------------------------------
+print 'Available boundary tags', domain.get_boundary_tags()
+print 'domain id', id(domain)
+
+def waveform(t):
+    delay = 900
+    A = project.amplitude
+    T = project.period
+    if t < delay:
+        # Let things settle
+        return project.tide
+    else:
+        return project.tide + A*sin(2*pi*(t-delay)/T)
+
+Bf = Transmissive_Momentum_Set_Stage_boundary(domain, waveform)
+Br = Reflective_boundary(domain)
+Bd = Dirichlet_boundary([project.tide,0,0])
+
+
+print 'Set boundary'
+domain.set_boundary({'tide': Bd,
+                     'ocean': Bf})
+
+
+#------------------------------
+# Evolve system through time
+#------------------------------
+t0 = time.time()
+for t in domain.evolve(yieldstep = 5,
+                       finaltime = 10000):
+    domain.write_time()
+    domain.write_boundary_statistics(tags='ocean')     
+
+
+#------------------------------
+# Post processing
+#------------------------------
+x, y = domain.get_maximum_inundation_location()
+q = domain.get_maximum_inundation_elevation()
+
+print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+print 'That took %.2f seconds' %(time.time()-t0)
+    
+
+
Index: /anuga_work/production/wa/shark_bay_2007/run_shark_bay_frequency_sweep.py
===================================================================
--- /anuga_work/production/wa/shark_bay_2007/run_shark_bay_frequency_sweep.py	(revision 7411)
+++ /anuga_work/production/wa/shark_bay_2007/run_shark_bay_frequency_sweep.py	(revision 7411)
@@ -0,0 +1,242 @@
+"""Script for running tsunami inundation scenario for Dampier, WA, Australia.
+
+Source data such as elevation and boundary data is assumed to be available in
+directories specified by project_urs.py
+The output sww file is stored in project_urs.output_run_time_dir 
+
+The scenario is defined by a triangular mesh created from project_urs.polygon,
+the elevation data and a simulated tsunami generated with URS code.
+
+Ole Nielsen and Duncan Gray, GA - 2005 and Jane Sexton, Nick Bartzis, GA - 2006
+"""
+
+#------------------------------------------------------------------------------
+# Import necessary modules
+#------------------------------------------------------------------------------
+
+# Standard modules
+from os import sep,umask
+from os.path import dirname, basename
+from os import mkdir, access, F_OK
+from shutil import copy
+from math import sin, pi
+import time
+import sys
+
+# Related major packages
+from anuga.shallow_water import Domain
+from anuga.shallow_water import Dirichlet_boundary
+from anuga.shallow_water import File_boundary
+from anuga.shallow_water import Reflective_boundary
+from anuga.shallow_water import Field_boundary
+from anuga.shallow_water import Transmissive_Momentum_Set_Stage_boundary
+from Numeric import allclose
+
+from anuga.pmesh.mesh_interface import create_mesh_from_regions
+from anuga.shallow_water.data_manager import start_screen_catcher
+from anuga.shallow_water.data_manager import copy_code_files
+from anuga.shallow_water.data_manager import store_parameters
+from anuga_parallel.parallel_api import distribute, numprocs, myid, barrier
+from anuga_parallel.parallel_abstraction import get_processor_name
+from anuga.caching import myhash
+
+# Application specific imports
+import project                 # Definition of file names and polygons
+
+def run_model(**kwargs):
+    
+    tide = kwargs['tide']
+    alpha = kwargs['alpha']
+    friction = kwargs['friction']
+    time_thinning = kwargs['time_thinning']
+    scenario_name = kwargs['aa_scenario_name']
+    
+    #------------------------------------------------------------------------------
+    # Copy scripts to time stamped output directory and capture screen
+    # output to file
+    #------------------------------------------------------------------------------
+
+    #copy script must be before screen_catcher
+    print 'tide',tide
+    kwargs['est_num_trigs']=project.trigs_min
+    kwargs['num_cpu']=numprocs
+    kwargs['host']=project.host
+    kwargs['res_factor']=project.res_factor
+    kwargs['starttime']=project.starttime
+    kwargs['yieldstep']=project.yieldstep
+    kwargs['finaltime']=project.finaltime
+    
+    kwargs['output_dir']=project.output_run_time_dir
+    kwargs['bathy_file']=project.combined_dir_name + '.pts'
+#    kwargs['bathy_file']=project.combined_small_dir_name + '.pts'
+    kwargs['boundary_file']=project.boundary_name + '.sww'
+#    kwargs['Completed']=''
+
+    print 'output_dir',kwargs['output_dir']
+    if myid == 0:
+        copy_code_files(kwargs['output_dir'],__file__, 
+                        dirname(project.__file__)+sep+project.__name__+'.py' )
+
+        store_parameters(**kwargs)
+
+    barrier()
+
+    start_screen_catcher(kwargs['output_dir'], myid, numprocs)
+
+    print 'Processor Name:', get_processor_name()
+
+    #--------------------------------------------------------------------------
+    # Create the triangular mesh based on overall clipping polygon with a
+    # tagged
+    # boundary and interior regions defined in project.py along with
+    # resolutions (maximal area of per triangle) for each polygon
+    #--------------------------------------------------------------------------
+
+    #IMPORTANT don't cache create_mesh_from_region and Domain(mesh....) as it
+    # causes problems with the ability to cache set quantity which takes alot of times
+
+    # FIXME (Ole): Move to build_shark_bay.py
+    if myid == 0:
+    
+        print 'start create mesh from regions'
+        
+        create_mesh_from_regions(project.small_bounding_polygon,
+                                 boundary_tags=project.boundary_tags_small,
+                                 maximum_triangle_area=project.res_bounding_polygon,
+                                 interior_regions=project.interior_regions,
+                                 filename=project.mesh_name+'.msh',
+                                 fail_if_polygons_outside=False,
+                                 use_cache=False,
+                                 verbose=True)
+
+    #-------------------------------------------------------------------------
+    # Setup computational domain
+    #-------------------------------------------------------------------------
+    print 'Setup computational domain'
+
+    #domain = cache(Domain, (mesh_name), {'use_cache':True, 'verbose':True}, verbose=True)
+    #above don't work
+    domain = Domain(project.mesh_name+'.msh',
+                    use_cache=False, verbose=True)
+       
+    print domain.statistics()
+    print 'triangles',len(domain)
+    
+    kwargs['act_num_trigs']=len(domain)
+
+    #-------------------------------------------------------------------------
+    # Setup initial conditions
+    #-------------------------------------------------------------------------
+    if myid == 0:
+
+        IC = project.tide
+
+        print 'Set initial conditions'
+        domain.set_quantity('stage', IC)
+        domain.set_quantity('friction', friction)
+        print 'Set elevation'
+        domain.set_quantity('elevation', 
+                            filename = kwargs['bathy_file'],
+                            use_cache = True,
+                            verbose = True,
+                            alpha = alpha)
+        
+
+    #------------------------------------------------------
+    # Distribute domain to implement parallelism !!!
+    #------------------------------------------------------
+    barrier()
+    if numprocs > 1:
+        domain=distribute(domain)
+
+    #------------------------------------------------------
+    # Set domain parameters
+    #------------------------------------------------------
+    print 'domain id', id(domain)
+    domain.set_name(scenario_name)
+    domain.set_datadir(kwargs['output_dir'])
+    domain.set_default_order(2) # Apply second order scheme
+    domain.set_minimum_storable_height(0.01) # Don't store anything less than 1cm
+    domain.set_store_vertices_uniquely(False)
+    domain.set_quantities_to_be_stored(['stage', 'xmomentum', 'ymomentum'])
+    domain.set_maximum_allowed_speed(0.1) # Allow a little runoff (0.1 is OK)
+    print 'domain id', id(domain)
+    domain.tight_slope_limiters = True
+    
+
+    #-------------------------------------------------------------------------
+    # Setup boundary conditions 
+    #-------------------------------------------------------------------------
+    print 'Available boundary tags', domain.get_boundary_tags()
+    print 'domain id', id(domain)
+    #print 'Reading Boundary file',project.boundaries_dir_namea + '.sww'
+
+    if project.boundary_event == 'experimental':
+        # Artificial        
+        #Bf = Dirichlet_boundary([2,0,0])
+        def waveform(t):
+            delay = 900
+            A = project.amplitude
+            T = project.period
+            if t < delay:
+                # Let things settle
+                return project.tide
+            else:
+                return project.tide + A*sin(2*pi*(t-delay)/T)
+
+        Bf = Transmissive_Momentum_Set_Stage_boundary(domain, waveform)
+    else:    
+        Bf = Field_boundary(kwargs['boundary_file'],
+                            domain,
+                            time_thinning=time_thinning,
+                            mean_stage=tide, 
+                            use_cache=False,
+                            verbose=True)
+                    
+    kwargs['input_start_time']=domain.starttime
+
+    print 'finished reading boundary file'
+
+    Br = Reflective_boundary(domain)
+    Bd = Dirichlet_boundary([tide,0,0])
+
+
+    print'set_boundary'
+
+    domain.set_boundary({'tide': Bd,
+                         'ocean': Bf})     
+    print'finish set boundary'
+
+    #----------------------------------------------------------------------------
+    # Evolve system through time
+    #----------------------------------------------------------------------------
+
+    t0 = time.time()
+
+    for t in domain.evolve(yieldstep = 5,
+                           finaltime = 10000): 
+        domain.write_time()
+        domain.write_boundary_statistics(tags = 'ocean')     
+
+
+    x, y = domain.get_maximum_inundation_location()
+    q = domain.get_maximum_inundation_elevation()
+
+    print 'Maximum runup observed at (%.2f, %.2f) with elevation %.2f' %(x,y,q)
+
+    print 'That took %.2f seconds' %(time.time()-t0)
+    
+    kwargs['completed']=str(time.time()-t0)
+    
+    store_parameters(**kwargs)
+
+#-------------------------------------------------------------
+if __name__ == "__main__":
+
+    run_model(file_name=project.home+'detail.csv', aa_scenario_name=project.scenario_name,
+              ab_time=project.time, res_factor= project.res_factor, tide=project.tide, user=project.user,
+              alpha = project.alpha, friction=project.friction,
+              time_thinning = project.time_thinning,
+              dir_comment=project.dir_comment)
+
+
Index: /anuga_work/production/wa/swan_river_tin_2005/generate_tin.py
===================================================================
--- /anuga_work/production/wa/swan_river_tin_2005/generate_tin.py	(revision 7411)
+++ /anuga_work/production/wa/swan_river_tin_2005/generate_tin.py	(revision 7411)
@@ -0,0 +1,12 @@
+"""Generate TIN (triangular mesh) from Swan river elevation data
+
+Ole Nielsen, GA 2005
+"""
+
+from anuga.pyvolution.data_manager import hecras_cross_sections2pts
+
+filename = 'cross_sections'
+hecras_cross_sections2pts(filename, verbose = True)
+
+
+    
Index: /anuga_work/production/wa/swan_river_tin_2005/populate_mesh.py
===================================================================
--- /anuga_work/production/wa/swan_river_tin_2005/populate_mesh.py	(revision 7411)
+++ /anuga_work/production/wa/swan_river_tin_2005/populate_mesh.py	(revision 7411)
@@ -0,0 +1,31 @@
+"""Script for fitting data points to mesh
+"""
+
+from anuga.pyvolution.pmesh2domain import pmesh_to_domain_instance 
+from caching import cache
+from anuga.pyvolution.shallow_water import Domain, Reflective_boundary
+
+
+meshname = 'swan_mesh.msh'
+
+domain = cache(pmesh_to_domain_instance, (meshname, Domain),
+               dependencies = [meshname],                     
+               verbose = True)               
+
+
+domain.set_quantity('elevation',
+                    filename = 'cross_sections.pts',
+                    use_cache = True,
+                    verbose = True)
+
+print domain.get_boundary_tags()
+Br = Reflective_boundary(domain)
+domain.set_boundary( {'exterior': Br} )
+
+
+domain.set_name('swan_river')
+domain.set_datadir('.')
+domain.store = True
+
+for t in domain.evolve(yieldstep = 1, finaltime = 1):
+    domain.write_time()
Index: /anuga_work/production/wa/swan_river_tin_2005/thin_generate_alpha.py
===================================================================
--- /anuga_work/production/wa/swan_river_tin_2005/thin_generate_alpha.py	(revision 7411)
+++ /anuga_work/production/wa/swan_river_tin_2005/thin_generate_alpha.py	(revision 7411)
@@ -0,0 +1,25 @@
+
+
+
+
+from anuga.pyvolution.load_mesh.loadASCII import reduce_pts
+from anuga.pmesh.mesh import importMeshFromFile
+
+thin_points_file = 'thinned_cross_sections.pts'
+alpha_outline_file = 'alpha_outline.msh'
+mesh_file = 'swan_mesh.msh'
+
+reduce_pts('cross_sections.pts', thin_points_file,
+           10000, verbose = True) # max # of points = 10000
+
+m = importMeshFromFile(thin_points_file)
+m.auto_segment( remove_holes=True,
+               smooth_indents=True,
+               expand_pinch=True)
+m.exportASCIIsegmentoutlinefile(alpha_outline_file)
+
+
+m_outline = importMeshFromFile(alpha_outline_file)
+#m_outline.generateMesh(maxArea = 1000) #191291 triangles
+m_outline.generateMesh(maxArea = 1000) 
+m_outline.export_mesh_file(mesh_file)
