예제 #1
0
def calculate_boundary_points(boundary_polygon,
                              zone,
                              ll_lat,
                              ll_long,
                              grid_spacing,
                              lat_amount,
                              long_amount,
                              isSouthHemisphere=True,
                              use_cache=False,
                              verbose=False):
    args = (boundary_polygon, zone, ll_lat, ll_long, grid_spacing, lat_amount,
            long_amount, isSouthHemisphere)
    kwargs = {}

    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module' \
                  'could not be imported'
            raise Exception(msg)

        geo = cache(_calculate_boundary_points,
                    args,
                    kwargs,
                    verbose=verbose,
                    compression=False)
    else:
        geo = _calculate_boundary_points(*args, **kwargs)

    return geo
예제 #2
0
def llasc2pts(name_in, name_out=None,
            use_cache=False, show_progress=False, verbose=False,):
    """Read Digital Elevation model from the following ASCII format (.asc)

    Example:
    ncols        968
    nrows        698
    xllcorner    144.966666666667
    yllcorner    -18.500000000000
    cellsize     0.004166666667
    NODATA_value -32767
    138.3698 137.4194 136.5062 135.5558 ..........

    Convert name_in (.asc) to NetCDF format (.pts)

    """

    kwargs = {'name_out': name_out, 'verbose': verbose, 'show_progress': show_progress}

    if use_cache is True:
        from anuga.caching import cache
        result = cache(_convert_dem_from_llasc2pts, name_in, kwargs,
                       dependencies=[name_in],
                       verbose=verbose)

    else:
        result = _convert_dem_from_llasc2pts(*[name_in], **kwargs)

    return result
예제 #3
0
def calculate_boundary_points(boundary_polygon, zone, ll_lat,
                      ll_long, grid_spacing,
                      lat_amount, long_amount, isSouthHemisphere=True,
                      use_cache=False, verbose=False):
    args = (boundary_polygon,
            zone, ll_lat,
            ll_long, grid_spacing,
            lat_amount, long_amount, isSouthHemisphere)
    kwargs = {}

    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module' \
                  'could not be imported'
            raise Exception(msg)

        geo = cache(_calculate_boundary_points,
                    args, kwargs,
                    verbose=verbose,
                    compression=False)
    else:
        geo = apply(_calculate_boundary_points, args, kwargs)

    return geo
예제 #4
0
def create_domain_from_regions_sed(bounding_polygon,
                               boundary_tags,
                               maximum_triangle_area=None,
                               mesh_filename=None,
                               interior_regions=None,
                               interior_holes=None,
                               hole_tags=None,
                               poly_geo_reference=None,
                               mesh_geo_reference=None,
                               minimum_triangle_angle=28.0,
                               conserved_quantities=None,
                               evolved_quantities=None,
                               other_quantities=None,
                               fail_if_polygons_outside=True,
                               use_cache=False,
                               verbose=True):


    # Build arguments and keyword arguments for use with caching or apply.
    args = (bounding_polygon,
            boundary_tags)
    
    kwargs = {'maximum_triangle_area': maximum_triangle_area,
              'mesh_filename': mesh_filename,
              'interior_regions': interior_regions,
              'interior_holes': interior_holes,
              'hole_tags': hole_tags,
              'poly_geo_reference': poly_geo_reference,
              'mesh_geo_reference': mesh_geo_reference,
              'minimum_triangle_angle': minimum_triangle_angle,
              'conserved_quantities': conserved_quantities,
              'evolved_quantities': evolved_quantities,
              'other_quantities': other_quantities,
              'fail_if_polygons_outside': fail_if_polygons_outside,
              'verbose': verbose} #FIXME (Ole): See ticket:14

    # Call underlying engine with or without caching
    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module'+\
                  'could not be imported'
            raise (msg)


        domain = cache(_create_domain_from_regions_sed,
                       args, kwargs,
                       verbose=verbose,
                       compression=False)
    else:
        domain = apply(_create_domain_from_regions_sed,
                       args, kwargs)

    return domain
예제 #5
0
def fit_to_mesh(point_coordinates,
                vertex_coordinates=None,
                triangles=None,
                mesh=None,
                point_attributes=None,
                alpha=DEFAULT_ALPHA,
                verbose=False,
                mesh_origin=None,
                data_origin=None,
                max_read_lines=None,
                attribute_name=None,
                use_cache=False,
                cg_precon='Jacobi',
                use_c_cg=True):
    """Wrapper around internal function _fit_to_mesh for use with caching.
    """

    args = (point_coordinates, )
    kwargs = {
        'vertex_coordinates': vertex_coordinates,
        'triangles': triangles,
        'mesh': mesh,
        'point_attributes': point_attributes,
        'alpha': alpha,
        'verbose': verbose,
        'mesh_origin': mesh_origin,
        'data_origin': data_origin,
        'max_read_lines': max_read_lines,
        'attribute_name': attribute_name,
        'cg_precon': cg_precon,
        'use_c_cg': use_c_cg
    }

    if use_cache is True:
        if isinstance(point_coordinates, basestring):
            # We assume that point_coordinates is the name of a .csv/.txt
            # file which must be passed onto caching as a dependency
            # (in case it has changed on disk)
            dep = [point_coordinates]
        else:
            dep = None

        return cache(_fit_to_mesh,
                     args,
                     kwargs,
                     verbose=verbose,
                     compression=False,
                     dependencies=dep)
    else:
        res = apply(_fit_to_mesh, args, kwargs)
        "print intep should go out of range"
        return res
