Ejemplo n.º 1
0
    def test_geometry_inputs(self):
        '''
        Tests the geometry definition
        '''
        simple_polygon = polygon.Polygon([point.Point(2.0, 3.0), 
                                          point.Point(3.0, 3.0), 
                                          point.Point(3.0, 2.0),
                                          point.Point(2.0, 2.0)])

        simple_polygon_array = np.array([[2.0, 3.0], 
                                         [3.0, 3.0], 
                                         [3.0, 2.0],
                                         [ 2.0, 2.0]])
        # Using nhlib.geo.polygon.Polygon class as input
        self.area_source.create_geometry(simple_polygon, 0.0, 30.0)
        # Check that geometry is an instance of nhlib.geo.polygon.Polygon
        self.assertTrue(isinstance(self.area_source.geometry, 
                                   polygon.Polygon))

        np.testing.assert_array_almost_equal(self.area_source.geometry.lons,
                                             np.array([2., 3., 3., 2.]))
        np.testing.assert_array_almost_equal(self.area_source.geometry.lats,
                                             np.array([3., 3., 2., 2.]))
        self.assertAlmostEqual(0.0, self.area_source.upper_depth)
        self.assertAlmostEqual(30.0, self.area_source.lower_depth)

        self.area_source = mtkAreaSource('101', 'A Source')
        # Using numpy array as input
        self.area_source.create_geometry(simple_polygon_array, 0.0, 30.0)
        self.assertTrue(isinstance(self.area_source.geometry, 
                                   polygon.Polygon))

        # Check that geometry is an instance of nhlib.geo.polygon.Polygon
        np.testing.assert_array_almost_equal(self.area_source.geometry.lons,
                                             np.array([2., 3., 3., 2.]))
        np.testing.assert_array_almost_equal(self.area_source.geometry.lats,
                                             np.array([3., 3., 2., 2.]))

        self.assertAlmostEqual(0.0, self.area_source.upper_depth)
        self.assertAlmostEqual(30.0, self.area_source.lower_depth)

        # For any other input type - check ValueError is raised
        self.area_source = mtkAreaSource('101', 'A Source')
        with self.assertRaises(ValueError) as ver:
            self.area_source.create_geometry('a bad input', 0.0, 30.0)
        self.assertEqual(ver.exception.message,
                         'Unrecognised or unsupported geometry definition')

        # For numpy array with only two rows
        self.area_source = mtkAreaSource('101', 'A Source')
        simple_polygon_array = np.array([[2.0, 3.0], 
                                         [3.0, 3.0]])
        with self.assertRaises(ValueError) as ver:
            self.area_source.create_geometry(simple_polygon_array, 0.0, 30.0)
        self.assertEqual(ver.exception.message,
                         'Incorrectly formatted polygon geometry - '
                         'needs three or more vertices')
Ejemplo n.º 2
0
    def test_geometry_inputs(self):
        # Tests the geometry definition
        simple_polygon = polygon.Polygon([point.Point(2.0, 3.0),
                                          point.Point(3.0, 3.0),
                                          point.Point(3.0, 2.0),
                                          point.Point(2.0, 2.0)])

        simple_polygon_array = np.array([[2.0, 3.0],
                                         [3.0, 3.0],
                                         [3.0, 2.0],
                                         [2.0, 2.0]])
        # Using nhlib.geo.polygon.Polygon class as input
        self.area_source.create_geometry(simple_polygon, 0.0, 30.0)
        # Check that geometry is an instance of nhlib.geo.polygon.Polygon
        self.assertTrue(isinstance(self.area_source.geometry,
                                   polygon.Polygon))

        np.testing.assert_array_almost_equal(self.area_source.geometry.lons,
                                             np.array([2., 3., 3., 2.]))
        np.testing.assert_array_almost_equal(self.area_source.geometry.lats,
                                             np.array([3., 3., 2., 2.]))
        self.assertAlmostEqual(0.0, self.area_source.upper_depth)
        self.assertAlmostEqual(30.0, self.area_source.lower_depth)

        self.area_source = mtkAreaSource('101', 'A Source')
        # Using numpy array as input
        self.area_source.create_geometry(simple_polygon_array, 0.0, 30.0)
        self.assertTrue(isinstance(self.area_source.geometry,
                                   polygon.Polygon))

        # Check that geometry is an instance of nhlib.geo.polygon.Polygon
        np.testing.assert_array_almost_equal(self.area_source.geometry.lons,
                                             np.array([2., 3., 3., 2.]))
        np.testing.assert_array_almost_equal(self.area_source.geometry.lats,
                                             np.array([3., 3., 2., 2.]))

        self.assertAlmostEqual(0.0, self.area_source.upper_depth)
        self.assertAlmostEqual(30.0, self.area_source.lower_depth)

        # For any other input type - check ValueError is raised
        self.area_source = mtkAreaSource('101', 'A Source')
        with self.assertRaises(ValueError) as ver:
            self.area_source.create_geometry('a bad input', 0.0, 30.0)
        self.assertEqual(str(ver.exception),
                         'Unrecognised or unsupported geometry definition')

        # For numpy array with only two rows
        self.area_source = mtkAreaSource('101', 'A Source')
        simple_polygon_array = np.array([[2.0, 3.0],
                                         [3.0, 3.0]])
        with self.assertRaises(ValueError) as ver:
            self.area_source.create_geometry(simple_polygon_array, 0.0, 30.0)
        self.assertEqual(str(ver.exception),
                         'Incorrectly formatted polygon geometry - '
                         'needs three or more vertices')
