示例#1
0
def generate_channel1_domain(gpu=True):
    #--------------------------------------------------------------------------
    # Setup computational domain
    #--------------------------------------------------------------------------

    #points, vertices, boundary = anuga.rectangular_cross(10, 1,
    #                                               len1=10.0, len2=5.0) # Mesh
    points, vertices, boundary = anuga.rectangular_cross(1,
                                                         4,
                                                         len1=0.1,
                                                         len2=0.1)  # Mesh

    if gpu:
        domain = GPU_domain(points, vertices, boundary)  # Create domain
        for i in range(len(sys.argv)):
            if sys.argv[i] == '-gpu':
                domain.using_gpu = True
                print " --> Enable GPU version"
            elif sys.argv[i] == '-fs':
                finaltime = float(sys.argv[i + 1])
                print " --> Finaltime is reset as %f" % finaltime
            elif sys.argv[i] == '-test':
                domain.cotesting = True
                print " --> Enable Cotesting"
            elif sys.argv[i] == '-ustore':
                domain.store = True
                print " --> Disable storing"
    else:
        domain = anuga.Domain(points, vertices, boundary)  # Create domain
    domain.set_name('channel1')  # Output name

    #--------------------------------------------------------------------------
    # Setup initial conditions
    #--------------------------------------------------------------------------
    def topography(x, y):
        return -x / 10  # linear bed slope

    domain.set_quantity('elevation', topography)  # Use function for elevation
    domain.set_quantity('friction', 0.01)  # Constant friction
    domain.set_quantity(
        'stage',  # Dry bed
        expression='elevation')

    #--------------------------------------------------------------------------
    # Setup boundary conditions
    #--------------------------------------------------------------------------
    Bi = anuga.Dirichlet_boundary([0.4, 0, 0])  # Inflow
    Br = anuga.Reflective_boundary(domain)  # Solid reflective wall

    domain.set_boundary({'left': Bi, 'right': Br, 'top': Br, 'bottom': Br})

    return domain
示例#2
0
    def setUp(self):

        def elevation_function(x, y):
            return -x
        
        """ Setup for all tests. """
        
        mesh_file = tempfile.mktemp(".tsh")    
        points = [[0.0,0.0],[6.0,0.0],[6.0,6.0],[0.0,6.0]]
        m = Mesh()
        m.add_vertices(points)
        m.auto_segment()
        m.generate_mesh(verbose=False)
        m.export_mesh_file(mesh_file)
        
        # Create shallow water domain
        domain = anuga.Domain(mesh_file)
        os.remove(mesh_file)
 
        domain.default_order = 2

        # This test was made before tight_slope_limiters were introduced
        # Since were are testing interpolation values this is OK
        domain.tight_slope_limiters = 0
                
        # Set some field values
        domain.set_quantity('elevation', elevation_function)
        domain.set_quantity('friction', 0.03)
        domain.set_quantity('xmomentum', 3.0)
        domain.set_quantity('ymomentum', 4.0)

        ######################
        # Boundary conditions
        B = anuga.Transmissive_boundary(domain)
        domain.set_boundary( {'exterior': B})

        # This call mangles the stage values.
        domain.distribute_to_vertices_and_edges()
        domain.set_quantity('stage', 1.0)

        domain.set_name('datatest' + str(time.time()))
        domain.smooth = True
        domain.reduction = mean
        
        self.domain = domain
示例#3
0
def generate_domain():
    #--------------------------------------------------------------------------
    # Setup computational domain
    #--------------------------------------------------------------------------
    length = 10.
    width = 5.
    dx = dy = 1.  # Resolution: Length of subdivisions on both axes

    points, vertices, boundary = anuga.rectangular_cross(int(length / dx),
                                                         int(width / dy),
                                                         len1=length,
                                                         len2=width)

    domain = anuga.Domain(points, vertices, boundary)
    domain.set_name('channel2')  # Output name

    #--------------------------------------------------------------------------
    # Setup initial conditions
    #--------------------------------------------------------------------------
    def topography(x, y):
        return -x / 10  # linear bed slope

    domain.set_quantity('elevation', topography)  # Use function for elevation
    domain.set_quantity('friction', 0.01)  # Constant friction
    domain.set_quantity('stage',
                        expression='elevation')  # Dry initial condition

    #--------------------------------------------------------------------------
    # Setup boundary conditions
    #--------------------------------------------------------------------------
    Bi = anuga.Dirichlet_boundary([0.4, 0, 0])  # Inflow
    Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
    Bo = anuga.Dirichlet_boundary([-5, 0, 0])  # Outflow

    domain.set_boundary({'left': Bi, 'right': Br, 'top': Br, 'bottom': Br})
    import sys
    if len(sys.argv) > 1 and "gpu" in sys.argv:
        domain.using_gpu = True
    else:
        domain.using_gpu = False
    print sys.argv, "gpu" in sys.argv
    return domain
    def test_estimate_time_mem(self):
        points, vertices, boundary = anuga.rectangular_cross(10,
                                                             5,
                                                             len1=10.0,
                                                             len2=5.0)  # Mesh

        domain = anuga.Domain(points, vertices, boundary)  # Create domain
        tri_num = len(domain)
        yieldstep = 360
        finaltime = 3600

        time, memory = estimate_time_mem(domain,
                                         yieldstep,
                                         finaltime,
                                         use_test_constants=True,
                                         log_results=False)

        actual = system_constants[TEST_CON]['tri_a_T'] * tri_num ** 2 + \
            system_constants[TEST_CON]['tri_b_T'] * tri_num + \
            system_constants[TEST_CON]['tim_a_T'] * finaltime + \
            (system_constants[TEST_CON]['fil_a_T'] * finaltime / yieldstep) + \
            system_constants[TEST_CON]['cons_T']
        self.assertEqual(time, actual)
示例#5
0
        'top': [7, 8, 9, 10, 11],
        'outflow': [6]
    },
    #boundary_tags=None,
    maximum_triangle_area=0.1,
    breaklines=riverWalls.values(),
    interior_regions=interior_regions,
    filename=meshname,
    use_cache=False,
    verbose=True)

#------------------------------------------------------------------------------
# SETUP COMPUTATIONAL DOMAIN
#------------------------------------------------------------------------------

domain = anuga.Domain(meshname, use_cache=False, verbose=True)
domain.set_minimum_storable_height(0.0)
domain.riverwallData.create_riverwalls(riverWalls)
domain.set_name(outname)

print(domain.statistics())

#------------------------------------------------------------------------------
# APPLY MANNING'S ROUGHNESSES
#------------------------------------------------------------------------------

domain.set_quantity('friction', 0.025)

# Set a Initial Water Level over the Domain
domain.set_quantity('stage', 0)
extslope=0.04
buffslope=0.2
lakeslope=0.4
initbreachwidth=0.08
initbreachdepth=0.08

lakeregion=[[0,0],[0.28,0],[0.28,craterwidth],[0,craterwidth],[0,0]]
nextregion=[[0.28,0],[0.28,craterwidth],[4,craterwidth],[4,0],[0.28,0]]
endregion=[[4,craterwidth],[5,craterwidth],[5,0],[4,0],[4,craterwidth]]


meshname='lake.msh'
m = anuga.create_mesh_from_regions(domainpolygon, boundary_tags, maximum_triangle_area=low_res,interior_regions=interior_regions,filename=meshname, use_cache=False)
evolved_quantities =  ['stage', 'xmomentum', 'ymomentum', 'concentration', 'sedvolx', 'sedvoly']
#evolved_quantities =  ['stage', 'xmomentum', 'ymomentum', 'concentration']
domain = anuga.Domain(meshname, use_cache=False, evolved_quantities = evolved_quantities)
domain.g = anuga.g  # make sure the domain inherits the package's gravity.

print 'Number of triangles = ', len(domain)

def find_nearest(array, value):
    array = np.asarray(array)
    idx = (np.abs(array - value)).argmin()
    return idx
    
def topography(x, y):
    maxx = np.max(x)
    miny, maxy = np.min(y), np.max(y)
    
    #sets slope of flume surface
    z=(4.0-x)*(extslope)
# Domain
#-------------------------------------------------------------------------------
n = 75#50
m = 75#50
lenx = 8000.0
leny = 8000.0
origin = (-4000.0, -4000.0)



#===============================================================================
# Create Sequential Domain
#===============================================================================
if myid == 0:
    points, elements, boundary = anuga.rectangular_cross(m, n, lenx, leny, origin)
    domain = anuga.Domain(points, elements, boundary)


    domain.set_name(output_file)                
    domain.set_datadir(output_dir)
    
    domain.set_flow_algorithm(alg)

    
    #-------------------------------------------------------------------------------
    # Initial conditions
    #-------------------------------------------------------------------------------
    t = 0.0
    D0 = 1000.
    L = 2500.
    R0 = 2000.
示例#8
0
from anuga.coordinate_transforms.geo_reference import Geo_reference
import anuga.load_mesh.loadASCII as loadASCII

file_name = "output_skewed.msh"
myid = 0
verbose = True

# The parallel interface
#from anuga import distribute, myid, numprocs, finalize, barrier

#------------------------------------------------------------------------------
# Do the domain creation on processor 0
#------------------------------------------------------------------------------
print '##################### %i #########################' % myid
if anuga.myid == 0:
    domain = anuga.Domain(mesh_filename=file_name)

else:
    domain = None

#------------------------------------------------------------------------------
# Now produce parallel domain
#------------------------------------------------------------------------------
domain = anuga.distribute(domain, verbose=verbose)