예제 #6
0
def fit_to_mesh(point_coordinates,
                vertex_coordinates=None,
                triangles=None,
                mesh=None,
                point_attributes=None,
                alpha=DEFAULT_ALPHA,
                verbose=False,
                mesh_origin=None,
                data_origin=None,
                max_read_lines=None,
                attribute_name=None,
                use_cache=False,
                cg_precon='Jacobi',
                use_c_cg=True):
    """Wrapper around internal function _fit_to_mesh for use with caching.
    """

    args = (point_coordinates, )
    kwargs = {'vertex_coordinates': vertex_coordinates,
              'triangles': triangles,
              'mesh': mesh,
              'point_attributes': point_attributes,
              'alpha': alpha,
              'verbose': verbose,
              'mesh_origin': mesh_origin,
              'data_origin': data_origin,
              'max_read_lines': max_read_lines,
              'attribute_name': attribute_name,
              'cg_precon': cg_precon,
              'use_c_cg': use_c_cg
              }

    if use_cache is True:
        if isinstance(point_coordinates, basestring):
            # We assume that point_coordinates is the name of a .csv/.txt
            # file which must be passed onto caching as a dependency
            # (in case it has changed on disk)
            dep = [point_coordinates]
        else:
            dep = None

        return cache(_fit_to_mesh,
                     args, kwargs,
                     verbose=verbose,
                     compression=False,
                     dependencies=dep)
    else:
        res = apply(_fit_to_mesh,
                     args, kwargs)
        "print intep should go out of range"
        return res
예제 #7
0
def dem2pts(
    name_in,
    name_out=None,
    easting_min=None,
    easting_max=None,
    northing_min=None,
    northing_max=None,
    use_cache=False,
    verbose=False,
):
    """Read Digitial Elevation model from the following NetCDF format (.dem)

    Example:

    ncols         3121
    nrows         1800
    xllcorner     722000
    yllcorner     5893000
    cellsize      25
    NODATA_value  -9999
    138.3698 137.4194 136.5062 135.5558 ..........

    name_in may be a .asc or .dem file to be converted.

    Convert to NetCDF pts format which is

    points:  (Nx2) float array
    elevation: N float array
    """

    kwargs = {
        'name_out': name_out,
        'easting_min': easting_min,
        'easting_max': easting_max,
        'northing_min': northing_min,
        'northing_max': northing_max,
        'verbose': verbose
    }

    if use_cache is True:
        from anuga.caching import cache
        result = cache(_dem2pts,
                       name_in,
                       kwargs,
                       dependencies=[name_in],
                       verbose=verbose)

    else:
        result = apply(_dem2pts, [name_in], kwargs)

    return result
예제 #8
0
    def get_intersecting_segments(self, polyline,
                                  use_cache=False,
                                  verbose=False):
        """Find edges intersected by polyline

        Input:
            polyline - list of points forming a segmented line
            use_cache
            verbose

        Output:
            list of instances of class Triangle_intersection

        The polyline may break inside any triangle causing multiple
        segments per triangle - consequently the same triangle may
        appear in several entries.

        If a polyline segment coincides with a triangle edge,
        the the entire shared segment will be used.
        Onle one of the triangles thus intersected will be used and that
        is the first one encountered.

        Intersections with single vertices are ignored.

        Resulting segments are unsorted
        """

        V = self.get_vertex_coordinates()
        N = len(self)

        # Adjust polyline to mesh spatial origin
        polyline = self.geo_reference.get_relative(polyline)

        if use_cache is True:
            segments = cache(get_intersecting_segments,
                             (V, N, polyline),
                             {'verbose': verbose},
                             verbose=verbose)
        else:
            segments = get_intersecting_segments(V, N, polyline,
                                                 verbose=verbose)


        return segments
예제 #9
0
def pmesh_to_domain_instance(source, DomainClass, use_cache=False,
                             verbose=False):
    """Converts a mesh file(.tsh or .msh), to a Domain instance.

    file_name is the name of the mesh file to convert, including the extension

    DomainClass is the Class that will be returned.
    It must be a subclass of Domain, with the same interface as domain.

    use_cache: True means that caching is attempted for the computed domain.    
    """

    if use_cache is True:
        from anuga.caching import cache
        result = cache(_pmesh_to_domain_instance, (source, DomainClass),
                       dependencies=[source], verbose=verbose)
    else:
        result = apply(_pmesh_to_domain_instance, (source, DomainClass))        
        
    return result
