예제 #1
0
    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')
예제 #2
0
    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')
예제 #3
0
    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)
예제 #4
0
    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)
예제 #5
0
 def test_quantity_consistency(self):
     """
         Check that the expected relations exist between stage, elevation,
             height, xmom,xvel,ymom,yvel
     """
     for flowAlg in flow_algorithms:
         if(verbose):
             print flowAlg
         self.create_domain(InitialOceanStage=1., InitialLandStage=0., flowAlg=flowAlg, verbose=verbose)
         pc=util.get_centroids('test_plot_utils.sww')
         l=len(pc.time)-1
         self.quantity_consistency_check(pc,l)
         
     os.remove('test_plot_utils.sww')
예제 #6
0
    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')
예제 #7
0
    def test_quantity_consistency(self):
        """
            Check that the expected relations exist between stage, elevation,
                height, xmom,xvel,ymom,yvel
        """
        for flowAlg in flow_algorithms:
            if (verbose):
                print flowAlg
            self.create_domain(InitialOceanStage=1.,
                               InitialLandStage=0.,
                               flowAlg=flowAlg,
                               verbose=verbose)
            pc = util.get_centroids('test_plot_utils.sww')
            l = len(pc.time) - 1
            self.quantity_consistency_check(pc, l)

        os.remove('test_plot_utils.sww')
예제 #8
0
    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')
예제 #9
0
 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')
예제 #10
0
    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.) )
예제 #11
0
    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')
예제 #12
0
    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.))
예제 #13
0
    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
예제 #14
0
    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
예제 #15
0
"""
    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_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]
예제 #17
0
    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]
    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]
예제 #19
0
    Quick plot of the dam break outputs

"""
import numpy
from numpy import zeros
import anuga.utilities.plot_utils as util
import matplotlib

matplotlib.use("Agg")
from matplotlib import pyplot as pyplot
from math import sqrt, pi, cos, sin
from analytical_parabolic_basin import analytic_cannal

# Get the sww file
p_st = util.get_output("parabola.sww")
p2_st = util.get_centroids(p_st, velocity_extrapolation=True)  # (p_st, velocity_extrapolation=True)

index_origin = 3978
v = p2_st.y[index_origin]
v2 = p2_st.y == v


# Compute the analytical solution
time_level = 200
u, h, w, z = analytic_cannal(p2_st.x[v2], p2_st.time[time_level])

# Plot stages
pyplot.clf()
pyplot.plot(p2_st.x[v2], p2_st.stage[time_level, v2], "b.", label="numerical stage")
pyplot.plot(p2_st.x[v2], p2_st.elev[v2], "k-", label="bed elevation")
pyplot.plot(p2_st.x[v2], w, "r-", label="analytical stage")
예제 #20
0
##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
예제 #21
0
    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
    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]
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')
예제 #24
0
    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
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')
예제 #26
0
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()
예제 #27
0
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):
예제 #28
0
    def test_avalanche_wet(self):

        if verbose:
            print
            print indent + "Running simulation script"

        s = "numerical_avalanche_wet.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_wet import analytical_sol

        p_st = util.get_output("avalanche.sww")
        p2_st = util.get_centroids(p_st)

        v = p2_st.y[20]
        v2 = p2_st.y == v

        x_n = p2_st.x[v2]

        u0, h0, w0, z0, p0 = analytical_sol(x_n, p2_st.time[0])
        u20, h20, w20, z20, p20 = analytical_sol(x_n, p2_st.time[20])
        u40, h40, w40, z40, p40 = analytical_sol(x_n, p2_st.time[40])

        w0_n = p2_st.stage[0, v2]
        w20_n = p2_st.stage[20, v2]
        w40_n = p2_st.stage[40, v2]

        z_n = p2_st.elev[v2]

        uh0_n = p2_st.xmom[0, v2]
        uh20_n = p2_st.xmom[20, v2]
        uh40_n = p2_st.xmom[40, v2]

        u0_n = p2_st.xvel[0, v2]
        u20_n = p2_st.xvel[20, v2]
        u40_n = p2_st.xvel[40, v2]

        # Test stages
        # Calculate L^1 error at times corrsponding to slices 20, 40
        eh20 = numpy.sum(numpy.abs(w20_n - w20)) / numpy.sum(numpy.abs(w20))
        eh40 = numpy.sum(numpy.abs(w40_n - w40)) / numpy.sum(numpy.abs(w40))

        print
        print indent + "Errors in stage: ", eh20, eh40

        # Test xmomenta
        # Calculate L^1 error at times corrsponding to slices 20, 40
        euh20 = numpy.sum(numpy.abs(uh20_n - u20 * h20)) / numpy.sum(numpy.abs(u20 * h20))
        euh40 = numpy.sum(numpy.abs(uh40_n - u40 * h40)) / numpy.sum(numpy.abs(u40 * h40))

        print indent + "Errors in xmomentum: ", euh20, euh40

        # Test xvelocity
        # Calculate L^1 error at times corrsponding to slices 20, 40
        eu20 = numpy.sum(numpy.abs(u20_n - u20)) / numpy.sum(numpy.abs(u20))
        eu40 = numpy.sum(numpy.abs(u40_n - u40)) / numpy.sum(numpy.abs(u40))

        print indent + "Errors in xvelocity: ", eu20, eu40

        assert eh20 < 0.01, "L^1 error %g greater than 1 percent" % eh20
        assert eh40 < 0.01, "L^1 error %g greater than 1 percent" % eh40

        assert euh20 < 0.025, "L^1 error %g greater than 2.5 percent" % euh20
        assert euh40 < 0.025, "L^1 error %g greater than 2.5 percent" % euh40

        assert eu20 < 0.02, "L^1 error %g greater than 2 percent" % eu20
        assert eu40 < 0.01, "L^1 error %g greater than 2 percent" % eu40
