示例#1
0
    def create_domain(self, InitialOceanStage, InitialLandStage, flowAlg,
                      verbose):
        """
         Make the domain and set the flow algorithm for a test. Produces an sww
         that we can use for testing
        """
        boundaryPolygon = [[0., 0.], [0., 100.], [100.0, 100.0], [100.0, 0.0]]
        anuga.create_mesh_from_regions(boundaryPolygon,
                                       boundary_tags={
                                           'left': [0],
                                           'top': [1],
                                           'right': [2],
                                           'bottom': [3]
                                       },
                                       maximum_triangle_area=20.,
                                       minimum_triangle_angle=28.0,
                                       filename='test_plot_utils.msh',
                                       interior_regions=[],
                                       verbose=False)

        domain = anuga.create_domain_from_file('test_plot_utils.msh')

        os.remove('test_plot_utils.msh')

        # 05/05/2014 -- riverwalls only work with DE0 and DE1
        domain.set_flow_algorithm(flowAlg)
        domain.set_name('test_plot_utils')

        domain.set_store_vertices_uniquely()

        def topography(x, y):
            return -x / 150.

        def stagefun(x, y):
            stg = InitialOceanStage * (x >= 50.) + InitialLandStage * (x < 50.)
            return stg

        domain.set_flow_algorithm(flowAlg)
        #domain.set_quantity('elevation',topography,location='centroids')
        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.03)
        #domain.set_quantity('stage', stagefun,location='centroids')
        domain.set_quantity('stage', stagefun)

        if (verbose):
            if (domain.store_centroids):
                print '   Centroids stored'
            else:
                print '    Centroids estimated from vertices'

        # Boundary conditions
        Br = anuga.Reflective_boundary(domain)
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

        for t in domain.evolve(yieldstep=0.2, finaltime=1.0):
            pass

        return