예제 #10
0
def dem2pts(name_in, name_out=None,
            easting_min=None, easting_max=None,
            northing_min=None, northing_max=None,
            use_cache=False, verbose=False,):
    """Read Digitial Elevation model from the following NetCDF format (.dem)

    Example:

    ncols         3121
    nrows         1800
    xllcorner     722000
    yllcorner     5893000
    cellsize      25
    NODATA_value  -9999
    138.3698 137.4194 136.5062 135.5558 ..........

    name_in may be a .asc or .dem file to be converted.

    Convert to NetCDF pts format which is

    points:  (Nx2) float array
    elevation: N float array
    """

    kwargs = {'name_out': name_out,
              'easting_min': easting_min,
              'easting_max': easting_max,
              'northing_min': northing_min,
              'northing_max': northing_max,
              'verbose': verbose}

    if use_cache is True:
        from anuga.caching import cache
        result = cache(_dem2pts, name_in, kwargs,
                       dependencies = [name_in],
                       verbose = verbose)

    else:
        result = apply(_dem2pts, [name_in], kwargs)

    return result
예제 #11
0
def pmesh_to_domain(file_name=None, mesh_instance=None, use_cache=False,
                    verbose=False):
    """Convert a pmesh file or a pmesh mesh instance to a bunch of lists
    that can be used to instanciate a domain object.

    use_cache: True means that caching is attempted for the computed domain.    
    """

    if verbose: log.critical('Pmesh_to_Domain: Initialising')
    
    if use_cache is True:
        from anuga.caching import cache
        result = cache(_pmesh_to_domain, (file_name, mesh_instance),
                       dependencies=[file_name], verbose=verbose)

    else:
        result = apply(_pmesh_to_domain, (file_name, mesh_instance))        

    if verbose: log.critical('Pmesh_to_Domain: Done')

    return result
예제 #12
0
    def test_create_mesh_from_regions_with_caching(self):
        x = -500
        y = -1000
        mesh_geo = geo_reference = Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0, 0], [100, 0], [100, 100], [0, 100]]

        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0, 1], 'bom': [2, 3]}

        inner1_polygon_absolute = [[10, 10], [20, 10], [20, 20], [10, 20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30, 30], [40, 30], [40, 40], [30, 40]]
        inner2_polygon = geo_ref_poly.\
                             change_points_geo_ref(inner2_polygon_absolute)

        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]

        interior_holes = None

        # Clear cache first
        from anuga.caching import cache

        cache(_create_mesh_from_regions, (polygon, boundary_tags), {
            'minimum_triangle_angle': 28.0,
            'maximum_triangle_area': 10000000,
            'interior_regions': interior_regions,
            'interior_holes': interior_holes,
            'poly_geo_reference': geo_ref_poly,
            'mesh_geo_reference': mesh_geo,
            'verbose': False
        },
              verbose=False,
              clear=1)

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     maximum_triangle_area=10000000,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo,
                                     verbose=False,
                                     use_cache=True)

        # Test the mesh instance
        self.assertTrue(len(m.regions) == 3, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs) == 12, 'FAILED!')
        self.assertTrue(len(m.userVertices) == 12, 'FAILED!')
        self.assertTrue(segs[0].tag == 'walls', 'FAILED!')
        self.assertTrue(segs[1].tag == 'walls', 'FAILED!')
        self.assertTrue(segs[2].tag == 'bom', 'FAILED!')
        self.assertTrue(segs[3].tag == 'bom', 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[0]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              polygon_absolute,
                              closed=False), 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[1]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              inner1_polygon_absolute,
                              closed=False), 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[2]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(
            is_inside_polygon([poly_point.x + x, poly_point.y + y],
                              inner2_polygon_absolute,
                              closed=False), 'FAILED!')

        # Now create m using cached values
        m_cache = create_mesh_from_regions(polygon,
                                           boundary_tags,
                                           10000000,
                                           interior_regions=interior_regions,
                                           poly_geo_reference=geo_ref_poly,
                                           mesh_geo_reference=mesh_geo,
                                           verbose=False,
                                           use_cache=True)