Ejemplo n.º 3
0
 def test_create_oqhazardlib_source(self):
     """
     """
     # Define a complete source
     area_geom = polygon.Polygon([point.Point(10., 10.),
                                  point.Point(12., 10.),
                                  point.Point(12., 8.),
                                  point.Point(10., 8.)])
     mfd1 = TruncatedGRMFD(5.0, 8.0, 0.1, 3.0, 1.0)
     self.area_source = mtkAreaSource('001',
         'A Point Source',
         trt='Active Shallow Crust',
         geometry = area_geom,
         upper_depth = 0.,
         lower_depth = 20.,
         mag_scale_rel=None,
         rupt_aspect_ratio=1.0,
         mfd=mfd1,
         nodal_plane_dist=None,
         hypo_depth_dist=None)
     test_source = self.area_source.create_oqhazardlib_source(TOM, 1.0,
                                                              10.0, True)
     self.assertIsInstance(test_source, AreaSource)
     self.assertIsInstance(test_source.mfd, TruncatedGRMFD)
     self.assertAlmostEqual(test_source.mfd.b_val, 1.0)
     self.assertIsInstance(test_source.nodal_plane_distribution, PMF)
     self.assertIsInstance(test_source.hypocenter_distribution, PMF)
     self.assertIsInstance(test_source.magnitude_scaling_relationship,
                           WC1994)
Ejemplo n.º 4
0
def parse_area_source_node(node, mfd_spacing=0.1):
    """
    Returns an "areaSource" node into an instance of the :class:
    hmtk.sources.area.mtkAreaSource
    """
    assert "areaSource" in node.tag
    area_taglist = get_taglist(node)
    # Get metadata
    area_id, name, trt = (node.attrib["id"],
                          node.attrib["name"],
                          node.attrib["tectonicRegion"])
    assert area_id  # Defensive validation!
    # Process geometry
    polygon, upper_depth, lower_depth = node_to_area_geometry(
        node.nodes[area_taglist.index("areaGeometry")])
    # Process scaling relation
    msr = node_to_scalerel(node.nodes[area_taglist.index("magScaleRel")])
    # Process aspect ratio
    aspect = float_(node.nodes[area_taglist.index("ruptAspectRatio")].text)
    # Process MFD
    mfd = node_to_mfd(node, area_taglist)
    # Process nodal planes
    npds = node_to_nodal_planes(
        node.nodes[area_taglist.index("nodalPlaneDist")])
    # Process hypocentral depths
    hdds = node_to_hdd(node.nodes[area_taglist.index("hypoDepthDist")])
    return mtkAreaSource(area_id, name, trt,
                         geometry=polygon,
                         upper_depth=upper_depth,
                         lower_depth=lower_depth,
                         mag_scale_rel=msr,
                         rupt_aspect_ratio=aspect,
                         mfd=mfd,
                         nodal_plane_dist=npds,
                         hypo_depth_dist=hdds)
