예제 #1
0
def SetBC(q, slope, domain):
    print('Setting BCs')
    # Define and set boundaries
    # Define transmissive boundary for downstream outlet
    Bt = anuga.Transmissive_boundary(domain)
    #Define reflective boundary for channel edges
    Br = anuga.Reflective_boundary(domain)
    # Define Dirichlet boundary for upstream inlet flow
    Bi = Inflow_boundary(domain, q, slope)
    domain.set_boundary({'inlet': Bi, 'exterior': Br, 'outlet': Bt})
    return domain
    def test_boundary_conditions(self):

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #bac, bce, ecf, dbe
        vertices = [[1, 0, 2], [1, 2, 4], [4, 2, 5], [3, 1, 4]]
        boundary = {
            (0, 0): 'First',
            (0, 2): 'First',
            (2, 0): 'Second',
            (2, 1): 'Second',
            (3, 1): 'Second',
            (3, 2): 'Second'
        }


        domain = Generic_Domain(points, vertices, boundary,
                        conserved_quantities =\
                        ['stage', 'xmomentum', 'ymomentum'])
        domain.check_integrity()

        domain.set_quantity('stage',
                            [[1, 2, 3], [5, 5, 5], [0, 0, 9], [-6, 3, 3]])

        domain.set_boundary({
            'First': anuga.Dirichlet_boundary([5, 2, 1]),
            'Second': anuga.Transmissive_boundary(domain)
        })

        domain.update_boundary()

        assert domain.quantities['stage'].boundary_values[0] == 5.  #Dirichlet
        assert domain.quantities['stage'].boundary_values[1] == 5.  #Dirichlet
        assert domain.quantities['stage'].boundary_values[2] ==\
               domain.get_conserved_quantities(2, edge=0)[0] #Transmissive (4.5)
        assert domain.quantities['stage'].boundary_values[3] ==\
               domain.get_conserved_quantities(2, edge=1)[0] #Transmissive (4.5)
        assert domain.quantities['stage'].boundary_values[4] ==\
               domain.get_conserved_quantities(3, edge=1)[0] #Transmissive (-1.5)
        assert domain.quantities['stage'].boundary_values[5] ==\
               domain.get_conserved_quantities(3, edge=2)[0] #Transmissive (-1.5)

        #Check enumeration
        for k, ((vol_id, edge_id), _) in enumerate(domain.boundary_objects):
            assert domain.neighbours[vol_id, edge_id] == -k - 1
예제 #3
0
    def setUp(self):

        def elevation_function(x, y):
            return -x
        
        """ Setup for all tests. """
        
        mesh_file = tempfile.mktemp(".tsh")    
        points = [[0.0,0.0],[6.0,0.0],[6.0,6.0],[0.0,6.0]]
        m = Mesh()
        m.add_vertices(points)
        m.auto_segment()
        m.generate_mesh(verbose=False)
        m.export_mesh_file(mesh_file)
        
        # Create shallow water domain
        domain = anuga.Domain(mesh_file)
        os.remove(mesh_file)
 
        domain.default_order = 2

        # This test was made before tight_slope_limiters were introduced
        # Since were are testing interpolation values this is OK
        domain.tight_slope_limiters = 0
                
        # Set some field values
        domain.set_quantity('elevation', elevation_function)
        domain.set_quantity('friction', 0.03)
        domain.set_quantity('xmomentum', 3.0)
        domain.set_quantity('ymomentum', 4.0)

        ######################
        # Boundary conditions
        B = anuga.Transmissive_boundary(domain)
        domain.set_boundary( {'exterior': B})

        # This call mangles the stage values.
        domain.distribute_to_vertices_and_edges()
        domain.set_quantity('stage', 1.0)

        domain.set_name('datatest' + str(time.time()))
        domain.smooth = True
        domain.reduction = mean
        
        self.domain = domain
예제 #4
0
def height(x,y):
    z = zeros(len(x), float)
    for i in range(len(x)):
        if x[i]<=0.0:
            z[i] = h0
        else:
            z[i] = h1
    return z
domain.set_quantity('stage', height)

#-----------------------------------------------------------------------------
# Setup boundary conditions
#------------------------------------------------------------------------------
from math import sin, pi, exp
Br = anuga.Reflective_boundary(domain)      # Solid reflective wall
Bt = anuga.Transmissive_boundary(domain)    # Continue all values on boundary 
Bd = anuga.Dirichlet_boundary([1,0.,0.]) # Constant boundary values