예제 #13
0
def create_mesh_from_regions(bounding_polygon,
                             boundary_tags,
                             maximum_triangle_area=None,
                             filename=None,
                             interior_regions=None,
                             interior_holes=None,
                             hole_tags=None,
                             poly_geo_reference=None,
                             mesh_geo_reference=None,
                             minimum_triangle_angle=28.0,
                             fail_if_polygons_outside=True,
                             breaklines=None,
                             use_cache=False,
                             verbose=True,
                             regionPtArea=None):
    """Create mesh from bounding polygons, and resolutions.

    bounding_polygon is a list of points in Eastings and Northings,
    relative to the poly_geo_reference.

    Boundary tags is a dictionary of symbolic tags. For every tag there
    is a list of indices referring to segments associated with that tag.
    If a segment is omitted an Exception will be raised.

    maximum_triangle_area is the maximal area per triangle
    for the bounding polygon, excluding the  interior regions.

    Interior_regions is a list of tuples consisting of (polygon,
    resolution) for each region to be separately refined. Do not have
    polygon lines cross or be on-top of each other.  Also do not have
    polygon close to each other.
    
    NOTE: If a interior_region is outside the bounding_polygon it should 
    throw an error
    
    Interior_holes is a list of polygons for each hole.
    hole_tags is an optional list of boundary tags for the holes, see
                boundary_tags parameter.

    This function does not allow segments to share points - use underlying
    pmesh functionality for that

    poly_geo_reference is the geo_reference of the bounding polygon and
    the interior polygons.
    If none, assume absolute.  Please pass one though, since absolute
    references have a zone.
    
    mesh_geo_reference is the geo_reference of the mesh to be created.
    If none is given one will be automatically generated.  It was use
    the lower left hand corner of  bounding_polygon (absolute)
    as the x and y values for the geo_ref.

    breaklines is a list of polygons. These lines will be preserved by the
               triangulation algorithm - useful for coastlines, walls, etc.
               The polygons are not closed.			   
    
    Returns the mesh instance if no filename is given

    Note, interior regions should be fully nested, as overlaps may cause
    unintended resolutions. 

    fail_if_polygons_outside: If True (the default) Exception in thrown
    where interior polygons fall outside bounding polygon. If False, these
    will be ignored and execution continued.
        
    
    """
    
    
    if verbose: log.resource_usage_timing(log.logging.INFO, "start_")
    if verbose: log.timingInfo("maximum_triangle_area, " + str(maximum_triangle_area))
    if verbose: log.timingInfo("minimum_triangle_angle, " + str(minimum_triangle_angle))
    if verbose: log.timingInfo("startMesh, '%s'" % log.CurrentDateTime())
    
    # Build arguments and keyword arguments for use with caching or apply.
    args = (bounding_polygon,
            boundary_tags)
    
    kwargs = {'maximum_triangle_area': maximum_triangle_area,
              'filename': filename,
              'interior_regions': interior_regions,
              'interior_holes': interior_holes,
              'hole_tags': hole_tags,
              'poly_geo_reference': poly_geo_reference,
              'mesh_geo_reference': mesh_geo_reference,
              'minimum_triangle_angle': minimum_triangle_angle,
              'fail_if_polygons_outside': fail_if_polygons_outside,
              'breaklines': breaklines,
              'verbose': verbose,
              'regionPtArea': regionPtArea}   # FIXME (Ole): Should be bypassed one day. See ticket:14

    # Call underlying engine with or without caching
    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module'+\
                  'could not be imported'
            raise Exception(msg)


        m = cache(_create_mesh_from_regions,
                  args, kwargs,
                  verbose=verbose,
                  compression=False)
    else:
        m = apply(_create_mesh_from_regions,
                  args, kwargs)


    
    return m    
예제 #14
0
def create_mesh_from_regions(bounding_polygon,
                             boundary_tags,
                             maximum_triangle_area=None,
                             filename=None,
                             interior_regions=None,
                             interior_holes=None,
                             hole_tags=None,
                             poly_geo_reference=None,
                             mesh_geo_reference=None,
                             minimum_triangle_angle=28.0,
                             fail_if_polygons_outside=True,
                             breaklines=None,
                             use_cache=False,
                             verbose=True,
                             regionPtArea=None):
    """Create mesh from bounding polygons, and resolutions.

    bounding_polygon is a list of points in Eastings and Northings,
    relative to the poly_geo_reference.

    Boundary tags is a dictionary of symbolic tags. For every tag there
    is a list of indices referring to segments associated with that tag.
    If a segment is omitted an Exception will be raised.

    maximum_triangle_area is the maximal area per triangle
    for the bounding polygon, excluding the  interior regions.

    Interior_regions is a list of tuples consisting of (polygon,
    resolution) for each region to be separately refined. Do not have
    polygon lines cross or be on-top of each other.  Also do not have
    polygon close to each other.
    
    NOTE: If a interior_region is outside the bounding_polygon it should 
    throw an error
    
    Interior_holes is a list of polygons for each hole.
    hole_tags is an optional list of boundary tags for the holes, see
                boundary_tags parameter.

    This function does not allow segments to share points - use underlying
    pmesh functionality for that

    poly_geo_reference is the geo_reference of the bounding polygon and
    the interior polygons.
    If none, assume absolute.  Please pass one though, since absolute
    references have a zone.
    
    mesh_geo_reference is the geo_reference of the mesh to be created.
    If none is given one will be automatically generated.  It was use
    the lower left hand corner of  bounding_polygon (absolute)
    as the x and y values for the geo_ref.

    breaklines is a list of polygons. These lines will be preserved by the
               triangulation algorithm - useful for coastlines, walls, etc.
               The polygons are not closed.			   
    
    Returns the mesh instance if no filename is given

    Note, interior regions should be fully nested, as overlaps may cause
    unintended resolutions. 

    fail_if_polygons_outside: If True (the default) Exception in thrown
    where interior polygons fall outside bounding polygon. If False, these
    will be ignored and execution continued.
        
    
    """

    if verbose: log.resource_usage_timing(log.logging.INFO, "start_")
    if verbose:
        log.timingInfo("maximum_triangle_area, " + str(maximum_triangle_area))
    if verbose:
        log.timingInfo("minimum_triangle_angle, " +
                       str(minimum_triangle_angle))
    if verbose: log.timingInfo("startMesh, '%s'" % log.CurrentDateTime())

    # Build arguments and keyword arguments for use with caching or apply.
    args = (bounding_polygon, boundary_tags)

    kwargs = {
        'maximum_triangle_area': maximum_triangle_area,
        'filename': filename,
        'interior_regions': interior_regions,
        'interior_holes': interior_holes,
        'hole_tags': hole_tags,
        'poly_geo_reference': poly_geo_reference,
        'mesh_geo_reference': mesh_geo_reference,
        'minimum_triangle_angle': minimum_triangle_angle,
        'fail_if_polygons_outside': fail_if_polygons_outside,
        'breaklines': breaklines,
        'verbose': verbose,
        'regionPtArea': regionPtArea
    }  # FIXME (Ole): Should be bypassed one day. See ticket:14

    # Call underlying engine with or without caching
    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module'+\
                  'could not be imported'
            raise Exception(msg)

        m = cache(_create_mesh_from_regions,
                  args,
                  kwargs,
                  verbose=verbose,
                  compression=False)
    else:
        m = apply(_create_mesh_from_regions, args, kwargs)

    return m