示例#2
0
    def create_domain_DE1(self, wallHeight, InitialOceanStage,
                          InitialLandStage):
        # Riverwall = list of lists, each with a set of x,y,z (and optional QFactor) values
        riverWall = {
            'centralWall': [[wallLoc, 0.0, wallHeight],
                            [wallLoc, 100.0, wallHeight]]
        }
        riverWall_Par = {'centralWall': {'Qfactor': 1.0}}
        # Make the domain
        anuga.create_mesh_from_regions(
            boundaryPolygon,
            boundary_tags={
                'left': [0],
                'top': [1],
                'right': [2],
                'bottom': [3]
            },
            maximum_triangle_area=200.,
            minimum_triangle_angle=28.0,
            filename='testRiverwall.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)

        domain = anuga.create_domain_from_file('testRiverwall.msh')

        # 05/05/2014 -- riverwalls only work with DE0 and DE1
        domain.set_flow_algorithm('DE1')
        domain.set_name('test_riverwall')

        domain.set_store_vertices_uniquely()

        def topography(x, y):
            return -x / 150.

        def stagefun(x, y):
            stg = InitialOceanStage * (x >= 50.) + InitialLandStage * (x < 50.)
            return stg

        # NOTE: Setting quantities at centroids is important for exactness of tests
        domain.set_quantity('elevation', topography, location='centroids')
        domain.set_quantity('friction', 0.03)
        domain.set_quantity('stage', stagefun, location='centroids')

        domain.riverwallData.create_riverwalls(riverWall,
                                               riverWall_Par,
                                               verbose=verbose)

        # Boundary conditions
        Br = anuga.Reflective_boundary(domain)
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

        return domain
示例#3
0
    def create_domain(self, InitialOceanStage, InitialLandStage, flowAlg, verbose):
        """
         Make the domain and set the flow algorithm for a test. Produces an sww
         that we can use for testing
        """
        boundaryPolygon=[ [0., 0.], [0., 100.], [100.0, 100.0], [100.0, 0.0]]
        anuga.create_mesh_from_regions(boundaryPolygon, 
                                   boundary_tags={'left': [0],
                                                'top': [1],
                                                'right': [2],
                                                'bottom': [3]},
                                   maximum_triangle_area = 20.,
                                   minimum_triangle_angle = 28.0,
                                   filename = 'test_plot_utils.msh',
                                   interior_regions =[ ],
                                   verbose=False)

        domain=anuga.create_domain_from_file('test_plot_utils.msh')
        
        os.remove('test_plot_utils.msh')

        # 05/05/2014 -- riverwalls only work with DE0 and DE1
        domain.set_flow_algorithm(flowAlg)
        domain.set_name('test_plot_utils')

        domain.set_store_vertices_uniquely()
       
        def topography(x,y):
            return -x/150. 

        def stagefun(x,y):
            stg=InitialOceanStage*(x>=50.) + InitialLandStage*(x<50.)
            return stg 

        domain.set_flow_algorithm(flowAlg)
        #domain.set_quantity('elevation',topography,location='centroids')     
        domain.set_quantity('elevation',topography)     
        domain.set_quantity('friction',0.03)             
        #domain.set_quantity('stage', stagefun,location='centroids')            
        domain.set_quantity('stage', stagefun)            
       
        if(verbose):
            if(domain.store_centroids):
                print '   Centroids stored'
            else:
                print '    Centroids estimated from vertices'

        # Boundary conditions
        Br=anuga.Reflective_boundary(domain)
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom':Br})

        for t in domain.evolve(yieldstep=0.2,finaltime=1.0):
            pass

        return 
    def create_domain_DE0(self, wallHeight, InitialOceanStage, InitialLandStage, riverWall=None, riverWall_Par=None):
        # Riverwall = list of lists, each with a set of x,y,z (and optional QFactor) values

        if(riverWall is None):
            riverWall={ 'centralWall':
                            [ [wallLoc, 0.0, wallHeight],
                              [wallLoc, 100.0, wallHeight]] 
                      }
        if(riverWall_Par is None):
            riverWall_Par={'centralWall':{'Qfactor':1.0}}
        # Make the domain
        anuga.create_mesh_from_regions(boundaryPolygon, 
                                 boundary_tags={'left': [0],
                                                'top': [1],
                                                'right': [2],
                                                'bottom': [3]},
                                   maximum_triangle_area = 200.,
                                   minimum_triangle_angle = 28.0,
                                   filename = 'testRiverwall.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)

        domain=anuga.create_domain_from_file('testRiverwall.msh')

        # 05/05/2014 -- riverwalls only work with DE0 and DE1
        domain.set_flow_algorithm('DE0')
        domain.set_name('test_riverwall')

        domain.set_store_vertices_uniquely()
       
        def topography(x,y):
            return -x/150. 

        def stagefun(x,y):
            stg=InitialOceanStage*(x>=50.) + InitialLandStage*(x<50.)
            return stg 

        # NOTE: Setting quantities at centroids is important for exactness of tests
        domain.set_quantity('elevation',topography,location='centroids')     
        domain.set_quantity('friction',0.03)             
        domain.set_quantity('stage', stagefun,location='centroids')            
        
        domain.riverwallData.create_riverwalls(riverWall,riverWall_Par,verbose=verbose) 

        # Boundary conditions
        Br=anuga.Reflective_boundary(domain)
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom':Br})

        return domain
示例#5
0
def build_mesh(project):
    """

    This is executed by processor 0 to build the mesh.

    """

    # Ensure mesh_breaklines include riverwalls and breaklines

    mesh_breaklines = \
        su.combine_breakLines_and_riverWalls_for_mesh(project.breaklines,
                                                      project.riverwalls)

    # Make the mesh

    anuga.create_mesh_from_regions(
        project.bounding_polygon,
        boundary_tags=project.boundary_tags,
        maximum_triangle_area=project.default_res,
        filename=project.meshname,
        interior_regions=project.interior_regions,
        use_cache=False,
        verbose=verbose,
        breaklines=mesh_breaklines,
        regionPtArea=project.region_point_areas,
    )

    # Make the domain using the mesh

    domain = anuga.create_domain_from_file(project.meshname)

    # Print some stats about mesh and domain

    print 'Number of triangles = ', len(domain)
    print 'The extent is ', domain.get_extent()
    print domain.statistics()

    # Print info on the smallest triangles

    small_areas = domain.areas.argsort()
    print ''
    print 'LOCATIONS OF TRIANGLES WITH SMALLEST AREAS'
    for i in range(10):
        j = small_areas[i]
        x = domain.centroid_coordinates[j, 0] \
            + domain.geo_reference.xllcorner
        y = domain.centroid_coordinates[j, 1] \
            + domain.geo_reference.yllcorner
        print '  Area ' + str(domain.areas[j]) + ' location: ' \
            + str(round(x, 1)) + ',' + str(round(y, 1))
    print ''

    return domain
示例#6
0
def build_mesh(project):
    """

    This is executed by processor 0 to build the mesh.

    """

    # Ensure mesh_breaklines include riverwalls and breaklines

    mesh_breaklines = su.combine_breakLines_and_riverWalls_for_mesh(project.breaklines, project.riverwalls)

    # Make the mesh

    anuga.create_mesh_from_regions(
        project.bounding_polygon,
        boundary_tags=project.boundary_tags,
        maximum_triangle_area=project.default_res,
        filename=project.meshname,
        interior_regions=project.interior_regions,
        use_cache=False,
        verbose=verbose,
        breaklines=mesh_breaklines,
        regionPtArea=project.region_point_areas,
    )

    # Make the domain using the mesh

    domain = anuga.create_domain_from_file(project.meshname)

    # Print some stats about mesh and domain

    print "Number of triangles = ", len(domain)
    print "The extent is ", domain.get_extent()
    print domain.statistics()

    # Print info on the smallest triangles

    small_areas = domain.areas.argsort()
    print ""
    print "LOCATIONS OF TRIANGLES WITH SMALLEST AREAS"
    for i in range(10):
        j = small_areas[i]
        x = domain.centroid_coordinates[j, 0] + domain.geo_reference.xllcorner
        y = domain.centroid_coordinates[j, 1] + domain.geo_reference.yllcorner
        print "  Area " + str(domain.areas[j]) + " location: " + str(round(x, 1)) + "," + str(round(y, 1))
    print ""

    return domain
    def create_domain(self, flowalg):
        # Riverwall = list of lists, each with a set of x,y,z (and optional QFactor) values

        # Make the domain
        anuga.create_mesh_from_regions(boundaryPolygon, 
                                 boundary_tags={'left': [0],
                                                'top': [1],
                                                'right': [2],
                                                'bottom': [3]},
                                   maximum_triangle_area = 200.,
                                   minimum_triangle_angle = 28.0,
                                   filename = 'test_boundaryfluxintegral.msh',
                                   use_cache=False,
                                   verbose=verbose)

        domain=anuga.create_domain_from_file('test_boundaryfluxintegral.msh')

        # 05/05/2014 -- riverwalls only work with DE0 and DE1
        domain.set_flow_algorithm(flowalg)
        domain.set_name('test_boundaryfluxintegral')

        domain.set_store_vertices_uniquely()
       
        def topography(x,y):
            return -x/150. 

        # NOTE: Setting quantities at centroids is important for exactness of tests
        domain.set_quantity('elevation',topography,location='centroids')     
        domain.set_quantity('friction',0.03)             
        domain.set_quantity('stage', topography,location='centroids')            
       
        # Boundary conditions
        Br=anuga.Reflective_boundary(domain)
        Bd=anuga.Dirichlet_boundary([0., 0., 0.])
        domain.set_boundary({'left': Br, 'right': Bd, 'top': Br, 'bottom':Br})

        return domain
        house_addition_poly_fun_pairs.append( 
            [ breaklines[i], house_height])
    house_addition_poly_fun_pairs.append(['All', 0.])

#------------------------------------------------------------------------------
# Make domain
#------------------------------------------------------------------------------

if myid == 0:
    mesh = anuga.create_mesh_from_regions(
            project.bounding_polygon,
            boundary_tags={'bottom': [0],
                           'right': [1],
                           'top': [2],
                           'left': [3]},
            maximum_triangle_area=remainder_res,
            interior_holes=holes,
            breaklines=breaklines,
            filename=meshname,
            interior_regions=interior_regions,
            use_cache=use_cache,
            verbose=verbose)

    domain = anuga.create_domain_from_file(meshname)
    
    domain.set_flow_algorithm(alg)
    if verbose: print domain.get_extent(absolute=True)

    #------------------------------------------------------------------------------
    # Setup initial conditions
    #------------------------------------------------------------------------------
def setup_domain(simulation):

    args = simulation.args
    verbose = args.verbose
    alg = args.alg

    N = args.N
    S = args.S
    E = args.E
    W = args.W

    from catchment_info import create_catchment_list
    from catchment_info import create_manning_list

    CatchmentList = create_catchment_list(simulation)
    ManningList = create_manning_list(simulation)

    #---------------------------------------------------------------------------
    # CREATING MESH
    #---------------------------------------------------------------------------

    bounding_polygon = [[W, S], [E, S], [E, N], [W, N]]

    interior_regions = read_polygon_list(CatchmentList)

    # FIXME: Have these in a shapefile / other file and read them in
    breaklines = [[[306612.336559443, 6193708.75358065],
                   [306604.441364239, 6193693.17994946]],
                  [[306977.886673843, 6193753.44134088],
                   [306978.027867398, 6193710.94208076]],
                  [[306956.001672788, 6193750.89985688],
                   [306956.707640564, 6193706.14149989]],
                  [[306627.303076293, 6193697.45809624],
                   [306620.525785644, 6193683.62112783]],
                  [[307236.83565407, 6193741.01630802],
                   [307231.682089306, 6193721.03741996]],
                  [[307224.975395434, 6193742.71063068],
                   [307220.880782334, 6193723.36711362]],
                  [[307624.764946969, 6193615.98941489],
                   [307617.98765632, 6193601.44647871]],
                  [[307613.328268998, 6193623.19028621],
                   [307607.751123568, 6193610.97704368]]]

    # Make the mesh
    create_mesh_from_regions(bounding_polygon,
                             boundary_tags={
                                 'south': [0],
                                 'east': [1],
                                 'north': [2],
                                 'west': [3]
                             },
                             maximum_triangle_area=args.maximum_triangle_area,
                             interior_regions=interior_regions,
                             filename=args.meshname,
                             breaklines=breaklines,
                             use_cache=False,
                             verbose=True)

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

    domain = Domain(args.meshname, use_cache=False, verbose=True)

    domain.set_flow_algorithm(alg)

    if (not domain.get_using_discontinuous_elevation()):
        raise Exception, 'This model run relies on a discontinuous elevation solver (because of how topography is set up)'

    domain.set_datadir(args.model_output_dir)
    domain.set_name(args.outname)

    print domain.statistics()

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

    if verbose: print 'Calculating complicated polygon friction function'
    friction_list = read_polygon_list(ManningList)
    domain.set_quantity(
        'friction',
        Polygon_function(friction_list,
                         default=args.base_friction,
                         geo_reference=domain.geo_reference))

    # Set a Initial Water Level over the Domain
    domain.set_quantity('stage', 0)

    if verbose: print 'Setting up elevation interpolation function'
    from anuga.utilities.quantity_setting_functions import make_nearestNeighbour_quantity_function

    if verbose: print 'READING %s' % args.basename + '.csv'
    elev_xyz = numpy.genfromtxt(fname=args.basename + '.csv', delimiter=',')

    # Use nearest-neighbour interpolation of elevation
    if verbose: print 'CREATING nearest neighbour interpolator'
    elev_fun_wrapper = make_nearestNeighbour_quantity_function(
        elev_xyz, domain)

    if verbose: print 'Applying elevation interpolation function'
    domain.set_quantity('elevation', elev_fun_wrapper, location='centroids')

    return domain
示例#10
0
        breaklines[i] = breaklines[i] + [breaklines[i][0]]
        house_addition_poly_fun_pairs.append([breaklines[i], house_height])
    house_addition_poly_fun_pairs.append(['All', 0.])

#------------------------------------------------------------------------------
# Make domain
#------------------------------------------------------------------------------

if myid == 0:
    mesh = anuga.create_mesh_from_regions(project.bounding_polygon,
                                          boundary_tags={
                                              'bottom': [0],
                                              'right': [1],
                                              'top': [2],
                                              'left': [3]
                                          },
                                          maximum_triangle_area=remainder_res,
                                          interior_holes=holes,
                                          breaklines=breaklines,
                                          filename=meshname,
                                          interior_regions=interior_regions,
                                          use_cache=use_cache,
                                          verbose=verbose)

    domain = anuga.create_domain_from_file(meshname)

    domain.set_flow_algorithm(alg)
    if verbose: print(domain.get_extent(absolute=True))

    #------------------------------------------------------------------------------
    # Setup initial conditions
    #------------------------------------------------------------------------------
示例#11
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
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')
示例#13
0
    [floodplain_width - 0.01, floodplain_length / 2., 0.5 * l0 * l0],
    [floodplain_width + 0.01, floodplain_length / 2., 0.5 * l0 * l0],
]

if (myid == 0):
    # Define domain with appropriate boundary conditions
    anuga.create_mesh_from_regions(
        boundary_polygon,
        boundary_tags={
            'left': [0],
            'top1': [1],
            'chan_out': [2],
            'top2': [3],
            'right': [4],
            'bottom1': [5],
            'chan_in': [6],
            'bottom2': [7]
        },
        maximum_triangle_area=1.0e+06,  #0.5*l0*l0,
        minimum_triangle_angle=28.0,
        filename='channel_floodplain1.msh',
        interior_regions=[],
        breaklines=breakLines.values(),
        regionPtArea=regionPtAreas,
        verbose=True)
    domain = anuga.create_domain_from_file('channel_floodplain1.msh')
    domain.set_name('channel_floodplain1')  # Output name
    domain.set_flow_algorithm(alg)
else:
    domain = None
示例#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
    # Make a directory to store outputs
    os.mkdir(project.output_run)
    print 'OUTPUT FOLDER IS: ', project.output_run
    anuga.copy_code_files(project.output_run,'run_model.py', 'project.py') # Write model files to folder
    
    #------------------------------------------------------------------------------
    # Create the triangular mesh and domain based on 
    # overall clipping polygon with a tagged
    # boundary and interior regions as defined in project.py
    #------------------------------------------------------------------------------
    anuga.create_mesh_from_regions(project.bounding_polygon,
                                   boundary_tags={'top': [0],
                                                  'ocean_east': [1],
                                                  'bottom': [2],
                                                  'onshore': [3]},
                               maximum_triangle_area=project.low_res_0,
                               filename=project.meshname,
                               interior_regions=[], #project.interior_regions,
                               breaklines=project.breakLines,
                               regionPtArea=project.regionPtAreas,
                               use_cache=False,
                               verbose=True)
    domain=anuga.create_domain_from_file(project.meshname)

    # Print some stats about mesh and domain
    print 'Number of triangles = ', len(domain)
    print 'The extent is ', domain.get_extent()
    print domain.statistics()
    
    domain.set_flow_algorithm('tsunami')
    domain.verbose=True
示例#16
0
E = 296730.
S = 6179960.

#------------------------------------------------------------------------------
# CREATING MESH
#------------------------------------------------------------------------------

bounding_polygon = [[W, S], [E, S], [E, N], [W, N]]

create_mesh_from_regions(bounding_polygon,
                         boundary_tags={
                             'south': [0],
                             'east': [1],
                             'north': [2],
                             'west': [3]
                         },
                         maximum_triangle_area=1.0,
                         filename=meshname,
                         use_cache=False,
                         verbose=True)

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

domain = Domain(meshname, use_cache=False, verbose=True)
domain.set_minimum_storable_height(0.0001)
domain.set_name(outname)
print(domain.statistics())
示例#17
0
    def create_domain(self,
                      InitialOceanStage,
                      InitialLandStage,
                      flowAlg='DE0',
                      verbose=False):
        """
         Make the domain and set the flow algorithm for a test. Produces an sww
         that we can use for testing
        """

        boundaryPolygon = [[minX, minY], [minX, minY + 100.],
                           [minX + 100., minY + 100.], [minX + 100., minY]]
        anuga.create_mesh_from_regions(
            boundaryPolygon,
            boundary_tags={
                'left': [0],
                'top': [1],
                'right': [2],
                'bottom': [3]
            },
            maximum_triangle_area=1.,
            minimum_triangle_angle=28.0,
            filename='test_quantity_setting_functions.msh',
            interior_regions=[],
            verbose=False)

        domain = anuga.create_domain_from_file(
            'test_quantity_setting_functions.msh')

        os.remove('test_quantity_setting_functions.msh')

        domain.set_flow_algorithm(flowAlg)
        domain.set_name('test_quantity_setting_functions')

        domain.set_store_vertices_uniquely()

        def topography(x, y):
            return -x / 150.

        def stagefun(x, y):
            stg = InitialOceanStage * (x >= 50.) + InitialLandStage * (x < 50.)
            return stg

        domain.set_flow_algorithm(flowAlg)
        # domain.set_quantity('elevation',topography,location='centroids')
        domain.set_quantity('elevation', topography)
        domain.set_quantity('friction', 0.03)
        #domain.set_quantity('stage', stagefun,location='centroids')
        domain.set_quantity('stage', stagefun)

        if (verbose):
            if (domain.store_centroids):
                print('   Centroids stored')
            else:
                print('    Centroids estimated from vertices')

        # Boundary conditions
        Br = anuga.Reflective_boundary(domain)
        domain.set_boundary({'left': Br, 'right': Br, 'top': Br, 'bottom': Br})

        return domain
示例#18
0
def start_sim(run_id, Runs, scenario_name, Scenario, session, **kwargs):
    yieldstep = kwargs['yieldstep']
    finaltime = kwargs['finaltime']
    logger = logging.getLogger(run_id)
    max_triangle_area = kwargs['max_triangle_area']
    logger.info('Starting hydrata_project')

    if run_id == 'local_run':
        base_dir = os.getcwd()
    else:
        base_dir = os.getcwd() + '/base_dir/%s/' % run_id

    outname = run_id
    meshname = base_dir + 'outputs/' + run_id + '.msh'

    def get_filename(data_type, file_type):
        files = os.listdir('%sinputs/%s' % (base_dir, data_type))
        filename = '%sinputs/%s/%s' % (
            base_dir, data_type, [f for f in files if f[-4:] == file_type][0])
        return filename

    boundary_data_filename = get_filename('boundary_data', '.shp')
    elevation_data_filename = get_filename('elevation_data', '.tif')
    try:
        structures_filename = get_filename('structures', '.shp')
    except OSError as e:
        structures_filename = None
    try:
        rain_data_filename = get_filename('rain_data', '.shp')
    except OSError as e:
        rain_data_filename = None
    try:
        inflow_data_filename = get_filename('inflow_data', '.shp')
    except OSError as e:
        inflow_data_filename = None
    try:
        friction_data_filename = get_filename('friction_data', '.shp')
    except OSError as e:
        friction_data_filename = None

    logger.info('boundary_data_filename: %s' % boundary_data_filename)
    logger.info('structures_filename: %s' % structures_filename)
    logger.info('rain_data_filename: %s' % rain_data_filename)
    logger.info('inflow_data_filename: %s' % inflow_data_filename)
    logger.info('friction_data_filename: %s' % friction_data_filename)
    logger.info('elevation_data_filename: %s' % elevation_data_filename)

    # create a list of project files
    vector_filenames = [
        boundary_data_filename, structures_filename, rain_data_filename,
        inflow_data_filename, friction_data_filename
    ]

    # set the projection system for ANUGA calculations from the geotiff elevation data
    elevation_data_gdal = gdal.Open(elevation_data_filename)
    project_spatial_ref = osr.SpatialReference()
    project_spatial_ref.ImportFromWkt(elevation_data_gdal.GetProjectionRef())
    project_spatial_ref_epsg_code = int(
        project_spatial_ref.GetAttrValue("AUTHORITY", 1))

    # check the spatial reference system of the project files matches that of the calculation
    for filename in vector_filenames:
        if filename:
            prj_text = open(filename[:-4] + '.prj').read()
            srs = osr.SpatialReference()
            srs.ImportFromESRI([prj_text])
            srs.AutoIdentifyEPSG()
            logger.info('filename is: %s' % filename)
            logger.info('EPSG is: %s' % srs.GetAuthorityCode(None))
            if str(srs.GetAuthorityCode(None)) != str(
                    project_spatial_ref_epsg_code):
                logger.warning('warning spatial refs are not maching: %s, %s' %
                               (srs.GetAuthorityCode(None),
                                project_spatial_ref_epsg_code))

    logger.info('Setting up structures...')
    if structures_filename:
        structures = []
        logger.info('processing structures from :%s' % structures_filename)
        ogr_shapefile = ogr.Open(structures_filename)
        ogr_layer = ogr_shapefile.GetLayer(0)
        ogr_layer_feature = ogr_layer.GetNextFeature()
        while ogr_layer_feature:
            structure = json.loads(ogr_layer_feature.GetGeometryRef().
                                   ExportToJson())['coordinates'][0]
            structures.append(structure)
            ogr_layer_feature = None
            ogr_layer_feature = ogr_layer.GetNextFeature()

        logger.info('structures: %s' % structures)
    else:
        logger.warning('warning: no structures found.')
        structures = None

    logger.info('Setting up friction...')
    frictions = []
    if friction_data_filename:
        logger.info('processing frictions from :%s' % friction_data_filename)
        ogr_shapefile = ogr.Open(friction_data_filename)
        ogr_layer = ogr_shapefile.GetLayer(0)
        ogr_layer_feature = ogr_layer.GetNextFeature()
        while ogr_layer_feature:
            friction_poly = json.loads(ogr_layer_feature.GetGeometryRef().
                                       ExportToJson())['coordinates'][0]
            friction_value = float(ogr_layer_feature.GetField('mannings'))
            friction_couple = [friction_poly, friction_value]
            frictions.append(friction_couple)
            ogr_layer_feature = None
            ogr_layer_feature = ogr_layer.GetNextFeature()

        frictions.append(['All', 0.04])
        logger.info('frictions: %s' % frictions)
    else:
        frictions.append(['All', 0.04])
        logger.info('warning: no frictions found.')

    logger.info('Setting up boundary conditions...')
    ogr_shapefile = ogr.Open(boundary_data_filename)
    ogr_layer = ogr_shapefile.GetLayer(0)
    ogr_layer_definition = ogr_layer.GetLayerDefn()
    logger.info('ogr_layer_definition.GetGeomType: %s' %
                ogr_layer_definition.GetGeomType())
    boundary_tag_index = 0
    bdy_tags = {}
    bdy = {}

    ogr_layer_feature = ogr_layer.GetNextFeature()
    while ogr_layer_feature:
        boundary_tag_key = ogr_layer_feature.GetField('bdy_tag_k')
        boundary_tag_value = ogr_layer_feature.GetField('bdy_tag_v')
        bdy_tags[boundary_tag_key] = [
            boundary_tag_index * 2, boundary_tag_index * 2 + 1
        ]
        bdy[boundary_tag_key] = boundary_tag_value
        geom = ogr_layer_feature.GetGeometryRef().GetPoints()
        ogr_layer_feature = None
        ogr_layer_feature = ogr_layer.GetNextFeature()
        boundary_tag_index = boundary_tag_index + 1
        logger.info('bdy_tags: %s' % bdy_tags)
    logger.info('bdy: %s' % bdy)

    boundary_data = su.read_polygon(boundary_data_filename)

    create_mesh_from_regions(boundary_data,
                             boundary_tags=bdy_tags,
                             maximum_triangle_area=max_triangle_area,
                             interior_regions=None,
                             interior_holes=structures,
                             filename=meshname,
                             use_cache=False,
                             verbose=True)

    domain = Domain(meshname, use_cache=False, verbose=True)
    domain.set_name(outname)
    domain.set_datadir(base_dir + '/outputs')
    logger.info(domain.statistics())
    poly_fun_pairs = [['Extent', elevation_data_filename.encode("utf-8")]]
    topography_function = qs.composite_quantity_setting_function(
        poly_fun_pairs,
        domain,
        nan_treatment='exception',
    )
    friction_function = qs.composite_quantity_setting_function(
        frictions, domain)
    domain.set_quantity('friction', friction_function, verbose=True)
    domain.set_quantity('stage', 0.0)
    domain.set_quantity('elevation',
                        topography_function,
                        verbose=True,
                        alpha=0.99)
    domain.set_minimum_storable_height(0.005)

    logger.info('Applying rainfall...')
    if rain_data_filename:
        ogr_shapefile = ogr.Open(rain_data_filename)
        ogr_layer = ogr_shapefile.GetLayer(0)
        rainfall = 0
        ogr_layer_feature = ogr_layer.GetNextFeature()
        while ogr_layer_feature:
            rainfall = float(ogr_layer_feature.GetField('rate_mm_hr'))
            polygon = su.read_polygon(rain_data_filename)
            logger.info("applying Polygonal_rate_operator with rate, polygon:")
            logger.info(rainfall)
            logger.info(polygon)
            Polygonal_rate_operator(domain,
                                    rate=rainfall,
                                    factor=1.0e-6,
                                    polygon=polygon,
                                    default_rate=0.0)
            ogr_layer_feature = None
            ogr_layer_feature = ogr_layer.GetNextFeature()

    logger.info('Applying surface inflows...')
    if inflow_data_filename:
        ogr_shapefile = ogr.Open(inflow_data_filename)
        ogr_layer = ogr_shapefile.GetLayer(0)
        ogr_layer_definition = ogr_layer.GetLayerDefn()
        ogr_layer_feature = ogr_layer.GetNextFeature()
        while ogr_layer_feature:
            in_fixed = float(ogr_layer_feature.GetField('in_fixed'))
            line = ogr_layer_feature.GetGeometryRef().GetPoints()
            logger.info("applying Inlet_operator with line, in_fixed:")
            logger.info(line)
            logger.info(in_fixed)
            Inlet_operator(domain, line, in_fixed, verbose=False)
            ogr_layer_feature = None
            ogr_layer_feature = ogr_layer.GetNextFeature()

    logger.info('Applying Boundary Conditions...')
    logger.info('Available boundary tags: %s' % domain.get_boundary_tags())

    Br = anuga.Reflective_boundary(domain)
    Bd = anuga.Dirichlet_boundary([0.0, 0.0, 0.0])
    Bt = anuga.Transmissive_boundary(domain)

    for key, value in bdy.iteritems():
        if value == 'Br':
            bdy[key] = Br
        elif value == 'Bd':
            bdy[key] = Bd
        elif value == 'Bt':
            bdy[key] = Bt
        else:
            logger.info(
                'No matching boundary condition exists - please check your shapefile attributes in: %s'
                % boundary_data_filename)

    # set a default value for exterior & interior boundary if it is not already set
    try:
        bdy['exterior']
    except KeyError:
        bdy['exterior'] = Br
    try:
        bdy['interior']
    except KeyError:
        bdy['interior'] = Br

    logger.info('bdy: %s' % bdy)

    domain.set_boundary(bdy)

    domain = distribute(domain)
    logger.info('Beginning evolve phase...')
    for t in domain.evolve(yieldstep, finaltime):
        domain.write_time()
        print domain.timestepping_statistics()
        logger.info(domain.timestepping_statistics(track_speeds=True))
        percentage_complete = round(domain.time / domain.finaltime, 3) * 100
        logger.info('%s percent complete' % percentage_complete)
        if run_id != 'local_run':
            write_percentage_complete(run_id, Runs, scenario_name, Scenario,
                                      session, percentage_complete)
    domain.sww_merge(delete_old=True)
    barrier()
    finalize()
    sww_file = base_dir + '/outputs/' + run_id + '.sww'
    sww_file = sww_file.encode(
        'utf-8',
        'ignore')  # sometimes run_id gets turned to a unicode object by celery
    util.Make_Geotif(swwFile=sww_file,
                     output_quantities=['depth', 'velocity'],
                     myTimeStep='max',
                     CellSize=max_triangle_area,
                     lower_left=None,
                     upper_right=None,
                     EPSG_CODE=project_spatial_ref_epsg_code,
                     proj4string=None,
                     velocity_extrapolation=True,
                     min_allowed_height=1.0e-05,
                     output_dir=(base_dir + '/outputs/'),
                     bounding_polygon=boundary_data,
                     internal_holes=structures,
                     verbose=False,
                     k_nearest_neighbours=3,
                     creation_options=[])
    logger.info("Done. Nice work.")
示例#19
0
def setup_domain(simulation):
    
    args = simulation.args
    verbose = args.verbose
    alg = args.alg
    
    N = args.N
    S = args.S
    E = args.E
    W = args.W
    
    from catchment_info import create_catchment_list
    from catchment_info import create_manning_list
    
    CatchmentList = create_catchment_list(simulation)
    ManningList = create_manning_list(simulation)
    
    #------------------------------------------------------------------------------
    # CREATING MESH
    #------------------------------------------------------------------------------
    
    bounding_polygon = [[W, S], [E, S], [E, N], [W, N]]
    #interior_regions = read_polygon_dir(CatchmentDictionary, join('Model', 'Bdy'))
    interior_regions = read_polygon_list(CatchmentList)

    # FIXME: Have these in a shapefile / other file and read them in    
    breaklines=[[[306612.336559443,6193708.75358065],
                 [306604.441364239,6193693.17994946]],
                [[306977.886673843,6193753.44134088],
                 [306978.027867398,6193710.94208076]],
                [[306956.001672788,6193750.89985688],
                 [306956.707640564,6193706.14149989]],
                [[306627.303076293,6193697.45809624],
                 [306620.525785644,6193683.62112783]],
                [[307236.83565407,6193741.01630802],
                 [307231.682089306,6193721.03741996]],
                [[307224.975395434,6193742.71063068],
                 [307220.880782334,6193723.36711362]],
                [[307624.764946969,6193615.98941489],
                 [307617.98765632,6193601.44647871]],
                [[307613.328268998,6193623.19028621],
                 [307607.751123568,6193610.97704368]]]

    # Make the mesh
    create_mesh_from_regions(bounding_polygon, 
        boundary_tags={'south': [0], 'east': [1], 'north': [2], 'west': [3]},
        maximum_triangle_area=args.maximum_triangle_area,
        interior_regions=interior_regions,
        filename=args.meshname,
        breaklines=breaklines,
        use_cache=False,
        verbose=True)
    
    #------------------------------------------------------------------------------
    # SETUP COMPUTATIONAL DOMAIN
    #------------------------------------------------------------------------------
    
    domain = Domain(args.meshname, use_cache=False, verbose=True)

    domain.set_flow_algorithm(alg)

    if(not domain.get_using_discontinuous_elevation()):
        raise Exception, 'This model run relies on a discontinuous elevation solver (because of how topography is set up)'

    domain.set_datadir(args.model_output_dir)
    domain.set_name(args.outname)
        
    print domain.statistics()
    
    #------------------------------------------------------------------------------
    # APPLY MANNING'S ROUGHNESSES
    #------------------------------------------------------------------------------
    
    if verbose: print 'Calculating complicated polygon friction function'
    friction_list = read_polygon_list(ManningList)
    domain.set_quantity('friction', Polygon_function(friction_list, default=args.base_friction, geo_reference=domain.geo_reference))
    
    # Set a Initial Water Level over the Domain
    domain.set_quantity('stage', 0)
   
    # Decompress the zip file to make a csv for reading 
    zipfile.ZipFile('DEM_bridges/towradgi_cleaner.zip').extract('towradgi.csv',path='DEM_bridges/')

    if verbose: print 'Setting up elevation interpolation function'
    from anuga.utilities.quantity_setting_functions import make_nearestNeighbour_quantity_function
    elev_xyz=numpy.genfromtxt(fname=args.basename+'.csv',delimiter=',')

    # Use nearest-neighbour interpolation of elevation 
    elev_fun_wrapper=make_nearestNeighbour_quantity_function(elev_xyz,domain)
    if verbose: print 'Applying elevation interpolation function'    
    domain.set_quantity('elevation', elev_fun_wrapper, location='centroids')

    os.remove('DEM_bridges/towradgi.csv') # Clean up csv file
    
    return domain
示例#20
0
craterlength=0.35
rimheight=0.12
rimwidth=0.14
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)
示例#21
0
import matplotlib.pyplot as plt