# Associate boundary tags with boundary objects
domain.set_boundary({'left': Bt, 'right': Bt, 'top': Br, 'bottom': Br})


#===============================================================================
vtk_visualiser = True
if vtk_visualiser:
    from anuga.visualiser import RealtimeVisualiser
    vis = RealtimeVisualiser(domain)
    vis.render_quantity_height("height",dynamic=True)
    #vis.render_quantity_height("stage", zScale =1.0, dynamic=True)
    vis.colour_height_quantity('stage', (0.0, 0.0, 1.0))
    vis.start()
예제 #5
0
    domain.get_quantity('elevation').smooth_vertex_values(
    )  # Steve's fix -- without this, substantial artificial velcities are generated everywhere in the domain. With this fix, there are artificial velocities near the coast, but not elsewhere.
    domain.set_quantity('friction', 0.0)  # Constant friction
    domain.set_quantity('stage', stagefun)  # Constant negative initial stage
else:
    domain = None

#--------------------------
# create Parallel Domain
#--------------------------
domain = distribute(domain)

# Setup boundary conditions
#--------------------------
Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
Bt = anuga.Transmissive_boundary(
    domain)  # Continue all values of boundary -- not used in this example
Bd = anuga.Dirichlet_boundary([-0.1, 0., 0.])  # Constant boundary values

#----------------------------------------------
# Associate boundary tags with boundary objects
#----------------------------------------------
domain.set_boundary({'left': Br, 'right': Bd, 'top': Br, 'bottom': Br})

#------------------------------
#Evolve the system through time
#------------------------------
#xwrite=open("xvel.out","wb")
#ywrite=open("yvel.out","wb")
## Set print options to be compatible with file writing via the 'print' statement
#numpy.set_printoptions(threshold=numpy.nan, linewidth=numpy.nan)
예제 #6
0
bridge = Internal_boundary_operator(domain,
                                    hecras_discharge_function,
                                    exchange_lines=[bridge_in, bridge_out],
                                    enquiry_gap=0.01,
                                    use_velocity_head=False,
                                    smoothing_timescale=30.0,
                                    logging=verbose)

#------------------------------------------------------------------------------
#
# Setup boundary conditions
#
#------------------------------------------------------------------------------

Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
Bt = anuga.Transmissive_boundary(domain)  # Transmissive boundary


Bout_sub = anuga.Dirichlet_boundary( \
        [-floodplain_length*floodplain_slope - chan_bankfull_depth + \
        chan_initial_depth, 0., 0.]) #An outflow boundary for subcritical steady flow


def outflow_stage_boundary(t):
    return -floodplain_length*floodplain_slope \
            + chan_initial_depth - chan_bankfull_depth