Ejemplo n.º 5
0
 def test_create_oqhazardlib_source(self):
     # Define a complete source
     area_geom = polygon.Polygon([point.Point(10., 10.),
                                  point.Point(12., 10.),
                                  point.Point(12., 8.),
                                  point.Point(10., 8.)])
     mfd1 = TruncatedGRMFD(5.0, 8.0, 0.1, 3.0, 1.0)
     self.area_source = mtkAreaSource(
         '001',
         'A Point Source',
         trt='Active Shallow Crust',
         geometry=area_geom,
         upper_depth=0.,
         lower_depth=20.,
         mag_scale_rel=None,
         rupt_aspect_ratio=1.0,
         mfd=mfd1,
         nodal_plane_dist=None,
         hypo_depth_dist=None)
     test_source = self.area_source.create_oqhazardlib_source(TOM, 1.0,
                                                              10.0, True)
     self.assertIsInstance(test_source, AreaSource)
     self.assertIsInstance(test_source.mfd, TruncatedGRMFD)
     self.assertAlmostEqual(test_source.mfd.b_val, 1.0)
     self.assertIsInstance(test_source.nodal_plane_distribution, PMF)
     self.assertIsInstance(test_source.hypocenter_distribution, PMF)
     self.assertIsInstance(test_source.magnitude_scaling_relationship,
                           WC1994)
Ejemplo n.º 6
0
def parse_area_source_node(node, mfd_spacing=0.1):
    """
    Returns an "areaSource" node into an instance of the :class:
    hmtk.sources.area.mtkAreaSource
    """
    assert "areaSource" in node.tag
    area_taglist = get_taglist(node)
    # Get metadata
    area_id, name, trt = (node.attrib["id"],
                          node.attrib["name"],
                          node.attrib["tectonicRegion"])
    assert area_id # Defensive validation!
    # Process geometry
    polygon, upper_depth, lower_depth = node_to_area_geometry(
        node.nodes[area_taglist.index("areaGeometry")])
    # Process scaling relation
    msr = node_to_scalerel(node.nodes[area_taglist.index("magScaleRel")])
    # Process aspect ratio
    aspect = float_(node.nodes[area_taglist.index("ruptAspectRatio")].text)
    # Process MFD
    mfd = node_to_mfd(node, area_taglist)
    # Process nodal planes
    npds = node_to_nodal_planes(
        node.nodes[area_taglist.index("nodalPlaneDist")])
    # Process hypocentral depths
    hdds = node_to_hdd(node.nodes[area_taglist.index("hypoDepthDist")])
    return mtkAreaSource(area_id, name, trt,
                         geometry=polygon,
                         upper_depth=upper_depth,
                         lower_depth=lower_depth,
                         mag_scale_rel=msr,
                         rupt_aspect_ratio=aspect,
                         mfd=mfd,
                         nodal_plane_dist=npds,
                         hypo_depth_dist=hdds)
Ejemplo n.º 7
0
    def test_select_events_in_source(self):
        '''
        Basic test of method to select events from catalogue in polygon
        '''
        self.area_source = mtkAreaSource('101', 'A Source')
        simple_polygon = polygon.Polygon([point.Point(2.0, 3.0), 
                                          point.Point(3.0, 3.0), 
                                          point.Point(3.0, 2.0),
                                          point.Point(2.0, 2.0)])
 
        self.catalogue.data['eventID'] = np.arange(0, 7, 1)
        self.catalogue.data['longitude'] = np.arange(1.0, 4.5, 0.5)
        self.catalogue.data['latitude'] = np.arange(1.0, 4.5, 0.5)
        self.catalogue.data['depth'] = np.ones(7, dtype=float)
        # Simple Case - No buffer
        selector0 = CatalogueSelector(self.catalogue)
        self.area_source.create_geometry(simple_polygon, 0., 30.)
        self.area_source.select_catalogue(selector0, 0.)
        np.testing.assert_array_almost_equal(
            np.array([2., 2.5, 3.]),
            self.area_source.catalogue.data['longitude'])

        np.testing.assert_array_almost_equal(
            np.array([2., 2.5, 3.]),
            self.area_source.catalogue.data['latitude'])
        
        np.testing.assert_array_almost_equal(
            np.array([1., 1., 1.]),
            self.area_source.catalogue.data['depth'])

        # Simple case - dilated by 200 km (selects all)
        self.area_source.select_catalogue(selector0, 200.)
        np.testing.assert_array_almost_equal(
            np.array([1., 1.5, 2., 2.5, 3., 3.5, 4.0]),
            self.area_source.catalogue.data['longitude'])

        np.testing.assert_array_almost_equal(
            np.array([1., 1.5, 2., 2.5, 3., 3.5, 4.0]),
            self.area_source.catalogue.data['latitude'])
        
        np.testing.assert_array_almost_equal(
            np.ones(7, dtype=float),
            self.area_source.catalogue.data['depth'])

        # Bad case - no events in catalogue
        self.catalogue = Catalogue()
        selector0 = CatalogueSelector(self.catalogue)

        with self.assertRaises(ValueError) as ver:
            self.area_source.select_catalogue(selector0, 0.0)
            self.assertEqual(ver.exception.message,
                             'No events found in catalogue!')