if anuga.myid == 0:
    # Print some stats about mesh and domain
    print 'Number of triangles = ', len(domain)
    print 'The extent is ', domain.get_extent()

domain.set_quantity('stage', -10)
    def test_momentum_jet(self):
        """test_momentum_jet
        
        Test that culvert_class can accept keyword use_momentum_jet
        This does not yet imply that the values have been tested. FIXME
        """

        length = 40.
        width = 5.

        dx = dy = 1  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)
        domain.set_name('Test_culvert_shallow')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z = -x / 1000

            N = len(x)
            for i in range(N):

                # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face
                    if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] -
                                                                5.0) / 5.0:
                        z[i] = z[i]
                    else:
                        z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                    z[i] += 2.5  # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face
                    if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] -
                                                                 12.0) / 2.5:
                        z[i] = z[i]
                    else:
                        z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity(
            'stage', expression='elevation + 1.0')  # Shallow initial condition

        # Boyd culvert
        culvert = Culvert_flow(
            domain,
            label='Culvert No. 1',
            description='This culvert is a test unit 1.2m Wide by 0.75m High',
            end_point0=[9.0, 2.5],
            end_point1=[13.0, 2.5],
            width=1.20,
            height=0.75,
            culvert_routine=boyd_generalised_culvert_model,
            number_of_barrels=1,
            use_momentum_jet=True,
            update_interval=2,
            verbose=False)

        domain.forcing_terms.append(culvert)

        # Call
        culvert(domain)

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        ref_volume = domain.get_quantity('stage').get_integral()
        for t in domain.evolve(yieldstep=0.1, finaltime=25):
            new_volume = domain.get_quantity('stage').get_integral()

            msg = (
                'Total volume has changed: Is %.8f m^3 should have been %.8f m^3'
                % (new_volume, ref_volume))
            assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
    def test_that_culvert_dry_bed_boyd_does_not_produce_flow(self):
        """test_that_culvert_in_dry_bed_boyd_does_not_produce_flow(self):
        
        Test that culvert on a sloping dry bed doesn't produce flows
        although there will be a 'pressure' head due to delta_w > 0

        This one is using the 'Boyd' variant        
        """

        path = get_pathname_from_package('anuga.culvert_flows')

        length = 40.
        width = 5.

        dx = dy = 1  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)
        domain.set_name('Test_culvert_dry')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z = -x / 1000

            N = len(x)
            for i in range(N):

                # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face
                    if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] -
                                                                5.0) / 5.0:
                        z[i] = z[i]
                    else:
                        z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                    z[i] += 2.5  # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face
                    if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] -
                                                                 12.0) / 2.5:
                        z[i] = z[i]
                    else:
                        z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity('stage',
                            expression='elevation')  # Dry initial condition

        filename = os.path.join(path, 'example_rating_curve.csv')

        culvert = Culvert_flow(
            domain,
            label='Culvert No. 1',
            description='This culvert is a test unit 1.2m Wide by 0.75m High',
            end_point0=[9.0, 2.5],
            end_point1=[13.0, 2.5],
            width=1.20,
            height=0.75,
            culvert_routine=boyd_generalised_culvert_model,
            number_of_barrels=1,
            update_interval=2,
            verbose=False)

        domain.forcing_terms.append(culvert)

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum

        Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        ref_volume = domain.get_quantity('stage').get_integral()
        for t in domain.evolve(yieldstep=1, finaltime=25):

            new_volume = domain.get_quantity('stage').get_integral()

            msg = 'Total volume has changed'
            assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
            pass
def run_simulation(parallel=False,
                   control_data=None,
                   test_points=None,
                   verbose=False):
    success = True

    ##-----------------------------------------------------------------------
    ## Setup domain
    ##-----------------------------------------------------------------------

    points, vertices, boundary = rectangular_cross(int(length / dx),
                                                   int(width / dy),
                                                   len1=length,
                                                   len2=width)

    domain = anuga.Domain(points, vertices, boundary)
    #rm *.swwdomain.set_name('output_parallel_inlet_operator')                 # Output name
    domain.set_store(False)
    domain.set_default_order(2)

    ##-----------------------------------------------------------------------
    ## Distribute domain
    ##-----------------------------------------------------------------------

    if parallel:
        domain = distribute(domain)
        #domain.dump_triangulation("frac_op_domain.png")

    ##-----------------------------------------------------------------------
    ## Setup boundary conditions
    ##-----------------------------------------------------------------------

    domain.set_quantity('elevation', topography)
    domain.set_quantity('friction', 0.01)  # Constant friction
    domain.set_quantity('stage',
                        expression='elevation')  # Dry initial condition

    Bi = anuga.Dirichlet_boundary([5.0, 0.0, 0.0])
    Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
    domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

    ##-----------------------------------------------------------------------
    ## Determine triangle index coinciding with test points
    ##-----------------------------------------------------------------------

    assert (test_points is not None)
    assert (len(test_points) == samples)

    tri_ids = []

    for point in test_points:
        try:
            k = domain.get_triangle_containing_point(point)
            if domain.tri_full_flag[k] == 1:
                tri_ids.append(k)
            else:
                tri_ids.append(-1)
        except:
            tri_ids.append(-2)

    if verbose: print 'P%d has points = %s' % (myid, tri_ids)

    if not parallel: control_data = []

    ################ Define Fractional Operators ##########################

    inlet0 = None
    inlet1 = None
    boyd_box0 = None

    inlet0 = Inlet_operator(domain, line0, Q0, verbose=False, default=0.0)
    inlet1 = Inlet_operator(domain, line1, Q1, verbose=False)

    if inlet0 is not None and verbose: inlet0.print_statistics()
    if inlet1 is not None and verbose: inlet1.print_statistics()
    #if boyd_box0 is not None and verbose: boyd_box0.print_statistics()

    ##-----------------------------------------------------------------------
    ## Evolve system through time
    ##-----------------------------------------------------------------------

    for t in domain.evolve(yieldstep=2.0, finaltime=40.0):
        if myid == 0 and verbose:
            domain.write_time()

        #print domain.volumetric_balance_statistics()

        stage = domain.get_quantity('stage')

        #if boyd_box0 is not None and verbose : boyd_box0.print_timestepping_statistics()

        #for i in range(samples):
        #    if tri_ids[i] >= 0:
        #        if verbose: print 'P%d tri %d, value = %s' %(myid, i, stage.centroid_values[tri_ids[i]])

        sys.stdout.flush()

        pass

    domain.sww_merge(delete_old=True)

    success = True

    ##-----------------------------------------------------------------------
    ## Assign/Test Control data
    ##-----------------------------------------------------------------------

    if not parallel:
        stage = domain.get_quantity('stage')

        for i in range(samples):
            assert (tri_ids[i] >= 0)
            control_data.append(stage.centroid_values[tri_ids[i]])

        if inlet0 is not None:
            control_data.append(inlet0.inlet.get_average_stage())
            control_data.append(inlet0.inlet.get_average_xmom())
            control_data.append(inlet0.inlet.get_average_ymom())
            control_data.append(inlet0.inlet.get_total_water_volume())
            control_data.append(inlet0.inlet.get_average_depth())

        if verbose: print 'P%d control_data = %s' % (myid, control_data)
    else:
        stage = domain.get_quantity('stage')

        for i in range(samples):
            if tri_ids[i] >= 0:
                local_success = num.allclose(control_data[i],
                                             stage.centroid_values[tri_ids[i]])
                success = success and local_success
                if verbose:
                    print 'P%d tri %d, control = %s, actual = %s, Success = %s' % (
                        myid, i, control_data[i],
                        stage.centroid_values[tri_ids[i]], local_success)

        if inlet0 is not None:
            inlet_master_proc = inlet0.inlet.get_master_proc()
            average_stage = inlet0.inlet.get_global_average_stage()
            average_xmom = inlet0.inlet.get_global_average_xmom()
            average_ymom = inlet0.inlet.get_global_average_ymom()
            average_volume = inlet0.inlet.get_global_total_water_volume()
            average_depth = inlet0.inlet.get_global_average_depth()

            if myid == inlet_master_proc:
                if verbose:
                    print 'P%d average stage, control = %s, actual = %s' % (
                        myid, control_data[samples], average_stage)

                    print 'P%d average xmom, control = %s, actual = %s' % (
                        myid, control_data[samples + 1], average_xmom)

                    print 'P%d average ymom, control = %s, actual = %s' % (
                        myid, control_data[samples + 2], average_ymom)

                    print 'P%d average volume, control = %s, actual = %s' % (
                        myid, control_data[samples + 3], average_volume)

                    print 'P%d average depth, control = %s, actual = %s' % (
                        myid, control_data[samples + 4], average_depth)

        assert (success)

    return control_data