Bout_tmss = anuga.shallow_water.boundaries.Transmissive_momentum_set_stage_boundary(
    domain, function=outflow_stage_boundary)
    def test_conserved_evolved_boundary_conditions(self):

        a = [0.0, 0.0]
        b = [0.0, 2.0]
        c = [2.0, 0.0]
        d = [0.0, 4.0]
        e = [2.0, 2.0]
        f = [4.0, 0.0]

        points = [a, b, c, d, e, f]
        #bac, bce, ecf, dbe
        vertices = [[1, 0, 2], [1, 2, 4], [4, 2, 5], [3, 1, 4]]
        boundary = {
            (0, 0): 'First',
            (0, 2): 'First',
            (2, 0): 'Second',
            (2, 1): 'Second',
            (3, 1): 'Second',
            (3, 2): 'Second'
        }

        try:
            domain = Generic_Domain(points, vertices, boundary,
                            conserved_quantities = ['stage', 'xmomentum', 'ymomentum'],
                            evolved_quantities =\
                                   ['stage', 'xmomentum', 'xvelocity', 'ymomentum', 'yvelocity'])
        except:
            pass
        else:
            msg = 'Should have caught the evolved quantities not being in order'
            raise Exception(msg)


        domain = Generic_Domain(points, vertices, boundary,
                        conserved_quantities = ['stage', 'xmomentum', 'ymomentum'],
                        evolved_quantities =\
                        ['stage', 'xmomentum', 'ymomentum', 'xvelocity', 'yvelocity'])

        domain.set_quantity('stage',
                            [[1, 2, 3], [5, 5, 5], [0, 0, 9], [6, -3, 3]])

        domain.set_boundary({
            'First': anuga.Dirichlet_boundary([5, 2, 1, 4, 6]),
            'Second': anuga.Transmissive_boundary(domain)
        })

        #        try:
        #            domain.update_boundary()
        #        except:
        #            pass
        #        else:
        #            msg = 'Should have caught the lack of conserved_values_to_evolved_values member function'
        #            raise Exception, msg

        domain.update_boundary()

        def conserved_values_to_evolved_values(q_cons, q_evol):

            q_evol[0:3] = q_cons
            q_evol[3] = old_div(q_cons[1], q_cons[0])
            q_evol[4] = old_div(q_cons[2], q_cons[0])

            return q_evol

        domain.conserved_values_to_evolved_values = conserved_values_to_evolved_values

        domain.update_boundary()

        assert domain.quantities['stage'].boundary_values[0] == 5.  #Dirichlet
        assert domain.quantities['stage'].boundary_values[1] == 5.  #Dirichlet
        assert domain.quantities['xvelocity'].boundary_values[
            0] == 4.  #Dirichlet
        assert domain.quantities['yvelocity'].boundary_values[
            1] == 6.  #Dirichlet

        q_cons = domain.get_conserved_quantities(2, edge=0)  #Transmissive
        assert domain.quantities['stage'].boundary_values[2] == q_cons[0]
        assert domain.quantities['xmomentum'].boundary_values[2] == q_cons[1]
        assert domain.quantities['ymomentum'].boundary_values[2] == q_cons[2]
        assert domain.quantities['xvelocity'].boundary_values[2] == old_div(
            q_cons[1], q_cons[0])
        assert domain.quantities['yvelocity'].boundary_values[2] == old_div(
            q_cons[2], q_cons[0])

        q_cons = domain.get_conserved_quantities(2, edge=1)  #Transmissive
        assert domain.quantities['stage'].boundary_values[3] == q_cons[0]
        assert domain.quantities['xmomentum'].boundary_values[3] == q_cons[1]
        assert domain.quantities['ymomentum'].boundary_values[3] == q_cons[2]
        assert domain.quantities['xvelocity'].boundary_values[3] == old_div(
            q_cons[1], q_cons[0])
        assert domain.quantities['yvelocity'].boundary_values[3] == old_div(
            q_cons[2], q_cons[0])

        q_cons = domain.get_conserved_quantities(3, edge=1)  #Transmissive
        assert domain.quantities['stage'].boundary_values[4] == q_cons[0]
        assert domain.quantities['xmomentum'].boundary_values[4] == q_cons[1]
        assert domain.quantities['ymomentum'].boundary_values[4] == q_cons[2]
        assert domain.quantities['xvelocity'].boundary_values[4] == old_div(
            q_cons[1], q_cons[0])
        assert domain.quantities['yvelocity'].boundary_values[4] == old_div(
            q_cons[2], q_cons[0])

        q_cons = domain.get_conserved_quantities(3, edge=2)  #Transmissive
        assert domain.quantities['stage'].boundary_values[5] == q_cons[0]
        assert domain.quantities['xmomentum'].boundary_values[5] == q_cons[1]
        assert domain.quantities['ymomentum'].boundary_values[5] == q_cons[2]
        assert domain.quantities['xvelocity'].boundary_values[5] == old_div(
            q_cons[1], q_cons[0])
        assert domain.quantities['yvelocity'].boundary_values[5] == old_div(
            q_cons[2], q_cons[0])
예제 #8
0
#------------------------------------------------------------------------------
# Setup boundary conditions
#------------------------------------------------------------------------------
#print 'Available boundary tags', domain.get_boundary_tags()


def tide_fun(t):
    return tide


Bd = anuga.Dirichlet_boundary([tide, 0, 0])  # Mean water level
#Bs = anuga.Transmissive_stage_zero_momentum_boundary(domain) # Neutral boundary
Bs = anuga.Transmissive_n_momentum_zero_t_momentum_set_stage_boundary(
    domain, tide_fun)
