Exemplo n.º 1
0
 def create_a_rain_operator(domain, base_filename):
     
     polygon = read_polygon(join(rain_polygon_dir, base_filename+'.csv'))
     rate = file_function(join(rain_rate_dir, base_filename+'.tms'), quantities=['rate'])
     
     return Rate_operator(domain, rate=rate, factor=1.0e-3, \
                          polygon = polygon)
def finalstats(domain, initialdomain, outfile='outstats.csv'):
    acrossthebreach=anuga.read_polygon('JezeroData/jezerobreachpoly.csv',closed=False)
    crossspacing=160
    breacherosion=0
    areasum=0
    for y in acrossthebreach:
        ybreacherosion=domain.get_quantity('elevation').get_values(interpolation_points=[y], location='centroids')-initialdomain.get_quantity('elevation').get_values(interpolation_points=[y], location='centroids')
        if ybreacherosion<0: areasum=areasum+float(ybreacherosion)*crossspacing    #rectangular integration  :)
        if ybreacherosion<breacherosion: breacherosion=float(ybreacherosion)
    
    areasum=-areasum  #because negative areas seem weird
    
    elevdiff=domain.quantities['elevation'].centroid_values-initialdomain.quantities['elevation'].centroid_values  #negative values are eroded, positive values are deposited
    finalremovedvolume=-np.sum(elevdiff[elevdiff<0]*domain.areas[elevdiff<0])
    
    transportedmask=domain.get_centroid_coordinates(absolute=True)[:,0]>54300
    heights=(domain.quantities['stage'].centroid_values-domain.quantities['elevation'].centroid_values)
    transportedvolume=(np.where(heights>0,heights,0)*domain.areas)[transportedmask].sum()

    
    print 'Breach Erosion Depth (m): '+str(-breacherosion)
    print 'Cross-sectional Area (m^2): '+str(areasum)
    print 'Outlet volume (m^3): '+str(finalremovedvolume)
    print 'Drained volume (m^3):' +str(transportedvolume)
    with open(outfile, 'a') as the_file:
        the_file.write(domain.get_name()+','+str(-breacherosion)+','+str(areasum)+','+str(finalremovedvolume)+','+str(transportedvolume)+'\n')
Exemplo n.º 3
0
def read_polygon_list(poly_list):
    # Alternative to read_polygon_dir -- allows us to control order of polygons
    from anuga import read_polygon
    
    result = []
    for i in range(len(poly_list)):
        result.append((read_polygon(poly_list[i][0]) , poly_list[i][1]))
    return result
def read_polygon_list(poly_list):
    # Alternative to read_polygon_dir -- allows us to control order of polygons
    from anuga import read_polygon

    result = []
    for i in range(len(poly_list)):
        result.append((read_polygon(poly_list[i][0]), poly_list[i][1]))
    return result
Exemplo n.º 5
0
def CreateDomain(topo_in, bound_in, datadir, inlet_btag, outlet_btag, res,
                 parlist):
    # Import Channel topography DEM
    # Create DEM from asc data
    anuga.asc2dem(topo_in + '.asc', use_cache=False, verbose=True)

    # Create DEM from asc data
    anuga.dem2pts(topo_in + '.dem', use_cache=False, verbose=True)

    # Define boundaries for mesh
    # Read in coordinate file
    bounding_polygon = anuga.read_polygon(bound_in + '.csv')
    print(inlet_btag)
    #Determine tag to assign as reflective exterior
    for i in numpy.arange(1, 4):
        print(i)
        if int(i) == int(inlet_btag):
            print(str(inlet_btag) + ' already taken')
        else:
            print(str(i) + ' used as exterior tag')
            break
    # Create mesh with bounding polygon
    domain = anuga.create_domain_from_regions(bounding_polygon,
                                              boundary_tags={
                                                  'inlet': [inlet_btag],
                                                  'exterior': [i],
                                                  'outlet': [outlet_btag]
                                              },
                                              maximum_triangle_area=res,
                                              mesh_filename=parlist + '.msh',
                                              use_cache=False,
                                              verbose=True)

    # Name domain and decide where to save
    domain.set_name(parlist)
    domain.set_datadir('.')
    return domain