예제 #15
0
def create_domain_from_regions(bounding_polygon,
                               boundary_tags,
                               maximum_triangle_area=None,
                               mesh_filename=None,
                               interior_regions=None,
                               interior_holes=None,
                               hole_tags=None,
                               poly_geo_reference=None,
                               mesh_geo_reference=None,
                               breaklines=None,
                               regionPtArea=None,
                               minimum_triangle_angle=28.0,
                               fail_if_polygons_outside=True,
                               use_cache=False,
                               verbose=False):
    """Create domain from bounding polygons and resolutions.

    bounding_polygon is a list of points in Eastings and Northings,
    relative to the zone stated in poly_geo_reference if specified.
    Otherwise points are just x, y coordinates with no particular 
    association to any location.

    boundary_tags is a dictionary of symbolic tags. For every tag there
    is a list of indices referring to segments associated with that tag.
    If a segment is omitted it will be assigned the default tag ''.

    maximum_triangle_area is the maximal area per triangle
    for the bounding polygon, excluding the  interior regions.

    Interior_regions is a list of tuples consisting of (polygon,
    resolution) for each region to be separately refined. Do not have
    polygon lines cross or be on-top of each other.  Also do not have
    polygon close to each other.
    
    NOTE: If a interior_region is outside the bounding_polygon it should 
    throw an error
    
    interior_holes is a list of polygons for each hole. These polygons do not
    need to be closed, but their points must be specified in a counter-clockwise
    order.

    hole_tags  is a list of tag segment dictionaries.

    This function does not allow segments to share points - use underlying
    pmesh functionality for that

    poly_geo_reference is the geo_reference of the bounding polygon and
    the interior polygons.
    If none, assume absolute.  Please pass one though, since absolute
    references have a zone.
    
    mesh_geo_reference is the geo_reference of the mesh to be created.
    If none is given one will be automatically generated.  It was use
    the lower left hand corner of  bounding_polygon (absolute)
    as the x and y values for the geo_ref.
    
    breaklines is a list of polygons. These lines will be preserved by the
               triangulation algorithm - useful for coastlines, walls, etc.
               The polygons are not closed.    
               
    regionPtArea is a list of user-specified point-based regions with max area  
    
    Returns the shallow water domain instance

    Note, interior regions should be fully nested, as overlaps may cause
    unintended resolutions. 

    fail_if_polygons_outside: If True (the default) Exception in thrown
    where interior polygons fall outside bounding polygon. If False, these
    will be ignored and execution continued.
        
    
    """

    # Build arguments and keyword arguments for use with caching or apply.
    args = (bounding_polygon, boundary_tags)

    if mesh_filename is None:
        import tempfile
        import time
        mesh_filename = 'mesh_%d.msh' % int(time.time())

    kwargs = {
        'maximum_triangle_area': maximum_triangle_area,
        'mesh_filename': mesh_filename,
        'interior_regions': interior_regions,
        'interior_holes': interior_holes,
        'hole_tags': hole_tags,
        'poly_geo_reference': poly_geo_reference,
        'mesh_geo_reference': mesh_geo_reference,
        'breaklines': breaklines,
        'regionPtArea': regionPtArea,
        'minimum_triangle_angle': minimum_triangle_angle,
        'fail_if_polygons_outside': fail_if_polygons_outside,
        'verbose': verbose
    }  #FIXME (Ole): See ticket:14

    # Call underlying engine with or without caching
    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module'+\
                  'could not be imported'
            raise (msg)

        domain = cache(_create_domain_from_regions,
                       args,
                       kwargs,
                       verbose=verbose,
                       compression=False)
    else:
        domain = apply(_create_domain_from_regions, args, kwargs)

    return domain
from anuga.fit_interpolate.fit import _fit_to_mesh
import project
import numpy as num
import time

internal_verbose = True # Verbosity used within this function

filename=project.bathymetry_filename
alpha=0.02
from anuga.config import points_file_block_line_size as max_read_lines

#-------------------------
# Create Domain from mesh
#-------------------------
domain = cache(Domain, 
               (project.mesh_filename, 
                {'verbose': True}), 
               verbose=False)

# Clear caching of underlying function                                            
args = (filename, )
kwargs = {'vertex_coordinates': None,
          'triangles': None,
          'mesh': domain.mesh,
          'point_attributes': None,
          'alpha': alpha,
          'verbose': internal_verbose,
          'mesh_origin': None,
          'data_origin': None,
          'max_read_lines': max_read_lines,
          'attribute_name': None 
          }