示例#12
0
def runOkushiri(par, n):
    # ------------------------------------------------------------------------------
    # Setup computational domain
    # ------------------------------------------------------------------------------
    xleft = 0
    xright = 5.448
    ybottom = 0
    ytop = 3.402

    # rectangular cross mesh
    points, vertices, boundary = anuga.rectangular_cross(
        int(n), int(n), xright - xleft, ytop - ybottom, (xleft, ybottom))

    newpoints = points.copy()

    # make refinement in x direction
    x = np.multiply([0., 0.1, 0.2, 0.335, 0.925, 1.], max(points[:, 0]))
    y = [0., 3., 4.25, 4.7, 5.3, max(points[:, 0])]
    f1 = interp1d(x, y, kind='quadratic')
    newpoints[:, 0] = f1(points[:, 0])

    # make refinement in y direction
    x = np.multiply([0., .125, .3, .7, .9, 1.], max(points[:, 1]))
    y = [0., 1.25, 1.75, 2.15, 2.65, max(points[:, 1])]
    f2 = interp1d(x, y, kind='quadratic')
    newpoints[:, 1] = f2(points[:, 1])

    c = abs(newpoints[:, 0] - 5.0) + .5 * abs(newpoints[:, 1] - 1.95)
    c = 0.125 * c

    points[:, 0] = c * points[:, 0] + (1 - c) * newpoints[:, 0]
    points[:, 1] = c * points[:, 1] + (1 - c) * newpoints[:, 1]

    # create domain
    domain = anuga.Domain(points, vertices, boundary)

    # don't store .sww file
    # domain.set_quantities_to_be_stored(None)

    # ------------------------------------------------------------------------------
    # Initial Conditions
    # ------------------------------------------------------------------------------
    domain.set_quantity('friction', 0.01)  # 0.0
    domain.set_quantity('stage', 0.0)
    domain.set_quantity(
        'elevation',
        filename='/home/rehmemk/git/anugasgpp/Okushiri/data/bathymetry.pts',
        alpha=0.02)

    # ------------------------------------------------------------------------------
    # Set simulation parameters
    # ------------------------------------------------------------------------------
    domain.set_name('output_okushiri')  # Output name
    domain.set_minimum_storable_height(0.001)  # Don't store w < 0.001m
    domain.set_flow_algorithm('DE0')

    # ------------------------------------------------------------------------------
    # Modify input wave
    # ------------------------------------------------------------------------------
    # rescale input parameter
    try:
        dummy = len(par)
    except:
        par = [par]
    par = np.dot(2, par)

    # load wave data
    # shutil.copyfile('boundary_wave_header.txt', 'boundary_wave_input.txt')
    data = np.loadtxt(
        '/home/rehmemk/git/anugasgpp/Okushiri/data/boundary_wave_original.txt',
        skiprows=1)
    t = data[:, 0]
    y = data[:, 1]
    energy = np.trapz(y**2, t)

    # define bumps [create input wave based on parameters]
    def bump(c):
        theta = c[0]
        position = c[1]
        weight = c[2]
        ybump = weight * np.exp(-.5 * (t - position)**2 * theta**-2)
        return ybump

    nbump = len(par)
    residual = y.copy()
    c = np.zeros((nbump, 3))
    for k in range(nbump):
        maxid = np.argmax(np.abs(residual))
        c0 = np.array([1.5, t[maxid], residual[maxid]])

        def cost(c):
            ybump = bump(c)
            cost = np.sqrt(np.mean((ybump - residual)**2))
            return cost

        c[k, :] = fmin(cost, c0, disp=False)
        residual -= bump(c[k, :])

    # deform wave
    ynew = residual.copy()
    for k in range(nbump):
        ynew += par[k] * bump(c[k, :])
    energynew = np.trapz(ynew**2, t)
    ynew = np.sqrt(energy / energynew) * ynew

    # write data
    data[:, 1] = ynew.copy()
    import scipy
    wave_function = scipy.interpolate.interp1d(t,
                                               ynew,
                                               kind='zero',
                                               fill_value='extrapolate')

    # MR: uncomment to plot input wave
    # points = np.linspace(-10, 30, 10000)
    # evals = np.zeros(len(points))
    # for i in range(len(evals)):
    #     evals[i] = wave_function(points[i])
    # plt.figure()
    # # plt.plot(points, evals)
    # # plt.plot(t, residual, 'r')
    # for k in range(nbump):
    #     plt.plot(t, par[k]*bump(c[k, :]), label='bum {}'.format(k))
    # plt.title('Okushiri Input Wave')
    # plt.show()

    # ------------------------------------------------------------------------------
    # Setup boundary conditions
    # ------------------------------------------------------------------------------

    # Create boundary function from input wave [replaced by wave function]

    # Create and assign boundary objects
    Bts = anuga.Transmissive_momentum_set_stage_boundary(domain, wave_function)
    Br = anuga.Reflective_boundary(domain)
    domain.set_boundary({'left': Bts, 'right': Br, 'top': Br, 'bottom': Br})

    # ------------------------------------------------------------------------------
    # Evolve system through time
    # ------------------------------------------------------------------------------

    # area for gulleys
    x1 = 4.85
    x2 = 5.25
    y1 = 2.05
    y2 = 1.85

    # gauges
    gauges = [[4.521, 1.196], [4.521, 1.696], [4.521, 2.196]]

    # index in gulley area
    x = domain.centroid_coordinates[:, 0]
    y = domain.centroid_coordinates[:, 1]
    v = np.sqrt((x - x1) ** 2 + (y - y1) ** 2) + \
        np.sqrt((x - x2) ** 2 + (y - y2) ** 2) < 0.5

    dplotter = Domain_plotter(domain, min_depth=0.001)

    k = 0
    # original number of timesteps is 451
    numTimeSteps = int(
        np.loadtxt(
            '/home/rehmemk/git/anugasgpp/Okushiri/data/numTimeSteps.txt'))
    meanstage = np.nan * np.ones((1, numTimeSteps))
    yieldstep = 0.05
    finaltime = (numTimeSteps - 1) * yieldstep
    meanlayer = 0

    # Do the actual calculation
    # for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
    #     # domain.write_time()

    #     # stage [=height of water]
    #     stage = domain.quantities['stage'].centroid_values[v]
    #     # averaging for smoothness
    #     meanstage[0, k] = np.mean(stage)
    #     # k is time
    #     k += 1

    # # PLOTTING

    # # Make movie of each timestep
    #     dplotter.save_depth_frame()
    # anim = dplotter.make_depth_animation()
    # anim.save('okushiri_%i.mp4' % n)
    # meanlayer = meanstage - meanstage[0, 0]

    # Plot the domain
    plt.figure()
    xya = np.loadtxt(
        '/home/rehmemk/git/anugasgpp/Okushiri/plots/Benchmark_2_Bathymetry.xya',
        skiprows=1,
        delimiter=',')
    X = xya[:, 0].reshape(393, 244)
    Y = xya[:, 1].reshape(393, 244)
    Z = xya[:, 2].reshape(393, 244)
    # Remove the white part of the seismic
    # Steves original code uses cmap('gist_earth')
    from matplotlib.colors import LinearSegmentedColormap
    interval = np.hstack([np.linspace(0.0, 0.3), np.linspace(0.5, 1.0)])
    colors = plt.cm.seismic(interval)
    my_cmap = LinearSegmentedColormap.from_list('name', colors)
    # Multiply heights by 400 so that we getreal scale, not model scale
    N1, N2 = np.shape(Z)
    for n1 in range(N1):
        for n2 in range(N2):
            Z[n1, n2] *= 400
    plt.contourf(X, Y, Z, 20, cmap=my_cmap)
    # plt.title('Bathymetry')
    cbar = plt.colorbar()
    cbar.ax.tick_params(labelsize=colorbarfontsize)
    # cbar.set_label('elevation', rotation=270)
    import matplotlib.patches
    from matplotlib.patches import Ellipse
    # plt.plot(x1, y1, 'o')
    # plt.plot(x2, y2, 'o')
    ellipse = Ellipse(((x2 + x1) / 2., (y1 + y2) / 2.),
                      width=0.5,
                      height=0.2,
                      angle=-20,
                      edgecolor='k',
                      fill=False,
                      label='area of interest',
                      linewidth=4)
    plt.gca().add_patch(ellipse)
    # plt.plot(gauges[0][0], gauges[0][1], 'ok')
    # plt.plot(gauges[1][0], gauges[1][1], 'ok')
    # plt.plot(gauges[2][0], gauges[2][1], 'ok', markersize=8, label='gauge')

    # plt.axis('off')
    plt.legend(loc='upper left', fontsize=legendfontsize)
    plt.gca().tick_params(axis='both', which='major', labelsize=tickfontsize)
    plt.tight_layout()
    # ---------------- hack to get ellpse shaped ellipse in legend------------
    import matplotlib.patches as mpatches
    from matplotlib.legend_handler import HandlerPatch
    colors = ["k"]
    texts = ["area of interest"]

    class HandlerEllipse(HandlerPatch):
        def create_artists(self, legend, orig_handle, xdescent, ydescent,
                           width, height, fontsize, trans):
            center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
            p = mpatches.Ellipse(xy=center,
                                 width=width + xdescent,
                                 height=height + ydescent)
            self.update_prop(p, orig_handle, legend)
            p.set_transform(trans)
            return [p]

    c = [
        mpatches.Circle((0.5, 0.5),
                        1,
                        facecolor='None',
                        edgecolor='k',
                        linewidth=3) for i in range(len(texts))
    ]
    plt.legend(c,
               texts,
               bbox_to_anchor=(0., 1.),
               loc='upper left',
               ncol=1,
               fontsize=16,
               handler_map={mpatches.Circle: HandlerEllipse()})
    # ----------------------------
    plt.savefig('okushiri_domain.pdf')

    # Plot the triangle mesh
    plt.figure()
    mittelblau = (0. / 255, 81. / 255, 158. / 255)
    plt.triplot(dplotter.triang, linewidth=0.3, color=mittelblau)
    plt.axis('off')
    plt.tight_layout()
    plt.savefig('okushiri_mesh_%i.pdf' % n)
    # Plot the domain and the triangle mesh
    plt.figure()
    plt.tripcolor(dplotter.triang,
                  facecolors=dplotter.elev,
                  edgecolors='k',
                  cmap='gist_earth')
    plt.colorbar()
    plt.tight_layout()
    plt.savefig('okushiri_domainandmesh_%i.pdf' % n)

    # make video from sww file
    # swwplotter = SWW_plotter('output_okushiri.sww', min_depth=0.001)
    # lilo = len(swwplotter.time)
    # for k in range(lilo):
    #     if k % 10 == 0:
    #         print ' '
    #     swwplotter.save_stage_frame(frame=k, vmin=-0.02, vmax=0.1)
    #     print '(', swwplotter.time[k], k, ')',
    # print ' '
    # swwanim = swwplotter.make_stage_animation()
    # swwanim.save('okushiri_fromswwfile.mp4')

    return meanlayer
