def test_advection_example(self): #Test that system can evolve from anuga.abstract_2d_finite_volumes.mesh_factory import rectangular points, vertices, boundary = rectangular(6, 6) #Create advection domain with direction (1,-1) domain = Advection_Domain(points, vertices, boundary, velocity=[1.0, -1.0]) # Initial condition is zero by default #Boundaries T = Transmissive_boundary(domain) D = Dirichlet_boundary(num.array([3.1415])) domain.set_boundary( {'left': D, 'right': T, 'bottom': T, 'top': T} ) domain.check_integrity() #Check that the boundary value gets propagated to all elements for t in domain.evolve(yieldstep = 0.05, finaltime = 10): if num.allclose(domain.quantities['stage'].centroid_values, 3.1415): break assert num.allclose(domain.quantities['stage'].centroid_values, 3.1415)
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_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)
domain = Parallel_Domain(points, vertices, boundary, full_send_dict=full_send_dict, ghost_recv_dict=ghost_recv_dict, velocity=[0.1, 0.0]) # Make a notes of which triangles are full and which are ghost tri_full_flag = build_full_flag(domain, ghost_recv_dict) #domain.initialise_visualiser(rect=rect) #Boundaries T = Transmissive_boundary(domain) #R = Reflective_boundary(domain) domain.set_boundary({ 'outflow': T, 'inflow': T, 'inner': T, 'exterior': T, 'open': T, 'ghost': None }) domain.set_quantity('stage', quantities['stage']) #--------- # Evolution t0 = time.time()
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 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. 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_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 domain1 gets time hacked back to 0: final = final + (domain2.get_starttime() - domain.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=final): #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