Exemplo n.º 6
0
    if verbose: print(domain.get_extent(absolute=True))

    #------------------------------------------------------------------------------
    # Setup initial conditions
    #------------------------------------------------------------------------------
    domain.set_quantity('stage', 0.0)

    # Friction -- 2 options
    variable_friction = True
    if not variable_friction:
        # Constant friction
        domain.set_quantity('friction', 0.02)

    else:
        # Set friction to 0.02 on roads, 0.04 elsewhere
        road_polygon = anuga.read_polygon('Road/RoadPolygon.csv')
        friction_function = qs.composite_quantity_setting_function(
            [[road_polygon, 0.02], ['All', 0.04]], domain)
        domain.set_quantity('friction', friction_function)

    # Elevation
    if houses_as_holes:
        domain.set_quantity('elevation',
                            filename='topography1.pts',
                            use_cache=use_cache,
                            verbose=verbose)

    else:
        domain.set_quantity('elevation',
                            filename='topography1.pts',
                            use_cache=use_cache,
Exemplo n.º 7
0
#Save Parameter List as Pkl
fname = identifier + '_par.pkl'
pickle_out = open(fname, "wb")
pickle.dump(Parameters, pickle_out)

# Import Channel topography DEM
# Create DEM from asc data
anuga.asc2dem(topo_in + '.asc', use_cache=False, verbose=True)

# Create DEM from asc data
anuga.dem2pts(topo_in + '.dem', use_cache=False, verbose=True)

# Define boundaries for mesh
# Read in coordinate file
bounding_polygon = anuga.read_polygon(bound_in + '.csv')
# Create mesh with bounding polygon
domain = anuga.create_domain_from_regions(bounding_polygon,
                                          boundary_tags={
                                              'inlet': [inlet_btag],
                                              'exterior': [ref_btag],
                                              'outlet': [outlet_btag]
                                          },
                                          maximum_triangle_area=res,
                                          mesh_filename=identifier + '.msh',
                                          use_cache=False,
                                          verbose=True)

# Name domain and decide where to save
domain.set_name(identifier)
domain.set_datadir('.')
Exemplo n.º 8
0
        rain.data_max_in_period = np.max(rain.data_accumulated)
        rain.radar_dir = None
        l0 = [5100.0, 100000.0]
        l1 = [5100.0, 103900.0]
        l2 = [3400., 103400.]
        l3 = [6000., 103400.]
        locations = [l0,l1,l2,l3] 

    else:
        pass

    
    print rain.radar_dir
    
    try: 
        p2 = anuga.read_polygon(Catchment_file)
        print 'Catchment File'
        print Catchment_file
        #print p2
    except:
        p2 = None
        pass
    
    try:
        p3 = anuga.read_polygon(State_boundary_file)
        print 'State_boundary_file'
        print State_boundary_file
        #print p3
    except:
        p3 = None
        pass
Exemplo n.º 9
0
ascii_grid_filenames = []
point_filenames = ['etopo4min_corrected.txt',
		   'etopo1minNan.txt',
                   'bathy_utmNan.txt']

verbose= True

# Filename for locations where timeseries are to be produced

#gauge_filename = 'gauges.csv'

#------------------------------------------------------------------------------
# Domain definitions
#------------------------------------------------------------------------------
# bounding polygon for study area
bounding_polygon = anuga.read_polygon('polygons/bounding_n.csv')
A = anuga.polygon_area(bounding_polygon) / 1000000.0
print ('Area of bounding polygon = %.2f km^2' % A)

#------------------------------------------------------------------------------
# Interior region definitions
#------------------------------------------------------------------------------
# Read interior polygons
#poly_1min = anuga.read_polygon('polygons/bounding_1min.csv')
poly_level1 = anuga.read_polygon('polygons/polygon_new1.csv')
poly_level2 = anuga.read_polygon('polygons/bounding_gps.csv')
poly_level3 = anuga.read_polygon('polygons/bounding_inundation.csv')

# Optionally plot points making up these polygons

#plot_polygons([bounding_polygon, poly_level1, poly_level2,poly_level3],figname="plot_polyl.png")
# Convert an elevation raster into a point file
anuga.asc2dem('topo.asc', use_cache = False, verbose = True)
anuga.dem2pts('topo.dem', use_cache = False, verbose = True)


"""
Include the process-specific quantities when creating the domain
"""        
evolved_quantities =  ['stage', 'xmomentum', 'ymomentum', 'concentration']

other_quantities=['elevation', 'friction', 'height', 'xvelocity', \
                  'yvelocity', 'x', 'y', 'vegetation', 'diffusivity']


# import bounding polygon text file, set boundary tags
bounding_polygon = anuga.read_polygon('outline.csv')
boundary_tags = {'bottom':[0],
                  'side1':[1],
				  'side2':[2],
				    'top':[3],
			      'side3':[4],
			      'side4':[5]}

"""
Create the domain with operator-specific function (accepts quantities)
"""
domain = create_domain_from_regions_sed(bounding_polygon,
								boundary_tags = boundary_tags,
								maximum_triangle_area = 200,
								mesh_filename = 'topo.msh',
								interior_regions = {},
Exemplo n.º 11
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import os
import anuga
import anuga_tools.animate as animate

rc('animation', html='jshtml')

cwd = os.getcwd()
data_dir = cwd + '/data/york'

# Polygon defining broad area of interest
bounding_polygon = anuga.read_polygon(os.path.join(data_dir, 'extent.csv'))

# Polygon defining particular area of interest
york_polygon = anuga.read_polygon(os.path.join(data_dir, 'york_selection.csv'))

# Elevation Data
topography_file = os.path.join(data_dir, 'se6051_dtm_1m.asc')

# Resolution for most of the mesh
base_resolution = 100.0  # m^2

# Resolution in particular area of interest
york_resolution = 50.0  # m^2

interior_regions = [[york_polygon, york_resolution]]

##
Exemplo n.º 12
0
    #--------------------------------------------------------------------------

    log.critical('Create computational domain')

else:
    print 'Hello from processor ', myid

barrier()
    

# Read in boundary from ordered sts file
event_sts = anuga.create_sts_boundary(project.event_sts)

# Reading the landward defined points, this incorporates the original clipping
# polygon minus the 100m contour
landward_boundary = anuga.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 = anuga.file_length(project.landward_boundary)


#======================================
# Create sequential domain
#======================================
if(myid==0):
    # Boundary tags refer to project.landward_boundary
Exemplo n.º 13
0
import sys
import anuga

from anuga import distribute, myid, numprocs, finalize

#------------------------------------------------------------------------------
# Do the domain creation on processor 0
#------------------------------------------------------------------------------
if myid == 0:
    # Create DEM from asc data
    anuga.asc2dem('11_fbe_c.asc', use_cache=False, verbose=True)

    # Create DEM from asc data
    anuga.dem2pts('11_fbe_c.dem', use_cache=False, verbose=True)

    bounding_polygon = anuga.read_polygon('channel.csv')

    domain = anuga.create_domain_from_regions(bounding_polygon,
                                              boundary_tags={'exterior': [1]},
                                              maximum_triangle_area=1,
                                              mesh_filename='11f.msh',
                                              use_cache=False,
                                              verbose=True)

    #Name domain
    domain.set_name('11_fbe_c')
    domain.set_datadir('.')

    #Set quantities for domain, set dry bed
    domain.set_quantity('elevation', filename='11_fbe_c.pts')
    domain.set_quantity('friction', 0.040)
Exemplo n.º 14
0
scenario = 'fixed_wave'  # Wave applied at the boundary
#scenario = 'slide' # Slide wave form applied inside the domain

#------------------------------------------------------------------------------
# Filenames
#------------------------------------------------------------------------------
name_stem = 'fixed_topobathy_clip'
meshname = name_stem + '.msh'
# Filename for tide gauges locations
gauge_filename = 'gauges_.csv'

#------------------------------------------------------------------------------
# Domain definitions
#------------------------------------------------------------------------------
# bounding polygon for study area
bounding_polygon = anuga.read_polygon('study_area_clip.csv')
A = anuga.polygon_area(bounding_polygon) / 1000000.0
print 'Area of bounding polygon = %.2f km^2' % A

#------------------------------------------------------------------------------
# Interior region definitions (to create different resolution triangular mesh)
#------------------------------------------------------------------------------
# Read interior polygons
# poly_extent0 = anuga.read_polygon('extent_pwrj01.csv')
# poly_extent1 = anuga.read_polygon('extent_pwrj02.csv')
poly_extent1 = anuga.read_polygon('extent_base.csv')
poly_extent2 = anuga.read_polygon('extent_b_e_clip.csv')
poly_extent3 = anuga.read_polygon('extent_b_w_clip.csv')
poly_extent4 = anuga.read_polygon('extent_crop_ne_clip.csv')
poly_extent5 = anuga.read_polygon('extent_crop_nw_clip.csv')
poly_extent6 = anuga.read_polygon('extent_crop_se_clip.csv')
Exemplo n.º 15
0
def run_model():
    """Run a tsunami simulation for a scenario."""

    # Read in boundary from ordered sts file
    event_sts = anuga.create_sts_boundary(project.event_sts)

    # Reading the landward defined points, this incorporates the original
    # clipping polygon minus the 100m contour
    landward_boundary = anuga.read_polygon(project.landward_boundary_file, do_complex_check=False)

    # 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 = anuga.file_length(project.landward_boundary_file)

    # Boundary tags refer to project.landward_boundary_file
    # 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
    log.debug('bounding_polygon_sts=%s' % str(bounding_polygon_sts))
    log.debug('boundary_tags=%s' % str(boundary_tags))
    log.debug('project.bounding_maxarea=%s' % str(project.bounding_maxarea))
    log.debug('project.interior_regions=%s' % str(project.interior_regions))
    log.debug('project.mesh_file=%s' % str(project.mesh_file))

    domain = anuga.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.mesh_file,
                                use_cache=False,
                                verbose=False)

    domain.geo_reference.zone = project.zone_number
    log.info('\n%s' % domain.statistics())

    domain.set_name(project.scenario)
    domain.set_datadir(project.output_folder)
    domain.set_minimum_storable_height(0.01)  # Don't store depth less than 1cm

    # set overall friction before setting in interior regions
    domain.set_quantity('friction', project.friction)

    # set friction in interior regions, if any defined
    friction_list = []
    for (irtype, filename, friction) in project.interior_regions_list:
        if irtype.lower() == 'friction':
            friction_list.append([filename, friction])
    if friction_list:
        log.debug('friction_list=%s' % str(friction_list))
        poly_friction = []
        for (fname, friction) in friction_list:
            full_fname = os.path.join(project.polygons_folder, fname)
            log.debug('Reading friction polygon: %s' % full_fname)
            poly = anuga.read_polygon(full_fname)
            poly_friction.append((poly, friction))
            log.debug('poly=%s' % str(poly))
        domain.set_quantity('friction',
                            anuga.Polygon_function(poly_friction,
                                                   default=project.friction,
                                                   geo_reference=domain.geo_reference))

    # Set the initial stage in the offcoast region only
    if project.land_initial_conditions:
        IC = anuga.Polygon_function(project.land_initial_conditions,
                                    default=project.initial_tide,
                                    geo_reference=domain.geo_reference)
    else:
        IC = project.initial_tide

    domain.set_quantity('stage', IC, use_cache=True, verbose=False)
    domain.set_quantity('elevation',
                        filename=project.combined_elevation_file,
                        use_cache=True, verbose=False, alpha=project.alpha)

    # Setup boundary conditions
    log.debug('Set boundary - available tags: %s' % domain.get_boundary_tags())

    Br = anuga.Reflective_boundary(domain)
    Bt = anuga.Transmissive_stage_zero_momentum_boundary(domain)
    Bd = anuga.Dirichlet_boundary([project.initial_tide, 0, 0])
    Bf = anuga.Field_boundary(project.event_sts+'.sts',
                        domain, mean_stage=project.initial_tide, time_thinning=1,
## NICK debug                        default_boundary=anuga.Dirichlet_boundary([0, 0, 0]),
                        default_boundary=Bt,
                        boundary_polygon=bounding_polygon_sts,
                        use_cache=True, verbose=False)

    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):
        log.info('\n%s' % domain.timestepping_statistics())
        log.info('\n%s' % domain.boundary_statistics(tags='ocean'))

    log.info('Simulation took %.2f seconds' % (time.time()-t0))