示例#13
0
#------------------------------------------------------------------------------

if myid == 0:
    print '>>>>> DUNE EROSION TEST SCRIPT V2'
    print '>>>>> Setting  up Domain on processor 0...'
    length = 36.
    width = 5.
    dx = dy = 0.1  # Resolution: Length of subdivisions on both axes
    print '>>>>> Domain has L = %f, W = %f, dx=dy= %f' % (length, width, dx)
    points, vertices, boundary = anuga.rectangular_cross(int(length / dx),
                                                         int(width / dy),
                                                         len1=length,
                                                         len2=width)
    points = points + 1000.0

    domain = anuga.Domain(points, vertices, boundary, geo_reference=geo)
    domain.set_flow_algorithm('DE0')
    domain.set_name('sanddune_testV2SR')  # Output name

    domain.set_store_vertices_uniquely(False)
    domain.set_quantities_to_be_stored({
        'elevation': 2,
        'stage': 2,
        'xmomentum': 2,
        'ymomentum': 2
    })

    domain.set_quantity('elevation', topography)  # elevation is a function
    domain.set_quantity('friction', 0.01)  # Constant friction
    domain.set_quantity('stage',
                        expression='elevation')  # Dry initial condition
示例#14
0
def main():
    try:
        try:
            usage = "usage: jezero.py -1*initialstage-in-m \n  Note that -2260 flows but barely does anything.  So range for jezero is ~2260 to 2200. \n"
            parser = optparse.OptionParser(usage=usage)

            (options, inargs) = parser.parse_args()
            if not inargs: parser.error("need parameters")
            jezerostage = -1.0 * float(inargs[0])
            # Before doing anything else, set gravity to Mars
            anuga.g = gravity

            #domain parameters
            poly_highres = anuga.read_polygon('JezeroData/PolyHi.csv')
            poly_bound = anuga.read_polygon(
                'JezeroData/PolyBoundBiggerPts.csv')
            base_scale = 25600  #160 m  #HIRES REGION
            lowres = 10000 * base_scale  # 10 km

            boundary_tags = {'exterior': [0]}

            # Define list of interior regions with associated resolutions
            interior_regions = [[poly_highres, base_scale]]

            meshname = 'JezeroData/jezero.msh'
            mesh = anuga.create_mesh_from_regions(
                poly_bound,
                boundary_tags=boundary_tags,
                maximum_triangle_area=lowres,
                interior_regions=interior_regions,
                verbose=True,
                filename=meshname,
                fail_if_polygons_outside=False)
            evolved_quantities = [
                'stage', 'xmomentum', 'ymomentum', 'concentration', 'sedvolx',
                'sedvoly'
            ]
            domain = anuga.Domain(meshname,
                                  use_cache=False,
                                  evolved_quantities=evolved_quantities)
            domain.g = anuga.g  # make sure the domain inherits the package's gravity.

            domain.set_quantity("elevation",
                                filename="JezeroData/jbigger.pts",
                                use_cache=False,
                                verbose=True)
            domain.smooth = True

            name = "jezero" + str(jezerostage) + "_" + str(
                grainD * 1000.0) + "mm"
            domain.set_name(name)

            # Choose between DE0 (less accurate), DE1 (more accurate, slower), DE2 (even more accurate, slower still)
            domain.set_flow_algorithm('DE0')
            domain.set_CFL(cfl=1.0)
            domain.set_minimum_allowed_height(
                0.01
            )  #raise the default minimum depth from 1 mm to 1 cm to speed the simulation (for computation)
            domain.set_minimum_storable_height(
                0.01
            )  #raise the default minimum depth from 1 mm to 1 cm to speed the simulation (for storage/visualization)
            domain.set_maximum_allowed_speed(
                1.0
            )  #maximum particle speed that is allowed in water shallower than minimum_allowed_height (back of the envelope suggests 1m/s should be below tau_crit)

            np.seterr(invalid='ignore')
            voltotal = np.sum(domain.quantities['elevation'].centroid_values *
                              domain.areas)
            domain.set_quantity('concentration', 0.00)  # Start with no esd
            domain.set_quantity(
                'friction', constantn
            )  # Constant Manning friction.  Only used to initialize domain (calculated every time step).
            domain.set_quantity('stage', -10000.0)
            stagepolygon = anuga.read_polygon('JezeroData/stage.csv')
            domain.set_quantity('stage', jezerostage, polygon=stagepolygon)
            domain.set_quantities_to_be_stored({
                'stage': 2,
                'xmomentum': 2,
                'ymomentum': 2,
                'elevation': 2
            })

            np.seterr(invalid='warn')
            Br = anuga.Reflective_boundary(domain)
            domain.set_boundary({'exterior': Br})

            #           fixed_inflow = anuga.Inlet_operator(domain, stagepolygon, Q=1000.0)
            operatezero = suspendedtransport_operator(domain)
            operateone = bedloadtransport_operator(domain)
            operatetwo = friction_operator(domain)
            operatethree = AoR_operator(domain)

            breachpoint = [[19080.340, 1097556.781]]
            initialdomain = copy.deepcopy(domain)
            initial = domain.get_quantity('elevation').get_values(
                interpolation_points=breachpoint, location='centroids')
            print str(initial)
            ystep = 300.0
            ftime = 86400.0 * 5.0
            polyline = [[40000, 1090000], [15000, 1120000]]
            count = 0
            for t in domain.evolve(yieldstep=ystep, finaltime=ftime):
                print domain.timestepping_statistics()
                print 'xmom:' + str(
                    domain.get_quantity('xmomentum').get_values(
                        interpolation_points=breachpoint,
                        location='centroids'))
                breacherosion = domain.get_quantity('elevation').get_values(
                    interpolation_points=breachpoint,
                    location='centroids') - initial
                print 'erosion: ' + str(breacherosion)
                volcurr = np.sum(
                    domain.quantities['elevation'].centroid_values *
                    domain.areas)
                volsed = np.sum(
                    domain.quantities['concentration'].centroid_values *
                    domain.quantities['height'].centroid_values * domain.areas)
                conservation = (volcurr + volsed - voltotal) / voltotal
                print 'conservation: ' + '{:.8%}'.format(conservation)
                count = count + 1

            time, Q = anuga.get_flow_through_cross_section(
                name + '.sww', polyline)
            print Q

            initname = "initial_" + name + ".asc"
            finname = "final_" + name + ".asc"
            fluxname = "flux_" + name + ".txt"
            np.savetxt(fluxname, Q)
            anuga.sww2dem(name + '.sww', initname, reduction=0)
            anuga.sww2dem(name + '.sww', finname, reduction=(count - 1))
            finalstats(domain, initialdomain)
            np.save('XconcC.npy',
                    domain.quantities['concentration'].centroid_values)
            np.save('XelevC.npy',
                    domain.quantities['elevation'].centroid_values)
            np.save('XxmC.npy', domain.quantities['xmomentum'].centroid_values)
            np.save('XymC.npy', domain.quantities['ymomentum'].centroid_values)
            np.save('XstageC.npy', domain.quantities['stage'].centroid_values)
            np.save('XconcV.npy',
                    domain.quantities['concentration'].vertex_values)
            np.save('XelevV.npy', domain.quantities['elevation'].vertex_values)
            np.save('XxmV.npy', domain.quantities['xmomentum'].vertex_values)
            np.save('XymV.npy', domain.quantities['ymomentum'].vertex_values)
            np.save('XstageV.npy', domain.quantities['stage'].vertex_values)

        except optparse.OptionError, msg:
            raise Usage(msg)

    except Usage, err:
        print >> sys.stderr, err.msg
        # print >>sys.stderr, "for help use --help"
        return 2