Bf = anuga.Flather_external_stage_zero_velocity_boundary(domain, tide_fun)
Bt = anuga.Transmissive_boundary(domain)  # Neutral boundary
Br = anuga.Reflective_boundary(domain)
# Boundary conditions for slide scenario
domain.set_boundary({'ocean_east': Bf, 'bottom': Bf, 'onshore': Br, 'top': Bf})
if myid == 0: print(domain.boundary_statistics(tags=['ocean_east', 'onshore']))
#------------------------------------------------------------------------------
# Evolve system through time
#------------------------------------------------------------------------------
# initial time

t0 = time.time()
min = 60
hour = 3600

# source file
예제 #9
0
def start_sim(run_id, Runs, scenario_name, Scenario, session, **kwargs):
    yieldstep = kwargs['yieldstep']
    finaltime = kwargs['finaltime']
    logger = logging.getLogger(run_id)
    max_triangle_area = kwargs['max_triangle_area']
    logger.info('Starting hydrata_project')

    if run_id == 'local_run':
        base_dir = os.getcwd()
    else:
        base_dir = os.getcwd() + '/base_dir/%s/' % run_id

    outname = run_id
    meshname = base_dir + 'outputs/' + run_id + '.msh'

    def get_filename(data_type, file_type):
        files = os.listdir('%sinputs/%s' % (base_dir, data_type))
        filename = '%sinputs/%s/%s' % (
            base_dir, data_type, [f for f in files if f[-4:] == file_type][0])
        return filename

    boundary_data_filename = get_filename('boundary_data', '.shp')
    elevation_data_filename = get_filename('elevation_data', '.tif')
    try:
        structures_filename = get_filename('structures', '.shp')
    except OSError as e:
        structures_filename = None
    try:
        rain_data_filename = get_filename('rain_data', '.shp')
    except OSError as e:
        rain_data_filename = None
    try:
        inflow_data_filename = get_filename('inflow_data', '.shp')
    except OSError as e:
        inflow_data_filename = None
    try:
        friction_data_filename = get_filename('friction_data', '.shp')
    except OSError as e:
        friction_data_filename = None

    logger.info('boundary_data_filename: %s' % boundary_data_filename)
    logger.info('structures_filename: %s' % structures_filename)
    logger.info('rain_data_filename: %s' % rain_data_filename)
    logger.info('inflow_data_filename: %s' % inflow_data_filename)
    logger.info('friction_data_filename: %s' % friction_data_filename)
    logger.info('elevation_data_filename: %s' % elevation_data_filename)

    # create a list of project files
    vector_filenames = [
        boundary_data_filename, structures_filename, rain_data_filename,
        inflow_data_filename, friction_data_filename
    ]

    # set the projection system for ANUGA calculations from the geotiff elevation data
    elevation_data_gdal = gdal.Open(elevation_data_filename)
    project_spatial_ref = osr.SpatialReference()
    project_spatial_ref.ImportFromWkt(elevation_data_gdal.GetProjectionRef())
    project_spatial_ref_epsg_code = int(
        project_spatial_ref.GetAttrValue("AUTHORITY", 1))

    # check the spatial reference system of the project files matches that of the calculation
    for filename in vector_filenames:
        if filename:
            prj_text = open(filename[:-4] + '.prj').read()
            srs = osr.SpatialReference()
            srs.ImportFromESRI([prj_text])
            srs.AutoIdentifyEPSG()
            logger.info('filename is: %s' % filename)
            logger.info('EPSG is: %s' % srs.GetAuthorityCode(None))
            if str(srs.GetAuthorityCode(None)) != str(
                    project_spatial_ref_epsg_code):
                logger.warning('warning spatial refs are not maching: %s, %s' %
                               (srs.GetAuthorityCode(None),
                                project_spatial_ref_epsg_code))

    logger.info('Setting up structures...')
    if structures_filename:
        structures = []
        logger.info('processing structures from :%s' % structures_filename)
        ogr_shapefile = ogr.Open(structures_filename)
        ogr_layer = ogr_shapefile.GetLayer(0)
        ogr_layer_feature = ogr_layer.GetNextFeature()
        while ogr_layer_feature:
            structure = json.loads(ogr_layer_feature.GetGeometryRef().
                                   ExportToJson())['coordinates'][0]
            structures.append(structure)
            ogr_layer_feature = None
            ogr_layer_feature = ogr_layer.GetNextFeature()

        logger.info('structures: %s' % structures)
    else:
        logger.warning('warning: no structures found.')
        structures = None

    logger.info('Setting up friction...')
    frictions = []
    if friction_data_filename:
        logger.info('processing frictions from :%s' % friction_data_filename)
        ogr_shapefile = ogr.Open(friction_data_filename)
        ogr_layer = ogr_shapefile.GetLayer(0)
        ogr_layer_feature = ogr_layer.GetNextFeature()
        while ogr_layer_feature:
            friction_poly = json.loads(ogr_layer_feature.GetGeometryRef().
                                       ExportToJson())['coordinates'][0]
            friction_value = float(ogr_layer_feature.GetField('mannings'))
            friction_couple = [friction_poly, friction_value]
            frictions.append(friction_couple)
            ogr_layer_feature = None
            ogr_layer_feature = ogr_layer.GetNextFeature()

        frictions.append(['All', 0.04])
        logger.info('frictions: %s' % frictions)
    else:
        frictions.append(['All', 0.04])
        logger.info('warning: no frictions found.')

    logger.info('Setting up boundary conditions...')
    ogr_shapefile = ogr.Open(boundary_data_filename)
    ogr_layer = ogr_shapefile.GetLayer(0)
    ogr_layer_definition = ogr_layer.GetLayerDefn()
    logger.info('ogr_layer_definition.GetGeomType: %s' %
                ogr_layer_definition.GetGeomType())
    boundary_tag_index = 0
    bdy_tags = {}
    bdy = {}

    ogr_layer_feature = ogr_layer.GetNextFeature()
    while ogr_layer_feature:
        boundary_tag_key = ogr_layer_feature.GetField('bdy_tag_k')
        boundary_tag_value = ogr_layer_feature.GetField('bdy_tag_v')
        bdy_tags[boundary_tag_key] = [
            boundary_tag_index * 2, boundary_tag_index * 2 + 1
        ]
        bdy[boundary_tag_key] = boundary_tag_value
        geom = ogr_layer_feature.GetGeometryRef().GetPoints()
        ogr_layer_feature = None
        ogr_layer_feature = ogr_layer.GetNextFeature()
        boundary_tag_index = boundary_tag_index + 1
        logger.info('bdy_tags: %s' % bdy_tags)
    logger.info('bdy: %s' % bdy)

    boundary_data = su.read_polygon(boundary_data_filename)

    create_mesh_from_regions(boundary_data,
                             boundary_tags=bdy_tags,
                             maximum_triangle_area=max_triangle_area,
                             interior_regions=None,
                             interior_holes=structures,
                             filename=meshname,
                             use_cache=False,
                             verbose=True)

    domain = Domain(meshname, use_cache=False, verbose=True)
    domain.set_name(outname)
    domain.set_datadir(base_dir + '/outputs')
    logger.info(domain.statistics())
    poly_fun_pairs = [['Extent', elevation_data_filename.encode("utf-8")]]
    topography_function = qs.composite_quantity_setting_function(
        poly_fun_pairs,
        domain,
        nan_treatment='exception',
    )
    friction_function = qs.composite_quantity_setting_function(
        frictions, domain)
    domain.set_quantity('friction', friction_function, verbose=True)
    domain.set_quantity('stage', 0.0)
    domain.set_quantity('elevation',
                        topography_function,
                        verbose=True,
                        alpha=0.99)
    domain.set_minimum_storable_height(0.005)

    logger.info('Applying rainfall...')
    if rain_data_filename:
        ogr_shapefile = ogr.Open(rain_data_filename)
        ogr_layer = ogr_shapefile.GetLayer(0)
        rainfall = 0
        ogr_layer_feature = ogr_layer.GetNextFeature()
        while ogr_layer_feature:
            rainfall = float(ogr_layer_feature.GetField('rate_mm_hr'))
            polygon = su.read_polygon(rain_data_filename)
            logger.info("applying Polygonal_rate_operator with rate, polygon:")
            logger.info(rainfall)
            logger.info(polygon)
            Polygonal_rate_operator(domain,
                                    rate=rainfall,
                                    factor=1.0e-6,
                                    polygon=polygon,
                                    default_rate=0.0)
            ogr_layer_feature = None
            ogr_layer_feature = ogr_layer.GetNextFeature()

    logger.info('Applying surface inflows...')
    if inflow_data_filename:
        ogr_shapefile = ogr.Open(inflow_data_filename)
        ogr_layer = ogr_shapefile.GetLayer(0)
        ogr_layer_definition = ogr_layer.GetLayerDefn()
        ogr_layer_feature = ogr_layer.GetNextFeature()
        while ogr_layer_feature:
            in_fixed = float(ogr_layer_feature.GetField('in_fixed'))
            line = ogr_layer_feature.GetGeometryRef().GetPoints()
            logger.info("applying Inlet_operator with line, in_fixed:")
            logger.info(line)
            logger.info(in_fixed)
            Inlet_operator(domain, line, in_fixed, verbose=False)
            ogr_layer_feature = None
            ogr_layer_feature = ogr_layer.GetNextFeature()

    logger.info('Applying Boundary Conditions...')
    logger.info('Available boundary tags: %s' % domain.get_boundary_tags())

    Br = anuga.Reflective_boundary(domain)
    Bd = anuga.Dirichlet_boundary([0.0, 0.0, 0.0])
    Bt = anuga.Transmissive_boundary(domain)

    for key, value in bdy.iteritems():
        if value == 'Br':
            bdy[key] = Br
        elif value == 'Bd':
            bdy[key] = Bd
        elif value == 'Bt':
            bdy[key] = Bt
        else:
            logger.info(
                'No matching boundary condition exists - please check your shapefile attributes in: %s'
                % boundary_data_filename)

    # set a default value for exterior & interior boundary if it is not already set
    try:
        bdy['exterior']
    except KeyError:
        bdy['exterior'] = Br
    try:
        bdy['interior']
    except KeyError:
        bdy['interior'] = Br

    logger.info('bdy: %s' % bdy)

    domain.set_boundary(bdy)

    domain = distribute(domain)
    logger.info('Beginning evolve phase...')
    for t in domain.evolve(yieldstep, finaltime):
        domain.write_time()
        print domain.timestepping_statistics()
        logger.info(domain.timestepping_statistics(track_speeds=True))
        percentage_complete = round(domain.time / domain.finaltime, 3) * 100
        logger.info('%s percent complete' % percentage_complete)
        if run_id != 'local_run':
            write_percentage_complete(run_id, Runs, scenario_name, Scenario,
                                      session, percentage_complete)
    domain.sww_merge(delete_old=True)
    barrier()
    finalize()
    sww_file = base_dir + '/outputs/' + run_id + '.sww'
    sww_file = sww_file.encode(
        'utf-8',
        'ignore')  # sometimes run_id gets turned to a unicode object by celery
    util.Make_Geotif(swwFile=sww_file,
                     output_quantities=['depth', 'velocity'],
                     myTimeStep='max',
                     CellSize=max_triangle_area,
                     lower_left=None,
                     upper_right=None,
                     EPSG_CODE=project_spatial_ref_epsg_code,
                     proj4string=None,
                     velocity_extrapolation=True,
                     min_allowed_height=1.0e-05,
                     output_dir=(base_dir + '/outputs/'),
                     bounding_polygon=boundary_data,
                     internal_holes=structures,
                     verbose=False,
                     k_nearest_neighbours=3,
                     creation_options=[])
    logger.info("Done. Nice work.")