Exemplo n.º 16
0
#scenario = 'slide'       # Slide wave form applied inside the domain

#------------------------------------------------------------------------------
# Filenames
#------------------------------------------------------------------------------
name_stem = 'cairns'
meshname = name_stem + '.msh'

# Filename for locations where timeseries are to be produced
gauge_filename = 'gauges.csv'

#------------------------------------------------------------------------------
# Domain definitions
#------------------------------------------------------------------------------
# bounding polygon for study area
bounding_polygon = anuga.read_polygon('extent.csv')

A = anuga.polygon_area(bounding_polygon) / 1000000.0
print('Area of bounding polygon = %.2f km^2' % A)

#------------------------------------------------------------------------------
# Interior region definitions
#------------------------------------------------------------------------------
# Read interior polygons
poly_cairns = anuga.read_polygon('cairns.csv')
poly_island0 = anuga.read_polygon('islands.csv')
poly_island1 = anuga.read_polygon('islands1.csv')
poly_island2 = anuga.read_polygon('islands2.csv')
poly_island3 = anuga.read_polygon('islands3.csv')
poly_shallow = anuga.read_polygon('shallow.csv')
# Setup Functions
#===============================================================================

# Convert an elevation raster into a point file
anuga.asc2dem('topo.asc', use_cache=False, verbose=True)
anuga.dem2pts('topo.dem', use_cache=False, verbose=True)
"""
Include the process-specific quantities when creating the domain
"""
evolved_quantities = ['stage', 'xmomentum', 'ymomentum', 'concentration']