示例#15
0
def run_culvert_flow_problem(depth):
    """Run flow with culvert given depth
    """

    length = 40.
    width = 5.

    dx = dy = 1  # Resolution: Length of subdivisions on both axes

    points, vertices, boundary = rectangular_cross(int(old_div(length, dx)),
                                                   int(old_div(width, dy)),
                                                   len1=length,
                                                   len2=width)
    domain = anuga.Domain(points, vertices, boundary)
    domain.set_name('Test_culvert_shallow')  # Output name
    domain.set_default_order(2)

    #----------------------------------------------------------------------
    # Setup initial conditions
    #----------------------------------------------------------------------

    def topography(x, y):
        """Set up a weir
        
        A culvert will connect either side
        """
        # General Slope of Topography
        z = old_div(-x, 1000)

        N = len(x)
        for i in range(N):

            # Sloping Embankment Across Channel
            if 5.0 < x[i] < 10.1:
                # Cut Out Segment for Culvert face
                if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] - 5.0) / 5.0:
                    z[i] = z[i]
                else:
                    z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
            if 10.0 < x[i] < 12.1:
                z[i] += 2.5  # Flat Crest of Embankment
            if 12.0 < x[i] < 14.5:
                # Cut Out Segment for Culvert face
                if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] -
                                                             12.0) / 2.5:
                    z[i] = z[i]
                else:
                    z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

        return z

    domain.set_quantity('elevation', topography)
    domain.set_quantity('friction', 0.01)  # Constant friction
    domain.set_quantity('stage', expression='elevation + %f' %
                        depth)  # Shallow initial condition

    # Boyd culvert
    culvert = Culvert_flow(
        domain,
        label='Culvert No. 1',
        description='This culvert is a test unit 1.2m Wide by 0.75m High',
        end_point0=[9.0, 2.5],
        end_point1=[13.0, 2.5],
        width=1.20,
        height=0.75,
        culvert_routine=boyd_generalised_culvert_model,
        number_of_barrels=1,
        update_interval=2,
        verbose=False)

    domain.forcing_terms.append(culvert)

    #-----------------------------------------------------------------------
    # Setup boundary conditions
    #-----------------------------------------------------------------------

    # Inflow based on Flow Depth and Approaching Momentum

    Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
    domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

    #-----------------------------------------------------------------------
    # Evolve system through time
    #-----------------------------------------------------------------------

    #print 'depth', depth
    ref_volume = domain.get_quantity('stage').get_integral()
    for t in domain.evolve(yieldstep=0.1, finaltime=10):
        new_volume = domain.get_quantity('stage').get_integral()

        msg = (
            'Total volume has changed: Is %.8f m^3 should have been %.8f m^3' %
            (new_volume, ref_volume))
        assert num.allclose(new_volume, ref_volume), msg

    os.remove('Test_culvert_shallow.sww')
    def test_that_culvert_runs_rating(self):
        """test_that_culvert_runs_rating
        
        This test exercises the culvert and checks values outside rating curve
        are dealt with       
        """

        path = get_pathname_from_package('anuga.culvert_flows')
        path = os.path.join(path, 'tests', 'data')

        length = 40.
        width = 5.

        dx = dy = 1  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)
        domain.set_name('Test_culvert')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z = -x / 1000

            N = len(x)
            for i in range(N):

                # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face
                    if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] -
                                                                5.0) / 5.0:
                        z[i] = z[i]
                    else:
                        z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                    z[i] += 2.5  # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face
                    if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] -
                                                                 12.0) / 2.5:
                        z[i] = z[i]
                    else:
                        z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity('stage',
                            expression='elevation')  # Dry initial condition

        filename = os.path.join(path, 'example_rating_curve.csv')
        culvert = Culvert_flow(domain,
                               culvert_description_filename=filename,
                               end_point0=[9.0, 2.5],
                               end_point1=[13.0, 2.5],
                               width=1.00,
                               use_velocity_head=True,
                               verbose=False)

        domain.forcing_terms.append(culvert)

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum
        Bi = anuga.Dirichlet_boundary([0.0, 0.0, 0.0])
        Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
        Bo = anuga.Dirichlet_boundary([-5, 0, 0])  # Outflow

        # Upstream and downstream conditions that will exceed the rating curve
        # I.e produce delta_h outside the range [0, 10] specified in the the
        # file example_rating_curve.csv
        Btus = anuga.Time_boundary(
            domain, lambda t: [100 * num.sin(2 * pi * (t - 4) / 10), 0.0, 0.0])
        Btds = anuga.Time_boundary(
            domain,
            lambda t: [-5 * (num.cos(2 * pi * (t - 4) / 20)), 0.0, 0.0])
        domain.set_boundary({
            'left': Btus,
            'right': Btds,
            'top': Br,
            'bottom': Br
        })

        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        min_delta_w = sys.maxint
        max_delta_w = -min_delta_w
        for t in domain.evolve(yieldstep=1, finaltime=25):
            delta_w = culvert.inlet.stage - culvert.outlet.stage

            if delta_w > max_delta_w: max_delta_w = delta_w
            if delta_w < min_delta_w: min_delta_w = delta_w

            pass

        # Check that extreme values in rating curve have been exceeded
        # so that we know that condition has been exercised
        assert min_delta_w < 0
        assert max_delta_w > 10

        os.remove('Test_culvert.sww')
    def OBSOLETE_XXXtest_that_culvert_rating_limits_flow_in_shallow_inlet_condition(
            self):
        """test_that_culvert_rating_limits_flow_in_shallow_inlet_condition
        
        Test that culvert on a sloping dry bed limits flows when very little water
        is present at inlet

        This one is using the rating curve variant
        """

        path = get_pathname_from_package('anuga.culvert_flows')

        length = 40.
        width = 5.

        dx = dy = 1  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)
        domain.set_name('Test_culvert_shallow')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            """Set up a weir
            
            A culvert will connect either side
            """
            # General Slope of Topography
            z = -x / 1000

            N = len(x)
            for i in range(N):

                # Sloping Embankment Across Channel
                if 5.0 < x[i] < 10.1:
                    # Cut Out Segment for Culvert face
                    if 1.0 + (x[i] - 5.0) / 5.0 < y[i] < 4.0 - (x[i] -
                                                                5.0) / 5.0:
                        z[i] = z[i]
                    else:
                        z[i] += 0.5 * (x[i] - 5.0)  # Sloping Segment  U/S Face
                if 10.0 < x[i] < 12.1:
                    z[i] += 2.5  # Flat Crest of Embankment
                if 12.0 < x[i] < 14.5:
                    # Cut Out Segment for Culvert face
                    if 2.0 - (x[i] - 12.0) / 2.5 < y[i] < 3.0 + (x[i] -
                                                                 12.0) / 2.5:
                        z[i] = z[i]
                    else:
                        z[i] += 2.5 - 1.0 * (x[i] - 12.0)  # Sloping D/S Face

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity(
            'stage', expression='elevation + 0.1')  # Shallow initial condition

        # Boyd culvert
        culvert = Culvert_flow(
            domain,
            label='Culvert No. 1',
            description='This culvert is a test unit 1.2m Wide by 0.75m High',
            end_point0=[9.0, 2.5],
            end_point1=[13.0, 2.5],
            width=1.20,
            height=0.75,
            culvert_routine=boyd_generalised_culvert_model,
            number_of_barrels=1,
            update_interval=2,
            verbose=False)

        # Rating curve
        #filename = os.path.join(path, 'example_rating_curve.csv')
        #culvert = Culvert_flow(domain,
        #                       culvert_description_filename=filename,
        #                       end_point0=[9.0, 2.5],
        #                       end_point1=[13.0, 2.5],
        #                       trigger_depth=0.01,
        #                       verbose=False)

        domain.forcing_terms.append(culvert)

        #-----------------------------------------------------------------------
        # Setup boundary conditions
        #-----------------------------------------------------------------------

        # Inflow based on Flow Depth and Approaching Momentum

        Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

        #-----------------------------------------------------------------------
        # Evolve system through time
        #-----------------------------------------------------------------------

        print 'depth', 0.1
        ref_volume = domain.get_quantity('stage').get_integral()
        for t in domain.evolve(yieldstep=0.1, finaltime=25):
            new_volume = domain.get_quantity('stage').get_integral()

            msg = (
                'Total volume has changed: Is %.8f m^3 should have been %.8f m^3'
                % (new_volume, ref_volume))
            assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg

        return
        # Now try this again for a depth of 10 cm and for a range of other depths
        for depth in [0.1, 0.2, 0.5, 1.0]:
            print 'depth', depth
            domain.set_time(0.0)

            domain.set_quantity('elevation', topography)
            domain.set_quantity('friction', 0.01)  # Constant friction
            domain.set_quantity('stage', expression='elevation + %f' % depth)

            ref_volume = domain.get_quantity('stage').get_integral()
            for t in domain.evolve(yieldstep=0.1, finaltime=25):
                new_volume = domain.get_quantity('stage').get_integral()

                msg = 'Total volume has changed: Is %.8f m^3 should have been %.8f m^3'\
                    % (new_volume, ref_volume)

                assert num.allclose(new_volume, ref_volume, rtol=1.0e-10), msg
