def create_domain(self, InitialOceanStage, InitialLandStage, flowAlg, verbose): """ Make the domain and set the flow algorithm for a test. Produces an sww that we can use for testing """ boundaryPolygon = [[0., 0.], [0., 100.], [100.0, 100.0], [100.0, 0.0]] anuga.create_mesh_from_regions(boundaryPolygon, boundary_tags={ 'left': [0], 'top': [1], 'right': [2], 'bottom': [3] }, maximum_triangle_area=20., minimum_triangle_angle=28.0, filename='test_plot_utils.msh', interior_regions=[], verbose=False) domain = anuga.create_domain_from_file('test_plot_utils.msh') os.remove('test_plot_utils.msh') # 05/05/2014 -- riverwalls only work with DE0 and DE1 domain.set_flow_algorithm(flowAlg) domain.set_name('test_plot_utils') domain.set_store_vertices_uniquely() def topography(x, y): return -x / 150. def stagefun(x, y): stg = InitialOceanStage * (x >= 50.) + InitialLandStage * (x < 50.) return stg domain.set_flow_algorithm(flowAlg) #domain.set_quantity('elevation',topography,location='centroids') domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.03) #domain.set_quantity('stage', stagefun,location='centroids') domain.set_quantity('stage', stagefun) if (verbose): if (domain.store_centroids): print ' Centroids stored' else: print ' Centroids estimated from vertices' # Boundary conditions Br = anuga.Reflective_boundary(domain) domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=0.2, finaltime=1.0): pass return
def create_domain_DE1(self, wallHeight, InitialOceanStage, InitialLandStage): # Riverwall = list of lists, each with a set of x,y,z (and optional QFactor) values riverWall = { 'centralWall': [[wallLoc, 0.0, wallHeight], [wallLoc, 100.0, wallHeight]] } riverWall_Par = {'centralWall': {'Qfactor': 1.0}} # Make the domain anuga.create_mesh_from_regions( boundaryPolygon, boundary_tags={ 'left': [0], 'top': [1], 'right': [2], 'bottom': [3] }, maximum_triangle_area=200., minimum_triangle_angle=28.0, filename='testRiverwall.msh', interior_regions=[], #[ [higherResPolygon, 1.*1.*0.5], # [midResPolygon, 3.0*3.0*0.5]], breaklines=list(riverWall.values()), use_cache=False, verbose=verbose, regionPtArea=regionPtAreas) domain = anuga.create_domain_from_file('testRiverwall.msh') # 05/05/2014 -- riverwalls only work with DE0 and DE1 domain.set_flow_algorithm('DE1') domain.set_name('test_riverwall') domain.set_store_vertices_uniquely() def topography(x, y): return -x / 150. def stagefun(x, y): stg = InitialOceanStage * (x >= 50.) + InitialLandStage * (x < 50.) return stg # NOTE: Setting quantities at centroids is important for exactness of tests domain.set_quantity('elevation', topography, location='centroids') domain.set_quantity('friction', 0.03) domain.set_quantity('stage', stagefun, location='centroids') domain.riverwallData.create_riverwalls(riverWall, riverWall_Par, verbose=verbose) # Boundary conditions Br = anuga.Reflective_boundary(domain) domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) return domain
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 generate_channel1_domain(gpu=True): #-------------------------------------------------------------------------- # Setup computational domain #-------------------------------------------------------------------------- #points, vertices, boundary = anuga.rectangular_cross(10, 1, # len1=10.0, len2=5.0) # Mesh points, vertices, boundary = anuga.rectangular_cross(1, 4, len1=0.1, len2=0.1) # Mesh if gpu: domain = GPU_domain(points, vertices, boundary) # Create domain for i in range(len(sys.argv)): if sys.argv[i] == '-gpu': domain.using_gpu = True print " --> Enable GPU version" elif sys.argv[i] == '-fs': finaltime = float(sys.argv[i + 1]) print " --> Finaltime is reset as %f" % finaltime elif sys.argv[i] == '-test': domain.cotesting = True print " --> Enable Cotesting" elif sys.argv[i] == '-ustore': domain.store = True print " --> Disable storing" else: domain = anuga.Domain(points, vertices, boundary) # Create domain domain.set_name('channel1') # Output name #-------------------------------------------------------------------------- # Setup initial conditions #-------------------------------------------------------------------------- def topography(x, y): return -x / 10 # linear bed slope domain.set_quantity('elevation', topography) # Use function for elevation domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity( 'stage', # Dry bed expression='elevation') #-------------------------------------------------------------------------- # Setup boundary conditions #-------------------------------------------------------------------------- Bi = anuga.Dirichlet_boundary([0.4, 0, 0]) # Inflow Br = anuga.Reflective_boundary(domain) # Solid reflective wall domain.set_boundary({'left': Bi, 'right': Br, 'top': Br, 'bottom': Br}) return domain
def _create_domain(self, d_length, d_width, dx, dy, elevation_0, elevation_1, stage_0, stage_1): points, vertices, boundary = rectangular_cross( int(old_div(d_length, dx)), int(old_div(d_width, dy)), len1=d_length, len2=d_width) domain = Domain(points, vertices, boundary) domain.set_name('Test_Outlet_Inlet') # Output name domain.set_store() domain.set_default_order(2) domain.H0 = 0.01 domain.tight_slope_limiters = 1 #print 'Size', len(domain) #------------------------------------------------------------------------------ # Setup initial conditions #------------------------------------------------------------------------------ def elevation(x, y): """Set up a elevation """ z = numpy.zeros(x.shape, dtype='d') z[:] = elevation_0 numpy.putmask(z, x > old_div(d_length, 2), elevation_1) return z def stage(x, y): """Set up stage """ z = numpy.zeros(x.shape, dtype='d') z[:] = stage_0 numpy.putmask(z, x > old_div(d_length, 2), stage_1) return z #print 'Setting Quantities....' domain.set_quantity('elevation', elevation) # Use function for elevation domain.set_quantity('stage', stage) # Use function for elevation Br = anuga.Reflective_boundary(domain) domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) return domain
def generate_domain(): #-------------------------------------------------------------------------- # Setup computational domain #-------------------------------------------------------------------------- length = 10. width = 5. dx = dy = 1. # Resolution: Length of subdivisions on both axes points, vertices, boundary = anuga.rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) domain = anuga.Domain(points, vertices, boundary) domain.set_name('channel2') # Output name #-------------------------------------------------------------------------- # Setup initial conditions #-------------------------------------------------------------------------- def topography(x, y): return -x / 10 # linear bed slope domain.set_quantity('elevation', topography) # Use function for elevation domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation') # Dry initial condition #-------------------------------------------------------------------------- # Setup boundary conditions #-------------------------------------------------------------------------- Bi = anuga.Dirichlet_boundary([0.4, 0, 0]) # Inflow Br = anuga.Reflective_boundary(domain) # Solid reflective wall Bo = anuga.Dirichlet_boundary([-5, 0, 0]) # Outflow domain.set_boundary({'left': Bi, 'right': Br, 'top': Br, 'bottom': Br}) import sys if len(sys.argv) > 1 and "gpu" in sys.argv: domain.using_gpu = True else: domain.using_gpu = False print sys.argv, "gpu" in sys.argv return domain
def setup_and_evolve(domain, verbose=False): domain.riverwallData.create_riverwalls(riverWall, riverWall_Par, verbose=verbose) #-------------------------- # Setup boundary conditions #-------------------------- Br = anuga.Reflective_boundary(domain) # Solid reflective wall def boundaryFun(t): output = -0.4 * exp(-t / 100.) - 0.1 output = min(output, -0.11) #output=min(output,-0.3) return output Bin_tmss = anuga.Transmissive_momentum_set_stage_boundary( domain=domain, function=boundaryFun) #---------------------------------------------- # Associate boundary tags with boundary objects #---------------------------------------------- domain.set_boundary({ 'left': Br, 'right': Bin_tmss, 'top': Br, 'bottom': Br }) #------------------------------ #Evolve the system through time #------------------------------ if verbose: print('Evolve') for t in domain.evolve(yieldstep=10.0, finaltime=150.0): if myid == 0 and verbose: print(domain.timestepping_statistics()) domain.sww_merge(delete_old=True)
def create_domain(self, flowalg): # Riverwall = list of lists, each with a set of x,y,z (and optional QFactor) values # Make the domain domain = anuga.create_domain_from_regions( boundaryPolygon, boundary_tags={ 'left': [0], 'top': [1], 'right': [2], 'bottom': [3] }, mesh_filename='test_boundaryfluxintegral.msh', maximum_triangle_area=200., minimum_triangle_angle=28.0, use_cache=False, verbose=verbose) # 05/05/2014 -- riverwalls only work with DE0 and DE1 domain.set_flow_algorithm(flowalg) domain.set_name('test_boundaryfluxintegral') domain.set_store_vertices_uniquely() def topography(x, y): return -x / 150. # NOTE: Setting quantities at centroids is important for exactness of tests domain.set_quantity('elevation', topography, location='centroids') domain.set_quantity('friction', 0.03) domain.set_quantity('stage', topography, location='centroids') # Boundary conditions Br = anuga.Reflective_boundary(domain) Bd = anuga.Dirichlet_boundary([0., 0., 0.]) domain.set_boundary({'left': Br, 'right': Bd, 'top': Br, 'bottom': Br}) return domain
domain = distribute(domain) domain.set_store_vertices_uniquely(True) domain.set_quantities_to_be_stored({ 'elevation': 2, 'stage': 2, 'xmomentum': 2, 'ymomentum': 2 }) #------------------------------------------------------------------------------ # Setup boundary conditions on the distributed domain #------------------------------------------------------------------------------ Bi = anuga.Dirichlet_boundary([1.2, 0, 0]) # Inflow at depth Br = anuga.Reflective_boundary(domain) # Solid reflective side walls Bo = anuga.Dirichlet_boundary([-5, 0, 0]) # uncontrolled outflow domain.set_boundary({'left': Bi, 'right': Bo, 'top': Br, 'bottom': Br}) #------------------------------------------------------------------------------ # Setup sanddune erosion operator #------------------------------------------------------------------------------ if myid == 0: print '>>>>> Setting up Erosion Area(s) to test...' # power up the erosion operator from anuga import Sanddune_erosion_operator # assign ns base elevations to partitioned domains
def test_momentum_jet(self): """test_momentum_jet Test that culvert_class can accept keyword use_momentum_jet This does not yet imply that the values have been tested. FIXME """ length = 40. width = 5. dx = dy = 1 # Resolution: Length of subdivisions on both axes points, vertices, boundary = rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) domain = anuga.Domain(points, vertices, boundary) domain.set_name('Test_culvert_shallow') # Output name domain.set_default_order(2) #---------------------------------------------------------------------- # Setup initial conditions #---------------------------------------------------------------------- def topography(x, y): """Set up a weir A culvert will connect either side """ # General Slope of Topography z = -x / 1000 N = len(x) for i in range(N): # Sloping Embankment Across Channel if 5.0 < x[i] < 10.1: # Cut Out Segment for Culvert face if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] - 5.0) / 5.0: z[i] = z[i] else: z[i] += 0.5 * (x[i] - 5.0) # Sloping Segment U/S Face if 10.0 < x[i] < 12.1: z[i] += 2.5 # Flat Crest of Embankment if 12.0 < x[i] < 14.5: # Cut Out Segment for Culvert face if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] - 12.0) / 2.5: z[i] = z[i] else: z[i] += 2.5 - 1.0 * (x[i] - 12.0) # Sloping D/S Face return z domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity( 'stage', expression='elevation + 1.0') # Shallow initial condition # Boyd culvert culvert = Culvert_flow( domain, label='Culvert No. 1', description='This culvert is a test unit 1.2m Wide by 0.75m High', end_point0=[9.0, 2.5], end_point1=[13.0, 2.5], width=1.20, height=0.75, culvert_routine=boyd_generalised_culvert_model, number_of_barrels=1, use_momentum_jet=True, update_interval=2, verbose=False) domain.forcing_terms.append(culvert) # Call culvert(domain) #----------------------------------------------------------------------- # Setup boundary conditions #----------------------------------------------------------------------- Br = anuga.Reflective_boundary(domain) # Solid reflective wall domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) #----------------------------------------------------------------------- # Evolve system through time #----------------------------------------------------------------------- ref_volume = domain.get_quantity('stage').get_integral() for t in domain.evolve(yieldstep=0.1, finaltime=25): new_volume = domain.get_quantity('stage').get_integral() msg = ( 'Total volume has changed: Is %.8f m^3 should have been %.8f m^3' % (new_volume, ref_volume)) assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
def OBSOLETE_XXXtest_that_culvert_rating_limits_flow_in_shallow_inlet_condition( self): """test_that_culvert_rating_limits_flow_in_shallow_inlet_condition Test that culvert on a sloping dry bed limits flows when very little water is present at inlet This one is using the rating curve variant """ path = get_pathname_from_package('anuga.culvert_flows') length = 40. width = 5. dx = dy = 1 # Resolution: Length of subdivisions on both axes points, vertices, boundary = rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) domain = anuga.Domain(points, vertices, boundary) domain.set_name('Test_culvert_shallow') # Output name domain.set_default_order(2) #---------------------------------------------------------------------- # Setup initial conditions #---------------------------------------------------------------------- def topography(x, y): """Set up a weir A culvert will connect either side """ # General Slope of Topography z = -x / 1000 N = len(x) for i in range(N): # Sloping Embankment Across Channel if 5.0 < x[i] < 10.1: # Cut Out Segment for Culvert face if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] - 5.0) / 5.0: z[i] = z[i] else: z[i] += 0.5 * (x[i] - 5.0) # Sloping Segment U/S Face if 10.0 < x[i] < 12.1: z[i] += 2.5 # Flat Crest of Embankment if 12.0 < x[i] < 14.5: # Cut Out Segment for Culvert face if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] - 12.0) / 2.5: z[i] = z[i] else: z[i] += 2.5 - 1.0 * (x[i] - 12.0) # Sloping D/S Face return z domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity( 'stage', expression='elevation + 0.1') # Shallow initial condition # Boyd culvert culvert = Culvert_flow( domain, label='Culvert No. 1', description='This culvert is a test unit 1.2m Wide by 0.75m High', end_point0=[9.0, 2.5], end_point1=[13.0, 2.5], width=1.20, height=0.75, culvert_routine=boyd_generalised_culvert_model, number_of_barrels=1, update_interval=2, verbose=False) # Rating curve #filename = os.path.join(path, 'example_rating_curve.csv') #culvert = Culvert_flow(domain, # culvert_description_filename=filename, # end_point0=[9.0, 2.5], # end_point1=[13.0, 2.5], # trigger_depth=0.01, # verbose=False) domain.forcing_terms.append(culvert) #----------------------------------------------------------------------- # Setup boundary conditions #----------------------------------------------------------------------- # Inflow based on Flow Depth and Approaching Momentum Br = anuga.Reflective_boundary(domain) # Solid reflective wall domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) #----------------------------------------------------------------------- # Evolve system through time #----------------------------------------------------------------------- print 'depth', 0.1 ref_volume = domain.get_quantity('stage').get_integral() for t in domain.evolve(yieldstep=0.1, finaltime=25): new_volume = domain.get_quantity('stage').get_integral() msg = ( 'Total volume has changed: Is %.8f m^3 should have been %.8f m^3' % (new_volume, ref_volume)) assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg return # Now try this again for a depth of 10 cm and for a range of other depths for depth in [0.1, 0.2, 0.5, 1.0]: print 'depth', depth domain.set_time(0.0) domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation + %f' % depth) ref_volume = domain.get_quantity('stage').get_integral() for t in domain.evolve(yieldstep=0.1, finaltime=25): new_volume = domain.get_quantity('stage').get_integral() msg = 'Total volume has changed: Is %.8f m^3 should have been %.8f m^3'\ % (new_volume, ref_volume) assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
def test_that_culvert_dry_bed_boyd_does_not_produce_flow(self): """test_that_culvert_in_dry_bed_boyd_does_not_produce_flow(self): Test that culvert on a sloping dry bed doesn't produce flows although there will be a 'pressure' head due to delta_w > 0 This one is using the 'Boyd' variant """ path = get_pathname_from_package('anuga.culvert_flows') length = 40. width = 5. dx = dy = 1 # Resolution: Length of subdivisions on both axes points, vertices, boundary = rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) domain = anuga.Domain(points, vertices, boundary) domain.set_name('Test_culvert_dry') # Output name domain.set_default_order(2) #---------------------------------------------------------------------- # Setup initial conditions #---------------------------------------------------------------------- def topography(x, y): """Set up a weir A culvert will connect either side """ # General Slope of Topography z = -x / 1000 N = len(x) for i in range(N): # Sloping Embankment Across Channel if 5.0 < x[i] < 10.1: # Cut Out Segment for Culvert face if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] - 5.0) / 5.0: z[i] = z[i] else: z[i] += 0.5 * (x[i] - 5.0) # Sloping Segment U/S Face if 10.0 < x[i] < 12.1: z[i] += 2.5 # Flat Crest of Embankment if 12.0 < x[i] < 14.5: # Cut Out Segment for Culvert face if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] - 12.0) / 2.5: z[i] = z[i] else: z[i] += 2.5 - 1.0 * (x[i] - 12.0) # Sloping D/S Face return z domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation') # Dry initial condition filename = os.path.join(path, 'example_rating_curve.csv') culvert = Culvert_flow( domain, label='Culvert No. 1', description='This culvert is a test unit 1.2m Wide by 0.75m High', end_point0=[9.0, 2.5], end_point1=[13.0, 2.5], width=1.20, height=0.75, culvert_routine=boyd_generalised_culvert_model, number_of_barrels=1, update_interval=2, verbose=False) domain.forcing_terms.append(culvert) #----------------------------------------------------------------------- # Setup boundary conditions #----------------------------------------------------------------------- # Inflow based on Flow Depth and Approaching Momentum Br = anuga.Reflective_boundary(domain) # Solid reflective wall domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) #----------------------------------------------------------------------- # Evolve system through time #----------------------------------------------------------------------- ref_volume = domain.get_quantity('stage').get_integral() for t in domain.evolve(yieldstep=1, finaltime=25): new_volume = domain.get_quantity('stage').get_integral() msg = 'Total volume has changed' assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg pass
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
def test_that_culvert_runs_rating(self): """test_that_culvert_runs_rating This test exercises the culvert and checks values outside rating curve are dealt with """ path = get_pathname_from_package('anuga.culvert_flows') path = os.path.join(path, 'tests', 'data') length = 40. width = 5. dx = dy = 1 # Resolution: Length of subdivisions on both axes points, vertices, boundary = rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) domain = anuga.Domain(points, vertices, boundary) domain.set_name('Test_culvert') # Output name domain.set_default_order(2) #---------------------------------------------------------------------- # Setup initial conditions #---------------------------------------------------------------------- def topography(x, y): """Set up a weir A culvert will connect either side """ # General Slope of Topography z = -x / 1000 N = len(x) for i in range(N): # Sloping Embankment Across Channel if 5.0 < x[i] < 10.1: # Cut Out Segment for Culvert face if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] - 5.0) / 5.0: z[i] = z[i] else: z[i] += 0.5 * (x[i] - 5.0) # Sloping Segment U/S Face if 10.0 < x[i] < 12.1: z[i] += 2.5 # Flat Crest of Embankment if 12.0 < x[i] < 14.5: # Cut Out Segment for Culvert face if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] - 12.0) / 2.5: z[i] = z[i] else: z[i] += 2.5 - 1.0 * (x[i] - 12.0) # Sloping D/S Face return z domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation') # Dry initial condition filename = os.path.join(path, 'example_rating_curve.csv') culvert = Culvert_flow(domain, culvert_description_filename=filename, end_point0=[9.0, 2.5], end_point1=[13.0, 2.5], width=1.00, use_velocity_head=True, verbose=False) domain.forcing_terms.append(culvert) #----------------------------------------------------------------------- # Setup boundary conditions #----------------------------------------------------------------------- # Inflow based on Flow Depth and Approaching Momentum Bi = anuga.Dirichlet_boundary([0.0, 0.0, 0.0]) Br = anuga.Reflective_boundary(domain) # Solid reflective wall Bo = anuga.Dirichlet_boundary([-5, 0, 0]) # Outflow # Upstream and downstream conditions that will exceed the rating curve # I.e produce delta_h outside the range [0, 10] specified in the the # file example_rating_curve.csv Btus = anuga.Time_boundary( domain, lambda t: [100 * num.sin(2 * pi * (t - 4) / 10), 0.0, 0.0]) Btds = anuga.Time_boundary( domain, lambda t: [-5 * (num.cos(2 * pi * (t - 4) / 20)), 0.0, 0.0]) domain.set_boundary({ 'left': Btus, 'right': Btds, 'top': Br, 'bottom': Br }) #----------------------------------------------------------------------- # Evolve system through time #----------------------------------------------------------------------- min_delta_w = sys.maxint max_delta_w = -min_delta_w for t in domain.evolve(yieldstep=1, finaltime=25): delta_w = culvert.inlet.stage - culvert.outlet.stage if delta_w > max_delta_w: max_delta_w = delta_w if delta_w < min_delta_w: min_delta_w = delta_w pass # Check that extreme values in rating curve have been exceeded # so that we know that condition has been exercised assert min_delta_w < 0 assert max_delta_w > 10 os.remove('Test_culvert.sww')
def runOkushiri(par, n): # ------------------------------------------------------------------------------ # Setup computational domain # ------------------------------------------------------------------------------ xleft = 0 xright = 5.448 ybottom = 0 ytop = 3.402 # rectangular cross mesh points, vertices, boundary = anuga.rectangular_cross( int(n), int(n), xright - xleft, ytop - ybottom, (xleft, ybottom)) newpoints = points.copy() # make refinement in x direction x = np.multiply([0., 0.1, 0.2, 0.335, 0.925, 1.], max(points[:, 0])) y = [0., 3., 4.25, 4.7, 5.3, max(points[:, 0])] f1 = interp1d(x, y, kind='quadratic') newpoints[:, 0] = f1(points[:, 0]) # make refinement in y direction x = np.multiply([0., .125, .3, .7, .9, 1.], max(points[:, 1])) y = [0., 1.25, 1.75, 2.15, 2.65, max(points[:, 1])] f2 = interp1d(x, y, kind='quadratic') newpoints[:, 1] = f2(points[:, 1]) c = abs(newpoints[:, 0] - 5.0) + .5 * abs(newpoints[:, 1] - 1.95) c = 0.125 * c points[:, 0] = c * points[:, 0] + (1 - c) * newpoints[:, 0] points[:, 1] = c * points[:, 1] + (1 - c) * newpoints[:, 1] # create domain domain = anuga.Domain(points, vertices, boundary) # don't store .sww file # domain.set_quantities_to_be_stored(None) # ------------------------------------------------------------------------------ # Initial Conditions # ------------------------------------------------------------------------------ domain.set_quantity('friction', 0.01) # 0.0 domain.set_quantity('stage', 0.0) domain.set_quantity( 'elevation', filename='/home/rehmemk/git/anugasgpp/Okushiri/data/bathymetry.pts', alpha=0.02) # ------------------------------------------------------------------------------ # Set simulation parameters # ------------------------------------------------------------------------------ domain.set_name('output_okushiri') # Output name domain.set_minimum_storable_height(0.001) # Don't store w < 0.001m domain.set_flow_algorithm('DE0') # ------------------------------------------------------------------------------ # Modify input wave # ------------------------------------------------------------------------------ # rescale input parameter try: dummy = len(par) except: par = [par] par = np.dot(2, par) # load wave data # shutil.copyfile('boundary_wave_header.txt', 'boundary_wave_input.txt') data = np.loadtxt( '/home/rehmemk/git/anugasgpp/Okushiri/data/boundary_wave_original.txt', skiprows=1) t = data[:, 0] y = data[:, 1] energy = np.trapz(y**2, t) # define bumps [create input wave based on parameters] def bump(c): theta = c[0] position = c[1] weight = c[2] ybump = weight * np.exp(-.5 * (t - position)**2 * theta**-2) return ybump nbump = len(par) residual = y.copy() c = np.zeros((nbump, 3)) for k in range(nbump): maxid = np.argmax(np.abs(residual)) c0 = np.array([1.5, t[maxid], residual[maxid]]) def cost(c): ybump = bump(c) cost = np.sqrt(np.mean((ybump - residual)**2)) return cost c[k, :] = fmin(cost, c0, disp=False) residual -= bump(c[k, :]) # deform wave ynew = residual.copy() for k in range(nbump): ynew += par[k] * bump(c[k, :]) energynew = np.trapz(ynew**2, t) ynew = np.sqrt(energy / energynew) * ynew # write data data[:, 1] = ynew.copy() import scipy wave_function = scipy.interpolate.interp1d(t, ynew, kind='zero', fill_value='extrapolate') # MR: uncomment to plot input wave # points = np.linspace(-10, 30, 10000) # evals = np.zeros(len(points)) # for i in range(len(evals)): # evals[i] = wave_function(points[i]) # plt.figure() # # plt.plot(points, evals) # # plt.plot(t, residual, 'r') # for k in range(nbump): # plt.plot(t, par[k]*bump(c[k, :]), label='bum {}'.format(k)) # plt.title('Okushiri Input Wave') # plt.show() # ------------------------------------------------------------------------------ # Setup boundary conditions # ------------------------------------------------------------------------------ # Create boundary function from input wave [replaced by wave function] # Create and assign boundary objects Bts = anuga.Transmissive_momentum_set_stage_boundary(domain, wave_function) Br = anuga.Reflective_boundary(domain) domain.set_boundary({'left': Bts, 'right': Br, 'top': Br, 'bottom': Br}) # ------------------------------------------------------------------------------ # Evolve system through time # ------------------------------------------------------------------------------ # area for gulleys x1 = 4.85 x2 = 5.25 y1 = 2.05 y2 = 1.85 # gauges gauges = [[4.521, 1.196], [4.521, 1.696], [4.521, 2.196]] # index in gulley area x = domain.centroid_coordinates[:, 0] y = domain.centroid_coordinates[:, 1] v = np.sqrt((x - x1) ** 2 + (y - y1) ** 2) + \ np.sqrt((x - x2) ** 2 + (y - y2) ** 2) < 0.5 dplotter = Domain_plotter(domain, min_depth=0.001) k = 0 # original number of timesteps is 451 numTimeSteps = int( np.loadtxt( '/home/rehmemk/git/anugasgpp/Okushiri/data/numTimeSteps.txt')) meanstage = np.nan * np.ones((1, numTimeSteps)) yieldstep = 0.05 finaltime = (numTimeSteps - 1) * yieldstep meanlayer = 0 # Do the actual calculation # for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime): # # domain.write_time() # # stage [=height of water] # stage = domain.quantities['stage'].centroid_values[v] # # averaging for smoothness # meanstage[0, k] = np.mean(stage) # # k is time # k += 1 # # PLOTTING # # Make movie of each timestep # dplotter.save_depth_frame() # anim = dplotter.make_depth_animation() # anim.save('okushiri_%i.mp4' % n) # meanlayer = meanstage - meanstage[0, 0] # Plot the domain plt.figure() xya = np.loadtxt( '/home/rehmemk/git/anugasgpp/Okushiri/plots/Benchmark_2_Bathymetry.xya', skiprows=1, delimiter=',') X = xya[:, 0].reshape(393, 244) Y = xya[:, 1].reshape(393, 244) Z = xya[:, 2].reshape(393, 244) # Remove the white part of the seismic # Steves original code uses cmap('gist_earth') from matplotlib.colors import LinearSegmentedColormap interval = np.hstack([np.linspace(0.0, 0.3), np.linspace(0.5, 1.0)]) colors = plt.cm.seismic(interval) my_cmap = LinearSegmentedColormap.from_list('name', colors) # Multiply heights by 400 so that we getreal scale, not model scale N1, N2 = np.shape(Z) for n1 in range(N1): for n2 in range(N2): Z[n1, n2] *= 400 plt.contourf(X, Y, Z, 20, cmap=my_cmap) # plt.title('Bathymetry') cbar = plt.colorbar() cbar.ax.tick_params(labelsize=colorbarfontsize) # cbar.set_label('elevation', rotation=270) import matplotlib.patches from matplotlib.patches import Ellipse # plt.plot(x1, y1, 'o') # plt.plot(x2, y2, 'o') ellipse = Ellipse(((x2 + x1) / 2., (y1 + y2) / 2.), width=0.5, height=0.2, angle=-20, edgecolor='k', fill=False, label='area of interest', linewidth=4) plt.gca().add_patch(ellipse) # plt.plot(gauges[0][0], gauges[0][1], 'ok') # plt.plot(gauges[1][0], gauges[1][1], 'ok') # plt.plot(gauges[2][0], gauges[2][1], 'ok', markersize=8, label='gauge') # plt.axis('off') plt.legend(loc='upper left', fontsize=legendfontsize) plt.gca().tick_params(axis='both', which='major', labelsize=tickfontsize) plt.tight_layout() # ---------------- hack to get ellpse shaped ellipse in legend------------ import matplotlib.patches as mpatches from matplotlib.legend_handler import HandlerPatch colors = ["k"] texts = ["area of interest"] class HandlerEllipse(HandlerPatch): def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent p = mpatches.Ellipse(xy=center, width=width + xdescent, height=height + ydescent) self.update_prop(p, orig_handle, legend) p.set_transform(trans) return [p] c = [ mpatches.Circle((0.5, 0.5), 1, facecolor='None', edgecolor='k', linewidth=3) for i in range(len(texts)) ] plt.legend(c, texts, bbox_to_anchor=(0., 1.), loc='upper left', ncol=1, fontsize=16, handler_map={mpatches.Circle: HandlerEllipse()}) # ---------------------------- plt.savefig('okushiri_domain.pdf') # Plot the triangle mesh plt.figure() mittelblau = (0. / 255, 81. / 255, 158. / 255) plt.triplot(dplotter.triang, linewidth=0.3, color=mittelblau) plt.axis('off') plt.tight_layout() plt.savefig('okushiri_mesh_%i.pdf' % n) # Plot the domain and the triangle mesh plt.figure() plt.tripcolor(dplotter.triang, facecolors=dplotter.elev, edgecolors='k', cmap='gist_earth') plt.colorbar() plt.tight_layout() plt.savefig('okushiri_domainandmesh_%i.pdf' % n) # make video from sww file # swwplotter = SWW_plotter('output_okushiri.sww', min_depth=0.001) # lilo = len(swwplotter.time) # for k in range(lilo): # if k % 10 == 0: # print ' ' # swwplotter.save_stage_frame(frame=k, vmin=-0.02, vmax=0.1) # print '(', swwplotter.time[k], k, ')', # print ' ' # swwanim = swwplotter.make_stage_animation() # swwanim.save('okushiri_fromswwfile.mp4') return meanlayer
def run_culvert_flow_problem(depth): """Run flow with culvert given depth """ length = 40. width = 5. dx = dy = 1 # Resolution: Length of subdivisions on both axes points, vertices, boundary = rectangular_cross(int(old_div(length, dx)), int(old_div(width, dy)), len1=length, len2=width) domain = anuga.Domain(points, vertices, boundary) domain.set_name('Test_culvert_shallow') # Output name domain.set_default_order(2) #---------------------------------------------------------------------- # Setup initial conditions #---------------------------------------------------------------------- def topography(x, y): """Set up a weir A culvert will connect either side """ # General Slope of Topography z = old_div(-x, 1000) N = len(x) for i in range(N): # Sloping Embankment Across Channel if 5.0 < x[i] < 10.1: # Cut Out Segment for Culvert face if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] - 5.0) / 5.0: z[i] = z[i] else: z[i] += 0.5 * (x[i] - 5.0) # Sloping Segment U/S Face if 10.0 < x[i] < 12.1: z[i] += 2.5 # Flat Crest of Embankment if 12.0 < x[i] < 14.5: # Cut Out Segment for Culvert face if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] - 12.0) / 2.5: z[i] = z[i] else: z[i] += 2.5 - 1.0 * (x[i] - 12.0) # Sloping D/S Face return z domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation + %f' % depth) # Shallow initial condition # Boyd culvert culvert = Culvert_flow( domain, label='Culvert No. 1', description='This culvert is a test unit 1.2m Wide by 0.75m High', end_point0=[9.0, 2.5], end_point1=[13.0, 2.5], width=1.20, height=0.75, culvert_routine=boyd_generalised_culvert_model, number_of_barrels=1, update_interval=2, verbose=False) domain.forcing_terms.append(culvert) #----------------------------------------------------------------------- # Setup boundary conditions #----------------------------------------------------------------------- # Inflow based on Flow Depth and Approaching Momentum Br = anuga.Reflective_boundary(domain) # Solid reflective wall domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) #----------------------------------------------------------------------- # Evolve system through time #----------------------------------------------------------------------- #print 'depth', depth ref_volume = domain.get_quantity('stage').get_integral() for t in domain.evolve(yieldstep=0.1, finaltime=10): new_volume = domain.get_quantity('stage').get_integral() msg = ( 'Total volume has changed: Is %.8f m^3 should have been %.8f m^3' % (new_volume, ref_volume)) assert num.allclose(new_volume, ref_volume), msg os.remove('Test_culvert_shallow.sww')
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."
def run_simulation(parallel=False, control_data=None, test_points=None, verbose=False): success = True ##----------------------------------------------------------------------- ## Setup domain ##----------------------------------------------------------------------- points, vertices, boundary = rectangular_cross(int(old_div(length, dx)), int(old_div(width, dy)), len1=length, len2=width) domain = anuga.Domain(points, vertices, boundary) #domain.set_name() # Output name domain.set_store(False) domain.set_default_order(2) ##----------------------------------------------------------------------- ## Distribute domain ##----------------------------------------------------------------------- if parallel: domain = distribute(domain) #domain.dump_triangulation("frac_op_domain.png") ##----------------------------------------------------------------------- ## Setup boundary conditions ##----------------------------------------------------------------------- domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation') # Dry initial condition Bi = anuga.Dirichlet_boundary([5.0, 0.0, 0.0]) Br = anuga.Reflective_boundary(domain) # Solid reflective wall domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) ##----------------------------------------------------------------------- ## Determine triangle index coinciding with test points ##----------------------------------------------------------------------- assert (test_points is not None) assert (len(test_points) == samples) tri_ids = [] for point in test_points: try: k = domain.get_triangle_containing_point(point) if domain.tri_full_flag[k] == 1: tri_ids.append(k) else: tri_ids.append(-1) except: tri_ids.append(-2) if verbose: print('P%d has points = %s' % (myid, tri_ids)) if not parallel: control_data = [] ################ Define Fractional Operators ########################## inlet0 = None inlet1 = None boyd_box0 = None inlet0 = Inlet_operator(domain, line0, Q0, verbose=False, label='Inlet_0') inlet1 = Inlet_operator(domain, line1, Q1, verbose=False, label='Inlet_1') # Enquiry point [ 19. 2.5] is contained in two domains in 4 proc case boyd_box0 = Boyd_box_operator(domain, end_points=[[9.0, 2.5], [19.0, 2.5]], losses=1.5, width=5.0, apron=5.0, use_momentum_jet=True, use_velocity_head=False, manning=0.013, label='Boyd_Box_0', verbose=False) #if inlet0 is not None and verbose: inlet0.print_statistics() #if inlet1 is not None and verbose: inlet1.print_statistics() if boyd_box0 is not None and verbose: print("++++", myid) boyd_box0.print_statistics() # if parallel: # factory = Parallel_operator_factory(domain, verbose = True) # # inlet0 = factory.inlet_operator_factory(line0, Q0) # inlet1 = factory.inlet_operator_factory(line1, Q1) # # boyd_box0 = factory.boyd_box_operator_factory(end_points=[[9.0, 2.5],[19.0, 2.5]], # losses=1.5, # width=1.5, # apron=5.0, # use_momentum_jet=True, # use_velocity_head=False, # manning=0.013, # verbose=False) # # else: # inlet0 = Inlet_operator(domain, line0, Q0) # inlet1 = Inlet_operator(domain, line1, Q1) # # # Enquiry point [ 19. 2.5] is contained in two domains in 4 proc case # boyd_box0 = Boyd_box_operator(domain, # end_points=[[9.0, 2.5],[19.0, 2.5]], # losses=1.5, # width=1.5, # apron=5.0, # use_momentum_jet=True, # use_velocity_head=False, # manning=0.013, # verbose=False) ####################################################################### ##----------------------------------------------------------------------- ## Evolve system through time ##----------------------------------------------------------------------- for t in domain.evolve(yieldstep=2.0, finaltime=20.0): if myid == 0 and verbose: domain.write_time() #print domain.volumetric_balance_statistics() stage = domain.get_quantity('stage') if boyd_box0 is not None and verbose: if myid == boyd_box0.master_proc: print('master_proc ', myid) boyd_box0.print_timestepping_statistics() #for i in range(samples): # if tri_ids[i] >= 0: # if verbose: print 'P%d tri %d, value = %s' %(myid, i, stage.centroid_values[tri_ids[i]]) sys.stdout.flush() pass domain.sww_merge(delete_old=True) success = True ##----------------------------------------------------------------------- ## Assign/Test Control data ##----------------------------------------------------------------------- if not parallel: stage = domain.get_quantity('stage') for i in range(samples): assert (tri_ids[i] >= 0) control_data.append(stage.centroid_values[tri_ids[i]]) if inlet0 is not None: control_data.append(inlet0.inlet.get_average_stage()) control_data.append(inlet0.inlet.get_average_xmom()) control_data.append(inlet0.inlet.get_average_ymom()) control_data.append(inlet0.inlet.get_total_water_volume()) control_data.append(inlet0.inlet.get_average_depth()) if verbose: print('P%d control_data = %s' % (myid, control_data)) else: stage = domain.get_quantity('stage') for i in range(samples): if tri_ids[i] >= 0: local_success = num.allclose(control_data[i], stage.centroid_values[tri_ids[i]]) success = success and local_success if verbose: print( 'P%d tri %d, control = %s, actual = %s, Success = %s' % (myid, i, control_data[i], stage.centroid_values[tri_ids[i]], local_success)) if inlet0 is not None: inlet_master_proc = inlet0.inlet.get_master_proc() average_stage = inlet0.inlet.get_global_average_stage() average_xmom = inlet0.inlet.get_global_average_xmom() average_ymom = inlet0.inlet.get_global_average_ymom() average_volume = inlet0.inlet.get_global_total_water_volume() average_depth = inlet0.inlet.get_global_average_depth() if myid == inlet_master_proc: if verbose: print('P%d average stage, control = %s, actual = %s' % (myid, control_data[samples], average_stage)) print('P%d average xmom, control = %s, actual = %s' % (myid, control_data[samples + 1], average_xmom)) print('P%d average ymom, control = %s, actual = %s' % (myid, control_data[samples + 2], average_ymom)) print('P%d average volume, control = %s, actual = %s' % (myid, control_data[samples + 3], average_volume)) print('P%d average depth, control = %s, actual = %s' % (myid, control_data[samples + 4], average_depth)) return control_data, success
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.")
def run_simulation(parallel=False, control_data=None, test_points=None, verbose=False): success = True ##----------------------------------------------------------------------- ## Setup domain ##----------------------------------------------------------------------- points, vertices, boundary = rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) domain = anuga.Domain(points, vertices, boundary) #rm *.swwdomain.set_name('output_parallel_inlet_operator') # Output name domain.set_store(False) domain.set_default_order(2) ##----------------------------------------------------------------------- ## Distribute domain ##----------------------------------------------------------------------- if parallel: domain = distribute(domain) #domain.dump_triangulation("frac_op_domain.png") ##----------------------------------------------------------------------- ## Setup boundary conditions ##----------------------------------------------------------------------- domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation') # Dry initial condition Bi = anuga.Dirichlet_boundary([5.0, 0.0, 0.0]) Br = anuga.Reflective_boundary(domain) # Solid reflective wall domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) ##----------------------------------------------------------------------- ## Determine triangle index coinciding with test points ##----------------------------------------------------------------------- assert (test_points is not None) assert (len(test_points) == samples) tri_ids = [] for point in test_points: try: k = domain.get_triangle_containing_point(point) if domain.tri_full_flag[k] == 1: tri_ids.append(k) else: tri_ids.append(-1) except: tri_ids.append(-2) if verbose: print 'P%d has points = %s' % (myid, tri_ids) if not parallel: control_data = [] ################ Define Fractional Operators ########################## inlet0 = None inlet1 = None boyd_box0 = None inlet0 = Inlet_operator(domain, line0, Q0, verbose=False, default=0.0) inlet1 = Inlet_operator(domain, line1, Q1, verbose=False) if inlet0 is not None and verbose: inlet0.print_statistics() if inlet1 is not None and verbose: inlet1.print_statistics() #if boyd_box0 is not None and verbose: boyd_box0.print_statistics() ##----------------------------------------------------------------------- ## Evolve system through time ##----------------------------------------------------------------------- for t in domain.evolve(yieldstep=2.0, finaltime=40.0): if myid == 0 and verbose: domain.write_time() #print domain.volumetric_balance_statistics() stage = domain.get_quantity('stage') #if boyd_box0 is not None and verbose : boyd_box0.print_timestepping_statistics() #for i in range(samples): # if tri_ids[i] >= 0: # if verbose: print 'P%d tri %d, value = %s' %(myid, i, stage.centroid_values[tri_ids[i]]) sys.stdout.flush() pass domain.sww_merge(delete_old=True) success = True ##----------------------------------------------------------------------- ## Assign/Test Control data ##----------------------------------------------------------------------- if not parallel: stage = domain.get_quantity('stage') for i in range(samples): assert (tri_ids[i] >= 0) control_data.append(stage.centroid_values[tri_ids[i]]) if inlet0 is not None: control_data.append(inlet0.inlet.get_average_stage()) control_data.append(inlet0.inlet.get_average_xmom()) control_data.append(inlet0.inlet.get_average_ymom()) control_data.append(inlet0.inlet.get_total_water_volume()) control_data.append(inlet0.inlet.get_average_depth()) if verbose: print 'P%d control_data = %s' % (myid, control_data) else: stage = domain.get_quantity('stage') for i in range(samples): if tri_ids[i] >= 0: local_success = num.allclose(control_data[i], stage.centroid_values[tri_ids[i]]) success = success and local_success if verbose: print 'P%d tri %d, control = %s, actual = %s, Success = %s' % ( myid, i, control_data[i], stage.centroid_values[tri_ids[i]], local_success) if inlet0 is not None: inlet_master_proc = inlet0.inlet.get_master_proc() average_stage = inlet0.inlet.get_global_average_stage() average_xmom = inlet0.inlet.get_global_average_xmom() average_ymom = inlet0.inlet.get_global_average_ymom() average_volume = inlet0.inlet.get_global_total_water_volume() average_depth = inlet0.inlet.get_global_average_depth() if myid == inlet_master_proc: if verbose: print 'P%d average stage, control = %s, actual = %s' % ( myid, control_data[samples], average_stage) print 'P%d average xmom, control = %s, actual = %s' % ( myid, control_data[samples + 1], average_xmom) print 'P%d average ymom, control = %s, actual = %s' % ( myid, control_data[samples + 2], average_ymom) print 'P%d average volume, control = %s, actual = %s' % ( myid, control_data[samples + 3], average_volume) print 'P%d average depth, control = %s, actual = %s' % ( myid, control_data[samples + 4], average_depth) assert (success) return control_data
def create_domain(self, InitialOceanStage, InitialLandStage, flowAlg='DE0', verbose=False): """ Make the domain and set the flow algorithm for a test. Produces an sww that we can use for testing """ boundaryPolygon = [[minX, minY], [minX, minY + 100.], [minX + 100., minY + 100.], [minX + 100., minY]] anuga.create_mesh_from_regions( boundaryPolygon, boundary_tags={ 'left': [0], 'top': [1], 'right': [2], 'bottom': [3] }, maximum_triangle_area=1., minimum_triangle_angle=28.0, filename='test_quantity_setting_functions.msh', interior_regions=[], verbose=False) domain = anuga.create_domain_from_file( 'test_quantity_setting_functions.msh') os.remove('test_quantity_setting_functions.msh') domain.set_flow_algorithm(flowAlg) domain.set_name('test_quantity_setting_functions') domain.set_store_vertices_uniquely() def topography(x, y): return -x / 150. def stagefun(x, y): stg = InitialOceanStage * (x >= 50.) + InitialLandStage * (x < 50.) return stg domain.set_flow_algorithm(flowAlg) # domain.set_quantity('elevation',topography,location='centroids') domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.03) #domain.set_quantity('stage', stagefun,location='centroids') domain.set_quantity('stage', stagefun) if (verbose): if (domain.store_centroids): print(' Centroids stored') else: print(' Centroids estimated from vertices') # Boundary conditions Br = anuga.Reflective_boundary(domain) domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) return domain
def setup_boundary_conditions(domain, project): """ Edit this if new types of boundary conditions need to be supported """ # Dict to hold { boundary_tag: boundary_condition_function } boundary_tags_and_conditions = {} for i in range(len(project.boundary_data)): bd = project.boundary_data[i] boundary_tag = bd[0] boundary_condition_type = bd[1] if boundary_condition_type == 'Reflective': # Simple reflective boundary boundary_tags_and_conditions[boundary_tag] = \ anuga.Reflective_boundary(domain) elif ((boundary_condition_type == 'Stage') | (boundary_condition_type == 'Flather_Stage')): # Here we read a timeseries, offset the starttime, and then pass # that function as a set stage transmissive or flather boundary boundary_data_file = bd[2] start_time = bd[3] # Read data boundary_data = scipy.genfromtxt(boundary_data_file, delimiter=',', skip_header=1) # Make start time = 0 boundary_data[:, 0] -= start_time # Make interpolation function stage_time_fun = scipy.interpolate.interp1d( boundary_data[:, 0], boundary_data[:, 1]) # Make boundary condition if boundary_condition_type == 'Stage': boundary_function = \ asb.Transmissive_n_momentum_zero_t_momentum_set_stage_boundary( domain, stage_time_fun) elif boundary_condition_type == 'Flather_Stage': boundary_function = \ asb.Flather_external_stage_zero_velocity_boundary( domain, stage_time_fun) boundary_tags_and_conditions[boundary_tag] = \ boundary_function else: msg = 'Boundary condition type ' + boundary_condition_type +\ ' for tag ' + boundary_tag + ' is not implemented' # Check that all tags in boundary_info have been set for i in range(len(project.boundary_tags)): tag = project.boundary_tags.keys()[i] if not (tag in boundary_tags_and_conditions.keys()): msg = 'Need to set boundary_tags_and_conditions for tag = ' \ + tag raise Exception(msg) # Set the boundary domain.set_boundary(boundary_tags_and_conditions) return
def generate_channel3_domain(gpu=True): #----------------------------------------------------------------------- # Setup computational domain #----------------------------------------------------------------------- length = 40. width = 5. dx = dy = .1 # Resolution: Length of subdivisions on both axes points, vertices, boundary = anuga.rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) if gpu: domain = GPU_domain(points, vertices, boundary) if '-gpu' in sys.argv: domain.using_gpu = True print " --> Enable GPU version" for i in range(len(sys.argv)): if sys.argv[i] == '-fs': global finaltime finaltime = float(sys.argv[i + 1]) print " --> Finaltime is reset as %f" % finaltime else: domain = anuga.Domain(points, vertices, boundary) domain.set_name('channel3') # Output name #print domain.statistics() #----------------------------------------------------------------------- # Setup initial conditions #----------------------------------------------------------------------- def topography(x, y): """Complex topography defined by a function of vectors x and y.""" z = -x / 10 N = len(x) for i in range(N): # Step if 10 < x[i] < 12: z[i] += 0.4 - 0.05 * y[i] # Constriction if 27 < x[i] < 29 and y[i] > 3: z[i] += 2 # Pole if (x[i] - 34)**2 + (y[i] - 2)**2 < 0.4**2: z[i] += 2 return z domain.set_quantity('elevation', topography) # elevation is a function domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation') # Dry initial condition #----------------------------------------------------------------------- # Setup boundary conditions #----------------------------------------------------------------------- Bi = anuga.Dirichlet_boundary([0.4, 0, 0]) # Inflow Br = anuga.Reflective_boundary(domain) # Solid reflective wall Bo = anuga.Dirichlet_boundary([-5, 0, 0]) # Outflow domain.set_boundary({'left': Bi, 'right': Bo, 'top': Br, 'bottom': Br}) return domain
def test_runup_sinusoid(self): """ Run a version of the validation test runup_sinusoid to ensure limiting solution has small velocity """ points, vertices, boundary = anuga.rectangular_cross(20,20, len1=1., len2=1.) domain=Domain(points,vertices,boundary) # Create Domain domain.set_flow_algorithm('DE0') domain.set_name('runup_sinusoid_v2') # Output to file runup.sww domain.set_datadir('.') # Use current folder domain.set_quantities_to_be_stored({'stage': 2, 'xmomentum': 2, 'ymomentum': 2, 'elevation': 1}) #domain.set_store_vertices_uniquely(True) #------------------ # Define topography #------------------ scale_me=1.0 def topography(x,y): return (-x/2.0 +0.05*num.sin((x+y)*50.0))*scale_me def stagefun(x,y): stge=-0.2*scale_me #+0.01*(x>0.9) return stge domain.set_quantity('elevation',topography) # Use function for elevation domain.get_quantity('elevation').smooth_vertex_values() domain.set_quantity('friction',0.03) # Constant friction domain.set_quantity('stage', stagefun) # Constant negative initial stage domain.get_quantity('stage').smooth_vertex_values() #-------------------------- # Setup boundary conditions #-------------------------- Br=anuga.Reflective_boundary(domain) # Solid reflective wall Bd=anuga.Dirichlet_boundary([-0.1*scale_me,0.,0.]) # Constant boundary values -- not used in this example #---------------------------------------------- # Associate boundary tags with boundary objects #---------------------------------------------- domain.set_boundary({'left': Br, 'right': Bd, 'top': Br, 'bottom':Br}) #------------------------------ #Evolve the system through time #------------------------------ for t in domain.evolve(yieldstep=7.0,finaltime=7.0): #print domain.timestepping_statistics() xx = domain.quantities['xmomentum'].centroid_values yy = domain.quantities['ymomentum'].centroid_values dd = domain.quantities['stage'].centroid_values - domain.quantities['elevation'].centroid_values #dd_raw=1.0*dd dd = (dd)*(dd>1.0e-03)+1.0e-03 vv = ( (xx/dd)**2 + (yy/dd)**2)**0.5 vv = vv*(dd>1.0e-03) #print 'Peak velocity is: ', vv.max(), vv.argmax() #print 'Volume is', sum(dd_raw*domain.areas) #print vv.max() assert num.all(vv<1.01e-01)
def main(): try: try: usage = "usage: lakeerode.py LakeRadius-in-meters [-m depthmultiplier] [-i initialbreachdepth]\n" parser = optparse.OptionParser(usage=usage) parser.add_option("-m", dest="dm", help="Depth Multiplier for lake") parser.add_option("-i", dest="initbreachdepth", help="Initial breach depth for flood") (options, inargs) = parser.parse_args() if not inargs: parser.error("need parameters") lakeradius = float(inargs[0]) dm = 1.0 #default if (options.dm): dm = float(options.dm) h = dm * 21.39 * math.pow( (lakeradius / 1000), 0.62 ) #max depth in meters to get V=0.01A**1.31 from Fassett and Head 2008 initbreachdepth = 15.0 #default lakebelowconfining = 5 if (options.initbreachdepth): initbreachdepth = float(options.initbreachdepth) initbreachdepth = initbreachdepth + lakebelowconfining #set this to be a real initial head, not dependent on lakebelowconfining extslope = -0.015 extslopeint = 0.015 #anuga critical parameter anuga.g = gravity #domain parameters domainpolygon = [[0, 0], [0 * lakeradius, 2 * lakeradius], [2 * lakeradius, 2 * lakeradius], [2 * lakeradius, 1.2 * lakeradius], [10 * lakeradius, 1.2 * lakeradius], [10 * lakeradius, 0.8 * lakeradius], [2 * lakeradius, 0.8 * lakeradius], [2 * lakeradius, 0], [0, 0]] outletregion = [[1.9 * lakeradius, 0.8 * lakeradius], [1.9 * lakeradius, 1.2 * lakeradius], [4.5 * lakeradius, 1.2 * lakeradius], [4.5 * lakeradius, 0.8 * lakeradius]] boundary_tags = {'exterior': [0]} high_resolution = (lakeradius / 100)**2 base_resolution = high_resolution * 80.0 initbreachwidth = lakeradius / 50.0 interior_regions = [[outletregion, high_resolution]] meshname = 'lake.msh' m = anuga.create_mesh_from_regions( domainpolygon, boundary_tags, maximum_triangle_area=base_resolution, interior_regions=interior_regions, filename=meshname, use_cache=False) evolved_quantities = [ 'stage', 'xmomentum', 'ymomentum', 'concentration', 'sedvolx', 'sedvoly' ] #evolved_quantities = ['stage', 'xmomentum', 'ymomentum', 'concentration'] domain = anuga.Domain(meshname, use_cache=False, evolved_quantities=evolved_quantities) domain.g = anuga.g # make sure the domain inherits the package's gravity. print 'Number of triangles = ', len(domain) def find_nearest(array, value): array = np.asarray(array) idx = (np.abs(array - value)).argmin() return idx def topography(x, y): xc = x - lakeradius yc = y - lakeradius #sets up lake ellipsoid = -(h**2 * (1 - ((xc**2 + yc**2) / lakeradius**2)))**0.5 z = np.where(ellipsoid < 0, ellipsoid, 0.0) #sets up exterior slope z = np.where( np.logical_and(x > lakeradius * 2, x <= lakeradius * 4), (x - lakeradius * 2) * extslope + abs(y - lakeradius) * extslopeint, z) #setup flatlying area z = np.where(x > lakeradius * 4, (lakeradius * 2) * extslope + abs(y - lakeradius) * extslopeint, z) # add gaussian noise, with zero mean and 0.1 m standard deviation. #z=z+np.random.normal(0,0.1,z.shape) # set up breach as a failure at the midpoint in a region #mask1 = (x>=(lakeradius*2+(initbreachdepth/extslope))) mask1 = (x >= lakeradius) #mask2 = (x<=(lakeradius*2-(initbreachdepth/extslope))) mask3 = (y >= ((lakeradius - (initbreachwidth / 2.0)))) mask4 = (y <= ((lakeradius + (initbreachwidth / 2.0)))) mask5 = (z > -initbreachdepth) #mask=mask1 & mask2 & mask3 & mask4 & mask5 mask = mask1 & mask3 & mask4 & mask5 z[mask] = -initbreachdepth return z def initialstage(x, y): clow = domain.get_quantity('elevation').get_values( interpolation_points=[[2 * lakeradius, lakeradius]]) istage = clow + initbreachdepth - lakebelowconfining #outsidelake. Force depth=0 (istage=topo) across rim. #istage=np.where(x>lakeradius*2,topography(x,y),istage) istage = np.where(x > lakeradius * 2, -10000, istage) return istage name = "Marslake" + str(lakeradius) + "_" + str( grainD * 1000) + "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) 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 ) #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') domain.set_quantity( 'elevation', topography, location='centroids') # elevation is a function voltotal = np.sum(domain.quantities['elevation'].centroid_values * domain.areas) domain.set_quantity('concentration', 0.00) # Start with no esd domain.set_quantity( 'friction', 0.0545 ) # Constant Manning friction. Only used to initialize domain (calculated every time step). domain.set_quantity('stage', initialstage, location='centroids') domain.set_quantities_to_be_stored({ 'stage': 2, 'xmomentum': 2, 'ymomentum': 2, 'elevation': 2 }) np.seterr(invalid='warn') # Setup boundary conditions Br = anuga.Reflective_boundary(domain) domain.set_boundary({'exterior': Br}) operatezero = suspendedtransport_operator(domain) operateone = bedloadtransport_operator(domain) operatetwo = friction_operator(domain) operatethree = AoR_operator(domain) initial = domain.get_quantity('elevation').get_values( interpolation_points=[[2 * lakeradius, lakeradius]], location='centroids') initialdomain = copy.deepcopy(domain) ystep = 300 ftime = 86400 * 10 count = 0 volthresh = 1000 for t in domain.evolve(yieldstep=ystep, finaltime=ftime): print domain.timestepping_statistics() print 'xmom:' + str( domain.get_quantity('xmomentum').get_values( interpolation_points=[[2 * lakeradius, lakeradius]], location='centroids')) volcurr = np.sum( domain.quantities['elevation'].centroid_values * domain.areas) breacherosion = domain.get_quantity('elevation').get_values( interpolation_points=[[2 * lakeradius, lakeradius]], location='centroids') - initial print 'erosion: ' + str(breacherosion) 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) if (volsed < volthresh) & (count > 0): print "No sediment moving...ending..." break count = count + 1 polyline = [[2 * lakeradius, lakeradius - 2 * initbreachwidth], [2 * lakeradius, lakeradius + 2 * initbreachwidth]] time, Q = anuga.get_flow_through_cross_section( name + '.sww', polyline) print Q initname = "initial_" + str(lakeradius) + "_" + str( grainD * 1000) + "mm" + ".asc" finname = "final_" + str(lakeradius) + "_" + str( grainD * 1000) + "mm" + ".asc" fluxname = "flux_" + str(lakeradius) + "_" + str( grainD * 1000) + "mm" + ".txt" np.savetxt(fluxname, Q) finalstats(domain, initialdomain, lakeradius) 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
# NOTE: Setting quantities at centroids is important for exactness of tests domain.set_quantity('elevation',topography,location='centroids') domain.set_quantity('stage', stagefun,location='centroids') #======================================== # Setup wall down the middle of the domain #======================================== domain.riverwallData.create_riverwalls(riverWall,riverWall_Par,verbose=False) #======================================== # Boundary conditions # Simple reflective BC all around #======================================== Br = anuga.Reflective_boundary(domain) domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom':Br}) #======================================== # Setup Pump # (1) First setup the pump characteristics # (2) Then locate the pump using the operator #======================================== pump_function = anuga.pumping_station_function( domain=domain, pump_capacity=100.0, hw_to_start_pumping=0.0, hw_to_stop_pumping=-1.0, initial_pump_rate=100.0, pump_rate_of_increase = 1.0,
def run(par, n, withNormalization, withResidual, wave_type='bumps', minimum_allowed_height=1e-5): # ------------------------------------------------------------------------------ # Setup computational domain # ------------------------------------------------------------------------------ xleft = 0 xright = 5.448 ybottom = 0 ytop = 3.402 # rectangular cross mesh points, vertices, boundary = anuga.rectangular_cross( int(n), int(n), xright - xleft, ytop - ybottom, (xleft, ybottom)) newpoints = points.copy() # make refinement in x direction x = np.multiply([0., 0.1, 0.2, 0.335, 0.925, 1.], max(points[:, 0])) y = [0., 3., 4.25, 4.7, 5.3, max(points[:, 0])] f1 = interp1d(x, y, kind='linear') newpoints[:, 0] = f1(points[:, 0]) # make refinement in y direction x = np.multiply([0., .125, .3, .7, .9, 1.], max(points[:, 1])) y = [0., 1.25, 1.75, 2.15, 2.65, max(points[:, 1])] f2 = interp1d(x, y, kind='linear') newpoints[:, 1] = f2(points[:, 1]) c = abs(newpoints[:, 0] - 5.0) + .5 * abs(newpoints[:, 1] - 1.95) c = 0.125 * c points[:, 0] = c * points[:, 0] + (1 - c) * newpoints[:, 0] points[:, 1] = c * points[:, 1] + (1 - c) * newpoints[:, 1] # create domain domain = anuga.Domain(points, vertices, boundary) # don't store .sww file domain.set_quantities_to_be_stored(None) # ------------------------------------------------------------------------------ # Initial Conditions # ------------------------------------------------------------------------------ domain.set_quantity('friction', 0.01) # 0.0 domain.set_quantity('stage', 0.0) domain.set_quantity( 'elevation', filename='/home/rehmemk/git/anugasgpp/Okushiri/data/bathymetry.pts', alpha=0.02) # ------------------------------------------------------------------------------ # Set simulation parameters # ------------------------------------------------------------------------------ domain.set_name('output_okushiri') # Output name # domain.set_minimum_storable_height(0.001) # Don't store w < 0.001m domain.set_minimum_storable_height(1.0) # Don't store w < 0.001m domain.set_flow_algorithm('DE0') # ------------------------------------------------------------------------------ # Modify input wave # ------------------------------------------------------------------------------ # rescale input parameter try: dummy = len(par) except: par = [par] par = np.dot(2, par) if wave_type == 'bumps': wave_function, _, _ = wave_functions.heights_wave( par, withResidual, withNormalization) elif wave_type == 'original': wave_function = wave_functions.original_wave_interpolant() elif wave_type == 'cubic': wave_function, _, _ = wave_functions.cubic_heights_wave( par, withResidual, withNormalization) else: print(f'Error. Wave type {wave_type} unknown') # ------------------------------------------------------------------------------ # Setup boundary conditions # ------------------------------------------------------------------------------ # Create boundary function from input wave [replaced by wave function] # Create and assign boundary objects Bts = anuga.Transmissive_momentum_set_stage_boundary(domain, wave_function) Br = anuga.Reflective_boundary(domain) domain.set_boundary({'left': Bts, 'right': Br, 'top': Br, 'bottom': Br}) # ------------------------------------------------------------------------------ # Evolve system through time # ------------------------------------------------------------------------------ # this prevents problems w.r.t. divisions by zero # It might decrease the acheivable accuracy domain.set_minimum_allowed_height(minimum_allowed_height) # default 1e-5 # area for gulleys x1 = 4.85 x2 = 5.25 y1 = 2.05 y2 = 1.85 # index in gulley area x = domain.centroid_coordinates[:, 0] y = domain.centroid_coordinates[:, 1] v = np.sqrt((x - x1) ** 2 + (y - y1) ** 2) + \ np.sqrt((x - x2) ** 2 + (y - y2) ** 2) < 0.5 # three gauges and a point somewhere on the boundary that could be used for verification # get id's of the corresponding triangles gauge = [[4.521, 1.196], [4.521, 1.696], [4.521, 2.196]] bdyloc = [0.00001, 2.5] g5_id = domain.get_triangle_containing_point(gauge[0]) g7_id = domain.get_triangle_containing_point(gauge[1]) g9_id = domain.get_triangle_containing_point(gauge[2]) bc_id = domain.get_triangle_containing_point(bdyloc) k = 0 # original number of timesteps is 451 numTimeSteps = 451 sumstage = np.nan * np.ones(numTimeSteps) stage_g5 = np.nan * np.ones(numTimeSteps) stage_g7 = np.nan * np.ones(numTimeSteps) stage_g9 = np.nan * np.ones(numTimeSteps) stage_bc = np.nan * np.ones(numTimeSteps) yieldstep = 0.05 finaltime = (numTimeSteps - 1) * yieldstep for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime): # domain.write_time() # stage [=height of water] stage = domain.quantities['stage'].centroid_values[v] stage_g5[k] = domain.quantities['stage'].centroid_values[g5_id] stage_g7[k] = domain.quantities['stage'].centroid_values[g7_id] stage_g9[k] = domain.quantities['stage'].centroid_values[g9_id] stage_bc[k] = domain.quantities['stage'].centroid_values[bc_id] # averaging for smoothness sumstage[k] = np.sum(stage) # k is time k += 1 # number of triangles which are active for the designated runup area numActiveTriangles = anuga.collect_value(np.count_nonzero(v)) averageStage = sumstage / numActiveTriangles # normalizing to zero level # averageStage -= averageStage[0] return [averageStage, stage_g5, stage_g7, stage_g9, stage_bc]