Index: /anuga_work/production/wa/busselton_2006/project.py
===================================================================
--- /anuga_work/production/wa/busselton_2006/project.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2006/project.py	(revision 7434)
@@ -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 7434)
+++ /anuga_work/production/wa/busselton_2006/run_busselton.py	(revision 7434)
@@ -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_2008/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/Arc_asc2raster_GDA94z50.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/Arc_asc2raster_GDA94z50.py	(revision 7434)
@@ -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_2008/Arc_txt2feature_class.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/Arc_txt2feature_class.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/Arc_txt2feature_class.py	(revision 7434)
@@ -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_2008/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/Arc_txt2feature_class_res.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/Arc_txt2feature_class_res.py	(revision 7434)
@@ -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_2008/build_boundary_27255.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/build_boundary_27255.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/build_boundary_27255.py	(revision 7434)
@@ -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_2008/build_boundary_27283.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/build_boundary_27283.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/build_boundary_27283.py	(revision 7434)
@@ -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_2008/build_boundary_68693.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/build_boundary_68693.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/build_boundary_68693.py	(revision 7434)
@@ -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_2008/build_busselton.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/build_busselton.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/build_busselton.py	(revision 7434)
@@ -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_2008/build_busselton_250m.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/build_busselton_250m.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/build_busselton_250m.py	(revision 7434)
@@ -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_2008/export_results.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/export_results.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/export_results.py	(revision 7434)
@@ -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_2008/export_results_max.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/export_results_max.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/export_results_max.py	(revision 7434)
@@ -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_2008/get_gauges.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/get_gauges.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/get_gauges.py	(revision 7434)
@@ -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_2008/get_runup.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/get_runup.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/get_runup.py	(revision 7434)
@@ -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_2008/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/get_timeseries.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/get_timeseries.py	(revision 7434)
@@ -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_2008/locate_indigeneous.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/locate_indigeneous.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/locate_indigeneous.py	(revision 7434)
@@ -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_2008/ph2_compare.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/ph2_compare.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/ph2_compare.py	(revision 7434)
@@ -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_2008/ph2_compare_table.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/ph2_compare_table.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/ph2_compare_table.py	(revision 7434)
@@ -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_2008/project.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/project.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/project.py	(revision 7434)
@@ -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_2008/project_250m.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/project_250m.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/project_250m.py	(revision 7434)
@@ -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_2008/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/run_boundary_points.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/run_boundary_points.py	(revision 7434)
@@ -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_2008/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/run_building_inundation.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/run_building_inundation.py	(revision 7434)
@@ -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_2008/run_busselton.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/run_busselton.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/run_busselton.py	(revision 7434)
@@ -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_2008/run_busselton_250m.py
===================================================================
--- /anuga_work/production/wa/busselton_2008/run_busselton_250m.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2008/run_busselton_250m.py	(revision 7434)
@@ -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_2009/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/Arc_asc2raster_GDA94z50.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/Arc_asc2raster_GDA94z50.py	(revision 7434)
@@ -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_2009/Arc_txt2feature_class.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/Arc_txt2feature_class.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/Arc_txt2feature_class.py	(revision 7434)
@@ -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_2009/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/Arc_txt2feature_class_res.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/Arc_txt2feature_class_res.py	(revision 7434)
@@ -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_2009/Busselton4distribution.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/Busselton4distribution.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/Busselton4distribution.py	(revision 7434)
@@ -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_2009/Inundation_polygon.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/Inundation_polygon.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/Inundation_polygon.py	(revision 7434)
@@ -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_2009/README.txt
===================================================================
--- /anuga_work/production/wa/busselton_2009/README.txt	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/README.txt	(revision 7434)
@@ -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_2009/build_elevation.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/build_elevation.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/build_elevation.py	(revision 7434)
@@ -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_2009/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/build_urs_boundary.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/build_urs_boundary.py	(revision 7434)
@@ -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_2009/export_results_max.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/export_results_max.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/export_results_max.py	(revision 7434)
@@ -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_2009/file_length.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/file_length.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/file_length.py	(revision 7434)
@@ -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_2009/get_runup.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/get_runup.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/get_runup.py	(revision 7434)
@@ -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_2009/get_runup_v2.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/get_runup_v2.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/get_runup_v2.py	(revision 7434)
@@ -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_2009/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/get_timeseries.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/get_timeseries.py	(revision 7434)
@@ -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_2009/project.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/project.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/project.py	(revision 7434)
@@ -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_2009/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/run_building_inundation.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/run_building_inundation.py	(revision 7434)
@@ -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_2009/run_model.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/run_model.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/run_model.py	(revision 7434)
@@ -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_2009/setup_model.py
===================================================================
--- /anuga_work/production/wa/busselton_2009/setup_model.py	(revision 7434)
+++ /anuga_work/production/wa/busselton_2009/setup_model.py	(revision 7434)
@@ -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_2008/Arc_asc2raster_GDA94z49.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/Arc_asc2raster_GDA94z49.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/Arc_asc2raster_GDA94z49.py	(revision 7434)
@@ -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_2008/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/Arc_txt2feature_class_res.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/Arc_txt2feature_class_res.py	(revision 7434)
@@ -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_2008/Arc_txt2feature_class_runup.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/Arc_txt2feature_class_runup.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/Arc_txt2feature_class_runup.py	(revision 7434)
@@ -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_2008/build_boundary_27255.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/build_boundary_27255.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/build_boundary_27255.py	(revision 7434)
@@ -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_2008/build_boundary_27283.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/build_boundary_27283.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/build_boundary_27283.py	(revision 7434)
@@ -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_2008/build_boundary_68693.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/build_boundary_68693.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/build_boundary_68693.py	(revision 7434)
@@ -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_2008/build_carnarvon.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/build_carnarvon.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/build_carnarvon.py	(revision 7434)
@@ -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_2008/build_carnarvon_250m.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/build_carnarvon_250m.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/build_carnarvon_250m.py	(revision 7434)
@@ -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_2008/export_results.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/export_results.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/export_results.py	(revision 7434)
@@ -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_2008/export_results_all.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/export_results_all.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/export_results_all.py	(revision 7434)
@@ -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_2008/export_results_max.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/export_results_max.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/export_results_max.py	(revision 7434)
@@ -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_2008/export_results_max_multiple_timesteps.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/export_results_max_multiple_timesteps.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/export_results_max_multiple_timesteps.py	(revision 7434)
@@ -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_2008/export_results_multiple_timesteps.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/export_results_multiple_timesteps.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/export_results_multiple_timesteps.py	(revision 7434)
@@ -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_2008/get_gauges.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/get_gauges.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/get_gauges.py	(revision 7434)
@@ -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_2008/get_runup.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/get_runup.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/get_runup.py	(revision 7434)
@@ -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_2008/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/get_timeseries.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/get_timeseries.py	(revision 7434)
@@ -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_2008/ph2_compare.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/ph2_compare.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/ph2_compare.py	(revision 7434)
@@ -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_2008/ph2_compare_table.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/ph2_compare_table.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/ph2_compare_table.py	(revision 7434)
@@ -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_2008/project.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/project.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/project.py	(revision 7434)
@@ -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_2008/project_250m.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/project_250m.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/project_250m.py	(revision 7434)
@@ -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_2008/run_boundary_points.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/run_boundary_points.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/run_boundary_points.py	(revision 7434)
@@ -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_2008/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/run_building_inundation.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/run_building_inundation.py	(revision 7434)
@@ -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_2008/run_carnarvon.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/run_carnarvon.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/run_carnarvon.py	(revision 7434)
@@ -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_2008/run_carnarvon_250m.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2008/run_carnarvon_250m.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2008/run_carnarvon_250m.py	(revision 7434)
@@ -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/carnarvon_2009/Arc_asc2raster_GDA94z49.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/Arc_asc2raster_GDA94z49.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/Arc_asc2raster_GDA94z49.py	(revision 7434)
@@ -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_2009/Arc_txt2feature_class_runup.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/Arc_txt2feature_class_runup.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/Arc_txt2feature_class_runup.py	(revision 7434)
@@ -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_2009/Carnarvon4distribution.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/Carnarvon4distribution.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/Carnarvon4distribution.py	(revision 7434)
@@ -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_2009/Inundation_polygon.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/Inundation_polygon.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/Inundation_polygon.py	(revision 7434)
@@ -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_2009/README.txt
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/README.txt	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/README.txt	(revision 7434)
@@ -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_2009/build_elevation.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/build_elevation.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/build_elevation.py	(revision 7434)
@@ -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_2009/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/build_urs_boundary.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/build_urs_boundary.py	(revision 7434)
@@ -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_2009/export_results_max.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/export_results_max.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/export_results_max.py	(revision 7434)
@@ -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_2009/file_length.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/file_length.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/file_length.py	(revision 7434)
@@ -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_2009/get_runup.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/get_runup.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/get_runup.py	(revision 7434)
@@ -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_2009/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/get_timeseries.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/get_timeseries.py	(revision 7434)
@@ -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_2009/project.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/project.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/project.py	(revision 7434)
@@ -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_2009/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/run_building_inundation.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/run_building_inundation.py	(revision 7434)
@@ -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_2009/run_model.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/run_model.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/run_model.py	(revision 7434)
@@ -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_2009/setup_model.py
===================================================================
--- /anuga_work/production/wa/carnarvon_2009/setup_model.py	(revision 7434)
+++ /anuga_work/production/wa/carnarvon_2009/setup_model.py	(revision 7434)
@@ -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_2009/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/Arc_asc2raster_GDA94z50.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/Arc_asc2raster_GDA94z50.py	(revision 7434)
@@ -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_2009/Arc_txt2feature_class.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/Arc_txt2feature_class.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/Arc_txt2feature_class.py	(revision 7434)
@@ -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_2009/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/Arc_txt2feature_class_res.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/Arc_txt2feature_class_res.py	(revision 7434)
@@ -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_2009/Geraldton4distribution.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/Geraldton4distribution.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/Geraldton4distribution.py	(revision 7434)
@@ -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_2009/Inundation_polygon.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/Inundation_polygon.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/Inundation_polygon.py	(revision 7434)
@@ -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_2009/README.txt
===================================================================
--- /anuga_work/production/wa/geraldton_2009/README.txt	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/README.txt	(revision 7434)
@@ -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_2009/build_elevation.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/build_elevation.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/build_elevation.py	(revision 7434)
@@ -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_2009/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/build_urs_boundary.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/build_urs_boundary.py	(revision 7434)
@@ -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_2009/export_results_max.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/export_results_max.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/export_results_max.py	(revision 7434)
@@ -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_2009/file_length.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/file_length.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/file_length.py	(revision 7434)
@@ -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_2009/get_runup.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/get_runup.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/get_runup.py	(revision 7434)
@@ -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_2009/get_timeseries.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/get_timeseries.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/get_timeseries.py	(revision 7434)
@@ -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_2009/project.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/project.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/project.py	(revision 7434)
@@ -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_2009/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/run_building_inundation.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/run_building_inundation.py	(revision 7434)
@@ -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_2009/run_model.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/run_model.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/run_model.py	(revision 7434)
@@ -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_2009/setup_model.py
===================================================================
--- /anuga_work/production/wa/geraldton_2009/setup_model.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_2009/setup_model.py	(revision 7434)
@@ -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_nick/README.txt
===================================================================
--- /anuga_work/production/wa/geraldton_nick/README.txt	(revision 7434)
+++ /anuga_work/production/wa/geraldton_nick/README.txt	(revision 7434)
@@ -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_nick/build_elevation.py
===================================================================
--- /anuga_work/production/wa/geraldton_nick/build_elevation.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_nick/build_elevation.py	(revision 7434)
@@ -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_nick/build_urs_boundary.py
===================================================================
--- /anuga_work/production/wa/geraldton_nick/build_urs_boundary.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_nick/build_urs_boundary.py	(revision 7434)
@@ -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_nick/export_results_max.py
===================================================================
--- /anuga_work/production/wa/geraldton_nick/export_results_max.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_nick/export_results_max.py	(revision 7434)
@@ -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_nick/file_length.py
===================================================================
--- /anuga_work/production/wa/geraldton_nick/file_length.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_nick/file_length.py	(revision 7434)
@@ -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_nick/project.py
===================================================================
--- /anuga_work/production/wa/geraldton_nick/project.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_nick/project.py	(revision 7434)
@@ -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_nick/run_model.py
===================================================================
--- /anuga_work/production/wa/geraldton_nick/run_model.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_nick/run_model.py	(revision 7434)
@@ -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_nick/setup_model.py
===================================================================
--- /anuga_work/production/wa/geraldton_nick/setup_model.py	(revision 7434)
+++ /anuga_work/production/wa/geraldton_nick/setup_model.py	(revision 7434)
@@ -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/perth_2009/Arc_asc2raster_GDA94z50.py
===================================================================
--- /anuga_work/production/wa/perth_2009/Arc_asc2raster_GDA94z50.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/Arc_asc2raster_GDA94z50.py	(revision 7434)
@@ -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_2009/Arc_txt2feature_class_res.py
===================================================================
--- /anuga_work/production/wa/perth_2009/Arc_txt2feature_class_res.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/Arc_txt2feature_class_res.py	(revision 7434)
@@ -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_2009/Arc_txt2feature_class_runup.py
===================================================================
--- /anuga_work/production/wa/perth_2009/Arc_txt2feature_class_runup.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/Arc_txt2feature_class_runup.py	(revision 7434)
@@ -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_2009/Inundation_polygon.py
===================================================================
--- /anuga_work/production/wa/perth_2009/Inundation_polygon.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/Inundation_polygon.py	(revision 7434)
@@ -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_2009/Perth4distribution.py
===================================================================
--- /anuga_work/production/wa/perth_2009/Perth4distribution.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/Perth4distribution.py	(revision 7434)
@@ -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_2009/build_elevation.py
===================================================================
--- /anuga_work/production/wa/perth_2009/build_elevation.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/build_elevation.py	(revision 7434)
@@ -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_2009/export_results_max.py
===================================================================
--- /anuga_work/production/wa/perth_2009/export_results_max.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/export_results_max.py	(revision 7434)
@@ -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_2009/get_runup.py
===================================================================
--- /anuga_work/production/wa/perth_2009/get_runup.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/get_runup.py	(revision 7434)
@@ -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_2009/project.py
===================================================================
--- /anuga_work/production/wa/perth_2009/project.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/project.py	(revision 7434)
@@ -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_2009/run_building_inundation.py
===================================================================
--- /anuga_work/production/wa/perth_2009/run_building_inundation.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/run_building_inundation.py	(revision 7434)
@@ -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_2009/run_model.py
===================================================================
--- /anuga_work/production/wa/perth_2009/run_model.py	(revision 7434)
+++ /anuga_work/production/wa/perth_2009/run_model.py	(revision 7434)
@@ -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)
