def test_triangle_areas(self): """ Check that triangle areas is working as it should """ self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg='DE0', verbose=verbose) p=util.get_output('test_plot_utils.sww') pc=util.get_centroids(p,velocity_extrapolation=True) # Check that subsetting works ta=util.triangle_areas(p) ta_1=util.triangle_areas(p,range(10)) assert(all(ta[range(10)]==ta_1)) # Independently compute an example and check it x0=p.x[p.vols[0][0]] y0=p.y[p.vols[0][0]] x1=p.x[p.vols[0][1]] y1=p.y[p.vols[0][1]] x2=p.x[p.vols[0][2]] y2=p.y[p.vols[0][2]] # Use 0.5 a * b len_a = ((x1-x0)**2 + (y1-y0)**2)**0.5 vec_01 = np.array([ x1-x0, y1-y0]) vec_01 = vec_01/((vec_01**2).sum())**0.5 vec_01_perp=np.array([vec_01[1], -vec_01[0]]) len_b = (x2-x0)*vec_01_perp[0] + (y2-y0)*vec_01_perp[1] assert(np.allclose(abs(0.5*len_a*len_b),ta[0])) os.remove('test_plot_utils.sww')
def test_triangle_areas(self): """ Check that triangle areas is working as it should """ self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg='DE0', verbose=verbose) p = util.get_output('test_plot_utils.sww') pc = util.get_centroids(p, velocity_extrapolation=True) # Check that subsetting works ta = util.triangle_areas(p) ta_1 = util.triangle_areas(p, range(10)) assert (all(ta[range(10)] == ta_1)) # Independently compute an example and check it x0 = p.x[p.vols[0][0]] y0 = p.y[p.vols[0][0]] x1 = p.x[p.vols[0][1]] y1 = p.y[p.vols[0][1]] x2 = p.x[p.vols[0][2]] y2 = p.y[p.vols[0][2]] # Use 0.5 a * b len_a = ((x1 - x0)**2 + (y1 - y0)**2)**0.5 vec_01 = np.array([x1 - x0, y1 - y0]) vec_01 = vec_01 / ((vec_01**2).sum())**0.5 vec_01_perp = np.array([vec_01[1], -vec_01[0]]) len_b = (x2 - x0) * vec_01_perp[0] + (y2 - y0) * vec_01_perp[1] assert (np.allclose(abs(0.5 * len_a * len_b), ta[0])) os.remove('test_plot_utils.sww')
def main(sww_file, quantity, timeslices): sww_path = _get_sww_path(sww_file) data = plot_utils.get_output(sww_path) xdata = data.x ydata = data.y csv_path = _get_csv_path(sww_path, quantity, timeslices) nd_data = _get_quantity(data, quantity, timeslices) _write_to_csv(csv_path, nd_data, xdata, ydata) return True
def test_near_points(self): """ Check that the near-points function is working """ self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg='DE0', verbose=verbose) p = util.get_output('test_plot_utils.sww') pc = util.get_centroids(p, velocity_extrapolation=True) # First check -- get points along y==50 nt = util.near_transect(pc, [20., 50.], [80., 50.], tol=10.) assert (all(abs(pc.y[nt[0]] - 50.) < 10.)) assert (all(nt[1] >= 0.)) assert (all(nt[1] <= 60.)) assert (np.allclose(pc.x[nt[0]] - 20., nt[1])) # Next check -- get points along x==50 nt = util.near_transect(pc, [50., 20.], [50., 80.], tol=10.) assert (all(abs(pc.x[nt[0]] - 50.) < 10.)) assert (all(nt[1] >= 0.)) assert (all(nt[1] <= 60.)) assert (np.allclose(pc.y[nt[0]] - 20., nt[1])) # Next check -- get points along x==y nt = util.near_transect(pc, [20., 20.], [80., 80.], tol=10.) assert (all(nt[1] >= 0.)) # Length of line is 60*sqrt(2) assert (all(nt[1] <= 60. * 2**0.5)) # Coords must be within 10*sqrt(2) of each other assert (all(abs(pc.x[nt[0]] - pc.y[nt[0]]) < 10. * 2**0.5)) # The dot product of the points along the line is equal to nt[1] dt_Prd = ((pc.x[nt[0]] - 20.) / 2.**0.5 + (pc.y[nt[0]] - 20.) / 2.**0.5) assert (np.allclose(dt_Prd, nt[1])) # Next check -- get points along x==2*y + 5 nt = util.near_transect(pc, [25., 10.], [85., 40.], tol=10.) assert (all(nt[1] >= 0.)) # Length of line is sqrt(60^2+30^3) assert (all(nt[1] <= (60.**2 + 30.**2)**0.5)) # The dot product of the points along the line is equal to nt[1] # Unit vector along line is (1,0.5)/ll ll = (1.**2 + 0.5**2)**0.5 dt_Prd = ((pc.x[nt[0]] - 25.) / ll + (pc.y[nt[0]] - 10.) * 0.5 / ll) assert (np.allclose(dt_Prd, nt[1])) os.remove('test_plot_utils.sww')
def test_water_volume(self): """ Check that water volume is right We assume triangle areas are computed ok, but note they are tested above """ self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg='DE0', verbose=verbose) p=util.get_output('test_plot_utils.sww') pc=util.get_centroids(p,velocity_extrapolation=True) # Check that subsetting works ta=util.triangle_areas(p) # Independently computed water volume wVol_2=(ta*pc.height[2,:]).sum() wv=util.water_volume(p,pc) assert(np.allclose(wVol_2, wv[2])) os.remove('test_plot_utils.sww')
def test_near_points(self): """ Check that the near-points function is working """ self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg='DE0', verbose=verbose) p=util.get_output('test_plot_utils.sww') pc=util.get_centroids(p,velocity_extrapolation=True) # First check -- get points along y==50 nt=util.near_transect(pc, [20., 50.], [80., 50.], tol=10.) assert(all(abs(pc.y[nt[0]]-50.)<10.)) assert(all(nt[1]>=0.)) assert(all(nt[1]<=60.)) assert(np.allclose(pc.x[nt[0]]-20., nt[1])) # Next check -- get points along x==50 nt=util.near_transect(pc, [50., 20.], [50., 80.], tol=10.) assert(all(abs(pc.x[nt[0]]-50.)<10.)) assert(all(nt[1]>=0.)) assert(all(nt[1]<=60.)) assert(np.allclose(pc.y[nt[0]]-20., nt[1])) # Next check -- get points along x==y nt=util.near_transect(pc, [20., 20.], [80., 80.], tol=10.) assert(all(nt[1]>=0.)) # Length of line is 60*sqrt(2) assert(all(nt[1]<=60.*2**0.5)) # Coords must be within 10*sqrt(2) of each other assert(all(abs( pc.x[nt[0]]-pc.y[nt[0]]) < 10.*2**0.5)) # The dot product of the points along the line is equal to nt[1] dt_Prd=( (pc.x[nt[0]]-20.)/2.**0.5 + (pc.y[nt[0]]-20.)/2.**0.5) assert(np.allclose(dt_Prd , nt[1])) # Next check -- get points along x==2*y + 5 nt=util.near_transect(pc, [25., 10.], [85., 40.], tol=10.) assert(all(nt[1]>=0.)) # Length of line is sqrt(60^2+30^3) assert(all(nt[1]<=(60.**2+30.**2)**0.5)) # The dot product of the points along the line is equal to nt[1] # Unit vector along line is (1,0.5)/ll ll=(1.**2+0.5**2)**0.5 dt_Prd=( (pc.x[nt[0]]-25.)/ll + (pc.y[nt[0]]-10.)*0.5/ll) assert(np.allclose(dt_Prd , nt[1])) os.remove('test_plot_utils.sww')
def test_triangle_containing_point(self): import matplotlib.tri as tri # older versions of matplotlib don't have this procedure if not hasattr(tri.Triangulation,"get_trifinder"): return self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg='DE0', verbose=verbose) p = util.get_output('test_plot_utils.sww') pc = util.get_centroids(p, velocity_extrapolation=True) # Compare lookup using the 2 different function point_index_1 = util.get_triangle_containing_point(p, [50., 50.]) tri_lookup = util.get_triangle_lookup_function(p) assert( point_index_1 == tri_lookup(50., 50.) )
def test_water_volume(self): """ Check that water volume is right We assume triangle areas are computed ok, but note they are tested above """ self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg='DE0', verbose=verbose) p = util.get_output('test_plot_utils.sww') pc = util.get_centroids(p, velocity_extrapolation=True) # Check that subsetting works ta = util.triangle_areas(p) # Independently computed water volume wVol_2 = (ta * pc.height[2, :]).sum() wv = util.water_volume(p, pc) assert (np.allclose(wVol_2, wv[2])) os.remove('test_plot_utils.sww')
def basic_checks(self): """ Check that dimensions are as required, and that if we extract centroids by passing the file name we get the same result as if we pass the get_output object """ p = util.get_output('test_plot_utils.sww') # Check that dimesions are ok l_time = len(p.time) l_space = len(p.x) assert (len(p.y) == l_space) assert (p.stage.shape == (l_time, l_space)) assert (p.vel.shape == (l_time, l_space)) assert (p.xmom.shape == (l_time, l_space)) assert (p.ymom.shape == (l_time, l_space)) assert (p.xvel.shape == (l_time, l_space)) assert (p.yvel.shape == (l_time, l_space)) assert (p.elev.shape == (l_space, )) assert (p.friction.shape == (l_space, )) p2 = util.get_centroids(p, velocity_extrapolation=True) l_space = len( p.vols) # len(vols in vertex quantities) = len(centroids) assert (p2.stage.shape == (l_time, l_space)) assert (p2.vel.shape == (l_time, l_space)) assert (p2.xmom.shape == (l_time, l_space)) assert (p2.ymom.shape == (l_time, l_space)) assert (p2.xvel.shape == (l_time, l_space)) assert (p2.yvel.shape == (l_time, l_space)) assert (p2.elev.shape == (l_space, )) assert (p2.friction.shape == (l_space, )) # Read centroids as a file, and check that it is the same as above for a couple of time-slices p3 = util.get_centroids('test_plot_utils.sww', velocity_extrapolation=True) self.everything_equal(p3, 2, p2, 2) self.everything_equal(p3, 4, p2, 4)
def test_triangle_containing_point(self): import matplotlib.tri as tri # older versions of matplotlib don't have this procedure if not hasattr(tri.Triangulation, "get_trifinder"): return self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg='DE0', verbose=verbose) p = util.get_output('test_plot_utils.sww') pc = util.get_centroids(p, velocity_extrapolation=True) # Compare lookup using the 2 different function point_index_1 = util.get_triangle_containing_point(p, [50., 50.]) tri_lookup = util.get_triangle_lookup_function(p) assert (point_index_1 == tri_lookup(50., 50.))
def basic_checks(self): """ Check that dimensions are as required, and that if we extract centroids by passing the file name we get the same result as if we pass the get_output object """ p=util.get_output('test_plot_utils.sww') # Check that dimesions are ok l_time=len(p.time) l_space=len(p.x) assert(len(p.y)==l_space) assert(p.stage.shape==(l_time,l_space)) assert(p.vel.shape==(l_time,l_space)) assert(p.xmom.shape==(l_time,l_space)) assert(p.ymom.shape==(l_time,l_space)) assert(p.xvel.shape==(l_time,l_space)) assert(p.yvel.shape==(l_time,l_space)) assert(p.elev.shape==(l_space,)) assert(p.friction.shape==(l_space,)) p2=util.get_centroids(p,velocity_extrapolation=True) l_space=len(p.vols) # len(vols in vertex quantities) = len(centroids) assert(p2.stage.shape==(l_time,l_space)) assert(p2.vel.shape==(l_time,l_space)) assert(p2.xmom.shape==(l_time,l_space)) assert(p2.ymom.shape==(l_time,l_space)) assert(p2.xvel.shape==(l_time,l_space)) assert(p2.yvel.shape==(l_time,l_space)) assert(p2.elev.shape==(l_space,)) assert(p2.friction.shape==(l_space,)) # Read centroids as a file, and check that it is the same as above for a couple of time-slices p3=util.get_centroids('test_plot_utils.sww',velocity_extrapolation=True) self.everything_equal(p3, 2, p2, 2) self.everything_equal(p3, 4, p2, 4)
""" Quick plot of the Carrier-Greenspan outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from analytical_carrier_greenspan import * p_st = util.get_output('carrier_greenspan.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) x_n = p2_st.x[v2] W1, P1, Z1, H1, U1 = analytic_cg(x_n, p2_st.time[288], h0=5e2, L=5e4, a=1.0, Tp=900.0) W2, P2, Z2, H2, U2 = analytic_cg(x_n, p2_st.time[296], h0=5e2, L=5e4, a=1.0, Tp=900.0) W3, P3, Z3, H3, U3 = analytic_cg(x_n,
elif c==2: VerP[r] = table[r][c] elif c==3: VerZ[r] = table[r][c] elif c==4: VerH[r] = table[r][c] elif c==5: VerU[r] = table[r][c] Vertices_left = -1.0*Vertices[::-1] VerW_left = VerW[::-1] VerP_left = -1.0*VerP[::-1] VerZ_left = VerZ[::-1] VerH_left = VerH[::-1] VerU_left = -1.0*VerU[::-1] p_st = util.get_output('radial_dam.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[79598] v2=(p2_st.y==v) #Plot stages pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[-1,v2],'b.-', label='numerical stage') pyplot.plot(Vertices, VerW,'r-', label='reference stage') pyplot.plot(Vertices_left, VerW_left,'r-') pyplot.title('Stage at an instant in time') pyplot.legend(loc='best') pyplot.xlabel('Radial position') pyplot.ylabel('Stage') pyplot.savefig('stage_plot.png')
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from analytical_avalanche_dry import * p_st = util.get_output('avalanche.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) x_n = p2_st.x[v2] u0, h0, w0, z0, p0 = analytical_sol(x_n, p2_st.time[0]) u10, h10, w10, z10, p10 = analytical_sol(x_n, p2_st.time[10]) u30, h30, w30, z30, p30 = analytical_sol(x_n, p2_st.time[30]) w0_n = p2_st.stage[0, v2] w10_n = p2_st.stage[10, v2] w30_n = p2_st.stage[30, v2] z_n = p2_st.elev[v2] uh0_n = p2_st.xmom[0, v2] uh10_n = p2_st.xmom[10, v2] uh30_n = p2_st.xmom[30, v2]
from anuga.utilities import plot_utils as util from matplotlib import pyplot as pyplot import numpy verbose = True swwfile = 'merewether_1m.sww' p = util.get_output(swwfile) p2 = util.get_centroids(p) # Time index at last time tindex = len(p2.time) - 1 if verbose: print('calculating experimental transect') x_data = [0.0, 3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0, 27.0, 30.0, 33.0] #vel = [ 0.0, 0.0, 1.1, 3.2, 3.4, 2.4, 3.2, 3.2, 3.7, 3.1, 0.4, 0.0] vel_data = [0.0, 0.4, 3.1, 3.7, 3.2, 3.2, 2.4, 3.4, 3.2, 1.1, 0.0, 0.0] #depth = [ 0.0, 0.0, 0.1, 0.5, 0.45, 0.4, 0.55, 0.1, 0.1, 0.05, 0.04, 0.0] depth_data = [0.0, 0.04, 0.05, 0.1, 0.1, 0.55, 0.4, 0.45, 0.5, 0.1, 0.0, 0.0] from scipy import interpolate fvel = interpolate.interp1d(x_data, vel_data) fdepth = interpolate.interp1d(x_data, depth_data) if verbose: print('calculating model heights at observation points') # Get nearest wet points to 'point observations' point_observations = numpy.genfromtxt('Observations/ObservationPoints.csv', delimiter=",", skip_header=1)
""" #--------------- # Import Modules #--------------- import time import anuga import numpy import scipy import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from anuga.utilities import plot_utils as util #-------------- # Get variables #-------------- p=util.get_output('channel.sww', 0.001) p2=util.get_centroids(p,velocity_extrapolation=True) #------------------ # Select line #------------------ #v=(y==2.5) #v=(p2.y==p2.y[3]) #------------------------------- # Define variables of case study #------------------------------- mann=0.03 # Manning's coef bedslope=-0.1 fluxin=20./100. #The momentum flux at the upstream boundary ( = discharge / width)
""" Quick plot for outputs of the transcritical flow with a shock """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from analytical_MacDonald import * from numpy import ones p_st = util.get_output('MacDonald.sww') p2_st = util.get_centroids(p_st) tid = -1 v = p2_st.y[10] v2 = (p2_st.y == v) h, z = analytic_sol(p2_st.x[v2]) #Plot the stages############################################################## pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[tid, v2], 'b.-', label='numerical stage') # 0*T/6 pyplot.plot(p2_st.x[v2], h + z, 'r-', label='analytical stage') pyplot.plot(p2_st.x[v2], z, 'k-', label='bed elevation') pyplot.title('Stage at time %g' % p2_st.time[tid]) ##pyplot.ylim(-5.0,5.0) pyplot.legend(loc='best') pyplot.xlabel('Xposition')
#from anuga.utilities import plot_utils as util from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot import scipy, numpy p= util.get_output('runup_v2.sww') p2=util.get_centroids(p,velocity_extrapolation=True) # Find points with x<1km v = p2.x<1000. # Get analytical solution snapshots t160=numpy.genfromtxt('./DATA/t160.csv',delimiter=',',skip_header=1) t175=numpy.genfromtxt('./DATA/t175.csv',delimiter=',',skip_header=1) t220=numpy.genfromtxt('./DATA/t220.csv',delimiter=',',skip_header=1) shoreline=numpy.genfromtxt('./DATA/Shoreline.csv',delimiter=',',skip_header=1) # Offset x by 200m, to reflect how the mesh is set up t160[:,0] = t160[:,0]+200. t175[:,0] = t175[:,0]+200. t220[:,0] = t220[:,0]+200. # Make plots t_wanted=[160., 175., 220.] pyplot.clf() for i,t in enumerate(t_wanted): tmp=abs(p2.time-t) p2_ind=tmp.argmin()
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from numpy import ones, zeros p_st = util.get_output('steep_island.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) z = zeros(len(p2_st.x[v2])) xx = p2_st.x[v2] for i in range(len(p2_st.x[v2])): if 0 <= xx[i] <= 200.0: z[i] = max(-0.01 * (xx[i] - 200) + 4.0, 4.5) elif 900.0 <= xx[i] <= 1000.0: z[i] = 6.0 elif 1800.0 <= xx[i] <= 2000.0: z[i] = max((4.5 / 40000) * (xx[i] - 1800)**2 + 2.0, 4.5) else: z[i] = 4.5 #p_dev = util.get_output('dam_break.sww', 0.001) #p2_dev=util.get_centroids(p_dev, velocity_extrapolation=True)
""" Quick plot for outputs of the transcritical flow with a shock """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from analytical_with_shock import * from numpy import ones p_st = util.get_output('transcritical.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[10] v2=(p2_st.y==v) tid = -1 h,z = analytic_sol(p2_st.x[v2]) #Plot the stages############################################################## pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[tid,v2], 'b.-', label='numerical stage') # 0*T/6 pyplot.plot(p2_st.x[v2], h+z,'r-', label='analytical stage') pyplot.plot(p2_st.x[v2], z,'k-', label='bed elevation') pyplot.title('Stage at time %s secs'% p2_st.time[tid]) ##pyplot.ylim(-5.0,5.0) pyplot.legend(loc='best') pyplot.xlabel('Xposition') pyplot.ylabel('Stage')
from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot p2=util.get_output('data_wave.sww',0.001) p=util.get_centroids(p2,velocity_extrapolation=True) maxx=p.x.max() minx=p.x.min() v1 = abs(p.x -minx).argmin() v2 = abs(p.x -0.5*(minx+maxx)).argmin() v3 = abs(p.x -maxx).argmin() pyplot.clf() pyplot.plot(p.time, p.stage[:,v1], label='Left edge of domain') pyplot.plot(p.time, p.stage[:,v2], label='Middle of domain') pyplot.plot(p.time, p.stage[:,v3], label='Right edge of domain') pyplot.ylim((-1.5,2.0)) pyplot.legend() pyplot.xlabel('Time') pyplot.ylabel('Amplitude') pyplot.title('Stage over time at 3 points in space') pyplot.savefig('wave_atten.png') #pyplot.show() pyplot.clf() pyplot.plot(p.time, p.xmom[:,v1], label='Left edge of domain') pyplot.plot(p.time, p.xmom[:,v2], label='Middle of domain')
def run_simulation(parallel=False, verbose=False): #-------------------------------------------------------------------------- # Setup computational domain and quantities #-------------------------------------------------------------------------- if myid == 0: anuga.create_mesh_from_regions(boundaryPolygon, boundary_tags={'left': [0], 'top': [1], 'right': [2], 'bottom': [3]}, maximum_triangle_area = 1.0e+20, minimum_triangle_angle = 28.0, filename = 'runup.msh', interior_regions = [ [higherResPolygon, 1.*1.*0.5], [midResPolygon, 3.0*3.0*0.5]], breaklines=riverWall.values(), use_cache=False, verbose=verbose, regionPtArea=regionPtAreas) sdomain=anuga.create_domain_from_file('runup.msh') sdomain.set_flow_algorithm(alg) sdomain.set_name('s_riverwall') sdomain.set_datadir('.') sdomain.set_store_vertices_uniquely() #------------------ # Define topography #------------------ def topography(x,y): return -x/150.*scale_me def stagefun(x,y): stg=-0.5*scale_me return stg sdomain.set_quantity('elevation',topography) # Use function for elevation sdomain.set_quantity('friction',0.03) # Constant friction sdomain.set_quantity('stage', stagefun) # Constant negative initial stage else: sdomain = None #-------------------------------------------------------------------------- # Create the parallel domains #-------------------------------------------------------------------------- if parallel: if myid == 0 and verbose : print 'DISTRIBUTING TO PARALLEL DOMAIN' pdomain = distribute(sdomain, verbose=verbose) pdomain.set_name('p_riverwall') pdomain.set_store_vertices_uniquely() if myid == 0 and verbose: print 60*'=' print 'EVOLVING pdomain' print 60*'=' setup_and_evolve(pdomain, verbose=verbose) barrier() if myid == 0: if verbose: print 60*'=' print 'EVOLVING sdomain' print 60*'=' setup_and_evolve(sdomain, verbose=verbose) barrier() #--------------------------------- # Now compare the merged sww files #--------------------------------- if myid == 0: if verbose: print 'COMPARING SWW FILES' sdomain_v = util.get_output('s_riverwall.sww') sdomain_c = util.get_centroids(sdomain_v) pdomain_v = util.get_output('p_riverwall.sww') pdomain_c = util.get_centroids(pdomain_v) # Test some values against the original ordering if verbose: order = 0 print 'PDOMAIN CENTROID VALUES' print num.linalg.norm(sdomain_c.x-pdomain_c.x,ord=order) print num.linalg.norm(sdomain_c.y-pdomain_c.y,ord=order) print num.linalg.norm(sdomain_c.stage[-1]-pdomain_c.stage[-1],ord=order) print num.linalg.norm(sdomain_c.xmom[-1]-pdomain_c.xmom[-1],ord=order) print num.linalg.norm(sdomain_c.ymom[-1]-pdomain_c.ymom[-1],ord=order) print num.linalg.norm(sdomain_c.xvel[-1]-pdomain_c.xvel[-1],ord=order) print num.linalg.norm(sdomain_c.yvel[-1]-pdomain_c.yvel[-1],ord=order) assert num.allclose(sdomain_c.stage,pdomain_c.stage) assert num.allclose(sdomain_c.xmom,pdomain_c.xmom) assert num.allclose(sdomain_c.ymom,pdomain_c.ymom) assert num.allclose(sdomain_c.xvel,pdomain_c.xvel) assert num.allclose(sdomain_c.yvel,pdomain_c.yvel) assert num.allclose(sdomain_v.x,pdomain_v.x) assert num.allclose(sdomain_v.y,pdomain_v.y) import os os.remove('s_riverwall.sww') os.remove('p_riverwall.sww') os.remove('runup.msh')
def test_carrier_greenspan_periodic(self): if verbose: print print indent+'Running simulation script' s = 'numerical_carrier_greenspan.py' res = anuga.run_anuga_script(s,args=args) # Test that script runs ok assert res == 0 if verbose: print indent+'Testing accuracy' import anuga.utilities.plot_utils as util from analytical_carrier_greenspan import analytic_cg p_st = util.get_output('carrier_greenspan.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[10] v2=(p2_st.y==v) x_n = p2_st.x[v2] #ids = [288, 296, 304, 312, 320, 328] ids = [296, 304, 320, 328] # For the velocity and xmomentum calculations use # absolute error (as the exact solution is 0) use_absolute = [False, False, False, False] n = len(ids) W, P, Z, H, U = [], [], [], [], [] W_n, U_n, UH_n = [], [], [] for i, id in enumerate(ids): w0, p0, z0, h0, u0 = analytic_cg(x_n, p2_st.time[id], h0=5e2, L=5e4, a=1.0, Tp=900.0) W.append(w0) H.append(h0) U.append(u0) W_n.append(p2_st.stage[id,v2]) UH_n.append(p2_st.xmom[id,v2]) U_n.append(p2_st.xvel[id,v2]) #print id, numpy.max(H[i]), numpy.min(H[i]) #print id, numpy.max(U[i]), numpy.min(U[i]) #print id, numpy.max(U_n[i]), numpy.min(U_n[i]) #Test stages # Calculate L^1 error at times ew = numpy.zeros(n) for i, id in enumerate(ids): ew[i] = numpy.sum(numpy.abs(W_n[i]-W[i]))/numpy.sum(numpy.abs(W[i])) print print indent+'L^1 Errors in stage: ', ew #Test xmomenta # Calculate L^1 error at times euh = numpy.zeros(n) for i, id in enumerate(ids): if use_absolute[i]: euh[i] = numpy.sum(numpy.abs(UH_n[i]-U[i]*H[i]))/len(U[i]) else: euh[i] = numpy.sum(numpy.abs(UH_n[i]-U[i]*H[i]))/numpy.sum(numpy.abs(UH_n[i])) print indent+'L^1 Errors in xmomentum: ',euh #Test xvelocity # Calculate L^1 error at times eu = numpy.zeros(n) for i, id in enumerate(ids): if use_absolute[i]: eu[i] = numpy.sum(numpy.abs(U_n[i]-U[i]))/len(U[i]) else: eu[i] = numpy.sum(numpy.abs(U_n[i]-U[i]))/numpy.sum(numpy.abs(U[i])) print indent+'L^1 Errors in xvelocity: ', eu for i, id in enumerate(ids): assert ew[i] < 0.01, 'L^1 error %g greater than 1 percent'% ew[i] for i, id in enumerate(ids): assert euh[i] < 0.025, 'L^1 error %g greater than 2.5 percent'% euh[i] for i, id in enumerate(ids): assert eu[i] < 0.1, 'L^1 error %g greater than 10 percent'% eu[i]
from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot import numpy from project import * filename = 'channel_floodplain.sww' # Time-index to plot outputs from p2 = util.get_output(filename) p = util.get_centroids(p2, velocity_extrapolation=True) v = (p.x > 6.0) * (p.x < 8.0) print numpy.any(v) # Numerical results along a central channel 'slice' index = -1 V1 = p.stage[index, v] - p.elev[v] V2 = p.yvel[index, v] V3 = p.xvel[index, v] ########################################################################## # Analytical solution of steady uniform 2D flow in a trapezoidal channel. ########################################################################## Qin = 4.6932 # Inflow discharge slp = 1. / 300. # Floodplain slope (= water slope for steady uniform flow) man_n = 0.03 # Manning's n Bcentral = 6.0 #Flat bed width of the trapezoidal channel alpha = 0.5 # Side slope of the trapezoidal banks
""" Quick plot for outputs of the transcritical flow with a shock """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from analytical_with_shock import * from numpy import ones p_st = util.get_output('transcritical.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) tid = -1 h, z = analytic_sol(p2_st.x[v2]) #Plot the stages############################################################## pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[tid, v2], 'b.-', label='numerical stage') # 0*T/6 pyplot.plot(p2_st.x[v2], h + z, 'r-', label='analytical stage') pyplot.plot(p2_st.x[v2], z, 'k-', label='bed elevation') pyplot.title('Stage at time %s secs' % p2_st.time[tid]) ##pyplot.ylim(-5.0,5.0) pyplot.legend(loc='best')
def test_avalanche_dry(self): if verbose: print print indent + 'Running simulation script' # Run basic script (can be parallel if -np used in call # to this script s = 'numerical_avalanche_dry.py' res = anuga.run_anuga_script(s, args=args) # Test that script runs ok assert res == 0 if verbose: print indent + 'Testing accuracy' import anuga.utilities.plot_utils as util from analytical_avalanche_dry import analytical_sol p_st = util.get_output('avalanche.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) x_n = p2_st.x[v2] u0, h0, w0, z0, p0 = analytical_sol(x_n, p2_st.time[0]) u10, h10, w10, z10, p10 = analytical_sol(x_n, p2_st.time[10]) u30, h30, w30, z30, p30 = analytical_sol(x_n, p2_st.time[30]) w0_n = p2_st.stage[0, v2] w10_n = p2_st.stage[10, v2] w30_n = p2_st.stage[30, v2] z_n = p2_st.elev[v2] uh0_n = p2_st.xmom[0, v2] uh10_n = p2_st.xmom[10, v2] uh30_n = p2_st.xmom[30, v2] u0_n = p2_st.xvel[0, v2] u10_n = p2_st.xvel[10, v2] u30_n = p2_st.xvel[30, v2] #Test stages # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 eh10 = numpy.sum(numpy.abs(w10_n - w10)) / numpy.sum(numpy.abs(w10)) eh30 = numpy.sum(numpy.abs(w30_n - w30)) / numpy.sum(numpy.abs(w30)) print print indent + 'Errors in stage: ', eh10, eh30 #Test xmomenta # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 euh10 = numpy.sum(numpy.abs(uh10_n - u10 * h10)) / numpy.sum( numpy.abs(u10 * h10)) euh30 = numpy.sum(numpy.abs(uh30_n - u30 * h30)) / numpy.sum( numpy.abs(u30 * h30)) print indent + 'Errors in xmomentum: ', euh10, euh30 #Test xvelocity # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 eu10 = numpy.sum(numpy.abs(u10_n - u10)) / numpy.sum(numpy.abs(u10)) eu30 = numpy.sum(numpy.abs(u30_n - u30)) / numpy.sum(numpy.abs(u30)) print indent + 'Errors in xvelocity: ', eu10, eu30 assert eh10 < 0.01, 'L^1 error %g greater than 1 percent' % eh10 assert eh30 < 0.01, 'L^1 error %g greater than 1 percent' % eh30 assert euh10 < 0.025, 'L^1 error %g greater than 2.5 percent' % euh10 assert euh30 < 0.025, 'L^1 error %g greater than 2.5 percent' % euh30 assert eu10 < 0.2, 'L^1 error %g greater than 20 percent' % eu10 assert eu30 < 0.2, 'L^1 error %g greater than 20 percent' % eu30
""" Quick plot of the Carrier-Greenspan outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from analytical_cg_transient import * p_st = util.get_output('carrier_greenspan.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[10] v2=(p2_st.y==v) #Dimensional parameters L = 5e4 # Length of channel (m) h0 = 5e2 # Height at origin when the water is still g = 9.81 # Gravity #Dimensionless solution W1, Z1, U1 = analytical_sol(p2_st.x[v2]/L, p2_st.time[0]*sqrt(g*h0)/L) W2, Z2, U2 = analytical_sol(p2_st.x[v2]/L, p2_st.time[1]*sqrt(g*h0)/L) W3, Z3, U3 = analytical_sol(p2_st.x[v2]/L, p2_st.time[30]*sqrt(g*h0)/L) #Dimensional solution W1 = W1*h0 # dimensional U1 = U1*sqrt(g*h0) # dimensional Z1 = Z1*h0 # dimensional H1 = W1 - Z1 # dimensional
def velExtrap_timeSlices_check(self, ve): """ Check that time-slices are behaving as expected. Assumes sww has been made Is called by a test function for various flow algorithms """ p = util.get_output('test_plot_utils.sww') p2 = util.get_centroids(p, velocity_extrapolation=ve) # Check that dimesions are ok l_time = len(p.time) l_space = len(p.x) assert (p.timeSlices == range(l_time)) assert (p2.timeSlices == range(l_time)) # Try getting some time-slices, and checking all is as intended p_12 = util.get_output('test_plot_utils.sww', timeSlices=[0, 3]) pc_12 = util.get_centroids(p_12, velocity_extrapolation=ve) assert (p_12.timeSlices == [0, 3]) assert (pc_12.timeSlices == [0, 3]) self.everything_equal(p_12, 0, p, 0) self.everything_equal(p_12, 1, p, 3) self.everything_equal(pc_12, 0, p2, 0) self.everything_equal(pc_12, 1, p2, 3) # Try getting some time-slices, and checking all is as intended p_12a = util.get_output('test_plot_utils.sww', timeSlices=3) pc_12a = util.get_centroids(p_12a, velocity_extrapolation=ve) #print p_12a.timeSlices #print pc_12a.timeSlices assert (p_12a.timeSlices == [3]) assert (pc_12a.timeSlices == [3]) self.everything_equal(p_12a, 0, p, 3) self.everything_equal(pc_12a, 0, p2, 3) # Try getting some time-slices, and checking all is as intended p_12b = util.get_output('test_plot_utils.sww') pc_12b = util.get_centroids(p_12b, velocity_extrapolation=ve, timeSlices=3) #print p_12b.timeSlices #print pc_12b.timeSlices assert (p_12b.timeSlices == [0, 1, 2, 3, 4, 5]) assert (pc_12b.timeSlices == [3]) self.everything_equal(p_12b, 0, p, 0) self.everything_equal(p_12b, 5, p, 5) self.everything_equal(pc_12b, 0, p2, 3) # Check we can get the 'last' time, and it is correct p_l = util.get_output('test_plot_utils.sww', timeSlices='last') pc_l = util.get_centroids(p_l, velocity_extrapolation=ve) l_time = len(p.time) self.everything_equal(p_l, 0, p, l_time - 1) self.everything_equal(pc_l, 0, p2, l_time - 1) assert (p_l.timeSlices == [l_time - 1]) assert (pc_l.timeSlices == [l_time - 1]) # Check that we can get the 'max' time p_m = util.get_output('test_plot_utils.sww', timeSlices='max') pc_m = util.get_centroids(p_m, velocity_extrapolation=ve) assert (p_m.time == p.time.max()) assert (pc_m.time == p2.time.max()) assert (p_m.timeSlices == 'max') assert (pc_m.timeSlices == 'max') assert (all(p_m.stage[0, :] == p.stage.max(axis=0))) assert (all(pc_m.stage[0, :] == p2.stage.max(axis=0))) assert (all(p_m.vel[0, :] == p.vel.max(axis=0))) assert (all(pc_m.vel[0, :] == p2.vel.max(axis=0))) assert (all(p_m.height[0, :] == p.height.max(axis=0))) assert (all(pc_m.height[0, :] == p2.height.max(axis=0))) # Somewhat lazy test of variables where the sign is important assert (all(np.abs(p_m.xmom)[0, :] == np.abs(p.xmom).max(axis=0))) assert (all(np.abs(pc_m.xmom)[0, :] == np.abs(p2.xmom).max(axis=0))) assert (all(np.abs(p_m.ymom)[0, :] == np.abs(p.ymom).max(axis=0))) assert (all(np.abs(pc_m.ymom)[0, :] == np.abs(p2.ymom).max(axis=0))) assert (all(np.abs(p_m.xvel)[0, :] == np.abs(p.xvel).max(axis=0))) assert (all(np.abs(pc_m.xvel)[0, :] == np.abs(p2.xvel).max(axis=0))) assert (all(np.abs(p_m.yvel)[0, :] == np.abs(p.yvel).max(axis=0))) assert (all(np.abs(pc_m.yvel)[0, :] == np.abs(p2.yvel).max(axis=0))) return
from anuga.utilities import plot_utils as util from matplotlib import pyplot as pyplot import numpy verbose= True swwfile = 'merewether_1m.sww' p=util.get_output(swwfile) p2=util.get_centroids(p) # Time index at last time tindex = len(p2.time)-1 if verbose: print 'calculating experimental transect' x_data = [ 0.0, 3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0, 27.0, 30.0, 33.0] #vel = [ 0.0, 0.0, 1.1, 3.2, 3.4, 2.4, 3.2, 3.2, 3.7, 3.1, 0.4, 0.0] vel_data = [ 0.0, 0.4, 3.1, 3.7, 3.2, 3.2, 2.4, 3.4, 3.2, 1.1, 0.0, 0.0] #depth = [ 0.0, 0.0, 0.1, 0.5, 0.45, 0.4, 0.55, 0.1, 0.1, 0.05, 0.04, 0.0] depth_data = [ 0.0, 0.04, 0.05, 0.1, 0.1, 0.55, 0.4, 0.45, 0.5, 0.1, 0.0, 0.0] from scipy import interpolate fvel = interpolate.interp1d(x_data, vel_data) fdepth = interpolate.interp1d(x_data, depth_data)
"""View results of runup_sinusoid.py """ #--------------- # Import Modules #--------------- from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot import numpy p1=util.get_output('dimensional_lid_driven.sww')#, 0.001) #p1=util.get_output('runup_sinusoid.sww') p2=util.get_centroids(p1)#, velocity_extrapolation=True) #p2=util.get_centroids(p1) #------------------ # Select line #------------------ #v=(p.y==0.5) v=(p2.y==p2.y[80]) #-------------------- # Make plot animation #-------------------- pyplot.close() #If the plot is open, there will be problems # Plot vertex values pyplot.clf() t1=int(len(p1.time)/2) t2=-1
def test_carrier_greenspan_periodic(self): if verbose: print print indent + 'Running simulation script' s = 'numerical_carrier_greenspan.py' res = anuga.run_anuga_script(s, args=args) # Test that script runs ok assert res == 0 if verbose: print indent + 'Testing accuracy' import anuga.utilities.plot_utils as util from analytical_carrier_greenspan import analytic_cg p_st = util.get_output('carrier_greenspan.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) x_n = p2_st.x[v2] #ids = [288, 296, 304, 312, 320, 328] ids = [296, 304, 320, 328] # For the velocity and xmomentum calculations use # absolute error (as the exact solution is 0) use_absolute = [False, False, False, False] n = len(ids) W, P, Z, H, U = [], [], [], [], [] W_n, U_n, UH_n = [], [], [] for i, id in enumerate(ids): w0, p0, z0, h0, u0 = analytic_cg(x_n, p2_st.time[id], h0=5e2, L=5e4, a=1.0, Tp=900.0) W.append(w0) H.append(h0) U.append(u0) W_n.append(p2_st.stage[id, v2]) UH_n.append(p2_st.xmom[id, v2]) U_n.append(p2_st.xvel[id, v2]) #print id, numpy.max(H[i]), numpy.min(H[i]) #print id, numpy.max(U[i]), numpy.min(U[i]) #print id, numpy.max(U_n[i]), numpy.min(U_n[i]) #Test stages # Calculate L^1 error at times ew = numpy.zeros(n) for i, id in enumerate(ids): ew[i] = numpy.sum(numpy.abs(W_n[i] - W[i])) / numpy.sum( numpy.abs(W[i])) print print indent + 'L^1 Errors in stage: ', ew #Test xmomenta # Calculate L^1 error at times euh = numpy.zeros(n) for i, id in enumerate(ids): if use_absolute[i]: euh[i] = numpy.sum(numpy.abs(UH_n[i] - U[i] * H[i])) / len( U[i]) else: euh[i] = numpy.sum( numpy.abs(UH_n[i] - U[i] * H[i])) / numpy.sum( numpy.abs(UH_n[i])) print indent + 'L^1 Errors in xmomentum: ', euh #Test xvelocity # Calculate L^1 error at times eu = numpy.zeros(n) for i, id in enumerate(ids): if use_absolute[i]: eu[i] = numpy.sum(numpy.abs(U_n[i] - U[i])) / len(U[i]) else: eu[i] = numpy.sum(numpy.abs(U_n[i] - U[i])) / numpy.sum( numpy.abs(U[i])) print indent + 'L^1 Errors in xvelocity: ', eu for i, id in enumerate(ids): assert ew[i] < 0.01, 'L^1 error %g greater than 1 percent' % ew[i] for i, id in enumerate(ids): assert euh[ i] < 0.025, 'L^1 error %g greater than 2.5 percent' % euh[i] for i, id in enumerate(ids): assert eu[i] < 0.1, 'L^1 error %g greater than 10 percent' % eu[i]
import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from analytical_supercritical import analytic_sol from numpy import ones, arange import anuga parser = anuga.create_standard_parser() parser.add_argument('-tid', type=int, default=-1, help='timestep id') args = parser.parse_args() tid = args.tid verbose = args.verbose if verbose: print('Read in swwfile') p_st = util.get_output('supercritical.sww') p2_st = util.get_centroids(p_st) #v = p2_st.y[10] #v2=(p2_st.y==v) #v2=(p2_st.y>-1.0) v2 = arange(len(p2_st.y)) if verbose: print('Calculate analytical solution') h, z = analytic_sol(p2_st.x[v2]) qexact = 10 #Plot the stages############################################################## if verbose: print('Create Stage plot') pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[tid, v2], 'b.-',
def quickPlots(swwFile=None, ocean_land_threshold=None, fig_dir=None, figScale=None): """ Routine to make a set of 'quick and dirty' plots of initial conditions + maxima. Useful for preliminary check on ANUGA outputs """ if(swwFile is None): parser.print_help() print ' ' raise Exception, 'Must give an sww file' # Make directory for figures try: os.mkdir(fig_dir) except: 'Cannot make directory' pass # Read in sww file p=util.get_output(swwFile) p2=util.get_centroids(p,velocity_extrapolation=True) xRange=p2.x.max()-p2.x.min() yRange=p2.y.max()-p2.y.min() figSize=(figScale, figScale*yRange/xRange) # Use spatial coordinates x=p2.x+p.xllcorner y=p2.y+p.yllcorner # Plot friction try: pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=p2.friction,edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Friction') pyplot.colorbar() pyplot.savefig(fig_dir+'/Friction.png') pyplot.close() except: print 'Cannot plot friction' # Plot elevation try: pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=p2.elev,edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Elevation') pyplot.colorbar() pyplot.savefig(fig_dir+'/Elevation.png') pyplot.close() except: print 'Cannot plot elevation' # Plot Initial Stage (where elevation<ocean_land_threshold) pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=p2.stage[0,:]*(p2.elev<ocean_land_threshold),edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Initial Stage (zero where elevation > '+ str(ocean_land_threshold) +' )') pyplot.colorbar() pyplot.savefig(fig_dir+'/Initial_stage.png') pyplot.close() # Plot Initial Depth pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=p2.height[0,:],edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Initial Depth') pyplot.colorbar() pyplot.savefig(fig_dir+'/Initial_depth.png') pyplot.close() # Initial Speed pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=p2.vel[0,:],edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Initial speed ') pyplot.colorbar() pyplot.savefig(fig_dir+'/Initial_speed.png') pyplot.close() # Triangle areas triA=util.triangle_areas(p) tri_len_scale=(triA*2)**0.5 pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=tri_len_scale,edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Mesh triangle side length scale (2*area)^0.5') pyplot.colorbar() pyplot.savefig(fig_dir+'/Triangle_side_length.png') pyplot.close() # Max stage in wet areas maxStage=p2.stage.max(axis=0) pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=maxStage*(maxStage>p2.elev), edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Max stage (zeroed in dry areas)') pyplot.colorbar() pyplot.savefig(fig_dir+'/Max_stage.png') pyplot.close() # Max depth maxDepth=p2.height.max(axis=0) pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=maxDepth, edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Max depth') pyplot.colorbar() pyplot.savefig(fig_dir+'/Max_depth.png') pyplot.close() # Max speed in wet areas maxSpeed=p2.vel.max(axis=0) pyplot.figure(figsize=figSize) pyplot.scatter(x,y,c=maxSpeed, edgecolors='none') pyplot.gca().set_aspect('equal') pyplot.title('Max speed') pyplot.colorbar() pyplot.savefig(fig_dir+'/Max_speed.png') pyplot.close()
def run_simulation(parallel=False, verbose=False): #-------------------------------------------------------------------------- # Setup computational domain and quantities #-------------------------------------------------------------------------- if myid == 0: domain = rectangular_cross_domain(M, N) domain.set_name('odomain') # Set sww filename domain.set_datadir('.') domain.set_quantity('elevation', topography) # Use function for elevation domain.set_quantity('friction', 0.0) # Constant friction domain.set_quantity('stage', expression='elevation') # Dry initial stage else: domain = None #-------------------------------------------------------------------------- # Create pickled partition #-------------------------------------------------------------------------- if myid == 0: if verbose: print 'DUMPING PARTITION DATA' sequential_distribute_dump(domain, numprocs, verbose=verbose, parameters=new_parameters) #-------------------------------------------------------------------------- # Create the parallel domains #-------------------------------------------------------------------------- if parallel: if myid == 0 and verbose : print 'DISTRIBUTING TO PARALLEL DOMAIN' pdomain = distribute(domain, verbose=verbose, parameters=new_parameters) pdomain.set_name('pdomain') if myid == 0 and verbose : print 'LOADING IN PARALLEL DOMAIN' sdomain = sequential_distribute_load(filename='odomain', verbose = verbose) sdomain.set_name('sdomain') if myid == 0 and verbose: print 'EVOLVING pdomain' setup_and_evolve(pdomain, verbose=verbose) if myid == 0 and verbose: print 'EVOLVING sdomain' setup_and_evolve(sdomain, verbose=verbose) if myid == 0: if verbose: print 'EVOLVING odomain' setup_and_evolve(domain, verbose=verbose) if myid == 0 and verbose: parameter_file=open('odomain.txt', 'w') from pprint import pprint pprint(domain.get_algorithm_parameters(),parameter_file,indent=4) parameter_file.close() parameter_file=open('sdomain.txt', 'w') from pprint import pprint pprint(sdomain.get_algorithm_parameters(),parameter_file,indent=4) parameter_file.close() parameter_file=open('pdomain.txt', 'w') from pprint import pprint pprint(pdomain.get_algorithm_parameters(),parameter_file,indent=4) parameter_file.close() assert num.allclose(pdomain.quantities['stage'].centroid_values, sdomain.quantities['stage'].centroid_values) assert num.allclose(pdomain.quantities['stage'].vertex_values, sdomain.quantities['stage'].vertex_values) assert num.allclose(pdomain.vertex_coordinates, sdomain.vertex_coordinates) assert num.allclose(pdomain.centroid_coordinates, sdomain.centroid_coordinates) #--------------------------------- # Now compare the merged sww files #--------------------------------- if myid == 0: if verbose: print 'COMPARING SWW FILES' odomain_v = util.get_output('odomain.sww') odomain_c = util.get_centroids(odomain_v) pdomain_v = util.get_output('pdomain.sww') pdomain_c = util.get_centroids(pdomain_v) sdomain_v = util.get_output('sdomain.sww') sdomain_c = util.get_centroids(sdomain_v) # Test some values against the original ordering if verbose: order = 2 print 'PDOMAIN CENTROID VALUES' print num.linalg.norm(odomain_c.x-pdomain_c.x,ord=order) print num.linalg.norm(odomain_c.y-pdomain_c.y,ord=order) print num.linalg.norm(odomain_c.stage[-1]-pdomain_c.stage[-1],ord=order) print num.linalg.norm(odomain_c.xmom[-1]-pdomain_c.xmom[-1],ord=order) print num.linalg.norm(odomain_c.ymom[-1]-pdomain_c.ymom[-1],ord=order) print num.linalg.norm(odomain_c.xvel[-1]-pdomain_c.xvel[-1],ord=order) print num.linalg.norm(odomain_c.yvel[-1]-pdomain_c.yvel[-1],ord=order) print 'SDOMAIN CENTROID VALUES' print num.linalg.norm(odomain_c.x-sdomain_c.x,ord=order) print num.linalg.norm(odomain_c.y-sdomain_c.y,ord=order) print num.linalg.norm(odomain_c.stage[-1]-sdomain_c.stage[-1],ord=order) print num.linalg.norm(odomain_c.xmom[-1]-sdomain_c.xmom[-1],ord=order) print num.linalg.norm(odomain_c.ymom[-1]-sdomain_c.ymom[-1],ord=order) print num.linalg.norm(odomain_c.xvel[-1]-sdomain_c.xvel[-1],ord=order) print num.linalg.norm(odomain_c.yvel[-1]-sdomain_c.yvel[-1],ord=order) print 'PDOMAIN VERTEX VALUES' print num.linalg.norm(odomain_v.stage[-1]-pdomain_v.stage[-1],ord=order) print num.linalg.norm(odomain_v.xmom[-1]-pdomain_v.xmom[-1],ord=order) print num.linalg.norm(odomain_v.ymom[-1]-pdomain_v.ymom[-1],ord=order) print num.linalg.norm(odomain_v.xvel[-1]-pdomain_v.xvel[-1],ord=order) print num.linalg.norm(odomain_v.yvel[-1]-pdomain_v.yvel[-1],ord=order) print 'SDOMAIN VERTEX VALUES' print num.linalg.norm(odomain_v.stage[-1]-sdomain_v.stage[-1],ord=order) print num.linalg.norm(odomain_v.xmom[-1]-sdomain_v.xmom[-1],ord=order) print num.linalg.norm(odomain_v.ymom[-1]-sdomain_v.ymom[-1],ord=order) print num.linalg.norm(odomain_v.xvel[-1]-sdomain_v.xvel[-1],ord=order) print num.linalg.norm(odomain_v.yvel[-1]-sdomain_v.yvel[-1],ord=order) assert num.allclose(odomain_c.stage,pdomain_c.stage) assert num.allclose(odomain_c.xmom,pdomain_c.xmom) assert num.allclose(odomain_c.ymom,pdomain_c.ymom) assert num.allclose(odomain_c.xvel,pdomain_c.xvel) assert num.allclose(odomain_c.yvel,pdomain_c.yvel) assert num.allclose(odomain_v.x,pdomain_v.x) assert num.allclose(odomain_v.y,pdomain_v.y) assert num.linalg.norm(odomain_v.x-pdomain_v.x,ord=0) == 0 assert num.linalg.norm(odomain_v.y-pdomain_v.y,ord=0) == 0 assert num.linalg.norm(odomain_v.stage[-1]-pdomain_v.stage[-1],ord=0) < 100 assert num.linalg.norm(odomain_v.xmom[-1]-pdomain_v.xmom[-1],ord=0) < 100 assert num.linalg.norm(odomain_v.ymom[-1]-pdomain_v.ymom[-1],ord=0) < 100 assert num.linalg.norm(odomain_v.xvel[-1]-pdomain_v.xvel[-1],ord=0) < 100 assert num.linalg.norm(odomain_v.yvel[-1]-pdomain_v.yvel[-1],ord=0) < 100 assert num.allclose(odomain_c.x,sdomain_c.x) assert num.allclose(odomain_c.y,sdomain_c.y) assert num.allclose(odomain_c.stage,sdomain_c.stage) assert num.allclose(odomain_c.xmom,sdomain_c.xmom) assert num.allclose(odomain_c.ymom,sdomain_c.ymom) assert num.allclose(odomain_c.xvel,sdomain_c.xvel) assert num.allclose(odomain_c.yvel,sdomain_c.yvel) assert num.allclose(odomain_v.x,sdomain_v.x) assert num.allclose(odomain_v.y,sdomain_v.y) order = 0 assert num.linalg.norm(odomain_v.x-sdomain_v.x,ord=order) == 0 assert num.linalg.norm(odomain_v.y-sdomain_v.y,ord=order) == 0 assert num.linalg.norm(odomain_v.stage[-1]-sdomain_v.stage[-1],ord=order) < 100 assert num.linalg.norm(odomain_v.xmom[-1]-sdomain_v.xmom[-1],ord=order) < 100 assert num.linalg.norm(odomain_v.ymom[-1]-sdomain_v.ymom[-1],ord=order) < 100 assert num.linalg.norm(odomain_v.xvel[-1]-sdomain_v.xvel[-1],ord=order) < 100 assert num.linalg.norm(odomain_v.yvel[-1]-sdomain_v.yvel[-1],ord=order) < 100 # COMPARE CENTROID PDOMAIN SDOMAIN assert num.allclose(pdomain_c.x,sdomain_c.x) assert num.allclose(pdomain_c.y,sdomain_c.y) assert num.allclose(pdomain_c.stage[-1],sdomain_c.stage[-1]) assert num.allclose(pdomain_c.xmom[-1],sdomain_c.xmom[-1]) assert num.allclose(pdomain_c.ymom[-1],sdomain_c.ymom[-1]) assert num.allclose(pdomain_c.xvel[-1],sdomain_c.xvel[-1]) assert num.allclose(pdomain_c.yvel[-1],sdomain_c.yvel[-1]) # COMPARE VERTEX PDOMAIN SDOMAIN assert num.allclose(pdomain_v.x,sdomain_v.x) assert num.allclose(pdomain_v.y,sdomain_v.y) assert num.allclose(pdomain_v.stage[-1],sdomain_v.stage[-1]) assert num.allclose(pdomain_v.xmom[-1],sdomain_v.xmom[-1]) assert num.allclose(pdomain_v.ymom[-1],sdomain_v.ymom[-1]) assert num.allclose(pdomain_v.xvel[-1],sdomain_v.xvel[-1]) assert num.allclose(pdomain_v.yvel[-1],sdomain_v.yvel[-1]) import os os.remove('odomain.sww') os.remove('pdomain.sww') os.remove('sdomain.sww') os.remove('odomain_P4_0.pickle') os.remove('odomain_P4_1.pickle') os.remove('odomain_P4_2.pickle') os.remove('odomain_P4_3.pickle')
def velExtrap_timeSlices_check(self, ve): """ Check that time-slices are behaving as expected. Assumes sww has been made Is called by a test function for various flow algorithms """ p=util.get_output('test_plot_utils.sww') p2=util.get_centroids(p,velocity_extrapolation=ve) # Check that dimesions are ok l_time=len(p.time) l_space=len(p.x) assert(p.timeSlices==range(l_time)) assert(p2.timeSlices==range(l_time)) # Try getting some time-slices, and checking all is as intended p_12=util.get_output('test_plot_utils.sww', timeSlices=[0, 3]) pc_12=util.get_centroids(p_12,velocity_extrapolation=ve) assert(p_12.timeSlices==[0,3]) assert(pc_12.timeSlices==[0,3]) self.everything_equal(p_12, 0, p, 0) self.everything_equal(p_12, 1, p, 3) self.everything_equal(pc_12, 0, p2, 0) self.everything_equal(pc_12, 1, p2, 3) # Try getting some time-slices, and checking all is as intended p_12a=util.get_output('test_plot_utils.sww', timeSlices=3) pc_12a=util.get_centroids(p_12a,velocity_extrapolation=ve) #print p_12a.timeSlices #print pc_12a.timeSlices assert(p_12a.timeSlices==[3]) assert(pc_12a.timeSlices==[3]) self.everything_equal(p_12a, 0, p, 3) self.everything_equal(pc_12a, 0, p2, 3) # Try getting some time-slices, and checking all is as intended p_12b=util.get_output('test_plot_utils.sww') pc_12b=util.get_centroids(p_12b,velocity_extrapolation=ve, timeSlices=3) #print p_12b.timeSlices #print pc_12b.timeSlices assert(p_12b.timeSlices==[0, 1, 2, 3, 4, 5]) assert(pc_12b.timeSlices==[3]) self.everything_equal(p_12b, 0, p, 0) self.everything_equal(p_12b, 5, p, 5) self.everything_equal(pc_12b, 0, p2, 3) # Check we can get the 'last' time, and it is correct p_l=util.get_output('test_plot_utils.sww', timeSlices='last') pc_l=util.get_centroids(p_l,velocity_extrapolation=ve) l_time=len(p.time) self.everything_equal(p_l, 0, p, l_time-1) self.everything_equal(pc_l, 0, p2, l_time-1) assert(p_l.timeSlices==[l_time-1]) assert(pc_l.timeSlices==[l_time-1]) # Check that we can get the 'max' time p_m=util.get_output('test_plot_utils.sww', timeSlices='max') pc_m=util.get_centroids(p_m,velocity_extrapolation=ve) assert(p_m.time==p.time.max()) assert(pc_m.time==p2.time.max()) assert(p_m.timeSlices=='max') assert(pc_m.timeSlices=='max') assert(all(p_m.stage[0,:]==p.stage.max(axis=0))) assert(all(pc_m.stage[0,:]==p2.stage.max(axis=0))) assert(all(p_m.vel[0,:]==p.vel.max(axis=0))) assert(all(pc_m.vel[0,:]==p2.vel.max(axis=0))) assert(all(p_m.height[0,:]==p.height.max(axis=0))) assert(all(pc_m.height[0,:]==p2.height.max(axis=0))) # Somewhat lazy test of variables where the sign is important assert(all(np.abs(p_m.xmom)[0,:]==np.abs(p.xmom).max(axis=0))) assert(all(np.abs(pc_m.xmom)[0,:]==np.abs(p2.xmom).max(axis=0))) assert(all(np.abs(p_m.ymom)[0,:]==np.abs(p.ymom).max(axis=0))) assert(all(np.abs(pc_m.ymom)[0,:]==np.abs(p2.ymom).max(axis=0))) assert(all(np.abs(p_m.xvel)[0,:]==np.abs(p.xvel).max(axis=0))) assert(all(np.abs(pc_m.xvel)[0,:]==np.abs(p2.xvel).max(axis=0))) assert(all(np.abs(p_m.yvel)[0,:]==np.abs(p.yvel).max(axis=0))) assert(all(np.abs(pc_m.yvel)[0,:]==np.abs(p2.yvel).max(axis=0))) return
from analytical_supercritical import analytic_sol from numpy import ones, arange import anuga parser = anuga.create_standard_parser() parser.add_argument("-tid", type=int, default=-1, help="timestep id") args = parser.parse_args() tid = args.tid verbose = args.verbose if verbose: print "Read in swwfile" p_st = util.get_output("supercritical.sww") p2_st = util.get_centroids(p_st) # v = p2_st.y[10] # v2=(p2_st.y==v) # v2=(p2_st.y>-1.0) v2 = arange(len(p2_st.y)) if verbose: print "Calculate analytical solution" h, z = analytic_sol(p2_st.x[v2]) qexact = 10 # Plot the stages############################################################## if verbose:
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot import analytical_dam_break_dry as analytic import numpy p_st = util.get_output('dam_break.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[10] v2=numpy.argwhere(p2_st.y==v).flatten() iv2 = numpy.argsort(p2_st.x[v2]) v2 = v2[iv2] #p_dev = util.get_output('dam_break.sww', 0.001) #p2_dev=util.get_centroids(p_dev, velocity_extrapolation=True) h0 = 1e-9 h1 = 10.0 h10,u10 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[10], h0=h0, h1=h1) h50,u50 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[50], h0=h0, h1=h1) #h100,u100 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[100], h0=h0, h1=h1) #Plot stages pyplot.clf()
np.savetxt(fo,vertex_val,delimiter=' ') f_mesh = project.tsh_file f_sww = "%s.sww" %os.path.join(project.out_dir, project.out_name) min_height = project.min_storable_h if not os.path.exists(f_sww): raise RuntimeError("File %s do not exist" %f_sww) #import mesh and initial model parameters mesh_instance = importMeshFromFile(f_mesh) domain = anuga.pmesh_to_domain_instance(mesh_instance, Domain) print 'Extracting data from %d elements......'%len(domain.get_triangles()) #Taking data from netCDF f_result = plot_utils.get_output(f_sww, min_height) topo = f_result.elev total_time = f_result.time.shape[0] # Change the variable time time = total_time time = time - 1 xmomentum = f_result.xmom[time] ymomentum = f_result.ymom[time] stage = f_result.stage[time] # Merging triangles and data information from netCDF fo_elev_name = os.path.join(project.base_dir, 'temp', 'elev_%s' %(project.out_name)) fo_xmom_name = os.path.join(project.base_dir, 'temp', 'xmom_%s' %(project.out_name)) fo_ymom_name = os.path.join(project.base_dir, 'temp', 'ymom_%s' %(project.out_name))
"""View results of runup_sinusoid.py """ #--------------- # Import Modules #--------------- from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot import numpy p1 = util.get_output('dimensional_lid_driven.sww') #, 0.001) #p1=util.get_output('runup_sinusoid.sww') p2 = util.get_centroids(p1) #, velocity_extrapolation=True) #p2=util.get_centroids(p1) #------------------ # Select line #------------------ #v=(p.y==0.5) v = (p2.y == p2.y[80]) #-------------------- # Make plot animation #-------------------- pyplot.close() #If the plot is open, there will be problems # Plot vertex values pyplot.clf() t1 = int(len(p1.time) / 2) t2 = -1
import numpy from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot ###################################################### # Get ANUGA p = util.get_output('channel_floodplain1.sww', 0.001) pc = util.get_centroids(p, velocity_extrapolation=True) # Indices in the central channel areas v = (pc.x > 10.0) * (pc.x < 30.0) ###################################################### # Get hecras info rasFile = 'hecras_tides_case/gauges.csv' rasGauges = numpy.genfromtxt(rasFile, skip_header=3, delimiter=",") # Output at 1 minute intervals rasTime = numpy.linspace(0., 60. * (rasGauges.shape[0] - 1), rasGauges.shape[0]) # Get station information for hecras rasFileO = open(rasFile) rasStations = rasFileO.readline().split(',') rasStations[-1] = rasStations[-1].replace('\r\n', '') rasFileO.close() ######################################################
def test_dam_break_dry(self): if verbose: print print indent + 'Running simulation script' s = 'numerical_dam_break_dry.py' res = anuga.run_anuga_script(s, args=args) # Test that script runs ok assert res == 0 if verbose: print indent + 'Testing accuracy' import anuga.utilities.plot_utils as util import analytical_dam_break_dry as analytic p_st = util.get_output('dam_break.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) h0 = 1.0 h1 = 10.0 # calculate analytic values at various time slices h10, u10 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[10], h0=h0, h1=h1) h50, u50 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[50], h0=h0, h1=h1) h100, u100 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[100], h0=h0, h1=h1) #Test stages # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 eh10 = numpy.sum(numpy.abs(p2_st.stage[10, v2] - h10)) / numpy.sum( numpy.abs(h10)) eh50 = numpy.sum(numpy.abs(p2_st.stage[50, v2] - h50)) / numpy.sum( numpy.abs(h50)) eh100 = numpy.sum(numpy.abs(p2_st.stage[100, v2] - h100)) / numpy.sum( numpy.abs(h100)) print print indent + 'Errors in stage: ', eh10, eh50, eh100 #Test xmomenta # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 euh10 = numpy.sum( numpy.abs(p2_st.xmom[10, v2] - u10 * h10)) / numpy.sum( numpy.abs(u10 * h10)) euh50 = numpy.sum( numpy.abs(p2_st.xmom[50, v2] - u50 * h50)) / numpy.sum( numpy.abs(u50 * h50)) euh100 = numpy.sum( numpy.abs(p2_st.xmom[100, v2] - u100 * h100)) / numpy.sum( numpy.abs(u100 * h100)) print indent + 'Errors in xmomentum: ', euh10, euh50, euh100 #Test xvelocity # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 eu10 = numpy.sum(numpy.abs(p2_st.xvel[10, v2] - u10)) / numpy.sum( numpy.abs(u10)) eu50 = numpy.sum(numpy.abs(p2_st.xvel[50, v2] - u50)) / numpy.sum( numpy.abs(u50)) eu100 = numpy.sum(numpy.abs(p2_st.xvel[100, v2] - u100)) / numpy.sum( numpy.abs(u100)) print indent + 'Errors in xvelocity: ', eu10, eu50, eu100 assert eh10 < 0.1, 'Relative L^1 error %g greater than 0.1' % eh10 assert eh50 < 0.1, 'Relative L^1 error %g greater than 0.1' % eh50 assert eh100 < 0.15, 'Relative L^1 error %g greater than 0.15' % eh100 assert euh10 < 0.25, 'Relative L^1 error %g greater than 0.25' % euh10 assert euh50 < 0.25, 'Relative L^1 error %g greater than 0.25' % euh50 assert euh100 < 0.25, 'Relative L^1 error %g greater than 0.25' % euh100 assert eu10 < 2.0, 'Relative L^1 error %g greater than 2.0' % eu10 assert eu50 < 2.0, 'Relative L^1 error %g greater than 2.0' % eu50 assert eu100 < 0.3, 'Relative L^1 error %g greater than 0.3' % eu100
def test_carrier_greenspan_transient(self): if verbose: print print indent + 'Running simulation script' s = 'numerical_cg_transient.py' res = anuga.run_anuga_script(s, args=args) # Test that script runs ok assert res == 0 if verbose: print indent + 'Testing accuracy' import anuga.utilities.plot_utils as util from analytical_cg_transient import analytical_sol p_st = util.get_output('carrier_greenspan.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) x_n = p2_st.x[v2] ids = [1, 15, 30] use_absolute = [False, True, True] n = len(ids) W, UH, Z, H, U = [], [], [], [], [] W_n, U_n, UH_n = [], [], [] #Dimensional parameters L = 5e4 # Length of channel (m) h0 = 5e2 # Height at origin when the water is still g = 9.81 # Gravity for i, id in enumerate(ids): w, z, u = analytical_sol(x_n / L, p2_st.time[id] * sqrt(g * h0) / L) w = w * h0 z = z * h0 u = u * sqrt(g * h0) h = w - z uh = u * h W.append(w) Z.append(z) H.append(h) U.append(u) UH.append(uh) W_n.append(p2_st.stage[id, v2]) UH_n.append(p2_st.xmom[id, v2]) U_n.append(p2_st.xvel[id, v2]) #print id, numpy.max(H[i]), numpy.min(H[i]) #print id, numpy.max(U[i]), numpy.min(U[i]) #print id, numpy.max(U_n[i]), numpy.min(U_n[i]) #Test stages # Calculate L^1 error at times ew = numpy.zeros(n) for i, id in enumerate(ids): ew[i] = numpy.sum(numpy.abs(W_n[i] - W[i])) / numpy.sum( numpy.abs(W[i])) print print indent + 'L^1 Errors in stage: ', ew #Test xmomenta # Calculate L^1 error at times euh = numpy.zeros(n) for i, id in enumerate(ids): euh[i] = numpy.sum(numpy.abs(UH_n[i] - U[i] * H[i])) / numpy.sum( numpy.abs(UH_n[i])) print indent + 'L^1 Errors in xmomentum: ', euh #Test xvelocity # Calculate L^1 error at times eu = numpy.zeros(n) for i, id in enumerate(ids): if use_absolute[i]: eu[i] = numpy.sum(numpy.abs(U_n[i] - U[i])) / len(U[i]) else: eu[i] = numpy.sum(numpy.abs(U_n[i] - U[i])) / numpy.sum( numpy.abs(U[i])) print indent + 'L^1 Errors in xvelocity: ', eu for i, id in enumerate(ids): assert ew[i] < 0.01, 'L^1 error %g greater than 1 percent' % ew[i] for i, id in enumerate(ids): assert euh[ i] < 0.025, 'L^1 error %g greater than 2.5 percent' % euh[i] for i, id in enumerate(ids): assert eu[ i] < 0.025, 'L^1 error %g greater than 2.5 percent' % eu[i]
import numpy from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot ###################################################### # Get ANUGA p = util.get_output('channel_floodplain1.sww', 0.001) pc=util.get_centroids(p, velocity_extrapolation=True) # Indices in the central channel areas v = (pc.x>10.0)*(pc.x<30.0) ###################################################### # Get hecras info rasFile='hecras_tides_case/gauges.csv' rasGauges=numpy.genfromtxt(rasFile,skip_header=3,delimiter=",") # Output at 1 minute intervals rasTime=numpy.linspace(0., 60.*(rasGauges.shape[0]-1), rasGauges.shape[0]) # Get station information for hecras rasFileO=open(rasFile) rasStations=rasFileO.readline().split(',') rasStations[-1]=rasStations[-1].replace('\r\n','') rasFileO.close() ###################################################### def get_corresponding_series(reach, station):
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as pyplot from numpy import ones, zeros p_st = util.get_output("immersed_bump.sww") p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = p2_st.y == v # p_dev = util.get_output('dam_break.sww', 0.001) # p2_dev=util.get_centroids(p_dev, velocity_extrapolation=True) # Plot stages pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[10, v2], "b.", label="numerical stage") pyplot.plot(p2_st.x[v2], p2_st.elev[v2], "k-", label="discretised bed") pyplot.plot(p2_st.x[v2], 0.5 * ones(len(p2_st.x[v2])), "r-", label="analytical stage") pyplot.title("Stage at an instant in time") pyplot.legend(loc="best") pyplot.ylim([0.0, 0.6]) pyplot.xlabel("Xposition") pyplot.ylabel("Stage") pyplot.savefig("stage_plot.png")
def test_dam_break_dry(self): if verbose: print print indent+'Running simulation script' s = 'numerical_dam_break_dry.py' res = anuga.run_anuga_script(s,args=args) # Test that script runs ok assert res == 0 if verbose: print indent+'Testing accuracy' import anuga.utilities.plot_utils as util import analytical_dam_break_dry as analytic p_st = util.get_output('dam_break.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[10] v2=(p2_st.y==v) h0 = 1.0 h1 = 10.0 # calculate analytic values at various time slices h10,u10 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[10], h0=h0, h1=h1) h50,u50 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[50], h0=h0, h1=h1) h100,u100 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[100], h0=h0, h1=h1) #Test stages # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 eh10 = numpy.sum(numpy.abs(p2_st.stage[10,v2]-h10))/numpy.sum(numpy.abs(h10)) eh50 = numpy.sum(numpy.abs(p2_st.stage[50,v2]-h50))/numpy.sum(numpy.abs(h50)) eh100 = numpy.sum(numpy.abs(p2_st.stage[100,v2]-h100))/numpy.sum(numpy.abs(h100)) print print indent+'Errors in stage: ',eh10, eh50, eh100 #Test xmomenta # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 euh10 = numpy.sum(numpy.abs(p2_st.xmom[10,v2]-u10*h10))/numpy.sum(numpy.abs(u10*h10)) euh50 = numpy.sum(numpy.abs(p2_st.xmom[50,v2]-u50*h50))/numpy.sum(numpy.abs(u50*h50)) euh100 = numpy.sum(numpy.abs(p2_st.xmom[100,v2]-u100*h100))/numpy.sum(numpy.abs(u100*h100)) print indent+'Errors in xmomentum: ',euh10, euh50, euh100 #Test xvelocity # Calculate L^1 error at times corrsponding to slices 10, 50 and 100 eu10 = numpy.sum(numpy.abs(p2_st.xvel[10,v2]-u10))/numpy.sum(numpy.abs(u10)) eu50 = numpy.sum(numpy.abs(p2_st.xvel[50,v2]-u50))/numpy.sum(numpy.abs(u50)) eu100 = numpy.sum(numpy.abs(p2_st.xvel[100,v2]-u100))/numpy.sum(numpy.abs(u100)) print indent+'Errors in xvelocity: ', eu10, eu50, eu100 assert eh10 < 0.1, 'Relative L^1 error %g greater than 0.1'% eh10 assert eh50 < 0.1, 'Relative L^1 error %g greater than 0.1'% eh50 assert eh100 < 0.15, 'Relative L^1 error %g greater than 0.15'% eh100 assert euh10 < 0.25, 'Relative L^1 error %g greater than 0.25'% euh10 assert euh50 < 0.25, 'Relative L^1 error %g greater than 0.25'% euh50 assert euh100 < 0.25, 'Relative L^1 error %g greater than 0.25'% euh100 assert eu10 < 2.0, 'Relative L^1 error %g greater than 2.0'% eu10 assert eu50 < 2.0, 'Relative L^1 error %g greater than 2.0'% eu50 assert eu100 < 0.3, 'Relative L^1 error %g greater than 0.3'% eu100
##21098, ##21102, ##21106, ##21110, ##21114, ##21118, ##21122, ##21126, ##21130 ## ] indicesR = [25232, 25236, 25240, 25244, 25248, 25252, 25256, 25260, 25264, 25268, 25272, 25276] # Get the sww file p = util.get_output("dam_break.sww") p2 = util.get_centroids(p) N = len(p2.time) Sh = zeros(N) for i in range(N): for k in range(len(indicesL)): Sh[i] += p2.stage[i, indicesL[k]] ** 2 Sh[i] -= p2.stage[i, indicesR[k]] ** 2 fudge_factor = 1.0 length = 0.12 g = 9.8 rho_w = 1024 average_pressure = 0.5 * g * Sh / len(indicesL) * rho_w
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from numpy import ones, zeros, ones_like p_st = util.get_output('varying_width.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[116] v2 = (p2_st.y == v) #p_dev = util.get_output('dam_break.sww', 0.001) #p2_dev=util.get_centroids(p_dev, velocity_extrapolation=True) #Plot stages pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[-1, v2], 'b.', label='numerical stage') pyplot.plot(p2_st.x[v2], 12. * ones_like(p2_st.x[v2]), 'r--', label='analytical stage') pyplot.plot(p2_st.x[v2], p2_st.elev[v2], 'k-', label='discretised bed') pyplot.title('Stage at an instant in time') pyplot.legend(loc='best') pyplot.xlabel('Xposition') pyplot.ylabel('Stage')
""" Quick plot of the subcritical-flow outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from analytical_subcritical import * from numpy import ones, arange p_st = util.get_output('subcritical.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[10] #v2=(p2_st.y==v) v#2=(p2_st.y>-1.0) v2 = arange(len(p2_st.y)) h,z = analytic_sol(p2_st.x[v2]) #Plot the stages############################################################## pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[-1,v2], 'b.-', label='numerical stage') # 0*T/6 pyplot.plot(p2_st.x[v2], h+z,'r-', label='analytical stage') pyplot.plot(p2_st.x[v2], z,'k-', label='bed elevation') pyplot.title('Stage at time = %s secs'% p2_st.time[-1]) ##pyplot.ylim(-5.0,5.0) pyplot.legend(loc='best') pyplot.xlabel('Xposition') pyplot.ylabel('Stage')
elif c==2: VerP[r] = table[r][c] elif c==3: VerZ[r] = table[r][c] elif c==4: VerH[r] = table[r][c] elif c==5: VerU[r] = table[r][c] Vertices_left = -1.0*Vertices[::-1] VerW_left = VerW[::-1] VerP_left = -1.0*VerP[::-1] VerZ_left = VerZ[::-1] VerH_left = VerH[::-1] VerU_left = -1.0*VerU[::-1] p_st = util.get_output('radial_dam_break.sww') p2_st=util.get_centroids(p_st) v = p2_st.y[79598] v2=(p2_st.y==v) #Plot stages pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[-1,v2],'b.-', label='numerical stage') pyplot.plot(Vertices, VerW,'r-', label='reference stage') pyplot.plot(Vertices_left, VerW_left,'r-') pyplot.title('Stage at an instant in time') pyplot.legend(loc='best') pyplot.xlabel('Radial position') pyplot.ylabel('Stage') pyplot.savefig('stage_plot.png')
"""View results of runup.py """ #--------------- # Import Modules #--------------- import scipy import anuga from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from numpy import zeros p2 = util.get_output('runup.sww', minimum_allowed_height=1.0e-03) p = util.get_centroids(p2, velocity_extrapolation=True) #------------------ # Select line #------------------ py_central = p.y[scipy.argmin(abs(p.y - 0.5))] v = (p.y == p.y[py_central]) #-------------------- # Make plot animation #-------------------- ##pyplot.close() #If the plot is open, there will be problems ##if False: ## line, = pyplot.plot( (p.x[v].min(),p.x[v].max()) ,(p.xvel[:,v].min(),p.xvel[:,v].max() ) ) ## for i in range(p.xmom.shape[0]): ## line.set_xdata(p.x[v])
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from numpy import ones, zeros p_st = util.get_output('immersed_bump.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = (p2_st.y == v) #p_dev = util.get_output('dam_break.sww', 0.001) #p2_dev=util.get_centroids(p_dev, velocity_extrapolation=True) #Plot stages pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[10, v2], 'b.', label='numerical stage') pyplot.plot(p2_st.x[v2], p2_st.elev[v2], 'k-', label='discretised bed') pyplot.plot(p2_st.x[v2], 0.5 * ones(len(p2_st.x[v2])), 'r-', label='analytical stage') pyplot.title('Stage at an instant in time') pyplot.legend(loc='best') pyplot.ylim([0.0, 0.6]) pyplot.xlabel('Xposition')
Compare the Towradgi model runs with various field observations """ import scipy import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot from anuga.utilities import plot_utils as util import gdal swwdir='MODEL_OUTPUTS/' swwname='Towradgi_historic_flood.sww' #'Aug98_hort_discontinous.sww' #'Towradgi_historic_flood.sww' p=util.get_output(swwdir+swwname) p2=util.get_centroids(p,velocity_extrapolation=True) floodLevels=scipy.genfromtxt('Validation/historic_1998_flood_levels_towradgi_ck.csv', delimiter=',',skip_header=1) pioneerLevel=scipy.genfromtxt('Validation/pioneer_timeseries.txt', skip_header=1) # Extract modelled peak at the coordinates in floodLevels modelled_ind=floodLevels[:,0]*0 modelled_level=floodLevels[:,0]*0 for i in range(len(modelled_level)): # Convert the physical coordinate to ANUGA coordinate system pt_x=floodLevels[i,0]-p.xllcorner pt_y=floodLevels[i,1]-p.yllcorner # Find the nearest index of the physical coordinate in the centroids myInd=( (p2.x-pt_x)**2 + (p2.y-pt_y)**2).argmin()
def run_simulation(parallel=False, verbose=False): #-------------------------------------------------------------------------- # Setup computational domain and quantities #-------------------------------------------------------------------------- if myid == 0: anuga.create_mesh_from_regions( boundaryPolygon, boundary_tags={ 'left': [0], 'top': [1], 'right': [2], 'bottom': [3] }, maximum_triangle_area=1.0e+20, minimum_triangle_angle=28.0, filename='runup.msh', interior_regions=[[higherResPolygon, 1. * 1. * 0.5], [midResPolygon, 3.0 * 3.0 * 0.5]], breaklines=list(riverWall.values()), use_cache=False, verbose=verbose, regionPtArea=regionPtAreas) sdomain = anuga.create_domain_from_file('runup.msh') sdomain.set_flow_algorithm(alg) sdomain.set_name('s_riverwall') sdomain.set_datadir('.') sdomain.set_store_vertices_uniquely() #------------------ # Define topography #------------------ def topography(x, y): return -x / 150. * scale_me def stagefun(x, y): stg = -0.5 * scale_me return stg sdomain.set_quantity('elevation', topography) # Use function for elevation sdomain.set_quantity('friction', 0.03) # Constant friction sdomain.set_quantity('stage', stagefun) # Constant negative initial stage else: sdomain = None #-------------------------------------------------------------------------- # Create the parallel domains #-------------------------------------------------------------------------- if parallel: if myid == 0 and verbose: print('DISTRIBUTING TO PARALLEL DOMAIN') pdomain = distribute(sdomain, verbose=verbose) pdomain.set_name('p_riverwall') pdomain.set_store_vertices_uniquely() if myid == 0 and verbose: print(60 * '=') print('EVOLVING pdomain') print(60 * '=') setup_and_evolve(pdomain, verbose=verbose) barrier() if myid == 0: if verbose: print(60 * '=') print('EVOLVING sdomain') print(60 * '=') setup_and_evolve(sdomain, verbose=verbose) barrier() #--------------------------------- # Now compare the merged sww files #--------------------------------- if myid == 0: if verbose: print('COMPARING SWW FILES') sdomain_v = util.get_output('s_riverwall.sww') sdomain_c = util.get_centroids(sdomain_v) pdomain_v = util.get_output('p_riverwall.sww') pdomain_c = util.get_centroids(pdomain_v) # Test some values against the original ordering if verbose: order = 0 print('PDOMAIN CENTROID VALUES') print(num.linalg.norm(sdomain_c.x - pdomain_c.x, ord=order)) print(num.linalg.norm(sdomain_c.y - pdomain_c.y, ord=order)) print( num.linalg.norm(sdomain_c.stage[-1] - pdomain_c.stage[-1], ord=order)) print( num.linalg.norm(sdomain_c.xmom[-1] - pdomain_c.xmom[-1], ord=order)) print( num.linalg.norm(sdomain_c.ymom[-1] - pdomain_c.ymom[-1], ord=order)) print( num.linalg.norm(sdomain_c.xvel[-1] - pdomain_c.xvel[-1], ord=order)) print( num.linalg.norm(sdomain_c.yvel[-1] - pdomain_c.yvel[-1], ord=order)) assert num.allclose(sdomain_c.stage, pdomain_c.stage) assert num.allclose(sdomain_c.xmom, pdomain_c.xmom) assert num.allclose(sdomain_c.ymom, pdomain_c.ymom) assert num.allclose(sdomain_c.xvel, pdomain_c.xvel) assert num.allclose(sdomain_c.yvel, pdomain_c.yvel) assert num.allclose(sdomain_v.x, pdomain_v.x) assert num.allclose(sdomain_v.y, pdomain_v.y) import os os.remove('s_riverwall.sww') os.remove('p_riverwall.sww') os.remove('runup.msh')
""" Quick plot of the dam break outputs """ import anuga.utilities.plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot import analytical_dam_break_wet as analytic import numpy p_st = util.get_output('dam_break.sww') p2_st = util.get_centroids(p_st) v = p2_st.y[10] v2 = numpy.argwhere(p2_st.y == v).flatten() iv2 = numpy.argsort(p2_st.x[v2]) v2 = v2[iv2] h0 = 1.0 h1 = 10.0 h10, u10 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[10], h0=h0, h1=h1) h50, u50 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[50], h0=h0, h1=h1) h100, u100 = analytic.vec_dam_break(p2_st.x[v2], p2_st.time[100], h0=h0, h1=h1) #Plot stages pyplot.clf() pyplot.plot(p2_st.x[v2], p2_st.stage[10, v2], 'b.', label='numerical t=10') pyplot.plot(p2_st.x[v2], p2_st.stage[50, v2], 'g.', label='numerical t=50') pyplot.plot(p2_st.x[v2], p2_st.stage[100, v2], 'r.', label='numerical t=100')
from anuga.utilities import plot_utils as util import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as pyplot import numpy from project import * filename = 'channel_floodplain.sww' # Time-index to plot outputs from p2 = util.get_output(filename) p=util.get_centroids(p2, velocity_extrapolation=True) v = (p.x>6.0)*(p.x<8.0) print numpy.any(v) # Numerical results along a central channel 'slice' index= -1 V1 = p.stage[index,v] - p.elev[v] V2 = p.yvel[index,v] V3 = p.xvel[index,v] ########################################################################## # Analytical solution of steady uniform 2D flow in a trapezoidal channel. ########################################################################## Qin=4.6932 # Inflow discharge slp=1./300. # Floodplain slope (= water slope for steady uniform flow) man_n=0.03 # Manning's n Bcentral=6.0 #Flat bed width of the trapezoidal channel alpha=0.5 # Side slope of the trapezoidal banks