def rectangular_cross_domain(*args, **kwargs): """ Create a rectangular domain with triangulation made up of m+1 by n+1 uniform rectangular cells divided into 4 triangles in a cross pattern Arguments m: number of cells in x direction n: number of cells in y direction len1: length of domain in x direction (left to right) (default 1.0) len2: length of domain in y direction (bottom to top) (default 1.0) origin: tuple (x,y) specifying location of lower left corner of domain (default (0,0)) """ try: verbose = kwargs.pop('verbose') except: verbose = False points, vertices, boundary = rectangular_cross(*args, **kwargs) return Domain(points, vertices, boundary, verbose= verbose)
def _create_domain(self,d_length, d_width, dx, dy, elevation_0, elevation_1, stage_0, stage_1): points, vertices, boundary = rectangular_cross(int(d_length/dx), int(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 > 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 > 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 _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 test_merge_swwfiles(self): from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular, \ rectangular_cross from anuga.shallow_water.shallow_water_domain import Domain from anuga.file.sww import SWW_file from anuga.abstract_2d_finite_volumes.generic_boundary_conditions import \ Dirichlet_boundary Bd = Dirichlet_boundary([0.5, 0., 0.]) # Create shallow water domain domain = Domain(*rectangular_cross(2, 2)) domain.set_name('test1') domain.set_quantity('elevation', 2) domain.set_quantity('stage', 5) domain.set_boundary({'left': Bd, 'right': Bd, 'top': Bd, 'bottom': Bd}) for t in domain.evolve(yieldstep=0.5, finaltime=1): pass domain = Domain(*rectangular(3, 3)) domain.set_name('test2') domain.set_quantity('elevation', 3) domain.set_quantity('stage', 50) domain.set_boundary({'left': Bd, 'right': Bd, 'top': Bd, 'bottom': Bd}) for t in domain.evolve(yieldstep=0.5, finaltime=1): pass outfile = 'test_out.sww' _sww_merge(['test1.sww', 'test2.sww'], outfile) self.assertTrue(os.access(outfile, os.F_OK)) # remove temp files if not sys.platform == 'win32': os.remove('test1.sww') os.remove('test2.sww') os.remove(outfile)
def rectangular_cross_domain(*args, **kwargs): """ Create a rectangular domain with triangulation made up of m+1 by n+1 uniform rectangular cells divided into 4 triangles in a cross pattern Arguments m: number of cells in x direction n: number of cells in y direction len1: length of domain in x direction (left to right) (default 1.0) len2: length of domain in y direction (bottom to top) (default 1.0) origin: tuple (x,y) specifying location of lower left corner of domain (default (0,0)) """ try: verbose = kwargs.pop('verbose') except: verbose = False points, vertices, boundary = rectangular_cross(*args, **kwargs) return Domain(points, vertices, boundary, verbose=verbose)
def test_read_sww(self): """ Save to an sww file and then read back the info. Here we store the info "uniquely" """ # --------------------------------------------------------------------- # Import necessary modules # --------------------------------------------------------------------- from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular_cross from anuga.shallow_water.shallow_water_domain import Domain from anuga import Reflective_boundary from anuga.abstract_2d_finite_volumes.generic_boundary_conditions import Dirichlet_boundary, Time_boundary # --------------------------------------------------------------------- # Setup computational domain # --------------------------------------------------------------------- length = 8.0 width = 4.0 dx = dy = 2 # Resolution: Length of subdivisions on both axes inc = 0.05 # Elevation increment points, vertices, boundary = rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) domain = Domain(points, vertices, boundary) domain.set_name("read_sww_test" + str(domain.processor)) # Output name domain.set_quantities_to_be_stored({"elevation": 2, "stage": 2, "xmomentum": 2, "ymomentum": 2, "friction": 1}) domain.set_store_vertices_uniquely(True) # --------------------------------------------------------------------- # Setup initial conditions # --------------------------------------------------------------------- domain.set_quantity("elevation", 0.0) # Flat bed initially domain.set_quantity("friction", 0.01) # Constant friction domain.set_quantity("stage", 0.0) # Dry initial condition # ------------------------------------------------------------------ # Setup boundary conditions # ------------------------------------------------------------------ Bi = Dirichlet_boundary([0.4, 0, 0]) # Inflow Br = Reflective_boundary(domain) # Solid reflective wall Bo = Dirichlet_boundary([-5, 0, 0]) # Outflow domain.set_boundary({"left": Bi, "right": Bo, "top": Br, "bottom": Br}) # ------------------------------------------------------------------- # Evolve system through time # ------------------------------------------------------------------- for t in domain.evolve(yieldstep=1, finaltime=4.0): pass # Check that quantities have been stored correctly source = domain.get_name() + ".sww" # x = fid.variables['x'][:] # y = fid.variables['y'][:] # stage = fid.variables['stage'][:] # elevation = fid.variables['elevation'][:] # fid.close() # assert len(stage.shape) == 2 # assert len(elevation.shape) == 2 # M, N = stage.shape sww_file = sww.Read_sww(source) # print 'last frame number',sww_file.get_last_frame_number() assert num.allclose(sww_file.x, domain.get_vertex_coordinates()[:, 0]) assert num.allclose(sww_file.y, domain.get_vertex_coordinates()[:, 1]) assert num.allclose(sww_file.time, [0.0, 1.0, 2.0, 3.0, 4.0]) M = domain.get_number_of_triangles() assert num.allclose(num.reshape(num.arange(3 * M), (M, 3)), sww_file.vertices) last_frame_number = sww_file.get_last_frame_number() assert last_frame_number == 4 assert num.allclose(sww_file.get_bounds(), [0.0, length, 0.0, width]) assert "stage" in sww_file.quantities.keys() assert "friction" in sww_file.quantities.keys() assert "elevation" in sww_file.quantities.keys() assert "xmomentum" in sww_file.quantities.keys() assert "ymomentum" in sww_file.quantities.keys() for qname, q in sww_file.read_quantities(last_frame_number).items(): # print qname # print num.linalg.norm(num.abs((domain.get_quantity(qname).get_values()-q).flatten()), ord=1) assert num.allclose(domain.get_quantity(qname).get_values(), q) # ----------------------------------------- # Start the evolution off again at frame 3 # ----------------------------------------- sww_file.read_quantities(last_frame_number - 1) points, vertices, boundary = rectangular_cross(int(length / dx), int(width / dy), len1=length, len2=width) new_domain = Domain(points, vertices, boundary) new_domain.set_quantities_to_be_stored(None) new_domain.set_store_vertices_uniquely(True) for qname, q in sww_file.read_quantities(last_frame_number - 1).items(): new_domain.set_quantity(qname, q) # ------------------------------------------------------------------ # Setup boundary conditions # ------------------------------------------------------------------ Bi = Dirichlet_boundary([0.4, 0, 0]) # Inflow Br = Reflective_boundary(new_domain) # Solid reflective wall Bo = Dirichlet_boundary([-5, 0, 0]) # Outflow new_domain.set_boundary({"left": Bi, "right": Bo, "top": Br, "bottom": Br}) # ------------------------------------------------------------------- # Evolve system through time # ------------------------------------------------------------------- for t in new_domain.evolve(yieldstep=1.0, finaltime=1.0): pass # Compare new_domain and domain quantities for quantity in domain.get_quantity_names(): dv = domain.get_quantity(quantity).get_values() ndv = new_domain.get_quantity(quantity).get_values() # print dv-ndv assert num.allclose(dv, ndv, rtol=5.0e-2, atol=5.0e-2)
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 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 test_predicted_boyd_flow(self): """test_predicted_boyd_flow Test that flows predicted by the boyd method are consistent with what what is calculated in engineering codes. The data was supplied by Petar Milevski """ # FIXME(Ole) this is nowhere near finished path = get_pathname_from_package('anuga.culvert_flows') length = 12. width = 5. dx = dy = 0.5 # 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): # General Slope of Topography z = -x / 10 return z domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation') Q0 = domain.get_quantity('stage') Q1 = Quantity(domain) # Add depths to stage head_water_depth = 0.169 tail_water_depth = 0.089 inlet_poly = [[0, 0], [6, 0], [6, 5], [0, 5]] outlet_poly = [[6, 0], [12, 0], [12, 5], [6, 5]] Q1.set_values( Polygon_function([(inlet_poly, head_water_depth), (outlet_poly, tail_water_depth)])) domain.set_quantity('stage', Q0 + Q1) culvert = Culvert_flow(domain, label='Test culvert', description='4 m test culvert', end_point0=[4.0, 2.5], end_point1=[8.0, 2.5], width=1.20, height=0.75, culvert_routine=boyd_generalised_culvert_model, number_of_barrels=1, verbose=False) domain.forcing_terms.append(culvert) # Call culvert(domain)
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
#------------------------------------------------------------------------------ # Setup computational domain #------------------------------------------------------------------------------ print('Setting up domain') length = 40. width = 5. dx = dy = 1 # Resolution: Length of subdivisions on both axes #dx = dy = .5 # Resolution: Length of subdivisions on both axes #dx = dy = .5 # Resolution: Length of subdivisions on both axes #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 = Domain(points, vertices, boundary) domain.set_name('Test_Culv_Flat_WL') # Output name domain.set_default_order(2) domain.H0 = 0.01 domain.tight_slope_limiters = 1 print('Size', len(domain)) #------------------------------------------------------------------------------ # Setup initial conditions #------------------------------------------------------------------------------ def topography(x, y):
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 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 test_read_sww(self): """ Save to an sww file and then read back the info. Here we store the info "uniquely" """ #--------------------------------------------------------------------- # Import necessary modules #--------------------------------------------------------------------- from anuga.abstract_2d_finite_volumes.mesh_factory import \ rectangular_cross from anuga.shallow_water.shallow_water_domain import Domain from anuga import Reflective_boundary from anuga.abstract_2d_finite_volumes.generic_boundary_conditions\ import Dirichlet_boundary, Time_boundary #--------------------------------------------------------------------- # Setup computational domain #--------------------------------------------------------------------- length = 8. width = 4. dx = dy = 2 # Resolution: Length of subdivisions on both axes inc = 0.05 # Elevation increment points, vertices, boundary = rectangular_cross(int(length/dx), int(width/dy), len1=length, len2=width) domain = Domain(points, vertices, boundary) domain.set_name('read_sww_test'+str(domain.processor)) # Output name domain.set_quantities_to_be_stored({'elevation': 2, 'stage': 2, 'xmomentum': 2, 'ymomentum': 2, 'friction': 1}) domain.set_store_vertices_uniquely(True) #--------------------------------------------------------------------- # Setup initial conditions #--------------------------------------------------------------------- domain.set_quantity('elevation', 0.0) # Flat bed initially domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', 0.0) # Dry initial condition #------------------------------------------------------------------ # Setup boundary conditions #------------------------------------------------------------------ Bi = Dirichlet_boundary([0.4, 0, 0]) # Inflow Br = Reflective_boundary(domain) # Solid reflective wall Bo = Dirichlet_boundary([-5, 0, 0]) # Outflow domain.set_boundary({'left': Bi, 'right': Bo, 'top': Br, 'bottom': Br}) #------------------------------------------------------------------- # Evolve system through time #------------------------------------------------------------------- for t in domain.evolve(yieldstep=1, finaltime=4.0): pass # Check that quantities have been stored correctly source = domain.get_name() + '.sww' #x = fid.variables['x'][:] #y = fid.variables['y'][:] #stage = fid.variables['stage'][:] #elevation = fid.variables['elevation'][:] #fid.close() #assert len(stage.shape) == 2 #assert len(elevation.shape) == 2 #M, N = stage.shape sww_file = sww.Read_sww(source) #print 'last frame number',sww_file.get_last_frame_number() assert num.allclose(sww_file.x, domain.get_vertex_coordinates()[:,0]) assert num.allclose(sww_file.y, domain.get_vertex_coordinates()[:,1]) assert num.allclose(sww_file.time, [0.0, 1.0, 2.0, 3.0, 4.0]) M = domain.get_number_of_triangles() assert num.allclose(num.reshape(num.arange(3*M), (M,3)), sww_file.vertices) last_frame_number = sww_file.get_last_frame_number() assert last_frame_number == 4 assert num.allclose(sww_file.get_bounds(), [0.0, length, 0.0, width]) assert 'stage' in sww_file.quantities.keys() assert 'friction' in sww_file.quantities.keys() assert 'elevation' in sww_file.quantities.keys() assert 'xmomentum' in sww_file.quantities.keys() assert 'ymomentum' in sww_file.quantities.keys() for qname, q in sww_file.read_quantities(last_frame_number).items(): #print qname #print num.linalg.norm(num.abs((domain.get_quantity(qname).get_values()-q).flatten()), ord=1) assert num.allclose(domain.get_quantity(qname).get_values(), q) #----------------------------------------- # Start the evolution off again at frame 3 #----------------------------------------- sww_file.read_quantities(last_frame_number-1) points, vertices, boundary = rectangular_cross(int(length/dx), int(width/dy), len1=length, len2=width) new_domain = Domain(points, vertices, boundary) new_domain.set_quantities_to_be_stored(None) new_domain.set_store_vertices_uniquely(True) for qname, q in sww_file.read_quantities(last_frame_number-1).items(): new_domain.set_quantity(qname, q) #------------------------------------------------------------------ # Setup boundary conditions #------------------------------------------------------------------ Bi = Dirichlet_boundary([0.4, 0, 0]) # Inflow Br = Reflective_boundary(new_domain) # Solid reflective wall Bo = Dirichlet_boundary([-5, 0, 0]) # Outflow new_domain.set_boundary({'left': Bi, 'right': Bo, 'top': Br, 'bottom': Br}) #------------------------------------------------------------------- # Evolve system through time #------------------------------------------------------------------- for t in new_domain.evolve(yieldstep=1.0, finaltime=1.0): pass # Compare new_domain and domain quantities for quantity in domain.get_quantity_names(): dv = domain.get_quantity(quantity).get_values() ndv = new_domain.get_quantity(quantity).get_values() #print dv-ndv assert num.allclose( dv, ndv, rtol=5.e-2, atol=5.e-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 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) #domain.set_name('output_parallel_boyd_pipe_op') # Output name domain.set_store(False) domain.set_default_order(2) ##----------------------------------------------------------------------- ## Distribute domain ##----------------------------------------------------------------------- if parallel: domain = distribute(domain) #domain.dump_triangulation("boyd_pipe_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_pipe0 = None inlet0 = Inlet_operator(domain, line0, Q0, verbose = False) inlet1 = Inlet_operator(domain, line1, Q1, verbose = False) # Enquiry point [ 19. 2.5] is contained in two domains in 4 proc case boyd_pipe0 = Boyd_pipe_operator(domain, end_points=[[9.0, 2.5],[19.0, 2.5]], losses=1.5, diameter=5.0, apron=5.0, use_momentum_jet=True, use_velocity_head=False, manning=0.013, verbose=False) if inlet0 is not None and verbose: inlet0.print_statistics() if inlet1 is not None and verbose: inlet1.print_statistics() if boyd_pipe0 is not None and verbose: boyd_pipe0.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_pipe0 is not None and verbose : boyd_pipe0.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 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) if parallel: finalize() return control_data
def test_get_maximum_inundation_from_sww(self): """test_get_maximum_inundation_from_sww(self) Test of get_maximum_inundation_elevation() and get_maximum_inundation_location(). This is based on test_get_maximum_inundation_3(self) but works with the stored results instead of with the internal data structure. This test uses the underlying get_maximum_inundation_data for tests """ verbose = False from anuga.config import minimum_storable_height initial_runup_height = -0.4 final_runup_height = -0.3 filename = 'runup_test_2' #-------------------------------------------------------------- # Setup computational domain #-------------------------------------------------------------- N = 10 points, vertices, boundary = rectangular_cross(N, N) domain = Domain(points, vertices, boundary) domain.set_low_froude(0) domain.set_name(filename) domain.set_maximum_allowed_speed(1.0) #domain.set_minimum_storable_height(1.0e-5) domain.set_store_vertices_uniquely() # FIXME: This works better with old limiters so far domain.tight_slope_limiters = 0 #-------------------------------------------------------------- # Setup initial conditions #-------------------------------------------------------------- def topography(x, y): return old_div(-x, 2) # linear bed slope # Use function for elevation domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.) # Zero friction # Constant negative initial stage domain.set_quantity('stage', initial_runup_height) #-------------------------------------------------------------- # Setup boundary conditions #-------------------------------------------------------------- Br = Reflective_boundary(domain) # Reflective wall Bd = Dirichlet_boundary([final_runup_height, 0, 0]) # Constant inflow # All reflective to begin with (still water) domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) #-------------------------------------------------------------- # Test initial inundation height #-------------------------------------------------------------- indices = domain.get_wet_elements() z = domain.get_quantity('elevation').\ get_values(location='centroids', indices=indices) assert num.alltrue(z < initial_runup_height) q_ref = domain.get_maximum_inundation_elevation( minimum_height=minimum_storable_height) # First order accuracy assert num.allclose(q_ref, initial_runup_height, rtol=1.0 / N) #-------------------------------------------------------------- # Let triangles adjust #-------------------------------------------------------------- q_max = None for t in domain.evolve(yieldstep=0.1, finaltime=1.0): q = domain.get_maximum_inundation_elevation( minimum_height=minimum_storable_height) if verbose: domain.write_time() print(q) if q is None and q_max is None: pass elif q_max is None or q > q_max: q_max = q else: pass #-------------------------------------------------------------- # Test inundation height again #-------------------------------------------------------------- #q_ref = domain.get_maximum_inundation_elevation() q = get_maximum_inundation_elevation(filename + '.sww') msg = 'We got %f, should have been %f' % (q, q_max) assert num.allclose(q, q_max, rtol=2.0 / N), msg msg = 'We got %f, should have been %f' % (q, initial_runup_height) assert num.allclose(q, initial_runup_height, rtol=1.0 / N), msg # Test error condition if time interval is out try: q = get_maximum_inundation_elevation(filename + '.sww', time_interval=[2.0, 3.0]) except ValueError: pass else: msg = 'should have caught wrong time interval' raise_(Exception, msg) # Check correct time interval q, loc = get_maximum_inundation_data(filename + '.sww', time_interval=[0.0, 3.0]) msg = 'We got %f, should have been %f' % (q, initial_runup_height) assert num.allclose(q, initial_runup_height, rtol=1.0 / N), msg assert num.allclose(old_div(-loc[0], 2), q) # From topography formula #-------------------------------------------------------------- # Update boundary to allow inflow #-------------------------------------------------------------- domain.set_boundary({'right': Bd}) #-------------------------------------------------------------- # Evolve system through time #-------------------------------------------------------------- for t in domain.evolve(yieldstep=0.1, finaltime=3.0, skip_initial_step=True): q = domain.get_maximum_inundation_elevation( minimum_height=minimum_storable_height) if verbose: domain.write_time() print(q) if q > q_max: q_max = q #-------------------------------------------------------------- # Test inundation height again #-------------------------------------------------------------- indices = domain.get_wet_elements() z = domain.get_quantity('elevation').\ get_values(location='centroids', indices=indices) assert num.alltrue(z < final_runup_height + 1.0 / N) q = domain.get_maximum_inundation_elevation() # First order accuracy assert num.allclose(q, final_runup_height, rtol=1.0 / N) q, loc = get_maximum_inundation_data(filename + '.sww', time_interval=[3.0, 3.0]) msg = 'We got %f, should have been %f' % (q, final_runup_height) assert num.allclose(q, final_runup_height, rtol=1.0 / N), msg assert num.allclose(old_div(-loc[0], 2), q) # From topography formula q = get_maximum_inundation_elevation(filename + '.sww', verbose=verbose) loc = get_maximum_inundation_location(filename + '.sww') msg = 'We got %f, should have been %f' % (q, q_max) assert num.allclose(q, q_max, rtol=1.0 / N), msg assert num.allclose(old_div(-loc[0], 2), q) # From topography formula q = get_maximum_inundation_elevation(filename + '.sww', time_interval=[0, 3]) msg = 'We got %f, should have been %f' % (q, q_max) assert num.allclose(q, q_max, rtol=1.0 / N), msg # Check polygon mode # Runup region polygon = [[0.3, 0.0], [0.9, 0.0], [0.9, 1.0], [0.3, 1.0]] q = get_maximum_inundation_elevation(filename + '.sww', polygon=polygon, time_interval=[0, 3]) msg = 'We got %f, should have been %f' % (q, q_max) assert num.allclose(q, q_max, rtol=1.0 / N), msg # Offshore region polygon = [[0.9, 0.0], [1.0, 0.0], [1.0, 1.0], [0.9, 1.0]] q, loc = get_maximum_inundation_data(filename + '.sww', polygon=polygon, time_interval=[0, 3]) msg = 'We got %f, should have been %f' % (q, -0.475) assert num.allclose(q, -0.475, rtol=1.0 / N), msg assert is_inside_polygon(loc, polygon) assert num.allclose(old_div(-loc[0], 2), q) # From topography formula # Dry region polygon = [[0.0, 0.0], [0.4, 0.0], [0.4, 1.0], [0.0, 1.0]] q, loc = get_maximum_inundation_data(filename + '.sww', polygon=polygon, time_interval=[0, 3]) msg = 'We got %s, should have been None' % (q) assert q is None, msg msg = 'We got %s, should have been None' % (loc) assert loc is None, msg # Check what happens if no time point is within interval try: q = get_maximum_inundation_elevation(filename + '.sww', time_interval=[2.75, 2.75]) except AssertionError: pass else: msg = 'Time interval should have raised an exception' raise_(Exception, msg) # Cleanup try: pass #os.remove(domain.get_name() + '.sww') except: pass
def _create_domain(self,d_length, d_width, dx, dy, elevation_0, elevation_1, stage_0, stage_1, xvelocity_0 = 0.0, xvelocity_1 = 0.0, yvelocity_0 = 0.0, yvelocity_1 = 0.0): points, vertices, boundary = rectangular_cross(int(d_length/dx), int(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 > 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 > d_length/2, stage_1) return z def xmom(x,y): """Set up xmomentum """ z = numpy.zeros(x.shape,dtype='d') z[:] = xvelocity_0*(stage_0-elevation_0) numpy.putmask(z, x > d_length/2, xvelocity_1*(stage_1-elevation_1) ) return z def ymom(x,y): """Set up ymomentum """ z = numpy.zeros(x.shape,dtype='d') z[:] = yvelocity_0*(stage_0-elevation_0) numpy.putmask(z, x > d_length/2, yvelocity_1*(stage_1-elevation_1) ) return z #print 'Setting Quantities....' domain.set_quantity('elevation', elevation) # Use function for elevation domain.set_quantity('stage', stage) # Use function for elevation domain.set_quantity('xmomentum', xmom) domain.set_quantity('ymomentum', ymom) return domain
def test_earthquake_tsunami(self): from os import sep, getenv import sys from anuga.abstract_2d_finite_volumes.mesh_factory \ import rectangular_cross from anuga.abstract_2d_finite_volumes.quantity import Quantity from anuga.utilities.system_tools import get_pathname_from_package """ Pick the test you want to do; T= 0 test a point source, T= 1 test single rectangular source, T= 2 test multiple rectangular sources """ # Get path where this test is run path= get_pathname_from_package('anuga.tsunami_source') # Choose what test to proceed T=1 if T==0: # Fortran output file filename = path+sep+'tests'+sep+'data'+sep+'fullokada_SP.txt' # Initial condition of earthquake for multiple source x0 = 7000.0 y0 = 10000.0 length = 0 width =0 strike = 0.0 depth = 15.0 slip = 10.0 dip =15.0 rake =90.0 ns=1 NSMAX=1 elif T==1: # Fortran output file filename = path+sep+'tests'+sep+'data'+sep+'fullokada_SS.txt' # Initial condition of earthquake for multiple source x0 = 7000.0 y0 = 10000.0 length = 10.0 width =6.0 strike = 0.0 depth = 15.0 slip = 10.0 dip =15.0 rake =90.0 ns=1 NSMAX=1 elif T==2: # Fortran output file filename = path+sep+'tests'+sep+'data'+sep+'fullokada_MS.txt' # Initial condition of earthquake for multiple source x0 = [7000.0,10000.0] y0 = [10000.0,7000.0] length = [10.0,10.0] width =[6.0,6.0] strike = [0.0,0.0] depth = [15.0,15.0] slip = [10.0,10.0] dip = [15.0,15.0] rake = [90.0,90.0] ns=2 NSMAX=2 # Get output file from original okada fortran script. # Vertical displacement is listed under tmp. polyline_file=open(filename,'r') lines=polyline_file.readlines() polyline_file.close() tmp=[] stage=[] for line in lines [0:]: field = line.split(' ') z=float(field[2]) tmp.append(z) # Create domain dx = dy = 4000 l=20000 w=20000 # Create topography def topography(x,y): el=-1000 return el points, vertices, boundary = rectangular_cross(int(l/dx), int(w/dy), len1=l, len2=w) domain = Domain(points, vertices, boundary) domain.set_name('test') domain.set_quantity('elevation',topography) Ts = earthquake_tsunami(ns=ns,NSMAX=NSMAX,length=length, width=width, strike=strike,\ depth=depth,dip=dip, xi=x0, yi=y0,z0=0, slip=slip, rake=rake,\ domain=domain, verbose=False) # Create a variable to store vertical displacement throughout the domain tsunami = Quantity(domain) tsunami.set_values(Ts) interpolation_points=[] #k=0.0 #for i in range(0,6): # for j in range(0,6): # p=j*4000 # Yt=p # Xt=k # Z=tsunami.get_values(interpolation_points=[[Xt,Yt]] # ,location='edges') # stage.append(-Z[0]) # k=k+4000 # #assert allclose(stage,tmp,atol=1.e-3) # Here's a faster way - try that in the first test interpolation_points=[] k=0.0 for i in range(0,6): for j in range(0,6): p=j*4000 Yt=p Xt=k interpolation_points.append([Xt, Yt]) k=k+4000 Z=tsunami.get_values(interpolation_points=interpolation_points, location='edges') stage = -Z # FIXME(Ole): Why the sign flip? # Displacement in fortran code is looking downward #print 'c est fini' #print tmp #print 'hello',stage assert num.allclose(stage,tmp,atol=1.e-3)
import numpy as num """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') length = 40. width = 15. dx = dy = 0.5 # 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_gate_operator') # Output name domain.set_default_order(2) #domain.set_beta(1.5) #---------------------------------------------------------------------- # Setup initial conditions #---------------------------------------------------------------------- def topography(x, y): """Set up a weir A culvert will connect either side
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 test_Okada_func(self): from os import sep, getenv import sys from anuga.abstract_2d_finite_volumes.mesh_factory \ import rectangular_cross from anuga.abstract_2d_finite_volumes.quantity import Quantity from anuga.utilities.system_tools import get_pathname_from_package """ Pick the test you want to do; T= 0 test a point source, T= 1 test single rectangular source, T= 2 test multiple rectangular sources """ # Get path where this test is run path = get_pathname_from_package('anuga.tsunami_source') # Choose what test to proceed T = 1 if T == 0: # Fortran output file filename = path + sep + 'tests' + sep + 'data' + sep + 'fullokada_SP.txt' # Initial condition of earthquake for multiple source x0 = 7000.0 y0 = 10000.0 length = 0 width = 0 strike = 0.0 depth = 15.0 slip = 10.0 dip = 15.0 rake = 90.0 ns = 1 NSMAX = 1 elif T == 1: # Fortran output file filename = path + sep + 'tests' + sep + 'data' + sep + 'fullokada_SS.txt' # Initial condition of earthquake for multiple source x0 = 7000.0 y0 = 10000.0 length = 10.0 width = 6.0 strike = 0.0 depth = 15.0 slip = 10.0 dip = 15.0 rake = 90.0 ns = 1 NSMAX = 1 elif T == 2: # Fortran output file filename = path + sep + 'tests' + sep + 'data' + sep + 'fullokada_MS.txt' # Initial condition of earthquake for multiple source x0 = [7000.0, 10000.0] y0 = [10000.0, 7000.0] length = [10.0, 10.0] width = [6.0, 6.0] strike = [0.0, 0.0] depth = [15.0, 15.0] slip = [10.0, 10.0] dip = [15.0, 15.0] rake = [90.0, 90.0] ns = 2 NSMAX = 2 # Get output file from original okada fortran script. # Vertical displacement is listed under tmp. polyline_file = open(filename, 'r') lines = polyline_file.readlines() polyline_file.close() tmp = [] stage = [] for line in lines[0:]: field = line.split(' ') z = float(field[2]) tmp.append(z) #create domain dx = dy = 4000 l = 100000 w = 100000 #create topography def topography(x, y): el = -1000 return el #print int(l/dx) #print int(w/dy) points, vertices, boundary = rectangular_cross(int(old_div(l, dx)), int(old_div(w, dy)), len1=l, len2=w) domain = Domain(points, vertices, boundary) domain.set_name('test') domain.set_quantity('elevation', topography) #create variable with elevation data to implement in okada zrec0 = Quantity(domain) zrec0.set_values(0.0) zrec = zrec0.get_vertex_values(xy=True) # call okada Ts= Okada_func(ns=ns, NSMAX=NSMAX,length=length, width=width, dip=dip, \ x0=x0, y0=y0, strike=strike, depth=depth, \ slip=slip, rake=rake,zrec=zrec) #create a variable to store vertical displacement throughout the domain tsunami = Quantity(domain) tsunami.set_values(Ts) # get vertical displacement at each point of the domain respecting # original script's order interpolation_points = [] k = 0.0 for i in range(0, 6): for j in range(0, 6): p = j * 4000 Yt = p Xt = k interpolation_points.append([Xt, Yt]) k = k + 4000 Z = tsunami.get_values(interpolation_points=interpolation_points, location='edges') stage = -Z # FIXME(Ole): Why the sign flip? # Displacement in fortran code is looking downward #print tmp #print 'hello',stage assert num.allclose(stage, tmp, atol=1.e-3)
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_get_maximum_inundation_from_sww(self): """test_get_maximum_inundation_from_sww(self) Test of get_maximum_inundation_elevation() and get_maximum_inundation_location(). This is based on test_get_maximum_inundation_3(self) but works with the stored results instead of with the internal data structure. This test uses the underlying get_maximum_inundation_data for tests """ verbose = False from anuga.config import minimum_storable_height initial_runup_height = -0.4 final_runup_height = -0.3 filename = 'runup_test_2' #-------------------------------------------------------------- # Setup computational domain #-------------------------------------------------------------- N = 10 points, vertices, boundary = rectangular_cross(N, N) domain = Domain(points, vertices, boundary) domain.set_name(filename) domain.set_maximum_allowed_speed(1.0) #domain.set_minimum_storable_height(1.0e-5) domain.set_store_vertices_uniquely() # FIXME: This works better with old limiters so far domain.tight_slope_limiters = 0 #-------------------------------------------------------------- # Setup initial conditions #-------------------------------------------------------------- def topography(x, y): return -x/2 # linear bed slope # Use function for elevation domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.) # Zero friction # Constant negative initial stage domain.set_quantity('stage', initial_runup_height) #-------------------------------------------------------------- # Setup boundary conditions #-------------------------------------------------------------- Br = Reflective_boundary(domain) # Reflective wall Bd = Dirichlet_boundary([final_runup_height, 0, 0]) # Constant inflow # All reflective to begin with (still water) domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br}) #-------------------------------------------------------------- # Test initial inundation height #-------------------------------------------------------------- indices = domain.get_wet_elements() z = domain.get_quantity('elevation').\ get_values(location='centroids', indices=indices) assert num.alltrue(z < initial_runup_height) q_ref = domain.get_maximum_inundation_elevation(minimum_height=minimum_storable_height) # First order accuracy assert num.allclose(q_ref, initial_runup_height, rtol=1.0/N) #-------------------------------------------------------------- # Let triangles adjust #-------------------------------------------------------------- q_max = None for t in domain.evolve(yieldstep = 0.1, finaltime = 1.0): q = domain.get_maximum_inundation_elevation(minimum_height=minimum_storable_height) if verbose: domain.write_time() print q if q > q_max: q_max = q #-------------------------------------------------------------- # Test inundation height again #-------------------------------------------------------------- #q_ref = domain.get_maximum_inundation_elevation() q = get_maximum_inundation_elevation(filename+'.sww') msg = 'We got %f, should have been %f' % (q, q_max) assert num.allclose(q, q_max, rtol=2.0/N), msg msg = 'We got %f, should have been %f' % (q, initial_runup_height) assert num.allclose(q, initial_runup_height, rtol = 1.0/N), msg # Test error condition if time interval is out try: q = get_maximum_inundation_elevation(filename+'.sww', time_interval=[2.0, 3.0]) except ValueError: pass else: msg = 'should have caught wrong time interval' raise Exception, msg # Check correct time interval q, loc = get_maximum_inundation_data(filename+'.sww', time_interval=[0.0, 3.0]) msg = 'We got %f, should have been %f' % (q, initial_runup_height) assert num.allclose(q, initial_runup_height, rtol = 1.0/N), msg assert num.allclose(-loc[0]/2, q) # From topography formula #-------------------------------------------------------------- # Update boundary to allow inflow #-------------------------------------------------------------- domain.set_boundary({'right': Bd}) #-------------------------------------------------------------- # Evolve system through time #-------------------------------------------------------------- for t in domain.evolve(yieldstep = 0.1, finaltime = 3.0, skip_initial_step = True): q = domain.get_maximum_inundation_elevation(minimum_height=minimum_storable_height) if verbose: domain.write_time() print q if q > q_max: q_max = q #-------------------------------------------------------------- # Test inundation height again #-------------------------------------------------------------- indices = domain.get_wet_elements() z = domain.get_quantity('elevation').\ get_values(location='centroids', indices=indices) assert num.alltrue(z < final_runup_height+1.0/N) q = domain.get_maximum_inundation_elevation() # First order accuracy assert num.allclose(q, final_runup_height, rtol=1.0/N) q, loc = get_maximum_inundation_data(filename+'.sww', time_interval=[3.0, 3.0]) msg = 'We got %f, should have been %f' % (q, final_runup_height) assert num.allclose(q, final_runup_height, rtol=1.0/N), msg assert num.allclose(-loc[0]/2, q) # From topography formula q = get_maximum_inundation_elevation(filename+'.sww',verbose = verbose) loc = get_maximum_inundation_location(filename+'.sww') msg = 'We got %f, should have been %f' % (q, q_max) assert num.allclose(q, q_max, rtol=1.0/N), msg assert num.allclose(-loc[0]/2, q) # From topography formula q = get_maximum_inundation_elevation(filename+'.sww', time_interval=[0, 3]) msg = 'We got %f, should have been %f' % (q, q_max) assert num.allclose(q, q_max, rtol=1.0/N), msg # Check polygon mode # Runup region polygon = [[0.3, 0.0], [0.9, 0.0], [0.9, 1.0], [0.3, 1.0]] q = get_maximum_inundation_elevation(filename+'.sww', polygon = polygon, time_interval=[0, 3]) msg = 'We got %f, should have been %f' % (q, q_max) assert num.allclose(q, q_max, rtol=1.0/N), msg # Offshore region polygon = [[0.9, 0.0], [1.0, 0.0], [1.0, 1.0], [0.9, 1.0]] q, loc = get_maximum_inundation_data(filename+'.sww', polygon = polygon, time_interval=[0, 3]) msg = 'We got %f, should have been %f' % (q, -0.475) assert num.allclose(q, -0.475, rtol=1.0/N), msg assert is_inside_polygon(loc, polygon) assert num.allclose(-loc[0]/2, q) # From topography formula # Dry region polygon = [[0.0, 0.0], [0.4, 0.0], [0.4, 1.0], [0.0, 1.0]] q, loc = get_maximum_inundation_data(filename+'.sww', polygon = polygon, time_interval=[0, 3]) msg = 'We got %s, should have been None' % (q) assert q is None, msg msg = 'We got %s, should have been None' % (loc) assert loc is None, msg # Check what happens if no time point is within interval try: q = get_maximum_inundation_elevation(filename+'.sww', time_interval=[2.75, 2.75]) except AssertionError: pass else: msg = 'Time interval should have raised an exception' raise Exception, msg # Cleanup try: pass #os.remove(domain.get_name() + '.sww') except: pass
def test_predicted_boyd_flow(self): """test_predicted_boyd_flow Test that flows predicted by the boyd method are consistent with what what is calculated in engineering codes. The data was supplied by Petar Milevski """ # FIXME(Ole) this is nowhere near finished path = get_pathname_from_package('anuga.culvert_flows') length = 12. width = 5. dx = dy = 0.5 # 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): # General Slope of Topography z=-x/10 return z domain.set_quantity('elevation', topography) domain.set_quantity('friction', 0.01) # Constant friction domain.set_quantity('stage', expression='elevation') Q0 = domain.get_quantity('stage') Q1 = Quantity(domain) # Add depths to stage head_water_depth = 0.169 tail_water_depth = 0.089 inlet_poly = [[0,0], [6,0], [6,5], [0,5]] outlet_poly = [[6,0], [12,0], [12,5], [6,5]] Q1.set_values(Polygon_function([(inlet_poly, head_water_depth), (outlet_poly, tail_water_depth)])) domain.set_quantity('stage', Q0 + Q1) culvert = Culvert_flow(domain, label='Test culvert', description='4 m test culvert', end_point0=[4.0, 2.5], end_point1=[8.0, 2.5], width=1.20, height=0.75, culvert_routine=boyd_generalised_culvert_model, number_of_barrels=1, verbose=False) domain.forcing_terms.append(culvert) # Call culvert(domain)
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')
#------------------------------------------------------------------------------ # Setup computational domain #------------------------------------------------------------------------------ print 'Setting up domain' length = 120. #x-Dir width = 200. #y-dir dx = dy = 2.0 # Resolution: Length of subdivisions on both axes #dx = dy = .5 # Resolution: Length of subdivisions on both axes #dx = dy = .5 # Resolution: Length of subdivisions on both axes #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 = Domain(points, vertices, boundary) domain.set_name('Test_Outlet_Ctrl') # Output name domain.set_default_order(2) domain.H0 = 0.01 domain.tight_slope_limiters = 1 print 'Size', len(domain) #------------------------------------------------------------------------------ # Setup initial conditions #------------------------------------------------------------------------------ def topography(x, y): """Set up a weir
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 _create_domain(self, d_length, d_width, dx, dy, elevation_0, elevation_1, stage_0, stage_1, xvelocity_0=0.0, xvelocity_1=0.0, yvelocity_0=0.0, yvelocity_1=0.0): points, vertices, boundary = rectangular_cross(int(d_length / dx), int(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 > 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 > d_length / 2, stage_1) return z def xmom(x, y): """Set up xmomentum """ z = numpy.zeros(x.shape, dtype='d') z[:] = xvelocity_0 * (stage_0 - elevation_0) numpy.putmask(z, x > d_length / 2, xvelocity_1 * (stage_1 - elevation_1)) return z def ymom(x, y): """Set up ymomentum """ z = numpy.zeros(x.shape, dtype='d') z[:] = yvelocity_0 * (stage_0 - elevation_0) numpy.putmask(z, x > d_length / 2, yvelocity_1 * (stage_1 - elevation_1)) return z #print 'Setting Quantities....' domain.set_quantity('elevation', elevation) # Use function for elevation domain.set_quantity('stage', stage) # Use function for elevation domain.set_quantity('xmomentum', xmom) domain.set_quantity('ymomentum', ymom) return domain
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')