other_quantities=['elevation', 'friction', 'height', 'xvelocity', \
                  'yvelocity', 'x', 'y', 'vegetation', 'diffusivity']

# import bounding polygon text file, set boundary tags
bounding_polygon = anuga.read_polygon('outline.csv')
boundary_tags = {
    'bottom': [0],
    'side1': [1],
    'side2': [2],
    'top': [3],
    'side3': [4],
    'side4': [5]
}
"""
Create the domain with operator-specific function (accepts quantities)
"""
domain = create_domain_from_regions_sed(bounding_polygon,
                                        boundary_tags=boundary_tags,
                                        maximum_triangle_area=200,
                                        mesh_filename='topo.msh',
Exemplo n.º 18
0
def main():
    try:
        try:
            usage = "usage: jezero.py -1*initialstage-in-m \n  Note that -2260 flows but barely does anything.  So range for jezero is ~2260 to 2200. \n"
            parser = optparse.OptionParser(usage=usage)

            (options, inargs) = parser.parse_args()
            if not inargs: parser.error("need parameters")
            jezerostage = -1.0 * float(inargs[0])
            # Before doing anything else, set gravity to Mars
            anuga.g = gravity

            #domain parameters
            poly_highres = anuga.read_polygon('JezeroData/PolyHi.csv')
            poly_bound = anuga.read_polygon(
                'JezeroData/PolyBoundBiggerPts.csv')
            base_scale = 25600  #160 m  #HIRES REGION
            lowres = 10000 * base_scale  # 10 km

            boundary_tags = {'exterior': [0]}

            # Define list of interior regions with associated resolutions
            interior_regions = [[poly_highres, base_scale]]

            meshname = 'JezeroData/jezero.msh'
            mesh = anuga.create_mesh_from_regions(
                poly_bound,
                boundary_tags=boundary_tags,
                maximum_triangle_area=lowres,
                interior_regions=interior_regions,
                verbose=True,
                filename=meshname,
                fail_if_polygons_outside=False)
            evolved_quantities = [
                'stage', 'xmomentum', 'ymomentum', 'concentration', 'sedvolx',
                'sedvoly'
            ]
            domain = anuga.Domain(meshname,
                                  use_cache=False,
                                  evolved_quantities=evolved_quantities)
            domain.g = anuga.g  # make sure the domain inherits the package's gravity.

            domain.set_quantity("elevation",
                                filename="JezeroData/jbigger.pts",
                                use_cache=False,
                                verbose=True)
            domain.smooth = True

            name = "jezero" + str(jezerostage) + "_" + str(
                grainD * 1000.0) + "mm"
            domain.set_name(name)

            # Choose between DE0 (less accurate), DE1 (more accurate, slower), DE2 (even more accurate, slower still)
            domain.set_flow_algorithm('DE0')
            domain.set_CFL(cfl=1.0)
            domain.set_minimum_allowed_height(
                0.01
            )  #raise the default minimum depth from 1 mm to 1 cm to speed the simulation (for computation)
            domain.set_minimum_storable_height(
                0.01
            )  #raise the default minimum depth from 1 mm to 1 cm to speed the simulation (for storage/visualization)
            domain.set_maximum_allowed_speed(
                1.0
            )  #maximum particle speed that is allowed in water shallower than minimum_allowed_height (back of the envelope suggests 1m/s should be below tau_crit)

            np.seterr(invalid='ignore')
            voltotal = np.sum(domain.quantities['elevation'].centroid_values *
                              domain.areas)
            domain.set_quantity('concentration', 0.00)  # Start with no esd
            domain.set_quantity(
                'friction', constantn
            )  # Constant Manning friction.  Only used to initialize domain (calculated every time step).
            domain.set_quantity('stage', -10000.0)
            stagepolygon = anuga.read_polygon('JezeroData/stage.csv')
            domain.set_quantity('stage', jezerostage, polygon=stagepolygon)
            domain.set_quantities_to_be_stored({
                'stage': 2,
                'xmomentum': 2,
                'ymomentum': 2,
                'elevation': 2
            })

            np.seterr(invalid='warn')
            Br = anuga.Reflective_boundary(domain)
            domain.set_boundary({'exterior': Br})

            #           fixed_inflow = anuga.Inlet_operator(domain, stagepolygon, Q=1000.0)
            operatezero = suspendedtransport_operator(domain)
            operateone = bedloadtransport_operator(domain)
            operatetwo = friction_operator(domain)
            operatethree = AoR_operator(domain)

            breachpoint = [[19080.340, 1097556.781]]
            initialdomain = copy.deepcopy(domain)
            initial = domain.get_quantity('elevation').get_values(
                interpolation_points=breachpoint, location='centroids')
            print str(initial)
            ystep = 300.0
            ftime = 86400.0 * 5.0
            polyline = [[40000, 1090000], [15000, 1120000]]
            count = 0
            for t in domain.evolve(yieldstep=ystep, finaltime=ftime):
                print domain.timestepping_statistics()
                print 'xmom:' + str(
                    domain.get_quantity('xmomentum').get_values(
                        interpolation_points=breachpoint,
                        location='centroids'))
                breacherosion = domain.get_quantity('elevation').get_values(
                    interpolation_points=breachpoint,
                    location='centroids') - initial
                print 'erosion: ' + str(breacherosion)
                volcurr = np.sum(
                    domain.quantities['elevation'].centroid_values *
                    domain.areas)
                volsed = np.sum(
                    domain.quantities['concentration'].centroid_values *
                    domain.quantities['height'].centroid_values * domain.areas)
                conservation = (volcurr + volsed - voltotal) / voltotal
                print 'conservation: ' + '{:.8%}'.format(conservation)
                count = count + 1

            time, Q = anuga.get_flow_through_cross_section(
                name + '.sww', polyline)
            print Q

            initname = "initial_" + name + ".asc"
            finname = "final_" + name + ".asc"
            fluxname = "flux_" + name + ".txt"
            np.savetxt(fluxname, Q)
            anuga.sww2dem(name + '.sww', initname, reduction=0)
            anuga.sww2dem(name + '.sww', finname, reduction=(count - 1))
            finalstats(domain, initialdomain)
            np.save('XconcC.npy',
                    domain.quantities['concentration'].centroid_values)
            np.save('XelevC.npy',
                    domain.quantities['elevation'].centroid_values)
            np.save('XxmC.npy', domain.quantities['xmomentum'].centroid_values)
            np.save('XymC.npy', domain.quantities['ymomentum'].centroid_values)
            np.save('XstageC.npy', domain.quantities['stage'].centroid_values)
            np.save('XconcV.npy',
                    domain.quantities['concentration'].vertex_values)
            np.save('XelevV.npy', domain.quantities['elevation'].vertex_values)
            np.save('XxmV.npy', domain.quantities['xmomentum'].vertex_values)
            np.save('XymV.npy', domain.quantities['ymomentum'].vertex_values)
            np.save('XstageV.npy', domain.quantities['stage'].vertex_values)

        except optparse.OptionError, msg:
            raise Usage(msg)

    except Usage, err:
        print >> sys.stderr, err.msg
        # print >>sys.stderr, "for help use --help"
        return 2
Exemplo n.º 19
0
else:
    output_run = receive(0)


if(earthquake_type=='synthetic_slip'):
    # Location to save output synthetic earthqake files
    slip_output=output_run + '/' + synthetic_slip_dirname + '/' 

# Location to store the '.pts' file which is written prior to mesh generation
meshname = output_run + '/' + name_stem + '.msh'

#------------------------------------------------------------------------------
# Domain definitions
#------------------------------------------------------------------------------
# Use these very large zones as a boundary condition buffer.
bounding_polygon=anuga.read_polygon('INPUT_DATA/buffer_0.csv')
bounding_polygon_inner=anuga.read_polygon('INPUT_DATA/buffer_box.csv')
bounding_polygon_1 = anuga.read_polygon('INPUT_DATA/main_extent.csv')
# Site specific regions
if(detailed_region=='idealTsunami'):
    pass
else:
    err_mess='detailed_region not recognized'
    raise sys.exit(err_mess)

# Define resolutions (max area per triangle) for each polygon
#default_res = 400000*400000*0.5 # 400km triangles -- indended to be very very diffusive, to avoid boundary reflections
low_res_0=400000*400000*0.5 # 40km triangles -- intended to be very diffusive, avoid boundary reflections
low_res_1=40000*40000*0.5 # 40km triangles -- intended to be very diffusive, avoid boundary reflections
default_res_1 = 3000*3000*0.5 # Decent 'deep-water' resolution
interior_1_res=1000*1000*0.5 # Intermediate depth water resolution. 
Exemplo n.º 20
0
    if verbose: print domain.get_extent(absolute=True)

    #------------------------------------------------------------------------------
    # Setup initial conditions
    #------------------------------------------------------------------------------
    domain.set_quantity('stage', 0.0)

    # Friction -- 2 options
    variable_friction = True
    if not variable_friction:
        # Constant friction
        domain.set_quantity('friction', 0.02)

    else:
        # Set friction to 0.02 on roads, 0.04 elsewhere
        road_polygon = anuga.read_polygon('Road/RoadPolygon.csv')
        friction_function = qs.composite_quantity_setting_function(
            [ [road_polygon, 0.02], ['All', 0.04] ], 
            domain)
        domain.set_quantity('friction', friction_function)

    # Elevation
    if houses_as_holes:
        domain.set_quantity('elevation', filename='topography1.pts',
                              use_cache=use_cache,
                                  verbose=verbose)

    else:
        domain.set_quantity('elevation', filename='topography1.pts',
                              use_cache=use_cache,
                              verbose=verbose, location='vertices')
Exemplo n.º 21
0
import numpy

cache = False
verbose = True

# Define Scenario
# the final goal is to define a rainfall scenario
# Here, in order to test, we follow the example to first have a fixed wave scenario
scenario = 'fixed_wave'
name_stem = 'aw_small'
meshname = name_stem + '.msh'

gage_file_name = 'aw_small_gauges.csv'

# bounding polygon for study area
bounding_polygon = anuga.read_polygon('aw_small_extent.csv')
A = anuga.polygon_area(bounding_polygon) / 1000000.0
print 'Area of bounding polygon = %.2f km^2' % A

# Read interior polygons
poly_river = anuga.read_polygon('aw_small_river.csv')

# the greater the base_scale is the less the triangle it will be divided into
just_fitting = False
base_scale = 5000
background_res = 10 * base_scale
river_res = base_scale
city_res = base_scale

interior_regions = [[poly_river, river_res]]
Exemplo n.º 22
0
def run_model():
    """Run a tsunami simulation for a scenario."""

    log.info('@'*90)
    log.info('@ Running simulation')
    log.info('@'*90)

    # Read in boundary from ordered sts file
    event_sts = anuga.create_sts_boundary(project.event_sts)

    # Reading the landward defined points, this incorporates the original
    # clipping polygon minus the 100m contour
    landward_boundary = anuga.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 = anuga.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
    log.debug('bounding_polygon_sts=%s' % str(bounding_polygon_sts))
    log.debug('boundary_tags=%s' % str(boundary_tags))
    log.debug('project.bounding_maxarea=%s' % str(project.bounding_maxarea))
    log.debug('project.interior_regions=%s' % str(project.interior_regions))
    log.debug('project.meshes=%s' % str(project.meshes))

    domain = anuga.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=False,
                                verbose=False)

    domain.geo_reference.zone = project.zone
    log.info('\n%s' % domain.statistics())

    domain.set_name(project.scenario_name)
    domain.set_datadir(project.output_folder)
    domain.set_minimum_storable_height(0.01)  # Don't store depth less than 1cm

    # Set the initial stage in the offcoast region only
    if project.land_initial_conditions:
        IC = anuga.Polygon_function(project.land_initial_conditions,
                                    default=project.tide,
                                    geo_reference=domain.geo_reference)
    else:
        IC = project.tide

    domain.set_quantity('stage', IC, use_cache=True, verbose=False)
    domain.set_quantity('friction', project.friction)
    domain.set_quantity('elevation',
                        filename=project.combined_elevation_filestem+'.pts',
                        use_cache=True, verbose=False, alpha=project.alpha)

    # Setup boundary conditions
    log.debug('Set boundary - available tags: %s' % domain.get_boundary_tags())

    Br = anuga.Reflective_boundary(domain)
    Bt = anuga.Transmissive_stage_zero_momentum_boundary(domain)
    Bd = anuga.Dirichlet_boundary([project.tide, 0, 0])
    Bf = anuga.Field_boundary(project.event_sts+'.sts',
                        domain, mean_stage=project.tide, time_thinning=1,
                        default_boundary=anuga.Dirichlet_boundary([0, 0, 0]),
                        boundary_polygon=bounding_polygon_sts,
                        use_cache=True, verbose=False)

    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):
        log.info('\n%s' % domain.timestepping_statistics())
        log.info('\n%s' % domain.boundary_statistics(tags='ocean'))

    log.info('Simulation took %.2f seconds' % (time.time()-t0))