Ejemplo n.º 8
0
    def test_select_events_in_source(self):
        '''
        Basic test of method to select events from catalogue in polygon
        '''
        self.area_source = mtkAreaSource('101', 'A Source')
        simple_polygon = polygon.Polygon([
            point.Point(2.0, 3.0),
            point.Point(3.0, 3.0),
            point.Point(3.0, 2.0),
            point.Point(2.0, 2.0)
        ])

        self.catalogue.data['eventID'] = np.arange(0, 7, 1)
        self.catalogue.data['longitude'] = np.arange(1.0, 4.5, 0.5)
        self.catalogue.data['latitude'] = np.arange(1.0, 4.5, 0.5)
        self.catalogue.data['depth'] = np.ones(7, dtype=float)
        # Simple Case - No buffer
        selector0 = CatalogueSelector(self.catalogue)
        self.area_source.create_geometry(simple_polygon, 0., 30.)
        self.area_source.select_catalogue(selector0, 0.)
        np.testing.assert_array_almost_equal(
            np.array([2., 2.5, 3.]),
            self.area_source.catalogue.data['longitude'])

        np.testing.assert_array_almost_equal(
            np.array([2., 2.5, 3.]),
            self.area_source.catalogue.data['latitude'])

        np.testing.assert_array_almost_equal(
            np.array([1., 1., 1.]), self.area_source.catalogue.data['depth'])

        # Simple case - dilated by 200 km (selects all)
        self.area_source.select_catalogue(selector0, 200.)
        np.testing.assert_array_almost_equal(
            np.array([1., 1.5, 2., 2.5, 3., 3.5, 4.0]),
            self.area_source.catalogue.data['longitude'])

        np.testing.assert_array_almost_equal(
            np.array([1., 1.5, 2., 2.5, 3., 3.5, 4.0]),
            self.area_source.catalogue.data['latitude'])

        np.testing.assert_array_almost_equal(
            np.ones(7, dtype=float), self.area_source.catalogue.data['depth'])

        # Bad case - no events in catalogue
        self.catalogue = Catalogue()
        selector0 = CatalogueSelector(self.catalogue)

        with self.assertRaises(ValueError) as ver:
            self.area_source.select_catalogue(selector0, 0.0)
            self.assertEqual(ver.exception.message,
                             'No events found in catalogue!')
Ejemplo n.º 9
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
Ejemplo n.º 10
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
Ejemplo n.º 11
0
    def test_create_oqnmrl_area_source(self):
        '''
        Tests the conversion of a point source to an instance of the :class:
        oqnrmllib.models.AreaSource
        '''
        # Define a complete source
        area_geom = polygon.Polygon([
            point.Point(10., 10.),
            point.Point(12., 10.),
            point.Point(12., 8.),
            point.Point(10., 8.)
        ])
        self.area_source = mtkAreaSource('001',
                                         'A Point Source',
                                         trt='Active Shallow Crust',
                                         geometry=area_geom,
                                         upper_depth=0.,
                                         lower_depth=20.,
                                         mag_scale_rel=None,
                                         rupt_aspect_ratio=1.0,
                                         mfd=models.TGRMFD(a_val=3.,
                                                           b_val=1.0,
                                                           min_mag=5.0,
                                                           max_mag=8.0),
                                         nodal_plane_dist=None,
                                         hypo_depth_dist=None)

        expected_source = models.AreaSource('001',
                                            'A Point Source',
                                            geometry=models.AreaGeometry(
                                                area_geom.wkt, 0., 20.),
                                            mag_scale_rel='WC1994',
                                            rupt_aspect_ratio=1.0,
                                            mfd=models.TGRMFD(a_val=3.,
                                                              b_val=1.0,
                                                              min_mag=5.0,
                                                              max_mag=8.0),
                                            nodal_plane_dist=None,
                                            hypo_depth_dist=None)
        test_source = self.area_source.create_oqnrml_source(use_defaults=True)
        self.assertTrue(isinstance(test_source, models.AreaSource))
        self.assertEqual(test_source.id, expected_source.id)
        self.assertEqual(test_source.name, expected_source.name)
        self.assertAlmostEqual(test_source.mfd.b_val,
                               expected_source.mfd.b_val)