예제 #17
0
def create_domain_from_regions(bounding_polygon,
                               boundary_tags,
                               maximum_triangle_area=None,
                               mesh_filename=None,
                               interior_regions=None,
                               interior_holes=None,
                               hole_tags=None,
                               poly_geo_reference=None,
                               mesh_geo_reference=None,
                               breaklines=None,
                               regionPtArea=None,
                               minimum_triangle_angle=28.0,
                               fail_if_polygons_outside=True,
                               use_cache=False,
                               verbose=False):
    

    """Create domain from bounding polygons and resolutions.

    bounding_polygon is a list of points in Eastings and Northings,
    relative to the zone stated in poly_geo_reference if specified.
    Otherwise points are just x, y coordinates with no particular 
    association to any location.

    boundary_tags is a dictionary of symbolic tags. For every tag there
    is a list of indices referring to segments associated with that tag.
    If a segment is omitted it will be assigned the default tag ''.

    maximum_triangle_area is the maximal area per triangle
    for the bounding polygon, excluding the  interior regions.

    Interior_regions is a list of tuples consisting of (polygon,
    resolution) for each region to be separately refined. Do not have
    polygon lines cross or be on-top of each other.  Also do not have
    polygon close to each other.
    
    NOTE: If a interior_region is outside the bounding_polygon it should 
    throw an error
    
    interior_holes is a list of polygons for each hole. These polygons do not
    need to be closed, but their points must be specified in a counter-clockwise
    order.

    hole_tags  is a list of tag segment dictionaries.

    This function does not allow segments to share points - use underlying
    pmesh functionality for that

    poly_geo_reference is the geo_reference of the bounding polygon and
    the interior polygons.
    If none, assume absolute.  Please pass one though, since absolute
    references have a zone.
    
    mesh_geo_reference is the geo_reference of the mesh to be created.
    If none is given one will be automatically generated.  It was use
    the lower left hand corner of  bounding_polygon (absolute)
    as the x and y values for the geo_ref.
    
    breaklines is a list of polygons. These lines will be preserved by the
               triangulation algorithm - useful for coastlines, walls, etc.
               The polygons are not closed.    
               
    regionPtArea is a list of user-specified point-based regions with max area  
    
    Returns the shallow water domain instance

    Note, interior regions should be fully nested, as overlaps may cause
    unintended resolutions. 

    fail_if_polygons_outside: If True (the default) Exception in thrown
    where interior polygons fall outside bounding polygon. If False, these
    will be ignored and execution continued.
        
    
    """


    # Build arguments and keyword arguments for use with caching or apply.
    args = (bounding_polygon,
            boundary_tags)
    
    if mesh_filename is None:
        import tempfile
        import time
        mesh_filename = 'mesh_%d.msh'%int(time.time())
    
    kwargs = {'maximum_triangle_area': maximum_triangle_area,
              'mesh_filename': mesh_filename,
              'interior_regions': interior_regions,
              'interior_holes': interior_holes,
              'hole_tags': hole_tags,
              'poly_geo_reference': poly_geo_reference,
              'mesh_geo_reference': mesh_geo_reference,
              'breaklines' : breaklines,
              'regionPtArea' : regionPtArea,
              'minimum_triangle_angle': minimum_triangle_angle,
              'fail_if_polygons_outside': fail_if_polygons_outside,
              'verbose': verbose} #FIXME (Ole): See ticket:14

    # Call underlying engine with or without caching
    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module'+\
                  'could not be imported'
            raise (msg)


        domain = cache(_create_domain_from_regions,
                       args, kwargs,
                       verbose=verbose,
                       compression=False)
    else:
        domain = apply(_create_domain_from_regions,
                       args, kwargs)

    return domain