示例#18
0
def generate_channel3_domain(gpu=True):
    #-----------------------------------------------------------------------
    # Setup computational domain
    #-----------------------------------------------------------------------
    length = 40.
    width = 5.
    dx = dy = .1  # Resolution: Length of subdivisions on both axes

    points, vertices, boundary = anuga.rectangular_cross(int(length / dx),
                                                         int(width / dy),
                                                         len1=length,
                                                         len2=width)
    if gpu:
        domain = GPU_domain(points, vertices, boundary)
        if '-gpu' in sys.argv:
            domain.using_gpu = True
            print " --> Enable GPU version"
        for i in range(len(sys.argv)):
            if sys.argv[i] == '-fs':
                global finaltime
                finaltime = float(sys.argv[i + 1])
                print " --> Finaltime is reset as %f" % finaltime

    else:
        domain = anuga.Domain(points, vertices, boundary)
    domain.set_name('channel3')  # Output name

    #print domain.statistics()

    #-----------------------------------------------------------------------
    # Setup initial conditions
    #-----------------------------------------------------------------------
    def topography(x, y):
        """Complex topography defined by a function of vectors x and y."""

        z = -x / 10

        N = len(x)
        for i in range(N):
            # Step
            if 10 < x[i] < 12:
                z[i] += 0.4 - 0.05 * y[i]

            # Constriction
            if 27 < x[i] < 29 and y[i] > 3:
                z[i] += 2

            # Pole
            if (x[i] - 34)**2 + (y[i] - 2)**2 < 0.4**2:
                z[i] += 2

        return z

    domain.set_quantity('elevation', topography)  # elevation is a function
    domain.set_quantity('friction', 0.01)  # Constant friction
    domain.set_quantity('stage',
                        expression='elevation')  # Dry initial condition

    #-----------------------------------------------------------------------
    # Setup boundary conditions
    #-----------------------------------------------------------------------
    Bi = anuga.Dirichlet_boundary([0.4, 0, 0])  # Inflow
    Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
    Bo = anuga.Dirichlet_boundary([-5, 0, 0])  # Outflow

    domain.set_boundary({'left': Bi, 'right': Bo, 'top': Br, 'bottom': Br})
    return domain
    def test_predicted_boyd_flow(self):
        """test_predicted_boyd_flow
        
        Test that flows predicted by the boyd method are consistent with what what
        is calculated in engineering codes.
        The data was supplied by Petar Milevski
        """

        # FIXME(Ole) this is nowhere near finished
        path = get_pathname_from_package('anuga.culvert_flows')

        length = 12.
        width = 5.

        dx = dy = 0.5  # Resolution: Length of subdivisions on both axes

        points, vertices, boundary = rectangular_cross(int(length / dx),
                                                       int(width / dy),
                                                       len1=length,
                                                       len2=width)
        domain = anuga.Domain(points, vertices, boundary)

        domain.set_name('test_culvert')  # Output name
        domain.set_default_order(2)

        #----------------------------------------------------------------------
        # Setup initial conditions
        #----------------------------------------------------------------------

        def topography(x, y):
            # General Slope of Topography
            z = -x / 10

            return z

        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.01)  # Constant friction
        domain.set_quantity('stage', expression='elevation')

        Q0 = domain.get_quantity('stage')
        Q1 = Quantity(domain)

        # Add depths to stage
        head_water_depth = 0.169
        tail_water_depth = 0.089

        inlet_poly = [[0, 0], [6, 0], [6, 5], [0, 5]]
        outlet_poly = [[6, 0], [12, 0], [12, 5], [6, 5]]

        Q1.set_values(
            Polygon_function([(inlet_poly, head_water_depth),
                              (outlet_poly, tail_water_depth)]))

        domain.set_quantity('stage', Q0 + Q1)

        culvert = Culvert_flow(domain,
                               label='Test culvert',
                               description='4 m test culvert',
                               end_point0=[4.0, 2.5],
                               end_point1=[8.0, 2.5],
                               width=1.20,
                               height=0.75,
                               culvert_routine=boyd_generalised_culvert_model,
                               number_of_barrels=1,
                               verbose=False)

        domain.forcing_terms.append(culvert)

        # Call
        culvert(domain)
示例#20
0
def main():
    try:
        try:
            usage = "usage: lakeerode.py LakeRadius-in-meters [-m depthmultiplier] [-i initialbreachdepth]\n"
            parser = optparse.OptionParser(usage=usage)
            parser.add_option("-m",
                              dest="dm",
                              help="Depth Multiplier for lake")
            parser.add_option("-i",
                              dest="initbreachdepth",
                              help="Initial breach depth for flood")
            (options, inargs) = parser.parse_args()
            if not inargs: parser.error("need parameters")
            lakeradius = float(inargs[0])

            dm = 1.0  #default
            if (options.dm): dm = float(options.dm)
            h = dm * 21.39 * math.pow(
                (lakeradius / 1000), 0.62
            )  #max depth in meters to get V=0.01A**1.31 from Fassett and Head 2008

            initbreachdepth = 15.0  #default
            lakebelowconfining = 5
            if (options.initbreachdepth):
                initbreachdepth = float(options.initbreachdepth)
            initbreachdepth = initbreachdepth + lakebelowconfining  #set this to be a real initial head, not dependent on lakebelowconfining
            extslope = -0.015
            extslopeint = 0.015

            #anuga critical parameter
            anuga.g = gravity

            #domain parameters
            domainpolygon = [[0, 0], [0 * lakeradius, 2 * lakeradius],
                             [2 * lakeradius, 2 * lakeradius],
                             [2 * lakeradius, 1.2 * lakeradius],
                             [10 * lakeradius, 1.2 * lakeradius],
                             [10 * lakeradius, 0.8 * lakeradius],
                             [2 * lakeradius, 0.8 * lakeradius],
                             [2 * lakeradius, 0], [0, 0]]
            outletregion = [[1.9 * lakeradius, 0.8 * lakeradius],
                            [1.9 * lakeradius, 1.2 * lakeradius],
                            [4.5 * lakeradius, 1.2 * lakeradius],
                            [4.5 * lakeradius, 0.8 * lakeradius]]

            boundary_tags = {'exterior': [0]}

            high_resolution = (lakeradius / 100)**2
            base_resolution = high_resolution * 80.0
            initbreachwidth = lakeradius / 50.0
            interior_regions = [[outletregion, high_resolution]]

            meshname = 'lake.msh'
            m = anuga.create_mesh_from_regions(
                domainpolygon,
                boundary_tags,
                maximum_triangle_area=base_resolution,
                interior_regions=interior_regions,
                filename=meshname,
                use_cache=False)
            evolved_quantities = [
                'stage', 'xmomentum', 'ymomentum', 'concentration', 'sedvolx',
                'sedvoly'
            ]
            #evolved_quantities =  ['stage', 'xmomentum', 'ymomentum', 'concentration']
            domain = anuga.Domain(meshname,
                                  use_cache=False,
                                  evolved_quantities=evolved_quantities)
            domain.g = anuga.g  # make sure the domain inherits the package's gravity.

            print 'Number of triangles = ', len(domain)

            def find_nearest(array, value):
                array = np.asarray(array)
                idx = (np.abs(array - value)).argmin()
                return idx

            def topography(x, y):
                xc = x - lakeradius
                yc = y - lakeradius

                #sets up lake
                ellipsoid = -(h**2 * (1 -
                                      ((xc**2 + yc**2) / lakeradius**2)))**0.5
                z = np.where(ellipsoid < 0, ellipsoid, 0.0)

                #sets up exterior slope
                z = np.where(
                    np.logical_and(x > lakeradius * 2, x <= lakeradius * 4),
                    (x - lakeradius * 2) * extslope +
                    abs(y - lakeradius) * extslopeint, z)

                #setup flatlying area
                z = np.where(x > lakeradius * 4, (lakeradius * 2) * extslope +
                             abs(y - lakeradius) * extslopeint, z)

                # add gaussian noise, with zero mean and 0.1 m standard deviation.
                #z=z+np.random.normal(0,0.1,z.shape)

                # set up breach as a failure at the midpoint in a region
                #mask1 = (x>=(lakeradius*2+(initbreachdepth/extslope)))
                mask1 = (x >= lakeradius)
                #mask2 = (x<=(lakeradius*2-(initbreachdepth/extslope)))
                mask3 = (y >= ((lakeradius - (initbreachwidth / 2.0))))
                mask4 = (y <= ((lakeradius + (initbreachwidth / 2.0))))
                mask5 = (z > -initbreachdepth)
                #mask=mask1 & mask2 & mask3 & mask4 & mask5
                mask = mask1 & mask3 & mask4 & mask5
                z[mask] = -initbreachdepth

                return z

            def initialstage(x, y):
                clow = domain.get_quantity('elevation').get_values(
                    interpolation_points=[[2 * lakeradius, lakeradius]])
                istage = clow + initbreachdepth - lakebelowconfining

                #outsidelake. Force depth=0 (istage=topo) across rim.
                #istage=np.where(x>lakeradius*2,topography(x,y),istage)
                istage = np.where(x > lakeradius * 2, -10000, istage)

                return istage

            name = "Marslake" + str(lakeradius) + "_" + str(
                grainD * 1000) + "mm"
            domain.set_name(name)
            # Choose between DE0 (less accurate), DE1 (more accurate, slower), DE2 (even more accurate, slower still)
            domain.set_flow_algorithm('DE0')
            domain.set_CFL(cfl=1)
            domain.set_minimum_allowed_height(
                0.01
            )  #raise the default minimum depth from 1 mm to 1 cm to speed the simulation (for computation)
            domain.set_minimum_storable_height(
                0.01
            )  #raise the default minimum depth from 1 mm to 1 cm to speed the simulation (for storage/visualization)
            domain.set_maximum_allowed_speed(
                1
            )  #maximum particle speed that is allowed in water shallower than minimum_allowed_height (back of the envelope suggests 1m/s should be below tau_crit)

            np.seterr(invalid='ignore')
            domain.set_quantity(
                'elevation', topography,
                location='centroids')  # elevation is a function
            voltotal = np.sum(domain.quantities['elevation'].centroid_values *
                              domain.areas)
            domain.set_quantity('concentration', 0.00)  # Start with no esd
            domain.set_quantity(
                'friction', 0.0545
            )  # Constant Manning friction.  Only used to initialize domain (calculated every time step).
            domain.set_quantity('stage', initialstage, location='centroids')
            domain.set_quantities_to_be_stored({
                'stage': 2,
                'xmomentum': 2,
                'ymomentum': 2,
                'elevation': 2
            })

            np.seterr(invalid='warn')

            # Setup boundary conditions

            Br = anuga.Reflective_boundary(domain)
            domain.set_boundary({'exterior': Br})

            operatezero = suspendedtransport_operator(domain)
            operateone = bedloadtransport_operator(domain)
            operatetwo = friction_operator(domain)
            operatethree = AoR_operator(domain)

            initial = domain.get_quantity('elevation').get_values(
                interpolation_points=[[2 * lakeradius, lakeradius]],
                location='centroids')
            initialdomain = copy.deepcopy(domain)
            ystep = 300
            ftime = 86400 * 10
            count = 0
            volthresh = 1000
            for t in domain.evolve(yieldstep=ystep, finaltime=ftime):
                print domain.timestepping_statistics()
                print 'xmom:' + str(
                    domain.get_quantity('xmomentum').get_values(
                        interpolation_points=[[2 * lakeradius, lakeradius]],
                        location='centroids'))
                volcurr = np.sum(
                    domain.quantities['elevation'].centroid_values *
                    domain.areas)
                breacherosion = domain.get_quantity('elevation').get_values(
                    interpolation_points=[[2 * lakeradius, lakeradius]],
                    location='centroids') - initial
                print 'erosion: ' + str(breacherosion)
                volsed = np.sum(
                    domain.quantities['concentration'].centroid_values *
                    domain.quantities['height'].centroid_values * domain.areas)
                conservation = (volcurr + volsed - voltotal) / voltotal
                print 'conservation: ' + '{:.8%}'.format(conservation)
                if (volsed < volthresh) & (count > 0):
                    print "No sediment moving...ending..."
                    break
                count = count + 1
            polyline = [[2 * lakeradius, lakeradius - 2 * initbreachwidth],
                        [2 * lakeradius, lakeradius + 2 * initbreachwidth]]
            time, Q = anuga.get_flow_through_cross_section(
                name + '.sww', polyline)
            print Q

            initname = "initial_" + str(lakeradius) + "_" + str(
                grainD * 1000) + "mm" + ".asc"
            finname = "final_" + str(lakeradius) + "_" + str(
                grainD * 1000) + "mm" + ".asc"
            fluxname = "flux_" + str(lakeradius) + "_" + str(
                grainD * 1000) + "mm" + ".txt"
            np.savetxt(fluxname, Q)
            finalstats(domain, initialdomain, lakeradius)
            np.save('XconcC.npy',
                    domain.quantities['concentration'].centroid_values)
            np.save('XelevC.npy',
                    domain.quantities['elevation'].centroid_values)
            np.save('XxmC.npy', domain.quantities['xmomentum'].centroid_values)
            np.save('XymC.npy', domain.quantities['ymomentum'].centroid_values)
            np.save('XstageC.npy', domain.quantities['stage'].centroid_values)
            np.save('XconcV.npy',
                    domain.quantities['concentration'].vertex_values)
            np.save('XelevV.npy', domain.quantities['elevation'].vertex_values)
            np.save('XxmV.npy', domain.quantities['xmomentum'].vertex_values)
            np.save('XymV.npy', domain.quantities['ymomentum'].vertex_values)
            np.save('XstageV.npy', domain.quantities['stage'].vertex_values)

        except optparse.OptionError, msg:
            raise Usage(msg)

    except Usage, err:
        print >> sys.stderr, err.msg
        # print >>sys.stderr, "for help use --help"
        return 2