plt.figure()
plt.plot(b_polygon[:, 0], b_polygon[:, 1])
for i, v in enumerate(b_polygon):
    plt.annotate(str(v), xy=v, xytext=(-7, 7), textcoords='offset points')
plt.pause(0.01)

create_mesh_from_regions(
    bounding_polygon,
    boundary_tags={
        'inflow': [12],
        'bottom': [0, 1, 2, 3, 4, 5],
        '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)
示例#22
0
for record in lines:
    #Since we are dealing with multi polys, only take the first [0]
    coords = json.loads(record[0])["coordinates"][0]
    interior_regions.append([coords, 100])

#------------------------------------------------------------------------------
# Create the triangular mesh and domain based on
# overall clipping polygon with a tagged
# boundary and interior regions as defined in project.py
#------------------------------------------------------------------------------

meshname = project.tmppath + 'output.msh'

mesh = anuga.create_mesh_from_regions(
    bounding_polygon,
    boundary_tags={
        'top': [0],
        'east': [1],
        'bottom': [2],
        'west': [3]
    },
    maximum_triangle_area=project.default_res,
    filename=meshname,
    interior_regions=interior_regions,
    interior_holes=interior_holes,
    hole_tags=None,
    breaklines=breaklines,
    #breaklines = None,
    use_cache=False,
    verbose=True)
plt.plot(b[:,0],b[:,1])
plt.contour(x,y,z,[0.],colors='w')
plt.axis('equal')
#plt.axis('off')

plt.savefig('01bati_original+extent+curva0.png',bbox_inches='tight',dpi=300)

plt.close()

bounding_polygon=b[:-1,:]
tags={'left' : 	[3],  'bot' :	[0],'right' :	[1],'top' : [2]} 
#el tama\~no m\'aximo
dx=48*5
anuga.create_mesh_from_regions(bounding_polygon,
				    boundary_tags=tags,
				    maximum_triangle_area=dx*dx,     
				    filename='talcahuano4.msh',
				    use_cache=False,
				    verbose=True)

#----------la batimetria------------

#archivo con info de la proyeccion
sprj='Projection    UTM \n'+ \
'Zone          55\n'+\
'Datum         WGS84\n'+\
'Zunits        NO\n'+\
'Units         METERS\n'+\
'Spheroid      WGS84\n'+\
'Xshift        500000\n'+\
'Yshift        10000000\n'+\
'Parameters'
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')
                [floodplain_width/2., floodplain_length/2., 0.5*l0*l0], 
                [floodplain_width-0.01, floodplain_length/2., 0.5*l0*l0], 
                [floodplain_width+0.01, floodplain_length/2., 0.5*l0*l0], 

              ]

if(myid==0):
    # Define domain with appropriate boundary conditions
    anuga.create_mesh_from_regions(boundary_polygon, 
                                   boundary_tags={'left': [0],
                                                  'top1': [1],
                                                  'chan_out': [2],
                                                  'top2': [3],
                                                  'right': [4],
                                                  'bottom1': [5],
                                                  'chan_in': [6],
                                                  'bottom2': [7] },
                                   maximum_triangle_area = 1.0e+06, #0.5*l0*l0,
                                   minimum_triangle_angle = 28.0,
                                   filename = 'channel_floodplain1.msh',
                                   interior_regions = [ ],
                                   breaklines=breakLines.values(),
                                   regionPtArea=regionPtAreas,
                                   verbose=True)
    domain=anuga.create_domain_from_file('channel_floodplain1.msh')
    domain.set_name('channel_floodplain1') # Output name
    domain.set_flow_algorithm(alg)
else:
    domain=None

barrier()
domain=distribute(domain)
示例#26
0
                [45., 45., 1.0*1.0*0.5],
                [55., 55., 1.0*1.0*0.5],
                [65., 65., 3.0*3.0*0.5],
                [35., 35., 3.0*3.0*0.5] ]

if myid == 0:
    #==================================================================
    # Create Sequential Domain
    #==================================================================
    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=True,
                               regionPtArea=regionPtAreas)
    
    domain=anuga.create_domain_from_file('runup.msh')
    
    
    domain.set_flow_algorithm(alg)
    
    
    domain.set_name('runup_riverwall')                         
    domain.set_datadir('.')