예제 #18
0
def file_function(filename,
                  domain=None,
                  quantities=None,
                  interpolation_points=None,
                  time_thinning=1,
                  time_limit=None,
                  verbose=False,
                  use_cache=False,
                  boundary_polygon=None,
                  output_centroids=False):
    """Read time history of spatial data from NetCDF file and return
    a callable object.

    Input variables:
    
    filename - Name of sww, tms or sts file
       
       If the file has extension 'sww' then it is assumed to be spatio-temporal
       or temporal and the callable object will have the form f(t,x,y) or f(t)
       depending on whether the file contains spatial data

       If the file has extension 'tms' then it is assumed to be temporal only
       and the callable object will have the form f(t)

       Either form will return interpolated values based on the input file
       using the underlying interpolation_function.

    domain - Associated domain object   
       If domain is specified, model time (domain.starttime)
       will be checked and possibly modified.
    
       All times are assumed to be in UTC
       
       All spatial information is assumed to be in absolute UTM coordinates.

    quantities - the name of the quantity to be interpolated or a
                 list of quantity names. The resulting function will return
                 a tuple of values - one for each quantity
                 If quantities are None, the default quantities are
                 ['stage', 'xmomentum', 'ymomentum']
                 

    interpolation_points - list of absolute UTM coordinates for points (N x 2)
    or geospatial object or points file name at which values are sought

    time_thinning - 

    verbose - 

    use_cache: True means that caching of intermediate result of
               Interpolation_function is attempted

    boundary_polygon - 

    
    See Interpolation function in anuga.fit_interpolate.interpolation for
    further documentation
    """

    # FIXME (OLE): Should check origin of domain against that of file
    # In fact, this is where origin should be converted to that of domain
    # Also, check that file covers domain fully.

    # Take into account:
    # - domain's georef
    # - sww file's georef
    # - interpolation points as absolute UTM coordinates

    if quantities is None:
        if verbose:
            msg = 'Quantities specified in file_function are None,'
            msg += ' so using stage, xmomentum, and ymomentum in that order'
            log.critical(msg)
        quantities = ['stage', 'xmomentum', 'ymomentum']

    # Use domain's startime if available
    if domain is not None:
        domain_starttime = domain.get_starttime()
    else:
        domain_starttime = None

    # Build arguments and keyword arguments for use with caching or apply.
    args = (filename, )

    # FIXME (Ole): Caching this function will not work well
    # if domain is passed in as instances change hash code.
    # Instead we pass in those attributes that are needed (and return them
    # if modified)
    kwargs = {
        'quantities': quantities,
        'interpolation_points': interpolation_points,
        'domain_starttime': domain_starttime,
        'time_thinning': time_thinning,
        'time_limit': time_limit,
        'verbose': verbose,
        'boundary_polygon': boundary_polygon,
        'output_centroids': output_centroids
    }

    # Call underlying engine with or without caching
    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module'+\
                  'could not be imported'
            raise Exception(msg)

        f, starttime = cache(_file_function,
                             args,
                             kwargs,
                             dependencies=[filename],
                             compression=False,
                             verbose=verbose)
    else:
        f, starttime = apply(_file_function, args, kwargs)

    #FIXME (Ole): Pass cache arguments, such as compression, in some sort of
    #structure

    f.starttime = starttime
    f.filename = filename

    if domain is not None:
        #Update domain.startime if it is *earlier* than starttime from file
        if starttime > domain.starttime:
            msg = 'WARNING: Start time as specified in domain (%f)' \
                  % domain.starttime
            msg += ' is earlier than the starttime of file %s (%f).' \
                     % (filename, starttime)
            msg += ' Modifying domain starttime accordingly.'

            if verbose: log.critical(msg)

            domain.set_starttime(starttime)  #Modifying model time

            if verbose:
                log.critical('Domain starttime is now set to %f' %
                             domain.starttime)
    return f
