Пример #1
0
 def as_polygon(self):
     return Polygon([
         Point(self['xmin'], self['ymax']),
         Point(self['xmax'], self['ymax']),
         Point(self['xmax'], self['ymin']),
         Point(self['xmin'], self['ymin'])
     ])
Пример #2
0
    def create_geometry(self, input_geometry, upper_depth, lower_depth):
        '''
        If geometry is defined as a numpy array then create instance of
        nhlib.geo.polygon.Polygon class, otherwise if already instance of class
        accept class

        :param input_geometry:
            Input geometry (polygon) as either
            i) instance of nhlib.geo.polygon.Polygon class
            ii) numpy.ndarray [Longitude, Latitude]

        :param float upper_depth:
            Upper seismogenic depth (km)

        :param float lower_depth:
            Lower seismogenic depth (km)
        '''
        self._check_seismogenic_depths(upper_depth, lower_depth)

        # Check/create the geometry class
        if not isinstance(input_geometry, Polygon):
            if not isinstance(input_geometry, np.ndarray):
                raise ValueError('Unrecognised or unsupported geometry '
                                 'definition')

            if np.shape(input_geometry)[0] < 3:
                raise ValueError('Incorrectly formatted polygon geometry -'
                                 ' needs three or more vertices')
            geometry = []
            for row in input_geometry:
                geometry.append(Point(row[0], row[1], self.upper_depth))
            self.geometry = Polygon(geometry)
        else:
            self.geometry = input_geometry
Пример #3
0
    def test_select_within_polygon(self):
        # Tests the selection of points within polygon

        # Setup polygon
        nodes = np.array([[5.0, 6.0], [6.0, 6.0], [6.0, 5.0], [5.0, 5.0]])
        polygon0 = Polygon([Point(nodes[iloc, 0], nodes[iloc, 1])
                            for iloc in range(0, 4)])
        self.catalogue.data['longitude'] = np.arange(4.0, 7.5, 0.5)
        self.catalogue.data['latitude'] = np.arange(4.0, 7.5, 0.5)
        self.catalogue.data['depth'] = np.ones(7, dtype=float)
        # Simple case with nodes inside, outside and on the border of polygon
        selector0 = CatalogueSelector(self.catalogue)
        test_cat1 = selector0.within_polygon(polygon0)
        self.assertTrue(np.allclose(test_cat1.data['longitude'],
                                    np.array([5.0, 5.5, 6.0])))
        self.assertTrue(np.allclose(test_cat1.data['latitude'],
                                    np.array([5.0, 5.5, 6.0])))
        self.assertTrue(np.allclose(test_cat1.data['depth'],
                                    np.array([1.0, 1.0, 1.0])))
        # CASE 2: As case 1 with one of the inside nodes outside of the depths
        self.catalogue.data['depth'] = \
            np.array([1.0, 1.0, 1.0, 50.0, 1.0, 1.0, 1.0], dtype=float)
        selector0 = CatalogueSelector(self.catalogue)
        test_cat1 = selector0.within_polygon(polygon0, upper_depth=0.0,
                                             lower_depth=10.0)
        self.assertTrue(np.allclose(test_cat1.data['longitude'],
                                    np.array([5.0, 6.0])))
        self.assertTrue(np.allclose(test_cat1.data['latitude'],
                                    np.array([5.0, 6.0])))
        self.assertTrue(np.allclose(test_cat1.data['depth'],
                                    np.array([1.0])))
Пример #4
0
def node_to_area_geometry(node):
    """
    Reads an area geometry node and returns the polygon, upper depth and lower
    depth
    """
    assert "areaGeometry" in node.tag
    for subnode in node.nodes:
        if "Polygon" in subnode.tag:
            crds = [
                float(x)
                for x in subnode.nodes[0].nodes[0].nodes[0].text.split()
            ]
            polygon = Polygon([
                Point(crds[iloc], crds[iloc + 1])
                for iloc in range(0, len(crds), 2)
            ])
        elif "upperSeismoDepth" in subnode.tag:
            upper_depth = float_(subnode.text)
        elif "lowerSeismoDepth" in subnode.tag:
            lower_depth = float_(subnode.text)
        else:
            # Redundent
            pass
    assert lower_depth > upper_depth
    return polygon, upper_depth, lower_depth