Ejemplo n.º 12
0
    def test_create_oqnmrl_area_source(self):
        '''
        Tests the conversion of a point source to an instance of the :class:
        oqnrmllib.models.AreaSource 
        '''
        # Define a complete source
        area_geom = polygon.Polygon([point.Point(10., 10.), 
                                     point.Point(12., 10.), 
                                     point.Point(12., 8.), 
                                     point.Point(10., 8.)])
        self.area_source = mtkAreaSource('001', 
            'A Point Source', 
            trt='Active Shallow Crust',
            geometry = area_geom,
            upper_depth = 0.,
            lower_depth = 20.,
            mag_scale_rel=None,
            rupt_aspect_ratio=1.0,
            mfd=models.TGRMFD(a_val=3., b_val=1.0, min_mag=5.0, max_mag=8.0),
            nodal_plane_dist=None,
            hypo_depth_dist=None)

        expected_source = models.AreaSource(
            '001',
            'A Point Source',
            geometry=models.AreaGeometry(area_geom.wkt, 0., 20.),
            mag_scale_rel='WC1994',
            rupt_aspect_ratio=1.0,
            mfd=models.TGRMFD(a_val=3., b_val=1.0, min_mag=5.0, max_mag=8.0),
            nodal_plane_dist=None,
            hypo_depth_dist=None)
        test_source = self.area_source.create_oqnrml_source(use_defaults=True)
        self.assertTrue(isinstance(test_source, models.AreaSource))
        self.assertEqual(test_source.id, expected_source.id)
        self.assertEqual(test_source.name, expected_source.name)
        self.assertAlmostEqual(test_source.mfd.b_val, 
                               expected_source.mfd.b_val)
Ejemplo n.º 13
0
 def setUp(self):
     warnings.simplefilter("ignore")
     self.catalogue = Catalogue()
     self.area_source = mtkAreaSource('101', 'A Source')
Ejemplo n.º 14
0
 def setUp(self):
     warnings.simplefilter("ignore")
     self.catalogue = Catalogue()
     self.area_source = mtkAreaSource('101', 'A Source')
Ejemplo n.º 15
0
    points=[]
    for g in open(f_geom, 'r').readlines():
        c = g.strip().split(" ")
        points.append(geo.Point(float(c[1]), float(c[0])))
    points.append(points[0])
    print points
    geom = geo.Polygon(points)
    print geom
    
    a = area_source.mtkAreaSource(identifier = i, 
                  name = region, 
                  trt = "Stable Continental Crust", 
                  geometry = geom, 
                  upper_depth = "0", 
                  lower_depth = "40", 
                  mag_scale_rel = "WC1994", # default 
                  rupt_aspect_ratio = 1, 
                  mfd = mfd, 
                  nodal_plane_dist = None, 
                  hypo_depth_dist = None)

    sources.append(a)
    
    f.close()

s = source_model.mtkSourceModel(identifier="01", 
                                name = "PSHAB", 
                                sources = sources)

s.serialise_to_nrml(filename = "areas_pshab_dourado.xml", 
Ejemplo n.º 16
0
from openquake.nrmllib import models
from openquake.hazardlib import geo

from decimal import Decimal

a = area_source.mtkAreaSource(identifier = "01", 
                  name = "area source name", 
                  trt = "stable crust", 
                  geometry = geo.Polygon([geo.Point(-58.73, -10.33),
                                          geo.Point(-58.74, -13.54),
                                          geo.Point(-55.94, -13.59), 
                                          geo.Point(-56.58, -10.31),
                                          geo.Point(-58.73, -10.33)]), 
                  upper_depth = "0", 
                  lower_depth = "30", 
                  mag_scale_rel = "WC1994", # default 
                  rupt_aspect_ratio = 1, 
                  mfd = models.TGRMFD(min_mag=3.0,
                                      max_mag=7.0, 
                                      b_val=0.847, 
                                      a_val=0.737), 
                  nodal_plane_dist = models.NodalPlane(Decimal('1.0'), 
                                                       strike=0., 
                                                       dip=90.,
                                                       rake=0.), 
                  hypo_depth_dist = None)

#a.create_oqnrml_source

s = source_model.mtkSourceModel(identifier="09", 
                                        name = "sources model name",