예제 #10
0
def run_chennai(sim_id):
    project_root = os.path.abspath(os.path.dirname(__file__))
    if not os.path.exists(project_root):
        os.makedirs(project_root)
    print "project_root = " + project_root

    inputs_dir = '%s/inputs/' % project_root
    if not os.path.exists(inputs_dir):
        os.makedirs(inputs_dir)
    print "inputs_dir = " + inputs_dir

    working_dir = '%s/working/%s/' % (project_root, sim_id)
    if not os.path.exists(working_dir):
        os.makedirs(working_dir)
    print "working_dir = " + working_dir

    outputs_dir = '%s/outputs/%s' % (project_root, sim_id)
    if not os.path.exists(outputs_dir):
        os.makedirs(outputs_dir)
    print "outputs_dir = " + outputs_dir

    # get data
    print "downloading data..."
    urllib.urlretrieve(
        'http://chennaifloodmanagement.org/uploaded/layers/utm44_1arc_v3.tif',
        inputs_dir + 'utm44_1arc_v3.tif'
    )

    print os.listdir(inputs_dir)

    # configure logging TODO: get this working!
    log_location = project_root + '/' + sim_id + '.log'
    open(log_location, 'a').close()
    log.console_logging_level = log.INFO
    log.log_logging_level = log.DEBUG
    log.log_filename = log_location
    print "# log.log_filename is: " + log.log_filename
    print "# log_location is: " + log_location
    log.debug('A message at DEBUG level')
    log.info('Another message, INFO level')

    print "# starting"
    bounding_polygon_01 = [
        [303382.14647903712, 1488780.8996663219],
        [351451.89152459265, 1499834.3704521982],
        [378957.03975921532, 1493150.8764886451],
        [422656.80798244767, 1504204.3472745214],
        [433196.16384805075, 1471300.9923770288],
        [421885.63560203766, 1413463.0638462803],
        [408261.59021479468, 1372590.9276845511],
        [371245.31595511554, 1427344.16669366],
        [316492.0769460068, 1417833.0406686035],
        [303382.14647903712, 1488780.8996663219]
    ]
    boundary_tags_01 = {
        'inland': [0, 1, 2, 6, 7, 8],
        'ocean': [3, 4, 5]
    }
    print "# Create domain:"
    print "# mesh_filename = " + working_dir + 'mesh_01.msh'
    domain = anuga.create_domain_from_regions(bounding_polygon=bounding_polygon_01,
                                              boundary_tags=boundary_tags_01,
                                              mesh_filename=working_dir + 'mesh_01.msh',
                                              maximum_triangle_area=100000,
                                              verbose=True)
    domain.set_name(sim_id)
    domain.set_datadir(outputs_dir)
    poly_fun_pairs = [
            [
                'Extent',
                inputs_dir + 'utm44_1arc_v3.tif'
            ]
    ]
    print "# create topography_function"
    print "input raster = " + inputs_dir + 'utm44_1arc_v3.tif'
    topography_function = qs.composite_quantity_setting_function(
        poly_fun_pairs,
        domain,
        nan_treatment='exception',
    )
    print topography_function
    print "# set_quantity elevation"
    domain.set_quantity('elevation', topography_function)  # Use function for elevation
    domain.set_quantity('friction', 0.03)  # Constant friction
    domain.set_quantity('stage', 1)  # Constant initial stage

    print "# all quantities set"

    print "# Setup boundary conditions"
    Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
    Bt = anuga.Transmissive_boundary(domain)  # Continue all values on boundary
    Bd = anuga.Dirichlet_boundary([-20, 0., 0.])  # Constant boundary values
    Bi = anuga.Dirichlet_boundary([10.0, 0, 0])  # Inflow
    Bw = anuga.Time_boundary(
        domain=domain,  # Time dependent boundary
        function=lambda t: [(10 * sin(t * 2 * pi) - 0.3) * exp(-t), 0.0, 0.0]
    )

    print "# Associate boundary tags with boundary objects"
    domain.set_boundary({'inland': Br, 'ocean': Bd})
    print domain.get_boundary_tags()

    catchmentrainfall = Rainfall(
        domain=domain,
        rate=0.2
    )
    # # Note need path to File in String.
    # # Else assumed in same directory
    domain.forcing_terms.append(catchmentrainfall)

    print "# Evolve system through time"
    counter_timestep = 0
    for t in domain.evolve(yieldstep=300, finaltime=6000):
        counter_timestep += 1
        print counter_timestep
        print domain.timestepping_statistics()

    asc_out_momentum = outputs_dir + '/' + sim_id + '_momentum.asc'
    asc_out_depth = outputs_dir + '/' + sim_id + '_depth.asc'

    anuga.sww2dem(outputs_dir + '/' + sim_id + '.sww',
                  asc_out_momentum,
                  quantity='momentum',
                  number_of_decimal_places=3,
                  cellsize=30,
                  reduction=max,
                  verbose=True)
    anuga.sww2dem(outputs_dir + '/' + sim_id + '.sww',
                  asc_out_depth,
                  quantity='depth',
                  number_of_decimal_places=3,
                  cellsize=30,
                  reduction=max,
                  verbose=True)

    outputs =[asc_out_depth, asc_out_momentum]

    for output in outputs:
        print "# Convert ASCII grid to GeoTiff so geonode can import it"
        src_ds = gdal.Open(output)
        dst_filename = (output[:-3] + 'tif')

        print "# Create gtif instance"
        driver = gdal.GetDriverByName("GTiff")

        print "# Output to geotiff"
        dst_ds = driver.CreateCopy(dst_filename, src_ds, 0)

        print "# Properly close the datasets to flush the disk"
        dst_filename = None
        src_ds = None

    print "Done. Nice work."