示例#21
0
def run_simulation(parallel=False,
                   control_data=None,
                   test_points=None,
                   verbose=False):
    success = True

    ##-----------------------------------------------------------------------
    ## Setup domain
    ##-----------------------------------------------------------------------

    points, vertices, boundary = rectangular_cross(int(old_div(length, dx)),
                                                   int(old_div(width, dy)),
                                                   len1=length,
                                                   len2=width)

    domain = anuga.Domain(points, vertices, boundary)
    #domain.set_name()                 # Output name
    domain.set_store(False)
    domain.set_default_order(2)

    ##-----------------------------------------------------------------------
    ## Distribute domain
    ##-----------------------------------------------------------------------

    if parallel:
        domain = distribute(domain)
        #domain.dump_triangulation("frac_op_domain.png")

##-----------------------------------------------------------------------
## Setup boundary conditions
##-----------------------------------------------------------------------

    domain.set_quantity('elevation', topography)
    domain.set_quantity('friction', 0.01)  # Constant friction
    domain.set_quantity('stage',
                        expression='elevation')  # Dry initial condition

    Bi = anuga.Dirichlet_boundary([5.0, 0.0, 0.0])
    Br = anuga.Reflective_boundary(domain)  # Solid reflective wall
    domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

    ##-----------------------------------------------------------------------
    ## Determine triangle index coinciding with test points
    ##-----------------------------------------------------------------------

    assert (test_points is not None)
    assert (len(test_points) == samples)

    tri_ids = []

    for point in test_points:
        try:
            k = domain.get_triangle_containing_point(point)
            if domain.tri_full_flag[k] == 1:
                tri_ids.append(k)
            else:
                tri_ids.append(-1)
        except:
            tri_ids.append(-2)

    if verbose: print('P%d has points = %s' % (myid, tri_ids))

    if not parallel: control_data = []

    ################ Define Fractional Operators ##########################

    inlet0 = None
    inlet1 = None
    boyd_box0 = None

    inlet0 = Inlet_operator(domain, line0, Q0, verbose=False, label='Inlet_0')
    inlet1 = Inlet_operator(domain, line1, Q1, verbose=False, label='Inlet_1')

    # Enquiry point [ 19.    2.5] is contained in two domains in 4 proc case

    boyd_box0 = Boyd_box_operator(domain,
                                  end_points=[[9.0, 2.5], [19.0, 2.5]],
                                  losses=1.5,
                                  width=5.0,
                                  apron=5.0,
                                  use_momentum_jet=True,
                                  use_velocity_head=False,
                                  manning=0.013,
                                  label='Boyd_Box_0',
                                  verbose=False)

    #if inlet0 is not None and verbose: inlet0.print_statistics()
    #if inlet1 is not None and verbose: inlet1.print_statistics()

    if boyd_box0 is not None and verbose:
        print("++++", myid)
        boyd_box0.print_statistics()

#    if parallel:
#        factory = Parallel_operator_factory(domain, verbose = True)
#
#        inlet0 = factory.inlet_operator_factory(line0, Q0)
#        inlet1 = factory.inlet_operator_factory(line1, Q1)
#
#        boyd_box0 = factory.boyd_box_operator_factory(end_points=[[9.0, 2.5],[19.0, 2.5]],
#                                          losses=1.5,
#                                          width=1.5,
#                                          apron=5.0,
#                                          use_momentum_jet=True,
#                                          use_velocity_head=False,
#                                          manning=0.013,
#                                          verbose=False)
#
#    else:
#        inlet0 = Inlet_operator(domain, line0, Q0)
#        inlet1 = Inlet_operator(domain, line1, Q1)
#
#        # Enquiry point [ 19.    2.5] is contained in two domains in 4 proc case
#        boyd_box0 = Boyd_box_operator(domain,
#                          end_points=[[9.0, 2.5],[19.0, 2.5]],
#                          losses=1.5,
#                          width=1.5,
#                          apron=5.0,
#                          use_momentum_jet=True,
#                          use_velocity_head=False,
#                          manning=0.013,
#                          verbose=False)

#######################################################################

##-----------------------------------------------------------------------
## Evolve system through time
##-----------------------------------------------------------------------

    for t in domain.evolve(yieldstep=2.0, finaltime=20.0):
        if myid == 0 and verbose:
            domain.write_time()

        #print domain.volumetric_balance_statistics()

        stage = domain.get_quantity('stage')

        if boyd_box0 is not None and verbose:
            if myid == boyd_box0.master_proc:
                print('master_proc ', myid)
                boyd_box0.print_timestepping_statistics()

        #for i in range(samples):
        #    if tri_ids[i] >= 0:
        #        if verbose: print 'P%d tri %d, value = %s' %(myid, i, stage.centroid_values[tri_ids[i]])

        sys.stdout.flush()

        pass

    domain.sww_merge(delete_old=True)

    success = True

    ##-----------------------------------------------------------------------
    ## Assign/Test Control data
    ##-----------------------------------------------------------------------

    if not parallel:
        stage = domain.get_quantity('stage')

        for i in range(samples):
            assert (tri_ids[i] >= 0)
            control_data.append(stage.centroid_values[tri_ids[i]])

        if inlet0 is not None:
            control_data.append(inlet0.inlet.get_average_stage())
            control_data.append(inlet0.inlet.get_average_xmom())
            control_data.append(inlet0.inlet.get_average_ymom())
            control_data.append(inlet0.inlet.get_total_water_volume())
            control_data.append(inlet0.inlet.get_average_depth())

        if verbose: print('P%d control_data = %s' % (myid, control_data))
    else:
        stage = domain.get_quantity('stage')

        for i in range(samples):
            if tri_ids[i] >= 0:
                local_success = num.allclose(control_data[i],
                                             stage.centroid_values[tri_ids[i]])
                success = success and local_success
                if verbose:
                    print(
                        'P%d tri %d, control = %s, actual = %s, Success = %s' %
                        (myid, i, control_data[i],
                         stage.centroid_values[tri_ids[i]], local_success))

        if inlet0 is not None:
            inlet_master_proc = inlet0.inlet.get_master_proc()
            average_stage = inlet0.inlet.get_global_average_stage()
            average_xmom = inlet0.inlet.get_global_average_xmom()
            average_ymom = inlet0.inlet.get_global_average_ymom()
            average_volume = inlet0.inlet.get_global_total_water_volume()
            average_depth = inlet0.inlet.get_global_average_depth()

            if myid == inlet_master_proc:
                if verbose:
                    print('P%d average stage, control = %s, actual = %s' %
                          (myid, control_data[samples], average_stage))

                    print('P%d average xmom, control = %s, actual = %s' %
                          (myid, control_data[samples + 1], average_xmom))

                    print('P%d average ymom, control = %s, actual = %s' %
                          (myid, control_data[samples + 2], average_ymom))

                    print('P%d average volume, control = %s, actual = %s' %
                          (myid, control_data[samples + 3], average_volume))

                    print('P%d average depth, control = %s, actual = %s' %
                          (myid, control_data[samples + 4], average_depth))

    return control_data, success