Пример #5
0
def areas_to_oqt_sources(shapefile_filename):
    """
    :parameter str shapefile_filename:
        Name of the shapefile containing the polygons
    :parameter Boolean log:
        Flag controlling information while processing
    :returns:
        A list of :class:`openquake.mbt.oqt_project.OQtSource` istances
    """
    idname = 'Id'
    # Set the driver
    driver = ogr.GetDriverByName('ESRI Shapefile')
    datasource = driver.Open(shapefile_filename, 0)
    layer = datasource.GetLayer()
    # Reading sources geometry
    sources = {}
    id_set = set()
    for feature in layer:
        # Read the geometry
        geom = feature.GetGeometryRef()
        polygon = wkt.loads(geom.ExportToWkt())
        x, y = polygon.exterior.coords.xy
        points = _get_point_list(x, y)
        # Set the ID
        if isinstance(feature.GetField(idname), str):
            id_str = feature.GetField(idname)
        elif isinstance(feature.GetField(idname), int):
            id_str = '%d' % (feature.GetField(idname))
        else:
            raise ValueError('Unsupported source ID type')
        # Set tectonic region
        trt = _set_trt(feature.GetField('TectonicRe'))
        # Set lower seismogenic depth
        lsd = float(feature.GetField('Depth'))
        # Set coupling coefficient
        coupc = float(feature.GetField('coup_coef'))
        # Set coupling coefficient
        coupt = float(feature.GetField('coup_thick'))
        # Create the source
        src = OQtSource(
            source_id=id_str,
            source_type='AreaSource',
            polygon=Polygon(points),
            name=id_str,
            lower_seismogenic_depth=lsd,
            tectonic_region_type=trt,
        )
        src.coup_coef = coupc
        src.coup_thick = coupt
        # Append the new source
        if not id_set and set(id_str):
            sources[id_str] = src
        else:
            raise ValueError('Sources with non unique ID %s' % id_str)

    datasource.Destroy()
    return sources
Пример #6
0
def get_catalogue_bounding_polygon(catalogue):
    '''
    Returns a polygon containing the bounding box of the catalogue
    '''
    upper_lon = np.max(catalogue.data['longitude'])
    upper_lat = np.max(catalogue.data['latitude'])
    lower_lon = np.min(catalogue.data['longitude'])
    lower_lat = np.min(catalogue.data['latitude'])

    return Polygon([Point(lower_lon, upper_lat), Point(upper_lon, upper_lat),
                    Point(upper_lon, lower_lat), Point(lower_lon, lower_lat)])
Пример #7
0
def setUpMesh(lons, lats):
    # make the mesh
    points = []
    for lon, lat in zip(lons, lats):
        points.append(Point(lon, lat))

    newpoly = Polygon(points)
    # must use a fine mesh spacing to preserve symmetry (because
    # of auto-generated mesh coordinates)
    new_polygon_mesh = newpoly.discretize(2)

    return new_polygon_mesh
Пример #8
0
 def test_fault_source_outside_depth_range(self):
     """
     Tests the rates when the whole fault is inside the polygon
     """
     self.limits = {"polygon": Polygon([Point(14.9, 14.9),
                                        Point(14.9, 15.1),
                                        Point(15.1, 15.1),
                                        Point(15.1, 14.9)]),
                    "upper_depth": 21.0,
                    "lower_depth": 25.0}
     model1 = RatePolygon(self.limits, [SIMPLE_FAULT],
                          area_discretisation=4.0)
     model1.get_rates(7.0)
     self.assertAlmostEqual(model1.rates, 0.0)
Пример #9
0
 def test_point_source_outside_mag_limit(self):
     """
     Tests the case of a single point source outside the polygon
     """
     self.limits = {"polygon": Polygon([Point(14.9, 14.9),
                                        Point(14.9, 15.1),
                                        Point(15.1, 15.1),
                                        Point(15.1, 14.9)]),
                    "upper_depth": 0.0,
                    "lower_depth": 3.0}
     model1 = RatePolygon(self.limits, [POINT_SOURCE],
                          area_discretisation=4.0)
     model1.get_rates(5.5, 6.0)
     self.assertAlmostEqual(model1.rates, 0.0)
Пример #10
0
 def test_instantiation(self):
     """
     Tests simple instantiation of the class
     """
     self.limits = {"polygon": Polygon([Point(14.9, 14.9),
                                        Point(14.9, 15.1),
                                        Point(15.1, 15.1),
                                        Point(15.1, 14.9)]),
                    "upper_depth": 0.0,
                    "lower_depth": 10.0}
     model1 = RatePolygon(self.limits, [POINT_SOURCE],
                          area_discretisation=4.0)
     self.assertAlmostEqual(model1.upper_depth, 0.0)
     self.assertAlmostEqual(model1.lower_depth, 10.0)
     self.assertAlmostEqual(model1.rates, 0.0)