Exemplo n.º 23
0
scenario = 'fixed_wave'  # Wave applied at the boundary
#scenario = 'slide' # Slide wave form applied inside the domain

#------------------------------------------------------------------------------
# Filenames
#------------------------------------------------------------------------------
name_stem = 'fixed_topobathy'
meshname = name_stem + '.msh'
# Filename for tide gauges locations
gauge_filename = 'gauges_.csv'

#------------------------------------------------------------------------------
# Domain definitions
#------------------------------------------------------------------------------
# bounding polygon for study area
bounding_polygon = anuga.read_polygon('study_area3.csv')
A = anuga.polygon_area(bounding_polygon) / 1000000.0
print 'Area of bounding polygon = %.2f km^2' % A

#------------------------------------------------------------------------------
# Interior region definitions (to create different resolution triangular mesh)
#------------------------------------------------------------------------------
# Read interior polygons

poly_extent1 = anuga.read_polygon('extent_pwrj02.csv')
poly_extent2 = anuga.read_polygon('extent_b_e.csv')
poly_extent3 = anuga.read_polygon('extent_b_w.csv')
poly_extent4 = anuga.read_polygon('extent_c_n_e.csv')
poly_extent5 = anuga.read_polygon('extent_c_n_w.csv')
poly_extent6 = anuga.read_polygon('extent_c_s_e.csv')
poly_extent7 = anuga.read_polygon('extent_c_s_w.csv')
Exemplo n.º 24
0
meshname = 'model/terrain.tsh'

