def __init__(self, coordinates=None, vertices=None, boundary=None, tagged_elements=None, geo_reference=None, use_inscribed_circle=False, mesh_filename=None, use_cache=False, verbose=False, full_send_dict=None, ghost_recv_dict=None, starttime=0.0, processor=0, numproc=1, number_of_full_nodes=None, number_of_full_triangles=None): conserved_quantities = ['stage', 'xmomentum', 'ymomentum'] evolved_quantities = ['stage', 'xmomentum', 'ymomentum'] other_quantities = [ 'elevation', 'friction', 'height', 'xvelocity', 'yvelocity', 'x', 'y' ] Sww_domain.__init__(self, coordinates=coordinates, vertices=vertices, boundary=boundary, tagged_elements=tagged_elements, geo_reference=geo_reference, use_inscribed_circle=use_inscribed_circle, mesh_filename=mesh_filename, use_cache=use_cache, verbose=verbose, conserved_quantities=conserved_quantities, evolved_quantities=evolved_quantities, other_quantities=other_quantities, full_send_dict=full_send_dict, ghost_recv_dict=ghost_recv_dict, starttime=starttime, processor=processor, numproc=numproc, number_of_full_nodes=number_of_full_nodes, number_of_full_triangles=number_of_full_triangles) #------------------------------------------------ # set some defaults # Most of these override the options in config.py #------------------------------------------------ self.set_tsunami_defaults()
def __init__(self, coordinates=None, vertices=None, boundary=None, tagged_elements=None, geo_reference=None, use_inscribed_circle=False, mesh_filename=None, use_cache=False, verbose=False, full_send_dict=None, ghost_recv_dict=None, starttime=0.0, processor=0, numproc=1, number_of_full_nodes=None, number_of_full_triangles=None): conserved_quantities = [ 'stage', 'xmomentum', 'ymomentum'] evolved_quantities = [ 'stage', 'xmomentum', 'ymomentum'] other_quantities = [ 'elevation', 'friction', 'height', 'xvelocity', 'yvelocity', 'x', 'y' ] Sww_domain.__init__(self, coordinates = coordinates, vertices = vertices, boundary = boundary, tagged_elements = tagged_elements, geo_reference = geo_reference, use_inscribed_circle = use_inscribed_circle, mesh_filename = mesh_filename, use_cache = use_cache, verbose = verbose, conserved_quantities = conserved_quantities, evolved_quantities = evolved_quantities, other_quantities = other_quantities, full_send_dict = full_send_dict, ghost_recv_dict = ghost_recv_dict, starttime = starttime, processor = processor, numproc = numproc, number_of_full_nodes = number_of_full_nodes, number_of_full_triangles = number_of_full_triangles) #------------------------------------------------ # set some defaults # Most of these override the options in config.py #------------------------------------------------ self.set_tsunami_defaults()
def test_unique_verticesII(self): """ get values based on triangle lists. """ #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) domain.build_tagged_elements_dictionary({ 'bottom': [0, 1], 'top': [4, 5], 'all': [0, 1, 2, 3, 4, 5] }) #Set friction manning = 0.07 domain.set_quantity('friction', manning) domain.set_tag_region( Add_value_to_region('bottom', 'friction', 1.0, initial_quantity='friction', location='unique vertices')) #print domain.quantities['friction'].get_values() assert num.allclose(domain.quantities['friction'].get_values(),\ [[ 1.07, 1.07, 1.07], [ 1.07, 1.07, 1.07], [ 1.07, 0.07, 1.07], [ 0.07, 1.07, 0.07], [ 0.07, 0.07, 0.07], [ 0.07, 0.07, 0.07]])
def test_unique_verticesII(self): """ get values based on triangle lists. """ #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) domain.build_tagged_elements_dictionary({'bottom':[0,1], 'top':[4,5], 'all':[0,1,2,3,4,5]}) #Set friction manning = 0.07 domain.set_quantity('friction', manning) domain.set_tag_region(Add_value_to_region('bottom', 'friction', 1.0,initial_quantity='friction', location = 'unique vertices')) #print domain.quantities['friction'].get_values() assert num.allclose(domain.quantities['friction'].get_values(),\ [[ 1.07, 1.07, 1.07], [ 1.07, 1.07, 1.07], [ 1.07, 0.07, 1.07], [ 0.07, 1.07, 0.07], [ 0.07, 0.07, 0.07], [ 0.07, 0.07, 0.07]])
def test_unique_vertices_average_loc_unique_vert(self): """ get values based on triangle lists. """ #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) domain.build_tagged_elements_dictionary({'bottom':[0,1], 'top':[4,5], 'not_bottom':[2,3,4,5]}) #Set friction domain.set_quantity('friction', add_x_y) av_bottom = 2.0/3.0 add = 60.0 calc_frict = av_bottom + add domain.set_tag_region(Add_value_to_region('bottom', 'friction', add, initial_quantity='friction', location='unique vertices', average=True )) #print domain.quantities['friction'].get_values() frict_points = domain.quantities['friction'].get_values() assert num.allclose(frict_points[0],\ [ calc_frict, calc_frict, calc_frict]) assert num.allclose(frict_points[1],\ [ calc_frict, calc_frict, calc_frict]) assert num.allclose(frict_points[2],\ [ calc_frict, 1.0 + 2.0/3.0, calc_frict]) assert num.allclose(frict_points[3],\ [ 2.0/3.0,calc_frict, 1.0 + 2.0/3.0])
def test_fit_to_mesh_file2domain(self): from anuga.load_mesh.loadASCII import import_mesh_file, \ export_mesh_file import tempfile import os # create a .tsh file, no user outline mesh_dic = {} mesh_dic['vertices'] = [[0.0, 0.0], [0.0, 5.0], [5.0, 0.0]] mesh_dic['triangles'] = [[0, 2, 1]] mesh_dic['segments'] = [[0, 1], [2, 0], [1, 2]] mesh_dic['triangle_tags'] = [''] mesh_dic['vertex_attributes'] = [[], [], []] mesh_dic['vertiex_attribute_titles'] = [] mesh_dic['triangle_neighbors'] = [[-1, -1, -1]] mesh_dic['segment_tags'] = ['external', 'external', 'external'] mesh_file = tempfile.mktemp(".tsh") export_mesh_file(mesh_file,mesh_dic) # create a points .csv file point_file = tempfile.mktemp(".csv") fd = open(point_file,'w') fd.write("x,y, elevation, stage \n\ 1.0, 1.0,2.,4 \n\ 1.0, 3.0,4,8 \n\ 3.0,1.0,4.,8 \n") fd.close() mesh_output_file = tempfile.mktemp(".tsh") fit_to_mesh_file(mesh_file, point_file, mesh_output_file, alpha = 0.0) # load in the .tsh file we just wrote mesh_dic = import_mesh_file(mesh_output_file) #print "mesh_dic",mesh_dic ans =[[0.0, 0.0], [5.0, 10.0], [5.0,10.0]] assert num.allclose(mesh_dic['vertex_attributes'],ans) self.assertTrue(mesh_dic['vertex_attribute_titles'] == ['elevation','stage'], 'test_fit_to_mesh_file failed') domain = Domain(mesh_output_file, use_cache=True, verbose=False) answer = [0., 5., 5.] assert num.allclose(domain.quantities['elevation'].vertex_values, answer) #clean up os.remove(mesh_file) os.remove(point_file) os.remove(mesh_output_file)
def set_boundary(self, boundary_map): ## Specialisation of set_boundary, which also updates the 'boundary_flux_type' Sww_domain.set_boundary(self,boundary_map) # Add a flag which can be used to distinguish flux boundaries within # compute_fluxes_central # Initialise to zero (which means 'not a flux_boundary') self.boundary_flux_type = self.boundary_edges*0 # HACK to set the values of domain.boundary_flux for i in range(len(self.boundary_objects)): # Record the first 10 characters of the name of the boundary. # FIXME: There must be a better way than this! bndry_name = self.boundary_objects[i][1].__repr__()[0:10] if(bndry_name=='zero_mass_'): # Create flag 'boundary_flux_type' that can be read in # compute_fluxes_central self.boundary_flux_type[i]=1
def test_unique_vertices_average_loc_unique_vert_1_5(self): """ get values based on triangle lists. """ #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) domain.set_flow_algorithm('1_5') domain.build_tagged_elements_dictionary({ 'bottom': [0, 1], 'top': [4, 5], 'not_bottom': [2, 3, 4, 5] }) #Set friction domain.set_quantity('friction', add_x_y) av_bottom = 2.0 / 3.0 add = 60.0 calc_frict = av_bottom + add domain.set_tag_region( Add_value_to_region('bottom', 'friction', add, initial_quantity='friction', location='unique vertices', average=True)) #print domain.quantities['friction'].get_values() frict_points = domain.quantities['friction'].get_values() assert num.allclose(frict_points[0],\ [ calc_frict, calc_frict, calc_frict]) assert num.allclose(frict_points[1],\ [ calc_frict, calc_frict, calc_frict]) assert num.allclose(frict_points[2],\ [ calc_frict, 1.0 + 2.0/3.0, calc_frict]) assert num.allclose(frict_points[3],\ [ 2.0/3.0,calc_frict, 1.0 + 2.0/3.0])
def test_region_indices(self): """create region based on triangle lists.""" #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) region = Region(domain, indices=[0, 2, 3]) expected_indices = [0, 2, 3] assert num.allclose(region.indices, expected_indices)
def load_pts_as_polygon(points_file, minimum_triangle_angle=3.0): """ WARNING: This function is not fully working. Function to return a polygon returned from alpha shape, given a points file. WARNING: Alpha shape returns multiple polygons, but this function only returns one polygon. """ from anuga.pmesh.mesh import importMeshFromFile from anuga.shallow_water.shallow_water_domain import Domain mesh = importMeshFromFile(points_file) mesh.auto_segment() mesh.exportASCIIsegmentoutlinefile("outline.tsh") mesh2 = importMeshFromFile("outline.tsh") mesh2.generate_mesh(maximum_triangle_area=1000000000, minimum_triangle_angle=minimum_triangle_angle, verbose=False) mesh2.export_mesh_file('outline_meshed.tsh') domain = Domain("outline_meshed.tsh", use_cache=False) polygon = domain.get_boundary_polygon() return polygon
def test_region_polygon_expanded(self): """create region based on triangle lists.""" #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) region = Region(domain, polygon=[[0.0, 0.0], [0.5, 0.0], [0.5, 0.5]], expand_polygon=True) expected_indices = [0, 1, 2, 3] assert num.allclose(region.indices, expected_indices)
def load_pts_as_polygon(points_file, minimum_triangle_angle=3.0): """ WARNING: This function is not fully working. Function to return a polygon returned from alpha shape, given a points file. WARNING: Alpha shape returns multiple polygons, but this function only returns one polygon. """ from anuga.pmesh.mesh import importMeshFromFile from anuga.shallow_water.shallow_water_domain import Domain mesh = importMeshFromFile(points_file) mesh.auto_segment() mesh.exportASCIIsegmentoutlinefile("outline.tsh") mesh2 = importMeshFromFile("outline.tsh") mesh2.generate_mesh(maximum_triangle_area=1000000000, minimum_triangle_angle=minimum_triangle_angle, verbose=False) mesh2.export_mesh_file('outline_meshed.tsh') domain = Domain("outline_meshed.tsh", use_cache = False) polygon = domain.get_boundary_polygon() return polygon
def test_region_polygon(self): """create region based on triangle lists.""" #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) poly = [[0.0, 0.0], [0.5, 0.0], [0.5, 0.5]] #print poly region = Region(domain, polygon=poly) expected_indices = [1] assert num.allclose(region.indices, expected_indices)
def _create_domain_from_regions_sed(bounding_polygon, boundary_tags, maximum_triangle_area=None, mesh_filename=None, interior_regions=None, interior_holes=None, hole_tags=None, poly_geo_reference=None, mesh_geo_reference=None, minimum_triangle_angle=28.0, conserved_quantities=None, evolved_quantities=None, other_quantities=None, fail_if_polygons_outside=True, verbose=True): """_create_domain_from_regions_sed - internal function. See create_domain_from_regions in anuga/__init__.py for documentation. """ from anuga.pmesh.mesh_interface import create_mesh_from_regions create_mesh_from_regions(bounding_polygon, boundary_tags, maximum_triangle_area=maximum_triangle_area, interior_regions=interior_regions, filename=mesh_filename, interior_holes=interior_holes, hole_tags=hole_tags, poly_geo_reference=poly_geo_reference, mesh_geo_reference=mesh_geo_reference, minimum_triangle_angle=minimum_triangle_angle, fail_if_polygons_outside=fail_if_polygons_outside, use_cache=False, verbose=verbose) domain = Domain(mesh_filename, conserved_quantities=conserved_quantities, evolved_quantities=evolved_quantities, other_quantities=other_quantities, use_cache=False, verbose=verbose) return domain
def test_unique_vertices_average_loc_unique_vert_de0(self): """ get values based on triangle lists. """ #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) domain.build_tagged_elements_dictionary({ 'bottom': [0, 1], 'top': [4, 5], 'not_bottom': [2, 3, 4, 5] }) #Set friction domain.set_quantity('friction', add_x_y) av_bottom = 2.0 / 3.0 add = 60.0 calc_frict = av_bottom + add domain.set_tag_region( Add_value_to_region('bottom', 'friction', add, initial_quantity='friction', location='unique vertices', average=True)) #print domain.quantities['friction'].get_values() frict_points = domain.quantities['friction'].get_values() expected0 = [60.77777778, 60.77777778, 60.77777778] expected1 = [60.77777778, 60.77777778, 60.77777778] expected2 = [60.77777778, 1.66666667, 60.77777778] expected3 = [0.66666667, 60.77777778, 1.66666667] assert num.allclose(frict_points[0], expected0) assert num.allclose(frict_points[1], expected1) assert num.allclose(frict_points[2], expected2) assert num.allclose(frict_points[3], expected3)
def _create_domain_from_regions(bounding_polygon, boundary_tags, maximum_triangle_area=None, mesh_filename=None, interior_regions=None, interior_holes=None, hole_tags=None, poly_geo_reference=None, mesh_geo_reference=None, breaklines=None, regionPtArea=None, minimum_triangle_angle=28.0, fail_if_polygons_outside=True, verbose=True): """_create_domain_from_regions - internal function. See create_domain_from_regions for documentation. """ #from anuga.shallow_water.shallow_water_domain import Domain from anuga.pmesh.mesh_interface import create_mesh_from_regions create_mesh_from_regions(bounding_polygon, boundary_tags, maximum_triangle_area=maximum_triangle_area, interior_regions=interior_regions, filename=mesh_filename, interior_holes=interior_holes, hole_tags=hole_tags, poly_geo_reference=poly_geo_reference, mesh_geo_reference=mesh_geo_reference, breaklines=breaklines, regionPtArea=regionPtArea, minimum_triangle_angle=minimum_triangle_angle, fail_if_polygons_outside=fail_if_polygons_outside, use_cache=False, verbose=verbose) domain = Domain(mesh_filename, use_cache=False, verbose=verbose) return domain
def test_unique_vertices_average_loc_vert(self): """Get values based on triangle lists.""" #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) domain.build_tagged_elements_dictionary({ 'bottom': [0, 1], 'top': [4, 5], 'not_bottom': [2, 3, 4, 5] }) #Set friction domain.set_quantity('friction', add_x_y) av_bottom = 2.0 / 3.0 add = 60.0 calc_frict = av_bottom + add domain.set_tag_region( Add_value_to_region('bottom', 'friction', add, initial_quantity='friction', location='vertices', average=True)) frict_points = domain.quantities['friction'].get_values() expected = [calc_frict, calc_frict, calc_frict] msg = ('frict_points[0]=%s\nexpected=%s' % (str(frict_points[0]), str(expected))) assert num.allclose(frict_points[0], expected), msg msg = ('frict_points[1]=%s\nexpected=%s' % (str(frict_points[1]), str(expected))) assert num.allclose(frict_points[1], expected), msg
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_get_maximum_inundation_de0(self): """Test that sww information can be converted correctly to maximum runup elevation and location (without and with georeferencing) This test creates a slope and a runup which is maximal (~11m) at around 10s and levels out to the boundary condition (1m) at about 30s. """ import time, os from anuga.file.netcdf import NetCDFFile #Setup #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create basic mesh (100m x 100m) points, vertices, boundary = rectangular(20, 5, 100, 50) # Create shallow water domain domain = Domain(points, vertices, boundary) domain.default_order = 2 domain.set_minimum_storable_height(0.01) filename = 'runup_test_3' domain.set_name(filename) swwfile = domain.get_name() + '.sww' domain.set_datadir('.') domain.format = 'sww' domain.smooth = True # FIXME (Ole): Backwards compatibility # Look at sww file and see what happens when # domain.tight_slope_limiters = 1 domain.tight_slope_limiters = 0 domain.use_centroid_velocities = 0 # Backwards compatibility (7/5/8) Br = Reflective_boundary(domain) Bd = Dirichlet_boundary([1.0,0,0]) #---------- First run without geo referencing domain.set_quantity('elevation', lambda x,y: -0.2*x + 14) # Slope domain.set_quantity('stage', -6) domain.set_boundary( {'left': Br, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime = 50): pass # Check maximal runup runup = get_maximum_inundation_elevation(swwfile) location = get_maximum_inundation_location(swwfile) #print 'Runup, location', runup, location assert num.allclose(runup, 4.66666666667) assert num.allclose(location[0], 46.666668) # Check final runup runup = get_maximum_inundation_elevation(swwfile, time_interval=[45,50]) location = get_maximum_inundation_location(swwfile, time_interval=[45,50]) #print 'Runup, location:',runup, location assert num.allclose(runup, 3.81481488546) assert num.allclose(location[0], 51.666668) # Check runup restricted to a polygon p = [[50,1], [99,1], [99,49], [50,49]] runup = get_maximum_inundation_elevation(swwfile, polygon=p) location = get_maximum_inundation_location(swwfile, polygon=p) #print runup, location assert num.allclose(runup, 3.81481488546) assert num.allclose(location[0], 51.6666666) # Check that mimimum_storable_height works fid = NetCDFFile(swwfile, netcdf_mode_r) # Open existing file stage = fid.variables['stage_c'][:] z = fid.variables['elevation_c'][:] xmomentum = fid.variables['xmomentum_c'][:] ymomentum = fid.variables['ymomentum_c'][:] for i in range(stage.shape[0]): h = stage[i]-z # depth vector at time step i # Check every node location for j in range(stage.shape[1]): # Depth being either exactly zero implies # momentum being zero. # Or else depth must be greater than or equal to # the minimal storable height if h[j] == 0.0: assert xmomentum[i,j] == 0.0 assert ymomentum[i,j] == 0.0 else: assert h[j] >= 0.0 fid.close() # Cleanup os.remove(swwfile) #------------- Now the same with georeferencing domain.time=0.0 E = 308500 N = 6189000 #E = N = 0 domain.geo_reference = Geo_reference(56, E, N) domain.set_quantity('elevation', lambda x,y: -0.2*x + 14) # Slope domain.set_quantity('stage', -6) domain.set_boundary( {'left': Br, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime = 50): pass # Check maximal runup runup = get_maximum_inundation_elevation(swwfile) location = get_maximum_inundation_location(swwfile) #print runup, location assert num.allclose(runup,4.66666666667) assert num.allclose(location[0], 308546.66) # Check final runup runup = get_maximum_inundation_elevation(swwfile, time_interval=[45,50]) location = get_maximum_inundation_location(swwfile, time_interval=[45,50]) #print runup, location #1.66666666667 [308561.66, 6189006.5] assert num.allclose(runup, 3.81481488546) assert num.allclose(location[0], 308551.66) # Check runup restricted to a polygon p = num.array([[50,1], [99,1], [99,49], [50,49]], num.int) + num.array([E, N], num.int) #array default# runup = get_maximum_inundation_elevation(swwfile, polygon=p) location = get_maximum_inundation_location(swwfile, polygon=p) #print runup, location assert num.allclose(runup, 3.81481488546) assert num.allclose(location[0], 308551.66) # Cleanup os.remove(swwfile)
def setUp(self): # print "****set up****" # Create an sww file # Set up an sww that has a geo ref. # have it cover an area in Australia. 'gong maybe # Don't have many triangles though! # Site Name: GDA-MGA: (UTM with GRS80 ellipsoid) # Zone: 56 # Easting: 222908.705 Northing: 6233785.284 # Latitude: -34 0 ' 0.00000 '' Longitude: 150 0 ' 0.00000 '' # Grid Convergence: -1 40 ' 43.13 '' Point Scale: 1.00054660 # geo-ref # Zone: 56 # Easting: 220000 Northing: 6230000 # have a big area covered. mesh_file = tempfile.mktemp(".tsh") points_lat_long = [[-33, 152], [-35, 152], [-35, 150], [-33, 150]] spat = Geospatial_data(data_points=points_lat_long, points_are_lats_longs=True) points_ab = spat.get_data_points(absolute=True) geo = Geo_reference(56, 400000, 6000000) spat.set_geo_reference(geo) m = Mesh() m.add_vertices(spat) m.auto_segment() m.generate_mesh(verbose=False) m.export_mesh_file(mesh_file) # Create shallow water domain domain = Domain(mesh_file) os.remove(mesh_file) domain.default_order = 2 # Set some field values # domain.set_quantity('stage', 1.0) domain.set_quantity("elevation", -0.5) domain.set_quantity("friction", 0.03) ###################### # Boundary conditions B = Transmissive_boundary(domain) domain.set_boundary({"exterior": B}) ###################### # Initial condition - with jumps bed = domain.quantities["elevation"].vertex_values stage = num.zeros(bed.shape, num.float) h = 0.3 for i in range(stage.shape[0]): if i % 2 == 0: stage[i, :] = bed[i, :] + h else: stage[i, :] = bed[i, :] domain.set_quantity("stage", stage) domain.set_quantity("xmomentum", stage * 22.0) domain.set_quantity("ymomentum", stage * 55.0) domain.distribute_to_vertices_and_edges() self.domain = domain C = domain.get_vertex_coordinates() self.X = C[:, 0:6:2].copy() self.Y = C[:, 1:6:2].copy() self.F = bed # sww_file = tempfile.mktemp("") self.domain.set_name("tid_P0") self.domain.format = "sww" self.domain.smooth = True self.domain.reduction = mean sww = SWW_file(self.domain) sww.store_connectivity() sww.store_timestep() self.domain.time = 2.0 sww.store_timestep() self.sww = sww # so it can be deleted # Create another sww file mesh_file = tempfile.mktemp(".tsh") points_lat_long = [[-35, 152], [-36, 152], [-36, 150], [-35, 150]] spat = Geospatial_data(data_points=points_lat_long, points_are_lats_longs=True) points_ab = spat.get_data_points(absolute=True) geo = Geo_reference(56, 400000, 6000000) spat.set_geo_reference(geo) m = Mesh() m.add_vertices(spat) m.auto_segment() m.generate_mesh(verbose=False) m.export_mesh_file(mesh_file) # Create shallow water domain domain = Domain(mesh_file) os.remove(mesh_file) domain.default_order = 2 # Set some field values # domain.set_quantity('stage', 1.0) domain.set_quantity("elevation", -40) domain.set_quantity("friction", 0.03) ###################### # Boundary conditions B = Transmissive_boundary(domain) domain.set_boundary({"exterior": B}) ###################### # Initial condition - with jumps bed = domain.quantities["elevation"].vertex_values stage = num.zeros(bed.shape, num.float) h = 30.0 for i in range(stage.shape[0]): if i % 2 == 0: stage[i, :] = bed[i, :] + h else: stage[i, :] = bed[i, :] domain.set_quantity("stage", stage) domain.set_quantity("xmomentum", stage * 22.0) domain.set_quantity("ymomentum", stage * 55.0) domain.distribute_to_vertices_and_edges() self.domain2 = domain C = domain.get_vertex_coordinates() self.X2 = C[:, 0:6:2].copy() self.Y2 = C[:, 1:6:2].copy() self.F2 = bed # sww_file = tempfile.mktemp("") domain.set_name("tid_P1") domain.format = "sww" domain.smooth = True domain.reduction = mean sww = SWW_file(domain) sww.store_connectivity() sww.store_timestep() domain.time = 2.0 sww.store_timestep() self.swwII = sww # so it can be deleted # print "sww.filename", sww.filename # Create a csv file self.csv_file = tempfile.mktemp(".csv") fd = open(self.csv_file, "wb") writer = csv.writer(fd) writer.writerow( ["LONGITUDE", "LATITUDE", STR_VALUE_LABEL, CONT_VALUE_LABEL, "ROOF_TYPE", WALL_TYPE_LABEL, SHORE_DIST_LABEL] ) writer.writerow(["151.5", "-34", "199770", "130000", "Metal", "Timber", 20.0]) writer.writerow(["151", "-34.5", "150000", "76000", "Metal", "Double Brick", 200.0]) writer.writerow(["151", "-34.25", "150000", "76000", "Metal", "Brick Veneer", 200.0]) fd.close() # Create a csv file self.csv_fileII = tempfile.mktemp(".csv") fd = open(self.csv_fileII, "wb") writer = csv.writer(fd) writer.writerow( ["LONGITUDE", "LATITUDE", STR_VALUE_LABEL, CONT_VALUE_LABEL, "ROOF_TYPE", WALL_TYPE_LABEL, SHORE_DIST_LABEL] ) writer.writerow(["151.5", "-34", "199770", "130000", "Metal", "Timber", 20.0]) writer.writerow(["151", "-34.5", "150000", "76000", "Metal", "Double Brick", 200.0]) writer.writerow(["151", "-34.25", "150000", "76000", "Metal", "Brick Veneer", 200.0]) fd.close()
def setUp(self): import time self.verbose = Test_File_Conversion.verbose # Create basic mesh points, vertices, boundary = rectangular(2, 2) # Create shallow water domain domain = Domain(points, vertices, boundary) domain.default_order = 2 # Set some field values domain.set_quantity('elevation', lambda x,y: -x) domain.set_quantity('friction', 0.03) ###################### # Boundary conditions B = Transmissive_boundary(domain) domain.set_boundary( {'left': B, 'right': B, 'top': B, 'bottom': B}) ###################### #Initial condition - with jumps bed = domain.quantities['elevation'].vertex_values stage = num.zeros(bed.shape, num.float) h = 0.3 for i in range(stage.shape[0]): if i % 2 == 0: stage[i,:] = bed[i,:] + h else: stage[i,:] = bed[i,:] domain.set_quantity('stage', stage) domain.distribute_to_vertices_and_edges() self.initial_stage = copy.copy(domain.quantities['stage'].vertex_values) self.domain = domain C = domain.get_vertex_coordinates() self.X = C[:,0:6:2].copy() self.Y = C[:,1:6:2].copy() self.F = bed #Write A testfile (not realistic. Values aren't realistic) self.test_MOST_file = 'most_small' longitudes = [150.66667, 150.83334, 151., 151.16667] latitudes = [-34.5, -34.33333, -34.16667, -34] long_name = 'LON' lat_name = 'LAT' nx = 4 ny = 4 six = 6 for ext in ['_ha.nc', '_ua.nc', '_va.nc', '_e.nc']: fid = NetCDFFile(self.test_MOST_file + ext, netcdf_mode_w) fid.createDimension(long_name,nx) fid.createVariable(long_name,netcdf_float,(long_name,)) fid.variables[long_name].point_spacing='uneven' fid.variables[long_name].units='degrees_east' fid.variables[long_name][:] = longitudes fid.createDimension(lat_name,ny) fid.createVariable(lat_name,netcdf_float,(lat_name,)) fid.variables[lat_name].point_spacing='uneven' fid.variables[lat_name].units='degrees_north' fid.variables[lat_name][:] = latitudes fid.createDimension('TIME',six) fid.createVariable('TIME',netcdf_float,('TIME',)) fid.variables['TIME'].point_spacing='uneven' fid.variables['TIME'].units='seconds' fid.variables['TIME'][:] = [0.0, 0.1, 0.6, 1.1, 1.6, 2.1] name = ext[1:3].upper() if name == 'E.': name = 'ELEVATION' fid.createVariable(name,netcdf_float,('TIME', lat_name, long_name)) fid.variables[name].units='CENTIMETERS' fid.variables[name].missing_value=-1.e+034 fid.variables[name][:] = [[[0.3400644, 0, -46.63519, -6.50198], [-0.1214216, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0.3400644, 2.291054e-005, -23.33335, -6.50198], [-0.1213987, 4.581959e-005, -1.594838e-007, 1.421085e-012], [2.291054e-005, 4.582107e-005, 4.581715e-005, 1.854517e-009], [0, 2.291054e-005, 2.291054e-005, 0]], [[0.3400644, 0.0001374632, -23.31503, -6.50198], [-0.1212842, 0.0002756907, 0.006325484, 1.380492e-006], [0.0001374632, 0.0002749264, 0.0002742863, 6.665601e-008], [0, 0.0001374632, 0.0001374632, 0]], [[0.3400644, 0.0002520159, -23.29672, -6.50198], [-0.1211696, 0.0005075303, 0.01264618, 6.208276e-006], [0.0002520159, 0.0005040318, 0.0005027961, 2.23865e-007], [0, 0.0002520159, 0.0002520159, 0]], [[0.3400644, 0.0003665686, -23.27842, -6.50198], [-0.1210551, 0.0007413362, 0.01896192, 1.447638e-005], [0.0003665686, 0.0007331371, 0.0007313463, 4.734126e-007], [0, 0.0003665686, 0.0003665686, 0]], [[0.3400644, 0.0004811212, -23.26012, -6.50198], [-0.1209405, 0.0009771062, 0.02527271, 2.617787e-005], [0.0004811212, 0.0009622425, 0.0009599366, 8.152277e-007], [0, 0.0004811212, 0.0004811212, 0]]] fid.close()
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)
def test_get_mesh_and_quantities_from_de0_sww_file(self): """test_get_mesh_and_quantities_from_sww_file(self): """ # Generate a test sww file with non trivial georeference import time, os # Setup #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create basic mesh (100m x 5m) width = 5 length = 50 t_end = 10 points, vertices, boundary = rectangular(length, width, 50, 5) # Create shallow water domain domain = Domain(points, vertices, boundary, geo_reference = Geo_reference(56,308500,6189000)) domain.set_name('test_get_mesh_and_quantities_from_sww_file') swwfile = domain.get_name() + '.sww' domain.set_datadir('.') domain.set_flow_algorithm('DE0') Br = Reflective_boundary(domain) # Side walls Bd = Dirichlet_boundary([1, 0, 0]) # inflow domain.set_boundary( {'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime = t_end): pass # Read it # Get mesh and quantities from sww file X = get_mesh_and_quantities_from_file(swwfile, quantities=['elevation', 'stage', 'xmomentum', 'ymomentum'], verbose=False) mesh, quantities, time = X # Check that mesh has been recovered assert num.alltrue(mesh.triangles == domain.get_triangles()) assert num.allclose(mesh.nodes, domain.get_nodes()) # Check that time has been recovered assert num.allclose(time, range(t_end+1)) # Check that quantities have been recovered # (sww files use single precision) z=domain.get_quantity('elevation').get_values(location='unique vertices') assert num.allclose(quantities['elevation'], z) for q in ['stage', 'xmomentum', 'ymomentum']: # Get quantity at last timestep q_ref=domain.get_quantity(q).get_values(location='unique vertices') #print q,quantities[q] q_sww=quantities[q][-1,:] msg = 'Quantity %s failed to be recovered' %q assert num.allclose(q_ref, q_sww, atol=1.0e-2), msg
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 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_sww2pts_centroids_de0(self): """Test that sww information can be converted correctly to pts data at specified coordinates - in this case, the centroids. """ import time, os from anuga.file.netcdf import NetCDFFile # Used for points that lie outside mesh NODATA_value = 1758323 # Setup from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create shallow water domain domain = Domain(*rectangular(2, 2)) B = Transmissive_boundary(domain) domain.set_boundary( {'left': B, 'right': B, 'top': B, 'bottom': B}) domain.set_name('datatest_de0') ptsfile = domain.get_name() + '_elevation.pts' swwfile = domain.get_name() + '.sww' domain.set_datadir('.') domain.format = 'sww' domain.set_quantity('elevation', lambda x,y: -x-y) domain.geo_reference = Geo_reference(56,308500,6189000) sww = SWW_file(domain) sww.store_connectivity() sww.store_timestep() #self.domain.tight_slope_limiters = 1 domain.evolve_to_end(finaltime = 0.01) sww.store_timestep() # Check contents in NetCDF fid = NetCDFFile(sww.filename, netcdf_mode_r) # Get the variables x = fid.variables['x'][:] y = fid.variables['y'][:] elevation = fid.variables['elevation'][:] time = fid.variables['time'][:] stage = fid.variables['stage'][:] volumes = fid.variables['volumes'][:] # Invoke interpolation for vertex points points = num.concatenate( (x[:,num.newaxis],y[:,num.newaxis]), axis=1 ) points = num.ascontiguousarray(points) sww2pts(domain.get_name() + '.sww', quantity = 'elevation', data_points = points, NODATA_value = NODATA_value) ref_point_values = elevation point_values = Geospatial_data(ptsfile).get_attributes() #print 'P', point_values #print 'Ref', ref_point_values assert num.allclose(point_values, ref_point_values) # Invoke interpolation for centroids points = domain.get_centroid_coordinates() #print points sww2pts(domain.get_name() + '.sww', quantity = 'elevation', data_points = points, NODATA_value = NODATA_value) #ref_point_values = [-0.5, -0.5, -1, -1, -1, -1, -1.5, -1.5] #At centroids ref_point_values = [-0.77777777, -0.77777777, -0.99999998, -0.99999998, -0.99999998, -0.99999998, -1.22222221, -1.22222221] point_values = Geospatial_data(ptsfile).get_attributes() #print 'P', point_values #print 'Ref', ref_point_values assert num.allclose(point_values, ref_point_values) fid.close() #Cleanup os.remove(sww.filename) os.remove(ptsfile)
def test_get_flow_through_cross_section_stored_uniquely(self): """test_get_flow_through_cross_section_stored_uniquely(self): Test that the total flow through a cross section can be correctly obtained from an sww file. This test creates a flat bed with a known flow through it and tests that the function correctly returns the expected flow. The specifics are u = 2 m/s h = 1 m w = 3 m (width of channel) q = u*h*w = 6 m^3/s """ import time, os from anuga.file.netcdf import NetCDFFile # Setup #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create basic mesh (20m x 3m) width = 3 length = 20 t_end = 3 points, vertices, boundary = rectangular(length, width, length, width) # Create shallow water domain domain = Domain(points, vertices, boundary) domain.default_order = 2 domain.set_minimum_storable_height(0.01) domain.set_name('flowtest_uniquely') swwfile = domain.get_name() + '.sww' domain.set_store_vertices_uniquely() domain.set_datadir('.') domain.format = 'sww' domain.smooth = True h = 1.0 u = 2.0 uh = u * h Br = Reflective_boundary(domain) # Side walls Bd = Dirichlet_boundary([h, uh, 0]) # 2 m/s across the 3 m inlet: domain.set_quantity('elevation', 0.0) domain.set_quantity('stage', h) domain.set_quantity('xmomentum', uh) domain.set_boundary({'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime=t_end): pass # Check that momentum is as it should be in the interior I = [[0, width / 2.], [length / 2., width / 2.], [length, width / 2.]] f = file_function(swwfile, quantities=['stage', 'xmomentum', 'ymomentum'], interpolation_points=I, verbose=False) for t in range(t_end + 1): for i in range(3): assert num.allclose(f(t, i), [1, 2, 0], atol=1.0e-6) # Check flows through the middle for i in range(5): x = length / 2. + i * 0.23674563 # Arbitrary cross_section = [[x, 0], [x, width]] time, Q = get_flow_through_cross_section(swwfile, cross_section, verbose=False) assert num.allclose(Q, uh * width) # Try the same with partial lines x = length / 2. for i in range(5): start_point = [length / 2., i * width / 5.] #print start_point cross_section = [start_point, [length / 2., width]] time, Q = get_flow_through_cross_section(swwfile, cross_section, verbose=False) #print i, Q, (width-start_point[1]) assert num.allclose(Q, uh * (width - start_point[1])) # Verify no flow when line is parallel to flow cross_section = [[length / 2. - 10, width / 2.], [length / 2. + 10, width / 2.]] time, Q = get_flow_through_cross_section(swwfile, cross_section, verbose=False) #print i, Q assert num.allclose(Q, 0, atol=1.0e-5) # Try with lines on an angle (all flow still runs through here) cross_section = [[length / 2., 0], [length / 2. + width, width]] time, Q = get_flow_through_cross_section(swwfile, cross_section, verbose=False) assert num.allclose(Q, uh * width)
def test_get_maximum_inundation_de0(self): """Test that sww information can be converted correctly to maximum runup elevation and location (without and with georeferencing) This test creates a slope and a runup which is maximal (~11m) at around 10s and levels out to the boundary condition (1m) at about 30s. """ import time, os from anuga.file.netcdf import NetCDFFile verbose = False #Setup #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create basic mesh (100m x 100m) points, vertices, boundary = rectangular(20, 5, 100, 50) # Create shallow water domain domain = Domain(points, vertices, boundary) domain.set_flow_algorithm('DE0') domain.set_low_froude(0) domain.set_minimum_storable_height(0.01) filename = 'runup_test_3' domain.set_name(filename) swwfile = domain.get_name() + '.sww' domain.set_datadir('.') domain.format = 'sww' domain.smooth = True # FIXME (Ole): Backwards compatibility # Look at sww file and see what happens when # domain.tight_slope_limiters = 1 domain.tight_slope_limiters = 0 domain.use_centroid_velocities = 0 # Backwards compatibility (7/5/8) Br = Reflective_boundary(domain) Bd = Dirichlet_boundary([1.0, 0, 0]) #---------- First run without geo referencing domain.set_quantity('elevation', lambda x, y: -0.2 * x + 14) # Slope domain.set_quantity('stage', -6) domain.set_boundary({'left': Br, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime=50): pass # Check maximal runup runup, location, max_time = get_maximum_inundation_data( swwfile, return_time=True) if verbose: print('Runup, location', runup, location, max_time) assert num.allclose(runup, 3.33333325386) assert num.allclose(location, [53.333332, 43.333332]) assert num.allclose(max_time, 10.0) # Check runup in restricted time interval runup, location, max_time = get_maximum_inundation_data( swwfile, time_interval=[0, 9], return_time=True) if verbose: print('Runup, location:', runup, location, max_time) assert num.allclose(runup, 2.66666674614) assert num.allclose(location, [56.666668, 16.666666]) assert num.allclose(max_time, 9.0) # Check final runup runup, location = get_maximum_inundation_data(swwfile, time_interval=[45, 50]) if verbose: print('Runup, location:', runup, location, max_time) assert num.allclose(runup, 3.33333325386) assert num.allclose(location, [53.333332, 33.333332]) #assert num.allclose(max_time, 45.0) # Check runup restricted to a polygon p = [[50, 1], [99, 1], [99, 40], [50, 40]] runup, location = get_maximum_inundation_data(swwfile, polygon=p) #runup = get_maximum_inundation_elevation(swwfile, polygon=p) #location = get_maximum_inundation_location(swwfile, polygon=p) #print runup, location, max_time assert num.allclose(runup, 3.33333325386) assert num.allclose(location, [53.333332, 33.333332]) #assert num.allclose(max_time, 11.0) # Check that mimimum_storable_height works fid = NetCDFFile(swwfile, netcdf_mode_r) # Open existing file stage = fid.variables['stage_c'][:] z = fid.variables['elevation_c'][:] xmomentum = fid.variables['xmomentum_c'][:] ymomentum = fid.variables['ymomentum_c'][:] for i in range(stage.shape[0]): h = stage[i] - z # depth vector at time step i # Check every node location for j in range(stage.shape[1]): # Depth being either exactly zero implies # momentum being zero. # Or else depth must be greater than or equal to # the minimal storable height if h[j] == 0.0: assert xmomentum[i, j] == 0.0 assert ymomentum[i, j] == 0.0 else: assert h[j] >= 0.0 fid.close() # Cleanup os.remove(swwfile) #------------- Now the same with georeferencing domain.time = 0.0 E = 308500 N = 6189000 #E = N = 0 domain.geo_reference = Geo_reference(56, E, N) domain.set_quantity('elevation', lambda x, y: -0.2 * x + 14) # Slope domain.set_quantity('stage', -6) domain.set_boundary({'left': Br, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime=50): pass # Check maximal runup runup, location = get_maximum_inundation_data(swwfile) #print 'Runup, location', runup, location, max_time assert num.allclose(runup, 3.33333325386) assert num.allclose(location, [53.333332 + E, 43.333332 + N]) #assert num.allclose(max_time, 10.0) # Check runup in restricted time interval runup, location = get_maximum_inundation_data(swwfile, time_interval=[0, 9]) #print 'Runup, location:',runup, location, max_time assert num.allclose(runup, 2.66666674614) assert num.allclose(location, [56.666668 + E, 16.666666 + N]) #assert num.allclose(max_time, 9.0) # Check final runup runup, location = get_maximum_inundation_data(swwfile, time_interval=[45, 50]) #print 'Runup, location:',runup, location, max_time assert num.allclose(runup, 3.33333325386) assert num.allclose(location, [53.333332 + E, 33.333332 + N]) #assert num.allclose(max_time, 45.0) # Check runup restricted to a polygon p = num.array([[50, 1], [99, 1], [99, 40], [50, 40]], num.int) + num.array([E, N], num.int) runup, location = get_maximum_inundation_data(swwfile, polygon=p) #print runup, location, max_time assert num.allclose(runup, 3.33333325386) assert num.allclose(location, [53.333332 + E, 33.333332 + N]) #assert num.allclose(max_time, 11.0) # Cleanup os.remove(swwfile)
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
#------------------------------------------------------------------------------ print 'Setting up domain' length = 200. #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_WIDE_BRIDGE') # Output name #domain.set_default_order(2) #omain.H0 = 0.01 #domain.tight_slope_limiters = 1 domain.set_flow_algorithm('2_0') print 'Size', len(domain) #------------------------------------------------------------------------------ # Setup initial conditions #------------------------------------------------------------------------------ def topography(x, y):
def trial(self, num_of_points=20000, maxArea=1000, max_points_per_cell=13, is_fit=True, use_file_type=None, blocking_len=500000, segments_in_mesh=True, save=False, verbose=False, run_profile=False, gridded=True, geo_ref=True): ''' num_of_points ''' if geo_ref is True: geo = Geo_reference(xllcorner=2.0, yllcorner=2.0) else: geo = None mesh_dict = self._build_regular_mesh_dict(maxArea=maxArea, is_segments=segments_in_mesh, save=save, geo=geo) points_dict = self._build_points_dict(num_of_points=num_of_points, gridded=gridded, verbose=verbose) if is_fit is True: op = "Fit_" else: op = "Interp_" profile_file = op + "P" + str(num_of_points) + \ "T" + str(len(mesh_dict['triangles'])) + \ "PPC" + str(max_points_per_cell) + \ ".txt" # Apply the geo_ref to the points, so they are relative # Pass in the geo_ref domain = Domain(mesh_dict['vertices'], mesh_dict['triangles'], use_cache=False, verbose=verbose, geo_reference=geo) #Initial time and memory t0 = time.time() #m0 = None on windows m0 = mem_usage() # Apply the geo_ref to the points, so they are relative # Pass in the geo_ref geospatial = Geospatial_data(points_dict['points'], points_dict['point_attributes'], geo_reference=geo) del points_dict if is_fit is True: if use_file_type is None: points = geospatial filename = None else: #FIXME (DSG) check that the type fileName = tempfile.mktemp("." + use_file_type) geospatial.export_points_file(fileName, absolute=True) points = None filename = fileName if run_profile is True: s = """domain.set_quantity('elevation',points,filename=filename,use_cache=False)""" pobject = profile.Profile() presult = pobject.runctx(s, vars(sys.modules[__name__]), vars()) prof_file = tempfile.mktemp(".prof") presult.dump_stats(prof_file) # # Let process these results S = pstats.Stats(prof_file) saveout = sys.stdout pfile = open(profile_file, "w") sys.stdout = pfile s = S.sort_stats('cumulative').print_stats(60) sys.stdout = saveout pfile.close() os.remove(prof_file) else: domain.set_quantity('elevation', points, filename=filename, use_cache=False, verbose=verbose) if not use_file_type is None: os.remove(fileName) else: # run an interploate problem. if run_profile: # pass in the geospatial points # and the mesh origin s = """benchmark_interpolate(mesh_dict['vertices'],mesh_dict['vertex_attributes'],mesh_dict['triangles'],geospatial,max_points_per_cell=max_points_per_cell,mesh_origin=geo)""" pobject = profile.Profile() presult = pobject.runctx(s, vars(sys.modules[__name__]), vars()) prof_file = tempfile.mktemp(".prof") presult.dump_stats(prof_file) # # Let process these results S = pstats.Stats(prof_file) saveout = sys.stdout pfile = open(profile_file, "w") sys.stdout = pfile s = S.sort_stats('cumulative').print_stats(60) sys.stdout = saveout pfile.close() os.remove(prof_file) else: # pass in the geospatial points benchmark_interpolate(mesh_dict['vertices'], mesh_dict['vertex_attributes'], mesh_dict['triangles'], geospatial, mesh_origin=geo, max_points_per_cell=max_points_per_cell, verbose=verbose) time_taken_sec = (time.time() - t0) m1 = mem_usage() if m0 is None or m1 is None: memory_used = None else: memory_used = (m1 - m0) #print 'That took %.2f seconds' %time_taken_sec # return the times spent in first cell searching and # backing up. #search_one_cell_time, search_more_cells_time = search_times() #reset_search_times() #print "bench - build_quadtree_time", get_build_quadtree_time() return time_taken_sec, memory_used, len(mesh_dict['triangles']), \ get_build_quadtree_time()
def trial(self, num_of_points=20000, maxArea=1000, max_points_per_cell=13, is_fit=True, use_file_type=None, blocking_len=500000, segments_in_mesh=True, save=False, verbose=False, run_profile=False, gridded=True, geo_ref=True): ''' num_of_points ''' if geo_ref is True: geo = Geo_reference(xllcorner = 2.0, yllcorner = 2.0) else: geo = None mesh_dict = self._build_regular_mesh_dict(maxArea=maxArea, is_segments=segments_in_mesh, save=save, geo=geo) points_dict = self._build_points_dict(num_of_points=num_of_points, gridded=gridded, verbose=verbose) if is_fit is True: op = "Fit_" else: op = "Interp_" profile_file = op + "P" + str(num_of_points) + \ "T" + str(len(mesh_dict['triangles'])) + \ "PPC" + str(max_points_per_cell) + \ ".txt" # Apply the geo_ref to the points, so they are relative # Pass in the geo_ref domain = Domain(mesh_dict['vertices'], mesh_dict['triangles'], use_cache=False, verbose=verbose, geo_reference=geo) #Initial time and memory t0 = time.time() #m0 = None on windows m0 = mem_usage() # Apply the geo_ref to the points, so they are relative # Pass in the geo_ref geospatial = Geospatial_data(points_dict['points'], points_dict['point_attributes'], geo_reference=geo) del points_dict if is_fit is True: if use_file_type == None: points = geospatial filename = None else: #FIXME (DSG) check that the type fileName = tempfile.mktemp("." + use_file_type) geospatial.export_points_file(fileName, absolute=True) points = None filename = fileName if run_profile is True: s = """domain.set_quantity('elevation',points,filename=filename,use_cache=False)""" pobject = profile.Profile() presult = pobject.runctx(s, vars(sys.modules[__name__]), vars()) prof_file = tempfile.mktemp(".prof") presult.dump_stats(prof_file) # # Let process these results S = pstats.Stats(prof_file) saveout = sys.stdout pfile = open(profile_file, "w") sys.stdout = pfile s = S.sort_stats('cumulative').print_stats(60) sys.stdout = saveout pfile.close() os.remove(prof_file) else: domain.set_quantity('elevation',points,filename=filename, use_cache=False, verbose=verbose) if not use_file_type == None: os.remove(fileName) else: # run an interploate problem. if run_profile: # pass in the geospatial points # and the mesh origin s="""benchmark_interpolate(mesh_dict['vertices'],mesh_dict['vertex_attributes'],mesh_dict['triangles'],geospatial,max_points_per_cell=max_points_per_cell,mesh_origin=geo)""" pobject = profile.Profile() presult = pobject.runctx(s, vars(sys.modules[__name__]), vars()) prof_file = tempfile.mktemp(".prof") presult.dump_stats(prof_file) # # Let process these results S = pstats.Stats(prof_file) saveout = sys.stdout pfile = open(profile_file, "w") sys.stdout = pfile s = S.sort_stats('cumulative').print_stats(60) sys.stdout = saveout pfile.close() os.remove(prof_file) else: # pass in the geospatial points benchmark_interpolate(mesh_dict['vertices'], mesh_dict['vertex_attributes'], mesh_dict['triangles'], geospatial, mesh_origin=geo, max_points_per_cell=max_points_per_cell, verbose=verbose) time_taken_sec = (time.time()-t0) m1 = mem_usage() if m0 is None or m1 is None: memory_used = None else: memory_used = (m1 - m0) #print 'That took %.2f seconds' %time_taken_sec # return the times spent in first cell searching and # backing up. #search_one_cell_time, search_more_cells_time = search_times() #reset_search_times() #print "bench - build_quadtree_time", get_build_quadtree_time() return time_taken_sec, memory_used, len(mesh_dict['triangles']), \ get_build_quadtree_time()
def test_get_flow_through_cross_section_stored_uniquely(self): """test_get_flow_through_cross_section_stored_uniquely(self): Test that the total flow through a cross section can be correctly obtained from an sww file. This test creates a flat bed with a known flow through it and tests that the function correctly returns the expected flow. The specifics are u = 2 m/s h = 1 m w = 3 m (width of channel) q = u*h*w = 6 m^3/s """ import time, os from anuga.file.netcdf import NetCDFFile # Setup #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create basic mesh (20m x 3m) width = 3 length = 20 t_end = 3 points, vertices, boundary = rectangular(length, width, length, width) # Create shallow water domain domain = Domain(points, vertices, boundary) domain.default_order = 2 domain.set_minimum_storable_height(0.01) domain.set_name('flowtest_uniquely') swwfile = domain.get_name() + '.sww' domain.set_store_vertices_uniquely() domain.set_datadir('.') domain.format = 'sww' domain.smooth = True h = 1.0 u = 2.0 uh = u*h Br = Reflective_boundary(domain) # Side walls Bd = Dirichlet_boundary([h, uh, 0]) # 2 m/s across the 3 m inlet: domain.set_quantity('elevation', 0.0) domain.set_quantity('stage', h) domain.set_quantity('xmomentum', uh) domain.set_boundary( {'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime = t_end): pass # Check that momentum is as it should be in the interior I = [[0, width/2.], [length/2., width/2.], [length, width/2.]] f = file_function(swwfile, quantities=['stage', 'xmomentum', 'ymomentum'], interpolation_points=I, verbose=False) for t in range(t_end+1): for i in range(3): assert num.allclose(f(t, i), [1, 2, 0], atol=1.0e-6) # Check flows through the middle for i in range(5): x = length/2. + i*0.23674563 # Arbitrary cross_section = [[x, 0], [x, width]] time, Q = get_flow_through_cross_section(swwfile, cross_section, verbose=False) assert num.allclose(Q, uh*width) # Try the same with partial lines x = length/2. for i in range(5): start_point = [length/2., i*width/5.] #print start_point cross_section = [start_point, [length/2., width]] time, Q = get_flow_through_cross_section(swwfile, cross_section, verbose=False) #print i, Q, (width-start_point[1]) assert num.allclose(Q, uh*(width-start_point[1])) # Verify no flow when line is parallel to flow cross_section = [[length/2.-10, width/2.], [length/2.+10, width/2.]] time, Q = get_flow_through_cross_section(swwfile, cross_section, verbose=False) #print i, Q assert num.allclose(Q, 0, atol=1.0e-5) # Try with lines on an angle (all flow still runs through here) cross_section = [[length/2., 0], [length/2.+width, width]] time, Q = get_flow_through_cross_section(swwfile, cross_section, verbose=False) assert num.allclose(Q, uh*width)
def test_get_energy_through_cross_section(self): """test_get_energy_through_cross_section(self): Test that the specific and total energy through a cross section can be correctly obtained from an sww file. This test creates a flat bed with a known flow through it and tests that the function correctly returns the expected energies. The specifics are u = 2 m/s h = 1 m w = 3 m (width of channel) q = u*h*w = 6 m^3/s Es = h + 0.5*v*v/g # Specific energy head [m] Et = w + 0.5*v*v/g # Total energy head [m] This test uses georeferencing """ import time, os from anuga.file.netcdf import NetCDFFile # Setup #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create basic mesh (20m x 3m) width = 3 length = 20 t_end = 1 points, vertices, boundary = rectangular(length, width, length, width) # Create shallow water domain domain = Domain(points, vertices, boundary, geo_reference = Geo_reference(56,308500,6189000)) domain.default_order = 2 domain.set_minimum_storable_height(0.01) domain.set_name('flowtest') swwfile = domain.get_name() + '.sww' domain.set_datadir('.') domain.format = 'sww' domain.smooth = True e = -1.0 w = 1.0 h = w-e u = 2.0 uh = u*h Br = Reflective_boundary(domain) # Side walls Bd = Dirichlet_boundary([w, uh, 0]) # 2 m/s across the 3 m inlet: domain.set_quantity('elevation', e) domain.set_quantity('stage', w) domain.set_quantity('xmomentum', uh) domain.set_boundary( {'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime = t_end): pass # Check that momentum is as it should be in the interior I = [[0, width/2.], [length/2., width/2.], [length, width/2.]] I = domain.geo_reference.get_absolute(I) f = file_function(swwfile, quantities=['stage', 'xmomentum', 'ymomentum'], interpolation_points=I, verbose=False) for t in range(t_end+1): for i in range(3): #print i, t, f(t, i) assert num.allclose(f(t, i), [w, uh, 0], atol=1.0e-6) # Check energies through the middle for i in range(5): x = length/2. + i*0.23674563 # Arbitrary cross_section = [[x, 0], [x, width]] cross_section = domain.geo_reference.get_absolute(cross_section) time, Es = get_energy_through_cross_section(swwfile, cross_section, kind='specific', verbose=False) assert num.allclose(Es, h + 0.5*u*u/g) time, Et = get_energy_through_cross_section(swwfile, cross_section, kind='total', verbose=False) assert num.allclose(Et, w + 0.5*u*u/g)
def test_region_tags(self): """get values based on triangle lists.""" #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) domain.build_tagged_elements_dictionary({ 'bottom': [0, 1], 'top': [4, 5], 'all': [0, 1, 2, 3, 4, 5] }) #Set friction manning = 0.07 domain.set_quantity('friction', manning) a = Set_tag_region('bottom', 'friction', 0.09) b = Set_tag_region('top', 'friction', 1.0) domain.set_tag_region([a, b]) expected = [[0.09, 0.09, 0.09], [0.09, 0.09, 0.09], [0.07, 0.07, 0.07], [0.07, 0.07, 0.07], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]] msg = ( "\ndomain.quantities['friction']=%s\nexpected value=%s" % (str(domain.quantities['friction'].get_values()), str(expected))) assert num.allclose(domain.quantities['friction'].get_values(), expected), msg #c = Add_Value_To_region('all', 'friction', 10.0) domain.set_tag_region(Add_value_to_region('all', 'friction', 10.0)) #print domain.quantities['friction'].get_values() assert num.allclose(domain.quantities['friction'].get_values(), [[10.09, 10.09, 10.09], [10.09, 10.09, 10.09], [10.07, 10.07, 10.07], [10.07, 10.07, 10.07], [11.0, 11.0, 11.0], [11.0, 11.0, 11.0]]) # trying a function domain.set_tag_region(Set_tag_region('top', 'friction', add_x_y)) #print domain.quantities['friction'].get_values() assert num.allclose(domain.quantities['friction'].get_values(), [[10.09, 10.09, 10.09], [10.09, 10.09, 10.09], [10.07, 10.07, 10.07], [10.07, 10.07, 10.07], [5. / 3, 2.0, 2. / 3], [1.0, 2. / 3, 2.0]]) domain.set_quantity('elevation', 10.0) domain.set_quantity('stage', 10.0) domain.set_tag_region( Add_value_to_region('top', 'stage', 1.0, initial_quantity='elevation')) #print domain.quantities['stage'].get_values() assert num.allclose( domain.quantities['stage'].get_values(), [[10., 10., 10.], [10., 10., 10.], [10., 10., 10.], [10., 10., 10.], [11.0, 11.0, 11.0], [11.0, 11.0, 11.0]]) domain.set_quantity('elevation', 10.0) domain.set_quantity('stage', give_me_23) #this works as well, (is cleaner, but doesn't work for regions) #domain.set_quantity('stage', # domain.quantities['stage'].vertex_values+ \ # domain.quantities['elevation'].vertex_values) domain.set_tag_region(Add_quantities('top', 'elevation', 'stage')) #print domain.quantities['stage'].get_values() assert num.allclose( domain.quantities['elevation'].get_values(), [[10., 10., 10.], [10., 10., 10.], [10., 10., 10.], [10., 10., 10.], [33., 33.0, 33.], [33.0, 33., 33.]])
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_sww2domain1(self): ################################################ #Create a test domain, and evolve and save it. ################################################ #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular #Create basic mesh yiel=0.01 points, vertices, boundary = rectangular(10,10) #print "=============== boundary rect =======================" #print boundary #Create shallow water domain domain = Domain(points, vertices, boundary) domain.geo_reference = Geo_reference(56,11,11) domain.smooth = False domain.store = True domain.set_name('bedslope') domain.default_order=2 #Bed-slope and friction domain.set_quantity('elevation', lambda x,y: -x/3) domain.set_quantity('friction', 0.1) # Boundary conditions from math import sin, pi Br = Reflective_boundary(domain) Bt = Transmissive_boundary(domain) Bd = Dirichlet_boundary([0.2,0.,0.]) Bw = Time_boundary(domain=domain,function=lambda t: [(0.1*sin(t*2*pi)), 0.0, 0.0]) #domain.set_boundary({'left': Bd, 'right': Br, 'top': Br, 'bottom': Br}) domain.set_boundary({'left': Bd, 'right': Bd, 'top': Bd, 'bottom': Bd}) domain.quantities_to_be_stored['xmomentum'] = 2 domain.quantities_to_be_stored['ymomentum'] = 2 #Initial condition h = 0.05 elevation = domain.quantities['elevation'].vertex_values domain.set_quantity('stage', elevation + h) domain.check_integrity() #Evolution #domain.tight_slope_limiters = 1 for t in domain.evolve(yieldstep = yiel, finaltime = 0.05): #domain.write_time() pass #print boundary filename = domain.datadir + os.sep + domain.get_name() + '.sww' domain2 = load_sww_as_domain(filename, None, fail_if_NaN=False, verbose=self.verbose) # Unfortunately we loss the boundaries top, bottom, left and right, # they are now all lumped into "exterior" #print "=============== boundary domain2 =======================" #print domain2.boundary #print domain2.get_boundary_tags() #points, vertices, boundary = rectangular(15,15) #domain2.boundary = boundary ################### ##NOW TEST IT!!! ################### os.remove(filename) bits = ['vertex_coordinates'] for quantity in ['stage']: bits.append('get_quantity("%s").get_integral()' % quantity) bits.append('get_quantity("%s").get_values()' % quantity) for bit in bits: #print 'testing that domain.'+bit+' has been restored' #print bit #print 'done' #print eval('domain.'+bit) #print eval('domain2.'+bit) assert num.allclose(eval('domain.'+bit),eval('domain2.'+bit)) ###################################### #Now evolve them both, just to be sure ######################################x from time import sleep final = .1 domain.set_quantity('friction', 0.1) domain.store = False domain.set_boundary({'exterior': Bd, 'left' : Bd, 'right': Bd, 'top': Bd, 'bottom': Bd}) for t in domain.evolve(yieldstep = yiel, finaltime = final): #domain.write_time() pass #BUT since domain2 gets time hacked back to 0: # Load_sww_as_domain sets starttime for domain2 to the last time in the # sww file (which is the value of time+domain.starttime final2 = final - domain2.get_starttime() domain2.smooth = False domain2.store = False domain2.default_order=2 domain2.set_quantity('friction', 0.1) #Bed-slope and friction # Boundary conditions Bd2=Dirichlet_boundary([0.2,0.,0.]) domain2.boundary = domain.boundary #print 'domain2.boundary' #print domain2.boundary domain2.set_boundary({'exterior': Bd, 'left' : Bd, 'right': Bd, 'top': Bd, 'bottom': Bd}) #domain2.set_boundary({'exterior': Bd}) domain2.check_integrity() for t in domain2.evolve(yieldstep = yiel, finaltime = final2): #domain2.write_time() pass ################### ##NOW TEST IT!!! ################## bits = ['vertex_coordinates'] for quantity in ['elevation','stage', 'ymomentum','xmomentum']: bits.append('get_quantity("%s").get_integral()' %quantity) bits.append('get_quantity("%s").get_values()' %quantity) #print bits for bit in bits: #print bit #print eval('domain.'+bit) #print eval('domain2.'+bit) #print eval('domain.'+bit+'-domain2.'+bit) msg = 'Values in the two domains are different for ' + bit assert num.allclose(eval('domain.'+bit),eval('domain2.'+bit), rtol=5.e-2, atol=5.e-2), msg
def test_file_boundary_stsIV_sinewave_ordering(self): """test_file_boundary_stsIV_sinewave_ordering(self): Read correct points from ordering file and apply sts to boundary This one uses a sine wave and compares to time boundary """ lat_long_points=[[6.01, 97.0], [6.02, 97.0], [6.05, 96.9], [6.0, 97.0]] bounding_polygon=[[6.0, 97.0], [6.01, 97.0], [6.02,97.0], \ [6.02,97.02], [6.00,97.02]] tide = 0.35 time_step_count = 50 time_step = 0.1 times_ref = num.arange(0, time_step_count*time_step, time_step) n=len(lat_long_points) first_tstep=num.ones(n,num.int) last_tstep=(time_step_count)*num.ones(n,num.int) gauge_depth=20*num.ones(n,num.float) ha1=num.ones((n,time_step_count),num.float) ua1=3.*num.ones((n,time_step_count),num.float) va1=2.*num.ones((n,time_step_count),num.float) for i in range(n): ha1[i]=num.sin(times_ref) base_name, files = self.write_mux2(lat_long_points, time_step_count, time_step, first_tstep, last_tstep, depth=gauge_depth, ha=ha1, ua=ua1, va=va1) # Write order file file_handle, order_base_name = tempfile.mkstemp("") os.close(file_handle) os.remove(order_base_name) d="," order_file=order_base_name+'order.txt' fid=open(order_file,'w') # Write Header header='index, longitude, latitude\n' fid.write(header) indices=[3,0,1] for i in indices: line=str(i)+d+str(lat_long_points[i][1])+d+\ str(lat_long_points[i][0])+"\n" fid.write(line) fid.close() sts_file=base_name urs2sts(base_name, basename_out=sts_file, ordering_filename=order_file, mean_stage=tide, verbose=False) self.delete_mux(files) # Now read the sts file and check that values have been stored correctly. fid = NetCDFFile(sts_file + '.sts') # Check the time vector times = fid.variables['time'][:] #print times # Check sts quantities stage = fid.variables['stage'][:] xmomentum = fid.variables['xmomentum'][:] ymomentum = fid.variables['ymomentum'][:] elevation = fid.variables['elevation'][:] # Create beginnings of boundary polygon based on sts_boundary boundary_polygon = create_sts_boundary(base_name) os.remove(order_file) # Append the remaining part of the boundary polygon to be defined by # the user bounding_polygon_utm=[] for point in bounding_polygon: zone,easting,northing=redfearn(point[0],point[1]) bounding_polygon_utm.append([easting,northing]) boundary_polygon.append(bounding_polygon_utm[3]) boundary_polygon.append(bounding_polygon_utm[4]) #print 'boundary_polygon', boundary_polygon plot=False if plot: from pylab import plot,show,axis boundary_polygon=ensure_numeric(boundary_polygon) bounding_polygon_utm=ensure_numeric(bounding_polygon_utm) #plot(lat_long_points[:,0],lat_long_points[:,1],'o') plot(boundary_polygon[:,0], boundary_polygon[:,1]) plot(bounding_polygon_utm[:,0],bounding_polygon_utm[:,1]) show() assert num.allclose(bounding_polygon_utm,boundary_polygon) extent_res=1000000 meshname = 'urs_test_mesh' + '.tsh' interior_regions=None boundary_tags={'ocean': [0,1], 'otherocean': [2,3,4]} # have to change boundary tags from last example because now bounding # polygon starts in different place. create_mesh_from_regions(boundary_polygon, boundary_tags=boundary_tags, maximum_triangle_area=extent_res, filename=meshname, interior_regions=interior_regions, verbose=False) domain_fbound = Domain(meshname) domain_fbound.set_quantity('stage', tide) Bf = File_boundary(sts_file+'.sts', domain_fbound, boundary_polygon=boundary_polygon) Br = Reflective_boundary(domain_fbound) domain_fbound.set_boundary({'ocean': Bf,'otherocean': Br}) finaltime=time_step*(time_step_count-1) yieldstep=time_step temp_fbound=num.zeros(int(finaltime/yieldstep)+1,num.float) for i, t in enumerate(domain_fbound.evolve(yieldstep=yieldstep, finaltime=finaltime, skip_initial_step=False)): temp_fbound[i]=domain_fbound.quantities['stage'].centroid_values[2] domain_time = Domain(meshname) domain_time.set_quantity('stage', tide) Br = Reflective_boundary(domain_time) Bw = Time_boundary(domain=domain_time, function=lambda t: [num.sin(t)+tide,3.*(20.+num.sin(t)+tide),2.*(20.+num.sin(t)+tide)]) domain_time.set_boundary({'ocean': Bw,'otherocean': Br}) temp_time=num.zeros(int(finaltime/yieldstep)+1,num.float) domain_time.set_starttime(domain_fbound.get_starttime()) for i, t in enumerate(domain_time.evolve(yieldstep=yieldstep, finaltime=finaltime, skip_initial_step=False)): temp_time[i]=domain_time.quantities['stage'].centroid_values[2] assert num.allclose(temp_fbound, temp_time) assert num.allclose(domain_fbound.quantities['stage'].vertex_values, domain_time.quantities['stage'].vertex_values) assert num.allclose(domain_fbound.quantities['xmomentum'].vertex_values, domain_time.quantities['xmomentum'].vertex_values) assert num.allclose(domain_fbound.quantities['ymomentum'].vertex_values, domain_time.quantities['ymomentum'].vertex_values) try: os.remove(sts_file+'.sts') except: # Windoze can't remove this file for some reason pass os.remove(meshname)
def test_get_mesh_and_quantities_from_unique_vertices_DE0_sww_file(self): """test_get_mesh_and_quantities_from_unique_vertices_sww_file(self): """ # Generate a test sww file with non trivial georeference import time, os # Setup #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create basic mesh (100m x 5m) width = 5 length = 50 t_end = 10 points, vertices, boundary = rectangular(10, 1, length, width) # Create shallow water domain domain = Domain(points, vertices, boundary, geo_reference = Geo_reference(56,308500,6189000)) domain.set_name('test_get_mesh_and_quantities_from_unique_vertices_sww_file') swwfile = domain.get_name() + '.sww' domain.set_datadir('.') domain.set_flow_algorithm('DE0') domain.set_store_vertices_uniquely() Br = Reflective_boundary(domain) # Side walls Bd = Dirichlet_boundary([1, 0, 0]) # inflow domain.set_boundary( {'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime = t_end): pass # Read it # Get mesh and quantities from sww file X = get_mesh_and_quantities_from_file(swwfile, quantities=['elevation', 'stage', 'xmomentum', 'ymomentum'], verbose=False) mesh, quantities, time = X #print quantities #print time dhash = domain.get_nodes()[:,0]*10+domain.get_nodes()[:,1] mhash = mesh.nodes[:,0]*10+mesh.nodes[:,1] #print 'd_nodes',len(dhash) #print 'm_nodes',len(mhash) di = num.argsort(dhash) mi = num.argsort(mhash) minv = num.argsort(mi) dinv = num.argsort(di) #print 'd_tri',len(domain.get_triangles()) #print 'm_tri',len(mesh.triangles) # Check that mesh has been recovered # triangle order should be ok assert num.allclose(mesh.nodes[mi,:],domain.get_nodes()[di,:]) assert num.alltrue(minv[mesh.triangles] == dinv[domain.get_triangles()]) # Check that time has been recovered assert num.allclose(time, range(t_end+1)) z=domain.get_quantity('elevation').get_values(location='vertices').flatten() assert num.allclose(quantities['elevation'], z) for q in ['stage', 'xmomentum', 'ymomentum']: # Get quantity at last timestep q_ref=domain.get_quantity(q).get_values(location='vertices').flatten() #print q,quantities[q] q_sww=quantities[q][-1,:] msg = 'Quantity %s failed to be recovered' %q assert num.allclose(q_ref, q_sww, atol=1.0e-6), msg
def setUp(self): #print "****set up****" # Create an sww file # Set up an sww that has a geo ref. # have it cover an area in Australia. 'gong maybe #Don't have many triangles though! #Site Name: GDA-MGA: (UTM with GRS80 ellipsoid) #Zone: 56 #Easting: 222908.705 Northing: 6233785.284 #Latitude: -34 0 ' 0.00000 '' Longitude: 150 0 ' 0.00000 '' #Grid Convergence: -1 40 ' 43.13 '' Point Scale: 1.00054660 #geo-ref #Zone: 56 #Easting: 220000 Northing: 6230000 #have a big area covered. mesh_file = tempfile.mktemp(".tsh") points_lat_long = [[-33,152],[-35,152],[-35,150],[-33,150]] spat = Geospatial_data(data_points=points_lat_long, points_are_lats_longs=True) points_ab = spat.get_data_points( absolute = True) geo = Geo_reference(56,400000,6000000) spat.set_geo_reference(geo) m = Mesh() m.add_vertices(spat) m.auto_segment() m.generate_mesh(verbose=False) m.export_mesh_file(mesh_file) #Create shallow water domain domain = Domain(mesh_file) os.remove(mesh_file) domain.default_order=2 #Set some field values #domain.set_quantity('stage', 1.0) domain.set_quantity('elevation', -0.5) domain.set_quantity('friction', 0.03) ###################### # Boundary conditions B = Transmissive_boundary(domain) domain.set_boundary( {'exterior': B}) ###################### #Initial condition - with jumps bed = domain.quantities['elevation'].vertex_values stage = num.zeros(bed.shape, num.float) h = 0.3 for i in range(stage.shape[0]): if i % 2 == 0: stage[i,:] = bed[i,:] + h else: stage[i,:] = bed[i,:] domain.set_quantity('stage', stage) domain.set_quantity('xmomentum', stage*22.0) domain.set_quantity('ymomentum', stage*55.0) domain.distribute_to_vertices_and_edges() self.domain = domain C = domain.get_vertex_coordinates() self.X = C[:,0:6:2].copy() self.Y = C[:,1:6:2].copy() self.F = bed #sww_file = tempfile.mktemp("") self.domain.set_name('tid_P0') self.domain.format = 'sww' self.domain.smooth = True self.domain.reduction = mean sww = SWW_file(self.domain) sww.store_connectivity() sww.store_timestep() self.domain.time = 2. sww.store_timestep() self.sww = sww # so it can be deleted #Create another sww file mesh_file = tempfile.mktemp(".tsh") points_lat_long = [[-35,152],[-36,152],[-36,150],[-35,150]] spat = Geospatial_data(data_points=points_lat_long, points_are_lats_longs=True) points_ab = spat.get_data_points( absolute = True) geo = Geo_reference(56,400000,6000000) spat.set_geo_reference(geo) m = Mesh() m.add_vertices(spat) m.auto_segment() m.generate_mesh(verbose=False) m.export_mesh_file(mesh_file) #Create shallow water domain domain = Domain(mesh_file) os.remove(mesh_file) domain.default_order=2 #Set some field values #domain.set_quantity('stage', 1.0) domain.set_quantity('elevation', -40) domain.set_quantity('friction', 0.03) ###################### # Boundary conditions B = Transmissive_boundary(domain) domain.set_boundary( {'exterior': B}) ###################### #Initial condition - with jumps bed = domain.quantities['elevation'].vertex_values stage = num.zeros(bed.shape, num.float) h = 30. for i in range(stage.shape[0]): if i % 2 == 0: stage[i,:] = bed[i,:] + h else: stage[i,:] = bed[i,:] domain.set_quantity('stage', stage) domain.set_quantity('xmomentum', stage*22.0) domain.set_quantity('ymomentum', stage*55.0) domain.distribute_to_vertices_and_edges() self.domain2 = domain C = domain.get_vertex_coordinates() self.X2 = C[:,0:6:2].copy() self.Y2 = C[:,1:6:2].copy() self.F2 = bed #sww_file = tempfile.mktemp("") domain.set_name('tid_P1') domain.format = 'sww' domain.smooth = True domain.reduction = mean sww = SWW_file(domain) sww.store_connectivity() sww.store_timestep() domain.time = 2. sww.store_timestep() self.swwII = sww # so it can be deleted # print "sww.filename", sww.filename #Create a csv file self.csv_file = tempfile.mktemp(".csv") fd = open(self.csv_file,'wb') writer = csv.writer(fd) writer.writerow(['LONGITUDE','LATITUDE',STR_VALUE_LABEL,CONT_VALUE_LABEL,'ROOF_TYPE',WALL_TYPE_LABEL, SHORE_DIST_LABEL]) writer.writerow(['151.5','-34','199770','130000','Metal','Timber',20.]) writer.writerow(['151','-34.5','150000','76000','Metal','Double Brick',200.]) writer.writerow(['151','-34.25','150000','76000','Metal','Brick Veneer',200.]) fd.close() #Create a csv file self.csv_fileII = tempfile.mktemp(".csv") fd = open(self.csv_fileII,'wb') writer = csv.writer(fd) writer.writerow(['LONGITUDE','LATITUDE',STR_VALUE_LABEL,CONT_VALUE_LABEL,'ROOF_TYPE',WALL_TYPE_LABEL, SHORE_DIST_LABEL]) writer.writerow(['151.5','-34','199770','130000','Metal','Timber',20.]) writer.writerow(['151','-34.5','150000','76000','Metal','Double Brick',200.]) writer.writerow(['151','-34.25','150000','76000','Metal','Brick Veneer',200.]) fd.close()
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_region_tags(self): """get values based on triangle lists.""" #Create basic mesh points, vertices, boundary = rectangular(1, 3) #Create shallow water domain domain = Domain(points, vertices, boundary) domain.build_tagged_elements_dictionary({'bottom': [0,1], 'top': [4,5], 'all': [0,1,2,3,4,5]}) #Set friction manning = 0.07 domain.set_quantity('friction', manning) a = Set_tag_region('bottom', 'friction', 0.09) b = Set_tag_region('top', 'friction', 1.0) domain.set_tag_region([a, b]) expected = [[ 0.09, 0.09, 0.09], [ 0.09, 0.09, 0.09], [ 0.07, 0.07, 0.07], [ 0.07, 0.07, 0.07], [ 1.0, 1.0, 1.0], [ 1.0, 1.0, 1.0]] msg = ("\ndomain.quantities['friction']=%s\nexpected value=%s" % (str(domain.quantities['friction'].get_values()), str(expected))) assert num.allclose(domain.quantities['friction'].get_values(), expected), msg #c = Add_Value_To_region('all', 'friction', 10.0) domain.set_tag_region(Add_value_to_region('all', 'friction', 10.0)) #print domain.quantities['friction'].get_values() assert num.allclose(domain.quantities['friction'].get_values(), [[ 10.09, 10.09, 10.09], [ 10.09, 10.09, 10.09], [ 10.07, 10.07, 10.07], [ 10.07, 10.07, 10.07], [ 11.0, 11.0, 11.0], [ 11.0, 11.0, 11.0]]) # trying a function domain.set_tag_region(Set_tag_region('top', 'friction', add_x_y)) #print domain.quantities['friction'].get_values() assert num.allclose(domain.quantities['friction'].get_values(), [[ 10.09, 10.09, 10.09], [ 10.09, 10.09, 10.09], [ 10.07, 10.07, 10.07], [ 10.07, 10.07, 10.07], [ 5./3, 2.0, 2./3], [ 1.0, 2./3, 2.0]]) domain.set_quantity('elevation', 10.0) domain.set_quantity('stage', 10.0) domain.set_tag_region(Add_value_to_region('top', 'stage', 1.0,initial_quantity='elevation')) #print domain.quantities['stage'].get_values() assert num.allclose(domain.quantities['stage'].get_values(), [[ 10., 10., 10.], [ 10., 10., 10.], [ 10., 10., 10.], [ 10., 10., 10.], [ 11.0, 11.0, 11.0], [ 11.0, 11.0, 11.0]]) domain.set_quantity('elevation', 10.0) domain.set_quantity('stage', give_me_23) #this works as well, (is cleaner, but doesn't work for regions) #domain.set_quantity('stage', # domain.quantities['stage'].vertex_values+ \ # domain.quantities['elevation'].vertex_values) domain.set_tag_region(Add_quantities('top', 'elevation','stage')) #print domain.quantities['stage'].get_values() assert num.allclose(domain.quantities['elevation'].get_values(), [[ 10., 10., 10.], [ 10., 10., 10.], [ 10., 10., 10.], [ 10., 10., 10.], [ 33., 33.0, 33.], [ 33.0, 33., 33.]])
#------------------------------------------------------------------------------ # Setup computational domain #------------------------------------------------------------------------------ print 'Setting up domain' length = 200. #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_WIDE_BRIDGE') # Output name #domain.set_default_order(2) #omain.H0 = 0.01 #domain.tight_slope_limiters = 1 domain.set_flow_algorithm('2_0') print 'Size', len(domain) #------------------------------------------------------------------------------ # Setup initial conditions #------------------------------------------------------------------------------ def topography(x, y): """Set up a weir
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_sww2pts_centroids_de0(self): """Test that sww information can be converted correctly to pts data at specified coordinates - in this case, the centroids. """ import time, os from anuga.file.netcdf import NetCDFFile # Used for points that lie outside mesh NODATA_value = 1758323 # Setup from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create shallow water domain domain = Domain(*rectangular(2, 2)) B = Transmissive_boundary(domain) domain.set_boundary({'left': B, 'right': B, 'top': B, 'bottom': B}) domain.set_name('datatest_de0') ptsfile = domain.get_name() + '_elevation.pts' swwfile = domain.get_name() + '.sww' domain.set_datadir('.') domain.format = 'sww' domain.set_quantity('elevation', lambda x, y: -x - y) domain.geo_reference = Geo_reference(56, 308500, 6189000) sww = SWW_file(domain) sww.store_connectivity() sww.store_timestep() #self.domain.tight_slope_limiters = 1 domain.evolve_to_end(finaltime=0.01) sww.store_timestep() # Check contents in NetCDF fid = NetCDFFile(sww.filename, netcdf_mode_r) # Get the variables x = fid.variables['x'][:] y = fid.variables['y'][:] elevation = fid.variables['elevation'][:] time = fid.variables['time'][:] stage = fid.variables['stage'][:] volumes = fid.variables['volumes'][:] # Invoke interpolation for vertex points points = num.concatenate((x[:, num.newaxis], y[:, num.newaxis]), axis=1) points = num.ascontiguousarray(points) sww2pts(domain.get_name() + '.sww', quantity='elevation', data_points=points, NODATA_value=NODATA_value) ref_point_values = elevation point_values = Geospatial_data(ptsfile).get_attributes() #print 'P', point_values #print 'Ref', ref_point_values assert num.allclose(point_values, ref_point_values) # Invoke interpolation for centroids points = domain.get_centroid_coordinates() #print points sww2pts(domain.get_name() + '.sww', quantity='elevation', data_points=points, NODATA_value=NODATA_value) #ref_point_values = [-0.5, -0.5, -1, -1, -1, -1, -1.5, -1.5] #At centroids ref_point_values = [ -0.77777777, -0.77777777, -0.99999998, -0.99999998, -0.99999998, -0.99999998, -1.22222221, -1.22222221 ] point_values = Geospatial_data(ptsfile).get_attributes() #print 'P', point_values #print 'Ref', ref_point_values assert num.allclose(point_values, ref_point_values) fid.close() #Cleanup os.remove(sww.filename) os.remove(ptsfile)
def test_get_flow_through_cross_section_with_geo(self): """test_get_flow_through_cross_section(self): Test that the total flow through a cross section can be correctly obtained at run-time from the ANUGA domain. This test creates a flat bed with a known flow through it and tests that the function correctly returns the expected flow. The specifics are e = -1 m u = 2 m/s h = 2 m w = 3 m (width of channel) q = u*h*w = 12 m^3/s This run tries it with georeferencing and with elevation = -1 """ # Create basic mesh (20m x 3m) width = 3 length = 20 t_end = 1 points, vertices, boundary = rectangular(length, width, length, width) # Create shallow water domain domain = Domain(points, vertices, boundary, geo_reference=Geo_reference(56, 308500, 6189000)) domain.default_order = 2 domain.set_quantities_to_be_stored(None) e = -1.0 w = 1.0 h = w-e u = 2.0 uh = u*h Br = Reflective_boundary(domain) # Side walls Bd = Dirichlet_boundary([w, uh, 0]) # 2 m/s across the 3 m inlet: # Initial conditions domain.set_quantity('elevation', e) domain.set_quantity('stage', w) domain.set_quantity('xmomentum', uh) domain.set_boundary({'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) # Interpolation points down the middle I = [[0, width/2.], [length/2., width/2.], [length, width/2.]] interpolation_points = domain.geo_reference.get_absolute(I) for t in domain.evolve(yieldstep=0.1, finaltime=0.5): # Shortcuts to quantites stage = domain.get_quantity('stage') xmomentum = domain.get_quantity('xmomentum') ymomentum = domain.get_quantity('ymomentum') # Check that quantities are they should be in the interior w_t = stage.get_values(interpolation_points) uh_t = xmomentum.get_values(interpolation_points) vh_t = ymomentum.get_values(interpolation_points) assert num.allclose(w_t, w) assert num.allclose(uh_t, uh) assert num.allclose(vh_t, 0.0, atol=1.0e-6) # Check flows through the middle for i in range(5): x = length/2. + i*0.23674563 # Arbitrary cross_section = [[x, 0], [x, width]] cross_section = domain.geo_reference.get_absolute(cross_section) Q = domain.get_flow_through_cross_section(cross_section, verbose=False) assert num.allclose(Q, uh*width) import cPickle cPickle.dump(domain, open('domain_pickle.pickle', 'w')) domain_restored = cPickle.load(open('domain_pickle.pickle')) for t in domain_restored.evolve(yieldstep=0.1, finaltime=1.0): # Shortcuts to quantites stage = domain_restored.get_quantity('stage') xmomentum = domain_restored.get_quantity('xmomentum') ymomentum = domain_restored.get_quantity('ymomentum') # Check that quantities are they should be in the interior w_t = stage.get_values(interpolation_points) uh_t = xmomentum.get_values(interpolation_points) vh_t = ymomentum.get_values(interpolation_points) assert num.allclose(w_t, w) assert num.allclose(uh_t, uh) assert num.allclose(vh_t, 0.0, atol=1.0e-6) # Check flows through the middle for i in range(5): x = length/2. + i*0.23674563 # Arbitrary cross_section = [[x, 0], [x, width]] cross_section = domain_restored.geo_reference.get_absolute(cross_section) Q = domain_restored.get_flow_through_cross_section(cross_section, verbose=False) assert num.allclose(Q, uh*width)
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_inundation_damage_list(self): # create mesh mesh_file = tempfile.mktemp(".tsh") points = [[0.0, 0.0], [6.0, 0.0], [6.0, 6.0], [0.0, 6.0]] m = Mesh() m.add_vertices(points) m.auto_segment() m.generate_mesh(verbose=False) m.export_mesh_file(mesh_file) # Create shallow water domain domain = Domain(mesh_file) os.remove(mesh_file) domain.default_order = 2 # Set some field values domain.set_quantity("elevation", elevation_function) domain.set_quantity("friction", 0.03) domain.set_quantity("xmomentum", 22.0) domain.set_quantity("ymomentum", 55.0) ###################### # Boundary conditions B = Transmissive_boundary(domain) domain.set_boundary({"exterior": B}) # This call mangles the stage values. domain.distribute_to_vertices_and_edges() domain.set_quantity("stage", 0.3) # sww_file = tempfile.mktemp("") domain.set_name("datatest" + str(time.time())) domain.format = "sww" domain.smooth = True domain.reduction = mean sww = SWW_file(domain) sww.store_connectivity() sww.store_timestep() domain.set_quantity("stage", -0.3) domain.time = 2.0 sww.store_timestep() # Create a csv file csv_file = tempfile.mktemp(".csv") fd = open(csv_file, "wb") writer = csv.writer(fd) writer.writerow(["x", "y", STR_VALUE_LABEL, CONT_VALUE_LABEL, "ROOF_TYPE", WALL_TYPE_LABEL, SHORE_DIST_LABEL]) writer.writerow([5.5, 0.5, "10", "130000", "Metal", "Timber", 20]) writer.writerow([4.5, 1.0, "150", "76000", "Metal", "Double Brick", 20]) writer.writerow([0.1, 1.5, "100", "76000", "Metal", "Brick Veneer", 300]) writer.writerow([6.1, 1.5, "100", "76000", "Metal", "Brick Veneer", 300]) fd.close() extension = ".csv" csv_fileII = tempfile.mktemp(extension) fd = open(csv_fileII, "wb") writer = csv.writer(fd) writer.writerow(["x", "y", STR_VALUE_LABEL, CONT_VALUE_LABEL, "ROOF_TYPE", WALL_TYPE_LABEL, SHORE_DIST_LABEL]) writer.writerow([5.5, 0.5, "10", "130000", "Metal", "Timber", 20]) writer.writerow([4.5, 1.0, "150", "76000", "Metal", "Double Brick", 20]) writer.writerow([0.1, 1.5, "100", "76000", "Metal", "Brick Veneer", 300]) writer.writerow([6.1, 1.5, "100", "76000", "Metal", "Brick Veneer", 300]) fd.close() sww_file = domain.get_name() + "." + domain.format # print "sww_file",sww_file marker = "_gosh" inundation_damage(sww_file, [csv_file, csv_fileII], exposure_file_out_marker=marker, verbose=False) # Test one file csv_handle = Exposure(csv_file[:-4] + marker + extension) struct_loss = csv_handle.get_column(EventDamageModel.STRUCT_LOSS_TITLE) # print "struct_loss",struct_loss struct_loss = [float(x) for x in struct_loss] # pprint(struct_loss) assert num.allclose(struct_loss, [10.0, 150.0, 66.55333347876866, 0.0]) depth = csv_handle.get_column(EventDamageModel.MAX_DEPTH_TITLE) # print "depth",depth depth = [float(x) for x in depth] assert num.allclose(depth, [3.000000011920929, 2.9166666785875957, 2.2666666785875957, -0.3]) # Test another file csv_handle = Exposure(csv_fileII[:-4] + marker + extension) struct_loss = csv_handle.get_column(EventDamageModel.STRUCT_LOSS_TITLE) # print "struct_loss",struct_loss struct_loss = [float(x) for x in struct_loss] # pprint(struct_loss) assert num.allclose(struct_loss, [10.0, 150.0, 66.553333478768664, 0.0]) depth = csv_handle.get_column(EventDamageModel.MAX_DEPTH_TITLE) # print "depth",depth depth = [float(x) for x in depth] assert num.allclose(depth, [3.000000011920929, 2.9166666785875957, 2.2666666785875957, -0.3]) os.remove(sww.filename) os.remove(csv_file) os.remove(csv_fileII)
def test_get_energy_through_cross_section(self): """test_get_energy_through_cross_section(self): Test that the specific and total energy through a cross section can be correctly obtained from an sww file. This test creates a flat bed with a known flow through it and tests that the function correctly returns the expected energies. The specifics are u = 2 m/s h = 1 m w = 3 m (width of channel) q = u*h*w = 6 m^3/s Es = h + 0.5*v*v/g # Specific energy head [m] Et = w + 0.5*v*v/g # Total energy head [m] This test uses georeferencing """ import time, os from anuga.file.netcdf import NetCDFFile # Setup #from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular # Create basic mesh (20m x 3m) width = 3 length = 20 t_end = 1 points, vertices, boundary = rectangular(length, width, length, width) # Create shallow water domain domain = Domain(points, vertices, boundary, geo_reference=Geo_reference(56, 308500, 6189000)) domain.default_order = 2 domain.set_minimum_storable_height(0.01) domain.set_name('flowtest') swwfile = domain.get_name() + '.sww' domain.set_datadir('.') domain.format = 'sww' domain.smooth = True e = -1.0 w = 1.0 h = w - e u = 2.0 uh = u * h Br = Reflective_boundary(domain) # Side walls Bd = Dirichlet_boundary([w, uh, 0]) # 2 m/s across the 3 m inlet: domain.set_quantity('elevation', e) domain.set_quantity('stage', w) domain.set_quantity('xmomentum', uh) domain.set_boundary({'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) for t in domain.evolve(yieldstep=1, finaltime=t_end): pass # Check that momentum is as it should be in the interior I = [[0, width / 2.], [length / 2., width / 2.], [length, width / 2.]] I = domain.geo_reference.get_absolute(I) f = file_function(swwfile, quantities=['stage', 'xmomentum', 'ymomentum'], interpolation_points=I, verbose=False) for t in range(t_end + 1): for i in range(3): #print i, t, f(t, i) assert num.allclose(f(t, i), [w, uh, 0], atol=1.0e-6) # Check energies through the middle for i in range(5): x = length / 2. + i * 0.23674563 # Arbitrary cross_section = [[x, 0], [x, width]] cross_section = domain.geo_reference.get_absolute(cross_section) time, Es = get_energy_through_cross_section(swwfile, cross_section, kind='specific', verbose=False) assert num.allclose(Es, h + 0.5 * u * u / g) time, Et = get_energy_through_cross_section(swwfile, cross_section, kind='total', verbose=False) assert num.allclose(Et, w + 0.5 * u * u / g)
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
#------------------------------------------------------------------------------ # 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 A culvert will connect either side
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 setUp(self): import time self.verbose = Test_File_Conversion.verbose # Create basic mesh points, vertices, boundary = rectangular(2, 2) # Create shallow water domain domain = Domain(points, vertices, boundary) domain.default_order = 2 # Set some field values domain.set_quantity('elevation', lambda x, y: -x) domain.set_quantity('friction', 0.03) ###################### # Boundary conditions B = Transmissive_boundary(domain) domain.set_boundary({'left': B, 'right': B, 'top': B, 'bottom': B}) ###################### #Initial condition - with jumps bed = domain.quantities['elevation'].vertex_values stage = num.zeros(bed.shape, num.float) h = 0.3 for i in range(stage.shape[0]): if i % 2 == 0: stage[i, :] = bed[i, :] + h else: stage[i, :] = bed[i, :] domain.set_quantity('stage', stage) domain.distribute_to_vertices_and_edges() self.initial_stage = copy.copy( domain.quantities['stage'].vertex_values) self.domain = domain C = domain.get_vertex_coordinates() self.X = C[:, 0:6:2].copy() self.Y = C[:, 1:6:2].copy() self.F = bed #Write A testfile (not realistic. Values aren't realistic) self.test_MOST_file = 'most_small' longitudes = [150.66667, 150.83334, 151., 151.16667] latitudes = [-34.5, -34.33333, -34.16667, -34] long_name = 'LON' lat_name = 'LAT' nx = 4 ny = 4 six = 6 for ext in ['_ha.nc', '_ua.nc', '_va.nc', '_e.nc']: fid = NetCDFFile(self.test_MOST_file + ext, netcdf_mode_w) fid.createDimension(long_name, nx) fid.createVariable(long_name, netcdf_float, (long_name, )) fid.variables[long_name].point_spacing = 'uneven' fid.variables[long_name].units = 'degrees_east' fid.variables[long_name][:] = longitudes fid.createDimension(lat_name, ny) fid.createVariable(lat_name, netcdf_float, (lat_name, )) fid.variables[lat_name].point_spacing = 'uneven' fid.variables[lat_name].units = 'degrees_north' fid.variables[lat_name][:] = latitudes fid.createDimension('TIME', six) fid.createVariable('TIME', netcdf_float, ('TIME', )) fid.variables['TIME'].point_spacing = 'uneven' fid.variables['TIME'].units = 'seconds' fid.variables['TIME'][:] = [0.0, 0.1, 0.6, 1.1, 1.6, 2.1] name = ext[1:3].upper() if name == 'E.': name = 'ELEVATION' fid.createVariable(name, netcdf_float, ('TIME', lat_name, long_name)) fid.variables[name].units = 'CENTIMETERS' fid.variables[name].missing_value = -1.e+034 fid.variables[name][:] = [ [[0.3400644, 0, -46.63519, -6.50198], [-0.1214216, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0.3400644, 2.291054e-005, -23.33335, -6.50198], [-0.1213987, 4.581959e-005, -1.594838e-007, 1.421085e-012], [2.291054e-005, 4.582107e-005, 4.581715e-005, 1.854517e-009], [0, 2.291054e-005, 2.291054e-005, 0]], [[0.3400644, 0.0001374632, -23.31503, -6.50198], [-0.1212842, 0.0002756907, 0.006325484, 1.380492e-006], [0.0001374632, 0.0002749264, 0.0002742863, 6.665601e-008], [0, 0.0001374632, 0.0001374632, 0]], [[0.3400644, 0.0002520159, -23.29672, -6.50198], [-0.1211696, 0.0005075303, 0.01264618, 6.208276e-006], [0.0002520159, 0.0005040318, 0.0005027961, 2.23865e-007], [0, 0.0002520159, 0.0002520159, 0]], [[0.3400644, 0.0003665686, -23.27842, -6.50198], [-0.1210551, 0.0007413362, 0.01896192, 1.447638e-005], [0.0003665686, 0.0007331371, 0.0007313463, 4.734126e-007], [0, 0.0003665686, 0.0003665686, 0]], [[0.3400644, 0.0004811212, -23.26012, -6.50198], [-0.1209405, 0.0009771062, 0.02527271, 2.617787e-005], [0.0004811212, 0.0009622425, 0.0009599366, 8.152277e-007], [0, 0.0004811212, 0.0004811212, 0]] ] fid.close()
def test_get_flow_through_cross_section_with_geo(self): """test_get_flow_through_cross_section(self): Test that the total flow through a cross section can be correctly obtained at run-time from the ANUGA domain. This test creates a flat bed with a known flow through it and tests that the function correctly returns the expected flow. The specifics are e = -1 m u = 2 m/s h = 2 m w = 3 m (width of channel) q = u*h*w = 12 m^3/s This run tries it with georeferencing and with elevation = -1 """ # Create basic mesh (20m x 3m) width = 3 length = 20 t_end = 1 points, vertices, boundary = rectangular(length, width, length, width) # Create shallow water domain domain = Domain(points, vertices, boundary, geo_reference=Geo_reference(56, 308500, 6189000)) domain.default_order = 2 domain.set_quantities_to_be_stored(None) e = -1.0 w = 1.0 h = w - e u = 2.0 uh = u * h Br = Reflective_boundary(domain) # Side walls Bd = Dirichlet_boundary([w, uh, 0]) # 2 m/s across the 3 m inlet: # Initial conditions domain.set_quantity('elevation', e) domain.set_quantity('stage', w) domain.set_quantity('xmomentum', uh) domain.set_boundary({'left': Bd, 'right': Bd, 'top': Br, 'bottom': Br}) # Interpolation points down the middle I = [[0, width / 2.], [length / 2., width / 2.], [length, width / 2.]] interpolation_points = domain.geo_reference.get_absolute(I) for t in domain.evolve(yieldstep=0.1, finaltime=0.5): # Shortcuts to quantites stage = domain.get_quantity('stage') xmomentum = domain.get_quantity('xmomentum') ymomentum = domain.get_quantity('ymomentum') # Check that quantities are they should be in the interior w_t = stage.get_values(interpolation_points) uh_t = xmomentum.get_values(interpolation_points) vh_t = ymomentum.get_values(interpolation_points) assert num.allclose(w_t, w) assert num.allclose(uh_t, uh) assert num.allclose(vh_t, 0.0, atol=1.0e-6) # Check flows through the middle for i in range(5): x = length / 2. + i * 0.23674563 # Arbitrary cross_section = [[x, 0], [x, width]] cross_section = domain.geo_reference.get_absolute( cross_section) Q = domain.get_flow_through_cross_section(cross_section, verbose=False) assert num.allclose(Q, uh * width) import cPickle cPickle.dump(domain, open('domain_pickle.pickle', 'w')) domain_restored = cPickle.load(open('domain_pickle.pickle')) for t in domain_restored.evolve(yieldstep=0.1, finaltime=1.0): # Shortcuts to quantites stage = domain_restored.get_quantity('stage') xmomentum = domain_restored.get_quantity('xmomentum') ymomentum = domain_restored.get_quantity('ymomentum') # Check that quantities are they should be in the interior w_t = stage.get_values(interpolation_points) uh_t = xmomentum.get_values(interpolation_points) vh_t = ymomentum.get_values(interpolation_points) assert num.allclose(w_t, w) assert num.allclose(uh_t, uh) assert num.allclose(vh_t, 0.0, atol=1.0e-6) # Check flows through the middle for i in range(5): x = length / 2. + i * 0.23674563 # Arbitrary cross_section = [[x, 0], [x, width]] cross_section = domain_restored.geo_reference.get_absolute( cross_section) Q = domain_restored.get_flow_through_cross_section( cross_section, verbose=False) assert num.allclose(Q, uh * width)