Пример #11
0
    def _parse_area(cls, src_elem):
        """
        :param src_elem:
        :class:`lxml.etree._Element` instance representing a source.
        :returns:
            Fully populated :class:`openquake.nrmllib.models.AreaSource`
            object.
        """
        # Instantiate with identifier and name
        area = mtkAreaSource(src_elem.get('id'), src_elem.get('name'))
        print 'Area source - ID: %s, name: %s' % (area.id, area.name)

        # Set common attributes
        cls._set_common_attrs(area, src_elem)

        # Get geometry
        [gml_pos_list] = _xpath(src_elem, './/gml:posList')
        coords = gml_pos_list.text.split()
        input_polygon = Polygon([
            Point(float(coords[iloc]), float(coords[iloc + 1]))
            for iloc in range(0, len(coords), 2)
        ])

        # Area source polygon geometries are always 2-dimensional and on the
        # Earth's surface (depth == 0.0).
        if _xpath(src_elem, './/nrml:upperSeismoDepth')[0].text:
            upper_seismo_depth = float(
                _xpath(src_elem, './/nrml:upperSeismoDepth')[0].text)
        else:
            upper_seismo_depth = None

        if _xpath(src_elem, './/nrml:lowerSeismoDepth')[0].text:
            lower_seismo_depth = float(
                _xpath(src_elem, './/nrml:lowerSeismoDepth')[0].text)
        else:
            lower_seismo_depth = None

        area.create_geometry(input_polygon, upper_seismo_depth,
                             lower_seismo_depth)

        area.mfd = cls._parse_mfd(src_elem)
        area.nodal_plane_dist = cls._parse_nodal_plane_dist(src_elem)
        area.hypo_depth_dist = cls._parse_hypo_depth_dist(src_elem)

        return area
Пример #12
0
def load_geometry_from_shapefile(shapefile_filename):
    """
    :parameter str shapefile_filename:
        Name of the shapefile containing the polygons
    :parameter Boolean log:
        Flag controlling information while processing
    :returns:
        A list of :class:`openquake.mbt.oqt_project.OQtSource` istances
    """
    idname = 'Id'
    # Set the driver
    driver = ogr.GetDriverByName('ESRI Shapefile')
    datasource = driver.Open(shapefile_filename, 0)
    layer = datasource.GetLayer()
    # Reading sources geometry
    sources = {}
    id_set = set()
    for feature in layer:
        #
        # Read the geometry
        geom = feature.GetGeometryRef()
        polygon = wkt.loads(geom.ExportToWkt())
        x, y = polygon.exterior.coords.xy
        points = _get_point_list(x, y)
        #
        # Set the ID
        if isinstance(feature.GetField(idname), str):
            id_str = feature.GetField(idname)
        elif isinstance(feature.GetField(idname), int):
            id_str = '%d' % (feature.GetField(idname))
        else:
            raise ValueError('Unsupported source ID type')
        src = OQtSource(
            source_id=id_str,
            source_type='AreaSource',
            polygon=Polygon(points),
            name=id_str,
        )
        # Append the new source
        if not id_set and set(id_str):
            sources[id_str] = src
        else:
            raise ValueError('Sources with non unique ID %s' % id_str)
    return sources
Пример #13
0
    def _get_limits_maximum_rjb(self, maximum_distance):
        """
        Returns the bounding box of a polyon representing the locations of
        maximum distance from the rupture
        """
        top_left = deepcopy(self.surface.top_left)
        top_left.depth = 0.

        top_right = deepcopy(self.surface.top_right)
        top_right.depth = 0.

        bottom_left = deepcopy(self.surface.bottom_left)
        bottom_left.depth = 0.

        bottom_right = deepcopy(self.surface.bottom_right)
        bottom_right.depth = 0.

        surface_projection = Polygon(
            [top_left, top_right, bottom_right, bottom_left])
        dilated_projection = surface_projection.dilate(maximum_distance)
        return (np.min(dilated_projection.lons), np.max(
            dilated_projection.lons), np.min(dilated_projection.lats),
                np.max(dilated_projection.lats))
Пример #14
0
OUTSIDE_POINT_SOURCE = PointSource(
    "PNT000", "Point 000",
    "Active Shallow Crust",
    EvenlyDiscretizedMFD(5.0, 0.1, [1.0]),
    1.0,
    PointMSR(),
    1.0,
    PoissonTOM(1.0),
    0.0,
    20.0,
    Point(15.0, 15.2),
    PMF([(1.0, NodalPlane(0.0, 90.0, 0.0))]),
    PMF([(1.0, 5.0)]))

AREA_POLY = Polygon([Point(14.95, 15.05),
                     Point(15.05, 15.05),
                     Point(15.05, 14.95),
                     Point(14.95, 14.95)])

AREA_SOURCE = AreaSource("AREA000", "Area 000",
                         "Active Shallow Crust",
                         EvenlyDiscretizedMFD(5.0, 0.1, [1.0]),
                         1.0,
                         PointMSR(),
                         1.0,
                         PoissonTOM(1.0),
                         0.,
                         40.,
                         PMF([(1.0, NodalPlane(0.0, 90.0, 0.0))]),
                         PMF([(0.5, 5.0), (0.5, 15.0)]),
                         AREA_POLY,
                         4.0)