def file_function(filename,
                  domain=None,
                  quantities=None,
                  interpolation_points=None,
                  time_thinning=1,
                  time_limit=None,
                  verbose=False,
                  use_cache=False,
                  boundary_polygon=None,
                  output_centroids=False):
    """Read time history of spatial data from NetCDF file and return
    a callable object.

    Input variables:
    
    filename - Name of sww, tms or sts file
       
       If the file has extension 'sww' then it is assumed to be spatio-temporal
       or temporal and the callable object will have the form f(t,x,y) or f(t)
       depending on whether the file contains spatial data

       If the file has extension 'tms' then it is assumed to be temporal only
       and the callable object will have the form f(t)

       Either form will return interpolated values based on the input file
       using the underlying interpolation_function.

    domain - Associated domain object   
       If domain is specified, model time (domain.starttime)
       will be checked and possibly modified.
    
       All times are assumed to be in UTC
       
       All spatial information is assumed to be in absolute UTM coordinates.

    quantities - the name of the quantity to be interpolated or a
                 list of quantity names. The resulting function will return
                 a tuple of values - one for each quantity
                 If quantities are None, the default quantities are
                 ['stage', 'xmomentum', 'ymomentum']
                 

    interpolation_points - list of absolute UTM coordinates for points (N x 2)
    or geospatial object or points file name at which values are sought

    time_thinning - 

    verbose - 

    use_cache: True means that caching of intermediate result of
               Interpolation_function is attempted

    boundary_polygon - 

    
    See Interpolation function in anuga.fit_interpolate.interpolation for
    further documentation
    """

    # FIXME (OLE): Should check origin of domain against that of file
    # In fact, this is where origin should be converted to that of domain
    # Also, check that file covers domain fully.

    # Take into account:
    # - domain's georef
    # - sww file's georef
    # - interpolation points as absolute UTM coordinates

    if quantities is None:
        if verbose:
            msg = 'Quantities specified in file_function are None,'
            msg += ' so using stage, xmomentum, and ymomentum in that order'
            log.critical(msg)
        quantities = ['stage', 'xmomentum', 'ymomentum']

    # Use domain's startime if available
    if domain is not None:    
        domain_starttime = domain.get_starttime()
    else:
        domain_starttime = None

    # Build arguments and keyword arguments for use with caching or apply.
    args = (filename,)

    # FIXME (Ole): Caching this function will not work well
    # if domain is passed in as instances change hash code.
    # Instead we pass in those attributes that are needed (and return them
    # if modified)
    kwargs = {'quantities': quantities,
              'interpolation_points': interpolation_points,
              'domain_starttime': domain_starttime,
              'time_thinning': time_thinning,      
              'time_limit': time_limit,                                 
              'verbose': verbose,
              'boundary_polygon': boundary_polygon,
              'output_centroids': output_centroids}

    # Call underlying engine with or without caching
    if use_cache is True:
        try:
            from anuga.caching import cache
        except:
            msg = 'Caching was requested, but caching module'+\
                  'could not be imported'
            raise Exception(msg)

        f, starttime = cache(_file_function,
                             args, kwargs,
                             dependencies=[filename],
                             compression=False,                  
                             verbose=verbose)
    else:
        f, starttime = apply(_file_function,
                             args, kwargs)

    #FIXME (Ole): Pass cache arguments, such as compression, in some sort of
    #structure

    f.starttime = starttime
    f.filename = filename
    
    if domain is not None:
        #Update domain.startime if it is *earlier* than starttime from file
        if starttime > domain.starttime:
            msg = 'WARNING: Start time as specified in domain (%f)' \
                  % domain.starttime
            msg += ' is earlier than the starttime of file %s (%f).' \
                     % (filename, starttime)
            msg += ' Modifying domain starttime accordingly.'
            
            if verbose: log.critical(msg)

            domain.set_starttime(starttime) #Modifying model time

            if verbose: log.critical('Domain starttime is now set to %f'
                                     % domain.starttime)
    return f
    def test_create_mesh_from_regions_with_caching(self):
        x=-500
        y=-1000
        mesh_geo = geo_reference=Geo_reference(56, x, y)

        # These are the absolute values
        polygon_absolute = [[0,0], [100,0], [100,100], [0,100]]

        x_p = -10
        y_p = -40
        geo_ref_poly = Geo_reference(56, x_p, y_p)
        polygon = geo_ref_poly.change_points_geo_ref(polygon_absolute)

        boundary_tags = {'walls': [0,1], 'bom': [2,3]}

        inner1_polygon_absolute = [[10,10], [20,10], [20,20], [10,20]]
        inner1_polygon = geo_ref_poly.\
                            change_points_geo_ref(inner1_polygon_absolute)

        inner2_polygon_absolute = [[30,30], [40,30], [40,40], [30,40]]
        inner2_polygon = geo_ref_poly.\
                             change_points_geo_ref(inner2_polygon_absolute)

        interior_regions = [(inner1_polygon, 5), (inner2_polygon, 10)]

        interior_holes = None

        # Clear cache first
        from anuga.caching import cache

        cache(_create_mesh_from_regions,
              (polygon, boundary_tags),
              {'minimum_triangle_angle': 28.0,
               'maximum_triangle_area': 10000000,
               'interior_regions': interior_regions,
               'interior_holes': interior_holes,
               'poly_geo_reference': geo_ref_poly,
               'mesh_geo_reference': mesh_geo,
               'verbose': False},
              verbose=False,
              clear=1)

        m = create_mesh_from_regions(polygon,
                                     boundary_tags,
                                     maximum_triangle_area=10000000,
                                     interior_regions=interior_regions,
                                     poly_geo_reference=geo_ref_poly,
                                     mesh_geo_reference=mesh_geo,
                                     verbose=False,
                                     use_cache=True)


        # Test the mesh instance
        self.assertTrue(len(m.regions)==3, 'FAILED!')
        segs = m.getUserSegments()
        self.assertTrue(len(segs)==12, 'FAILED!')
        self.assertTrue(len(m.userVertices)==12, 'FAILED!')
        self.assertTrue(segs[0].tag=='walls', 'FAILED!')
        self.assertTrue(segs[1].tag=='walls', 'FAILED!')
        self.assertTrue(segs[2].tag=='bom', 'FAILED!')
        self.assertTrue(segs[3].tag=='bom', 'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[0]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          polygon_absolute,
                                          closed=False),
                        'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[1]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          inner1_polygon_absolute,
                                          closed=False),
                        'FAILED!')

        # Assuming the order of the region points is known.
        # (This isn't true, if you consider create_mesh_from_regions
        # a black box)
        poly_point = m.getRegions()[2]

        # poly_point values are relative to the mesh geo-ref
        # make them absolute
        self.assertTrue(is_inside_polygon([poly_point.x+x, poly_point.y+y],
                                          inner2_polygon_absolute,
                                          closed=False),
                        'FAILED!')

        # Now create m using cached values
        m_cache = create_mesh_from_regions(polygon,
                                           boundary_tags,
                                           10000000,
                                           interior_regions=interior_regions,
                                           poly_geo_reference=geo_ref_poly,
                                           mesh_geo_reference=mesh_geo,
                                           verbose=False,
                                           use_cache=True)
예제 #21
0
from anuga.fit_interpolate.fit import _fit_to_mesh
import project
import numpy as num
import time

internal_verbose = True  # Verbosity used within this function

filename = project.bathymetry_filename
alpha = 0.02
from anuga.config import points_file_block_line_size as max_read_lines

#-------------------------
# Create Domain from mesh
#-------------------------
domain = cache(Domain, (project.mesh_filename, {
    'verbose': True
}),
               verbose=False)

# Clear caching of underlying function
args = (filename, )
kwargs = {
    'vertex_coordinates': None,
    'triangles': None,
    'mesh': domain.mesh,
    'point_attributes': None,
    'alpha': alpha,
    'verbose': internal_verbose,
    'mesh_origin': None,
    'data_origin': None,
    'max_read_lines': max_read_lines,
    'attribute_name': None