示例#22
0
                                verbose=verbose)

barrier()

# configure my logging
import anuga.utilities.log as log
#log.console_logging_level = log.INFO
#log.log_logging_level = log.DEBUG
log.log_filename = './run_okushiri.log'

#-------------------------
# Create Domain from mesh
#-------------------------
if myid == 0:
    try:
        domain = anuga.Domain(mesh_filename, use_cache=False, verbose=verbose)
    except:
        msg = 'ERROR reading in mesh file. Have you run create_okushiri.py?'
        raise Exception(msg)

    if verbose: print(domain.statistics())

    #-------------------------
    # Initial Conditions
    #-------------------------
    domain.set_quantity('friction', 0.0025)
    domain.set_quantity('stage', 0.0)
    if verbose: print('set stage')
    if elevation_in_mesh is False:
        #         domain.set_quantity('elevation',
        #                         filename=bathymetry_filename_stem+'.pts',
# Setup computational domain
#------------------------------------------------------------------------------

if myid == 0:
    print '>>>>> DUNE EROSION TEST SCRIPT V2'
    print '>>>>> Setting  up Domain on processor 0...'
    length = 36.
    width = 5.
    dx = dy = 0.1  # Resolution: Length of subdivisions on both axes
    print '>>>>> Domain has L = %f, W = %f, dx=dy= %f' % (length, width, dx)
    points, vertices, boundary = anuga.rectangular_cross(int(length / dx),
                                                         int(width / dy),
                                                         len1=length,
                                                         len2=width)

    domain = anuga.Domain(points, vertices, boundary)
    domain.set_flow_algorithm('DE0')
    domain.set_name('sanddune_testV2SR')  # Output name
    domain.set_quantity('elevation', topography)  # elevation is a function
    domain.set_quantity('friction', 0.01)  # Constant friction
    domain.set_quantity('stage',
                        expression='elevation')  # Dry initial condition

    print domain.statistics()

    # get the indices of triangles in each erosion poly so can setup nsbase_ in domain
    poly1ind = (Region(domain, polygon=polygon1)).indices
    poly2ind = (Region(domain, polygon=polygon2)).indices
    print '>>>>> poly1ind is of length ', len(
        poly1ind), ' and contains triangles', poly1ind[0], ' to ', poly1ind[-1]
    print '>>>>> poly2ind is of length ', len(
示例#24
0
def run(par,
        n,
        withNormalization,
        withResidual,
        wave_type='bumps',
        minimum_allowed_height=1e-5):
    # ------------------------------------------------------------------------------
    # Setup computational domain
    # ------------------------------------------------------------------------------
    xleft = 0
    xright = 5.448
    ybottom = 0
    ytop = 3.402

    # rectangular cross mesh
    points, vertices, boundary = anuga.rectangular_cross(
        int(n), int(n), xright - xleft, ytop - ybottom, (xleft, ybottom))

    newpoints = points.copy()

    # make refinement in x direction
    x = np.multiply([0., 0.1, 0.2, 0.335, 0.925, 1.], max(points[:, 0]))
    y = [0., 3., 4.25, 4.7, 5.3, max(points[:, 0])]
    f1 = interp1d(x, y, kind='linear')
    newpoints[:, 0] = f1(points[:, 0])

    # make refinement in y direction
    x = np.multiply([0., .125, .3, .7, .9, 1.], max(points[:, 1]))
    y = [0., 1.25, 1.75, 2.15, 2.65, max(points[:, 1])]
    f2 = interp1d(x, y, kind='linear')
    newpoints[:, 1] = f2(points[:, 1])

    c = abs(newpoints[:, 0] - 5.0) + .5 * abs(newpoints[:, 1] - 1.95)
    c = 0.125 * c

    points[:, 0] = c * points[:, 0] + (1 - c) * newpoints[:, 0]
    points[:, 1] = c * points[:, 1] + (1 - c) * newpoints[:, 1]

    # create domain
    domain = anuga.Domain(points, vertices, boundary)

    # don't store .sww file
    domain.set_quantities_to_be_stored(None)

    # ------------------------------------------------------------------------------
    # Initial Conditions
    # ------------------------------------------------------------------------------
    domain.set_quantity('friction', 0.01)  # 0.0
    domain.set_quantity('stage', 0.0)
    domain.set_quantity(
        'elevation',
        filename='/home/rehmemk/git/anugasgpp/Okushiri/data/bathymetry.pts',
        alpha=0.02)

    # ------------------------------------------------------------------------------
    # Set simulation parameters
    # ------------------------------------------------------------------------------
    domain.set_name('output_okushiri')  # Output name
    # domain.set_minimum_storable_height(0.001)  # Don't store w < 0.001m
    domain.set_minimum_storable_height(1.0)  # Don't store w < 0.001m
    domain.set_flow_algorithm('DE0')

    # ------------------------------------------------------------------------------
    # Modify input wave
    # ------------------------------------------------------------------------------
    # rescale input parameter
    try:
        dummy = len(par)
    except:
        par = [par]
    par = np.dot(2, par)

    if wave_type == 'bumps':
        wave_function, _, _ = wave_functions.heights_wave(
            par, withResidual, withNormalization)
    elif wave_type == 'original':
        wave_function = wave_functions.original_wave_interpolant()
    elif wave_type == 'cubic':
        wave_function, _, _ = wave_functions.cubic_heights_wave(
            par, withResidual, withNormalization)
    else:
        print(f'Error. Wave type {wave_type} unknown')

    # ------------------------------------------------------------------------------
    # Setup boundary conditions
    # ------------------------------------------------------------------------------

    # Create boundary function from input wave [replaced by wave function]

    # Create and assign boundary objects
    Bts = anuga.Transmissive_momentum_set_stage_boundary(domain, wave_function)
    Br = anuga.Reflective_boundary(domain)
    domain.set_boundary({'left': Bts, 'right': Br, 'top': Br, 'bottom': Br})

    # ------------------------------------------------------------------------------
    # Evolve system through time
    # ------------------------------------------------------------------------------

    # this prevents problems w.r.t. divisions by zero
    # It might decrease the acheivable accuracy
    domain.set_minimum_allowed_height(minimum_allowed_height)  # default 1e-5

    # area for gulleys
    x1 = 4.85
    x2 = 5.25
    y1 = 2.05
    y2 = 1.85

    # index in gulley area
    x = domain.centroid_coordinates[:, 0]
    y = domain.centroid_coordinates[:, 1]
    v = np.sqrt((x - x1) ** 2 + (y - y1) ** 2) + \
        np.sqrt((x - x2) ** 2 + (y - y2) ** 2) < 0.5

    # three gauges and a point somewhere on the boundary that could be used for verification
    # get id's of the corresponding triangles
    gauge = [[4.521, 1.196], [4.521, 1.696], [4.521, 2.196]]
    bdyloc = [0.00001, 2.5]
    g5_id = domain.get_triangle_containing_point(gauge[0])
    g7_id = domain.get_triangle_containing_point(gauge[1])
    g9_id = domain.get_triangle_containing_point(gauge[2])
    bc_id = domain.get_triangle_containing_point(bdyloc)

    k = 0
    # original number of timesteps is 451
    numTimeSteps = 451
    sumstage = np.nan * np.ones(numTimeSteps)
    stage_g5 = np.nan * np.ones(numTimeSteps)
    stage_g7 = np.nan * np.ones(numTimeSteps)
    stage_g9 = np.nan * np.ones(numTimeSteps)
    stage_bc = np.nan * np.ones(numTimeSteps)
    yieldstep = 0.05
    finaltime = (numTimeSteps - 1) * yieldstep
    for t in domain.evolve(yieldstep=yieldstep, finaltime=finaltime):
        # domain.write_time()

        # stage [=height of water]
        stage = domain.quantities['stage'].centroid_values[v]
        stage_g5[k] = domain.quantities['stage'].centroid_values[g5_id]
        stage_g7[k] = domain.quantities['stage'].centroid_values[g7_id]
        stage_g9[k] = domain.quantities['stage'].centroid_values[g9_id]
        stage_bc[k] = domain.quantities['stage'].centroid_values[bc_id]
        # averaging for smoothness
        sumstage[k] = np.sum(stage)
        # k is time
        k += 1

    # number of triangles which are active for the designated runup area
    numActiveTriangles = anuga.collect_value(np.count_nonzero(v))
    averageStage = sumstage / numActiveTriangles
    # normalizing to zero level
    # averageStage -= averageStage[0]

    return [averageStage, stage_g5, stage_g7, stage_g9, stage_bc]