#------------------------------------------------------------------------------
# CREATING MESH
#------------------------------------------------------------------------------
riverWall_csv_files = glob.glob(
    'model/wall/*.csv')  # Make a list of the csv files in BREAKLINES
(riverWalls,
 riverWall_parameters) = su.readListOfRiverWalls(riverWall_csv_files)

CatchmentDictionary = {
    'model/kerb/kerb1.csv': 0.01,
    'model/kerb/kerb2.csv': 0.01
}

bounding_polygon = anuga.read_polygon('model/domain.csv')
interior_regions = anuga.read_polygon_dir(CatchmentDictionary, 'model/kerb')

import numpy as num
b_polygon = num.array(bounding_polygon)
print(b_polygon)
import matplotlib.pyplot as plt

plt.figure()
plt.plot(b_polygon[:, 0], b_polygon[:, 1])
for i, v in enumerate(b_polygon):
    plt.annotate(str(v), xy=v, xytext=(-7, 7), textcoords='offset points')
plt.pause(0.01)

create_mesh_from_regions(
    bounding_polygon,
Exemplo n.º 25
0
#scenario = 'slide'       # Slide wave form applied inside the domain

#------------------------------------------------------------------------------
# Filenames
#------------------------------------------------------------------------------
name_stem = cairns_dir+'cairns'
meshname =  name_stem + '.msh'

# Filename for locations where timeseries are to be produced
gauge_filename = cairns_dir + 'gauges.csv'

#------------------------------------------------------------------------------
# Domain definitions
#------------------------------------------------------------------------------
# bounding polygon for study area
bounding_polygon = anuga.read_polygon(cairns_dir+'extent.csv')

A = anuga.polygon_area(bounding_polygon) / 1000000.0
if __name__ == '_main_':
    print 'Area of bounding polygon = %.2f km^2' % A

#------------------------------------------------------------------------------
# Interior region definitions
#------------------------------------------------------------------------------
# Read interior polygons
poly_cairns = anuga.read_polygon(cairns_dir+'cairns.csv')
poly_island0 = anuga.read_polygon(cairns_dir+'islands.csv')
poly_island1 = anuga.read_polygon(cairns_dir+'islands1.csv')
poly_island2 = anuga.read_polygon(cairns_dir+'islands2.csv')
poly_island3 = anuga.read_polygon(cairns_dir+'islands3.csv')
poly_shallow = anuga.read_polygon(cairns_dir+'shallow.csv')
Exemplo n.º 26
0
def setup_model():
    """Perform sanity checks.

    The checks here can be simpler than for full-blown ANUGA as the directory
    structure is automatically generated.
    """

    # flag - we check many things and then don't proceed if anything wrong
    sanity_error = False               # checked at bottom of this file

    #####
    # check directory Structure
    #####

    if not os.path.exists(project.home):
        log.error("Sorry, data directory '%s' doesn't exist" % project.home)
        sanity_error = True

    if not os.path.exists(project.muxhome):
        log.error("Sorry, MUX directory '%s' doesn't exist" % project.muxhome)
        sanity_error = True

    if not os.path.exists(project.anuga_folder):
        log.error("Sorry, ANUGA directory '%s' doesn't exist"
                  % project.anuga_folder)
        sanity_error = True

    if not os.path.exists(project.topographies_folder):
        log.error("Sorry, topo directory '%s' doesn't exist"
                  % project.topographies_folder)
        sanity_error = True

    if not os.path.exists(project.polygons_folder):
        log.error("Sorry, polygon directory '%s' doesn't exist"
                  % project.polygons_folder)
        sanity_error = True

    if not os.path.exists(project.boundaries_folder):
        log.error("Sorry, boundaries directory '%s' doesn't exist"
                  % project.boundaries_folder)
        sanity_error = True

    if not os.path.exists(project.output_folder):
        log.error("Sorry, outputs directory '%s' doesn't exist"
                  % project.output_folder)
        sanity_error = True

    if not os.path.exists(project.gauges_folder):
        log.error("Sorry, gauges directory '%s' doesn't exist"
                  % project.gauges_folder)
        sanity_error = True

    if not os.path.exists(project.meshes_folder):
        log.error("Sorry, meshes directory '%s' doesn't exist"
                  % project.meshes_folder)
        sanity_error = True

    if not os.path.exists(project.mux_data_folder):
        log.error("Sorry, mux data directory '%s' doesn't exist"
                  % project.mux_data_folder)
        sanity_error = True

    # generate the event.lst file for the event
    get_multimux(project.event, project.multimux_folder, project.mux_input)

    # if multi_mux is True, check if multi-mux file exists
    if project.multi_mux:
        if not os.path.exists(project.mux_input):
            log.error("Sorry, MUX input file '%s' doesn't exist"
                      % project.mux_input)
            sanity_error = True

    if not os.path.exists(project.event_folder):
        log.error("Sorry, you must generate event %s with EventSelection."
                  % project.event)
        sanity_error = True

    #####
    # determine type of run, set some parameters depending on type
    #####

    if project.setup == 'trial':
        project.scale_factor = 100
        project.time_thinning = 96
        project.yieldstep = 240
    elif project.setup == 'basic':
        project.scale_factor = 4
        project.time_thinning = 12
        project.yieldstep = 120
    elif project.setup == 'final':
        project.scale_factor = 1
        project.time_thinning = 4
        project.yieldstep = 60
    else:
        log.error("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 = anuga.read_polygon(os.path.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 = anuga.read_polygon(os.path.join(project.polygons_folder,
                                                  filename))
        project.interior_regions.append([polygon,
                                         maxarea*project.scale_factor])

    # Initial bounding polygon for data clipping
    project.bounding_polygon = anuga.read_polygon(os.path.join(
                                                      project.polygons_folder,
                                                      project.bounding_polygon))
    project.bounding_maxarea = project.bounding_polygon_maxarea \
                               * project.scale_factor

    # Estimate the number of triangles
    log.debug('number_mesh_triangles(%s, %s, %s)'
              % (str(project.interior_regions),
                 str(project.bounding_polygon),
                 str(project.bounding_maxarea)))
    triangle_min = number_mesh_triangles(project.interior_regions,
                                         project.bounding_polygon,
                                         project.bounding_maxarea)

    log.info('minimum estimated number of triangles=%d' % triangle_min)