예제 #29
0
    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
예제 #30
0
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)
예제 #31
0
    def test_avalanche_wet(self):

        if verbose:
            print
            print indent + 'Running simulation script'

        s = 'numerical_avalanche_wet.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_wet import analytical_sol

        p_st = util.get_output('avalanche.sww')
        p2_st = util.get_centroids(p_st)

        v = p2_st.y[20]
        v2 = (p2_st.y == v)

        x_n = p2_st.x[v2]

        u0, h0, w0, z0, p0 = analytical_sol(x_n, p2_st.time[0])
        u20, h20, w20, z20, p20 = analytical_sol(x_n, p2_st.time[20])
        u40, h40, w40, z40, p40 = analytical_sol(x_n, p2_st.time[40])

        w0_n = p2_st.stage[0, v2]
        w20_n = p2_st.stage[20, v2]
        w40_n = p2_st.stage[40, v2]

        z_n = p2_st.elev[v2]

        uh0_n = p2_st.xmom[0, v2]
        uh20_n = p2_st.xmom[20, v2]
        uh40_n = p2_st.xmom[40, v2]

        u0_n = p2_st.xvel[0, v2]
        u20_n = p2_st.xvel[20, v2]
        u40_n = p2_st.xvel[40, v2]

        #Test stages
        # Calculate L^1 error at times corrsponding to slices 20, 40
        eh20 = numpy.sum(numpy.abs(w20_n - w20)) / numpy.sum(numpy.abs(w20))
        eh40 = numpy.sum(numpy.abs(w40_n - w40)) / numpy.sum(numpy.abs(w40))

        print
        print indent + 'Errors in stage: ', eh20, eh40

        #Test xmomenta
        # Calculate L^1 error at times corrsponding to slices 20, 40
        euh20 = numpy.sum(numpy.abs(uh20_n - u20 * h20)) / numpy.sum(
            numpy.abs(u20 * h20))
        euh40 = numpy.sum(numpy.abs(uh40_n - u40 * h40)) / numpy.sum(
            numpy.abs(u40 * h40))

        print indent + 'Errors in xmomentum: ', euh20, euh40

        #Test xvelocity
        # Calculate L^1 error at times corrsponding to slices 20, 40
        eu20 = numpy.sum(numpy.abs(u20_n - u20)) / numpy.sum(numpy.abs(u20))
        eu40 = numpy.sum(numpy.abs(u40_n - u40)) / numpy.sum(numpy.abs(u40))

        print indent + 'Errors in xvelocity: ', eu20, eu40

        assert eh20 < 0.01, 'L^1 error %g greater than 1 percent' % eh20
        assert eh40 < 0.01, 'L^1 error %g greater than 1 percent' % eh40

        assert euh20 < 0.025, 'L^1 error %g greater than 2.5 percent' % euh20
        assert euh40 < 0.025, 'L^1 error %g greater than 2.5 percent' % euh40

        assert eu20 < 0.02, 'L^1 error %g greater than 2 percent' % eu20
        assert eu40 < 0.01, 'L^1 error %g greater than 2 percent' % eu40
예제 #32
0
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')
예제 #33
0
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
"""
    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')
"""
    Quick plot of the dam break outputs

"""
import numpy
from numpy import zeros
import anuga.utilities.plot_utils as util
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as pyplot
from math import sqrt, pi, cos, sin
from analytical_parabolic_basin import analytic_cannal

# Get the sww file
p_st = util.get_output('parabola.sww')
p2_st = util.get_centroids(
    p_st, velocity_extrapolation=True)  #(p_st, velocity_extrapolation=True)

index_origin = 3978
v = p2_st.y[index_origin]
v2 = (p2_st.y == v)

# Compute the analytical solution
time_level = 200
u, h, w, z = analytic_cannal(p2_st.x[v2], p2_st.time[time_level])

#Plot stages
pyplot.clf()
pyplot.plot(p2_st.x[v2],
            p2_st.stage[time_level, v2],
            'b.',
            label='numerical stage')