Exemplo n.º 27
0
    # resolutions (maximal area of per triangle) for each polygon
    #--------------------------------------------------------------------------

    log.critical('Create computational domain')

else:
    print 'Hello from processor ', myid

barrier()

# Read in boundary from ordered sts file
event_sts = anuga.create_sts_boundary(project.event_sts)

# Reading the landward defined points, this incorporates the original clipping
# polygon minus the 100m contour
landward_boundary = anuga.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 = anuga.file_length(project.landward_boundary)

#======================================
# Create sequential domain
#======================================
if (myid == 0):
    # Boundary tags refer to project.landward_boundary
    # 4 points equals 5 segments start at N
Exemplo n.º 28
0
# Filenames
#------------------------------------------------------------------------------
name_stem = scenario_name = '${name_stem}'
event_number =  'T' + str(periodT)
rp = 10000

meshname = name_stem + '.msh'

# Filename for locations where timeseries are to be produced
gauge_filename = 'gauges_busselton.csv'

#------------------------------------------------------------------------------
# Domain definitions
#------------------------------------------------------------------------------
# bounding polygon for study area
bounding_polygon = anuga.read_polygon('busselton_extent_edit.csv')

A = anuga.polygon_area(bounding_polygon) / 1000000.0
print 'Area of bounding polygon = %.2f km^2' % A

#------------------------------------------------------------------------------
# Interior region definitions
#------------------------------------------------------------------------------
# Read interior polygons
poly_1 = anuga.read_polygon('busselton_1km.csv')
poly_2 = anuga.read_polygon('bunbury_1km_extend.csv')
poly_3 = anuga.read_polygon('busselton_20m.csv')
#poly_island2 = anuga.read_polygon('islands2.csv')
#poly_island3 = anuga.read_polygon('islands3.csv')
#poly_shallow = anuga.read_polygon('shallow.csv')
Exemplo n.º 29
0
#from culverts import *

#------------------------------------------------------------------------------
# Preparation of topographic data
# Convert ASC 2 DEM 2 PTS using source data and store result in source data
#------------------------------------------------------------------------------
# Create DEM from asc data
anuga.asc2dem(project.tmppath + 'dtm_utm.mean.asc',
              use_cache=False,
              verbose=verbose)
# Create pts file for onshore DEM
anuga.dem2pts(project.tmppath + 'dtm_utm.mean.dem',
              use_cache=False,
              verbose=verbose)

bounding_polygon = anuga.read_polygon(project.configpath + 'extent.csv')

#------------------------------------------------------------------------------
# Prepare breaklines
#
#------------------------------------------------------------------------------
conn_params = "host=titania dbname=research user=geodan"
conn = psycopg2.connect(conn_params)
cur = conn.cursor()
breaklines = []
querystring = """
WITH extent AS (
	SELECT ST_Transform(ST_SetSrid(ST_MakeEnvelope(%s),32631),28992) as geom
)

,transformed As(
        rain.rain_max_in_period = np.max(rain.precip_total)
        rain.radar_dir = None
        l0 = [5100.0, 100000.0]
        l1 = [5100.0, 103900.0]
        l2 = [3400., 103400.]
        l3 = [6000., 103400.]
        locations = [l0,l1,l2,l3] 

    else:
        pass

    
    print(rain.radar_dir)
    
    try: 
        p2 = anuga.read_polygon(Catchment_file)
        print('Catchment File')
        print(Catchment_file)
        #print p2
    except:
        p2 = None
        pass
    
    try:
        p3 = anuga.read_polygon(State_boundary_file)
        print('State_boundary_file')
        print(State_boundary_file)
        #print p3
    except:
        p3 = None
        pass
Exemplo n.º 31
0
              use_cache=False,
              verbose=True)

# Create DEM from asc data
anuga.dem2pts('11_fbe_c.dem', use_cache=False, verbose=True)

# Create roughness raster from asc data
#anuga.asc2dem('11_man_c.asc', use_cache=False, verbose=True)

# Create roughness raster from asc data
#anuga.dem2pts('11_man_c.dem', use_cache=False,
#              verbose=True)

# In[3]:

bounding_polygon = anuga.read_polygon('extent.csv')
domain = anuga.create_domain_from_regions(bounding_polygon,
                                          boundary_tags={
                                              'top': [0],
                                              'right': [1],
                                              'bottom': [2],
                                              'left': [3]
                                          },
                                          maximum_triangle_area=1,
                                          mesh_filename='11f.msh',
                                          use_cache=False,
                                          verbose=True)

#domain = anuga.Domain(points, vertices, boundary)
domain.set_name('11_fbe_c')
domain.set_datadir('.')