Example #1
0
    def updateRupture(self, eventxml=None, rupturefile=None):
        """Update rupture/origin information in container.

        Args:
            eventxml (str): Path to event.xml file.
            rupturefile (str): Path to rupture file (JSON or txt format).
        """
        if eventxml is None and rupturefile is None:
            return

        # the container is guaranteed to have at least a Point rupture
        # and the origin.
        rupture = self.getRuptureObject()
        origin = rupture.getOrigin()

        if eventxml is not None:
            origin = Origin.fromFile(eventxml)
            if rupturefile is not None:
                rupture = get_rupture(origin, file=rupturefile)
            else:
                rupture_dict = rupture._geojson
                rupture = rupture_from_dict_and_origin(rupture_dict, origin)
        else:  #no event.xml file, but we do have a rupture file
            rupture = get_rupture(origin, file=rupturefile)

        self.setRupture(rupture)
Example #2
0
def test_incorrect():
    rupture_text = """# Source: Ji, C., D. V. Helmberger, D. J. Wald, and K.-F. Ma (2003). Slip history and dynamic implications of the 1999 Chi-Chi, Taiwan, earthquake, J. Geophys. Res. 108, 2412, doi:10.1029/2002JB001764.
    24.27980 120.72300	0
    24.05000 121.00000	17
    24.07190 121.09300	17
    24.33120 121.04300	17
    24.33120 121.04300	17
    24.27980 120.72300	0
    >
    24.27980 120.72300	0
    23.70000 120.68000	0
    23.60400 120.97200	17
    24.05000 121.00000	17
    24.27980 120.72300	0
    >
    23.60400 120.97200	17
    23.70000 120.68000	0
    23.58850 120.58600	0
    23.40240 120.78900	17
    23.60400 120.97200	17"""  # noqa

    # Rupture requires an origin even when not used:
    origin = Origin({'eventsourcecode': 'test', 'lat': 0, 'lon': 0,
                     'depth': 5.0, 'mag': 7.0})
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf)
Example #3
0
    def updateRupture(self,eventxml = None, rupturefile = None):
        """Update rupture/origin information in container.

        Args:
            eventxml (str): Path to event.xml file.
            rupturefile (str): Path to rupture file (JSON or txt format).
        """
        if eventxml is None and rupturefile is None:
            return

        # the container is guaranteed to have at least a Point rupture
        # and the origin.
        rupture = self.getRuptureObject()
        origin = rupture.getOrigin()

        if eventxml is not None:
            origin = Origin.fromFile(eventxml)
            if rupturefile is not None:
                rupture = get_rupture(origin,file=rupturefile)
            else:
                rupture_dict = rupture._geojson
                rupture = rupture_from_dict_and_origin(rupture_dict,origin)
        else: #no event.xml file, but we do have a rupture file
            rupture = get_rupture(origin,file=rupturefile)

        self.setRupture(rupture)
Example #4
0
def test_no_origin():
    # No argument
    with pytest.raises(Exception):
        get_rupture()

    # Wrong type
    with pytest.raises(Exception):
        get_rupture(7.3)
Example #5
0
def test_rupture_from_dict():

    # Grab an EdgeRupture
    origin = Origin({
        'id': 'test',
        'lat': 0,
        'lon': 0,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 0.5

    # Specify mesh_dx
    rup_original = get_rupture(origin, file, mesh_dx=1.0)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 1.0

    # Quad rupture
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.getArea() == rup_original.getArea()
    # Note, there's a bit of an inconsistency highlighted here because
    # magnitude has key 'magnitude' in the izmit file, but 'mag' in
    # the origin and both get retained.

    # Point rupture
    origin = Origin({
        'id': 'test',
        'lon': -122.5,
        'lat': 37.3,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    rup_original = get_rupture(origin)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.lats == 37.3
    assert rup_from_dict.lons == -122.5
Example #6
0
def test_rupture():
    with tempfile.TemporaryDirectory() as tmpdir:
        # Read in a fault file
        rup1_file = os.path.join(
            shakedir, 'tests', 'data', 'eventdata', 'northridge', 'current',
            'northridge_fault.txt')
        rup1 = get_rupture(origin, rup1_file)

        # Known point is p0
        dx = 0
        dy = 0
        p0 = rup1.getQuadrilaterals()[0][0]
        px = p0.x
        py = p0.y
        pz = p0.z
        length = rup1.getLength()
        width = rup1.getWidth()
        strike = rup1.getStrike()
        dip = rup1.getDip()

        outfile = os.path.join(tmpdir, 'test.json')

        op = subprocess.Popen(
            [program, outfile],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=False
        )
        responses = (
            'test\n' +
            '1\n' +
            str(px) + '\n' +
            str(py) + '\n' +
            str(pz) + '\n' +
            str(dx) + '\n' +
            str(dy) + '\n' +
            str(length) + '\n' +
            str(width) + '\n' +
            str(strike) + '\n' +
            str(dip) + '\n'
        )
        op.communicate(responses.encode('ascii'))
        rup2 = get_rupture(origin, outfile)

        # testing, note that some difference will occur since the original
        # points are not necessarily coplanar or even rectangular, which
        # are conditions enfored on the derived rupture and so this cannot
        # be a very precise comparison.
        rtol = 1e-4
        np.testing.assert_allclose(rup2.lats, rup1.lats, rtol=rtol)
        np.testing.assert_allclose(rup2.lons, rup1.lons, rtol=rtol)
        rtol = 2e-3
        np.testing.assert_allclose(rup2.depths, rup1.depths, rtol=rtol)
Example #7
0
def test_extent_config():
    eventfile = os.path.join(datadir, 'event_oklahoma_large.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    config = {'extent': {'coefficients': {'coeffs': [27.24, 250.4, 579.1]}}}
    cmp_extent = (-100.61666666666666, -93.95, 32.916666666666664, 38.35)
    extent = get_extent(rupture, config)
    np.testing.assert_almost_equal(cmp_extent, extent)

    config = {
        'extent': {
            'magnitude_spans': {
                'span1': [0, 6, 4, 3],
                'span2': [6, 10, 6, 4]
            }
        }
    }
    extent = get_extent(rupture, config)
    cmp_extent = (-99.416, -95.416, 32.679, 38.679)
    np.testing.assert_almost_equal(cmp_extent, extent)

    config = {'extent': {'bounds': {'extent': [-100, 32, -95, 37]}}}
    extent = get_extent(rupture, config)
    cmp_extent = [-100, -95, 32, 37]
    np.testing.assert_almost_equal(extent, cmp_extent)
Example #8
0
def test_extent_config():
    eventfile = os.path.join(datadir, 'event_oklahoma_large.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)

    config = {
        'extent': {
            'magnitude_spans': {
                'span1': [0, 6, 4, 3],
                'span2': [6, 10, 6, 4]
            }
        }
    }
    extent = get_extent(rupture, config)
    cmp_extent = (-99.4166667, -95.4083333, 32.675, 38.6833333)
    np.testing.assert_almost_equal(cmp_extent, extent)

    # Test for relative_offset
    config = {
        'extent': {
            'magnitude_spans': {
                'span1': [0, 6, 4, 3],
                'span2': [6, 10, 6, 4]
            },
            'relative_offset': [0.25, 0.5],
        }
    }
    extent = get_extent(rupture, config)
    cmp_extent = (-98.4166667, -94.4083333, 35.675, 41.6833333)
    np.testing.assert_almost_equal(cmp_extent, extent)

    config = {'extent': {'bounds': {'extent': [-100, 32, -95, 37]}}}
    extent = get_extent(rupture, config)
    cmp_extent = [-100, -95, 32, 37]
    np.testing.assert_almost_equal(extent, cmp_extent)
Example #9
0
def test_get_extent_aspect():
    #
    # Test ruptures with weird aspect ratios
    #
    eventfile = os.path.join(datadir, 'event_wenchuan.xml')
    origin = Origin.fromFile(eventfile)
    #
    # Long horizontal rupture
    #
    rrep = io.StringIO(
        """
            100.0 30.0  0.0
            110.0 30.0 0.0
            110.0 30.0 5.0
            100.0 30.0 5.0
            100.0 30.0 0.0
            """
    )
    rupture = get_rupture(origin, rrep)
    W, E, S, N = get_extent(rupture)
    assert W == 97.18333333333334
    assert E == 113.51666666666667
    assert S == 25.616666666666667
    assert N == 34.06666666666666
    #
    # Long vertical rupture
    #
    rrep = io.StringIO(
        """
            100.0 24.0 0.0
            100.0 36.0 0.0
            100.0 36.0 5.0
            100.0 24.0 5.0
            100.0 24.0 0.0
            """
    )
    rupture = get_rupture(origin, rrep)
    W, E, S, N = get_extent(rupture)
    assert W == 92.53333333333333
    assert E == 108.89999999999999
    assert S == 21.03333333333333
    assert N == 38.46666666666667
Example #10
0
def test_get_extent_aspect():
    #
    # Test ruptures with weird aspect ratios
    #
    eventfile = os.path.join(datadir, 'event_wenchuan.xml')
    origin = Origin.fromFile(eventfile)
    #
    # Long horizontal rupture
    #
    rrep = io.StringIO(
        """
            100.0 30.0  0.0
            110.0 30.0 0.0
            110.0 30.0 5.0
            100.0 30.0 5.0
            100.0 30.0 0.0
            """
    )
    rupture = get_rupture(origin, rrep)
    W, E, S, N = get_extent(rupture)
    np.testing.assert_allclose(W, 92.65)
    np.testing.assert_allclose(E, 119.98333333333333)
    np.testing.assert_allclose(S, 19.833333333333332)
    np.testing.assert_allclose(N, 38.96666666666667)
    #
    # Long vertical rupture
    #
    rrep = io.StringIO(
        """
            100.0 24.0 0.0
            100.0 36.0 0.0
            100.0 36.0 5.0
            100.0 24.0 5.0
            100.0 24.0 0.0
            """
    )
    rupture = get_rupture(origin, rrep)
    W, E, S, N = get_extent(rupture)
    np.testing.assert_allclose(W, 88.48333333333333)
    np.testing.assert_allclose(E, 115.08333333333333)
    np.testing.assert_allclose(S, 16.1)
    np.testing.assert_allclose(N, 42.583333333333336)
Example #11
0
def test_get_extent_aspect():
    #
    # Test ruptures with weird aspect ratios
    #
    eventfile = os.path.join(datadir, 'event_wenchuan.xml')
    origin = Origin.fromFile(eventfile)
    #
    # Long horizontal rupture
    #
    rrep = io.StringIO(
            """
            30.0 100.0 0.0
            30.0 110.0 0.0
            30.0 110.0 5.0
            30.0 100.0 5.0
            30.0 100.0 0.0
            """
           )
    rupture = get_rupture(origin, rrep)
    W, E, S, N = get_extent(rupture)
    assert W == 97.18333333333334
    assert E == 113.51666666666667
    assert S == 25.616666666666667
    assert N == 34.06666666666666
    #
    # Long vertical rupture
    #
    rrep = io.StringIO(
            """
            24.0 100.0 0.0
            36.0 100.0 0.0
            36.0 100.0 5.0
            24.0 100.0 5.0
            24.0 100.0 0.0
            """
           )
    rupture = get_rupture(origin, rrep)
    W, E, S, N = get_extent(rupture)
    assert W == 92.53333333333333
    assert E == 108.89999999999999
    assert S == 21.03333333333333
    assert N == 38.46666666666667
Example #12
0
def test_get_extent_small_point():
    #
    # Do a point rupture
    # Small magnitude
    #
    eventfile = os.path.join(datadir, 'event_wenchuan_small.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    np.testing.assert_allclose(W, 102.33333333333333)
    np.testing.assert_allclose(E, 104.41666666666667)
    np.testing.assert_allclose(S, 30.083333333333332)
    np.testing.assert_allclose(N, 31.883333333333333)
Example #13
0
def test_get_extent_small_complex():
    #
    # Do a complex rupture
    #
    eventfile = os.path.join(datadir, 'event_wenchuan.xml')
    origin = Origin.fromFile(eventfile)
    faultfile = os.path.join(datadir, 'Hartzell11_fault.txt')
    rupture = get_rupture(origin, faultfile)
    W, E, S, N = get_extent(rupture)
    np.testing.assert_allclose(W, 95.28333333333333)
    np.testing.assert_allclose(E, 115.1)
    np.testing.assert_allclose(S, 23.083333333333332)
    np.testing.assert_allclose(N, 39.75)
Example #14
0
def test_get_extent_stable_large():
    #
    # Do an event in a stable region
    # Large magnitude
    #
    eventfile = os.path.join(datadir, 'event_oklahoma_large.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    assert W == -106.14999999999999
    assert E == -86.76666666666667
    assert S == 27.55
    assert N == 43.03333333333333
Example #15
0
def test_get_extent_stable_small():
    #
    # Do an event in a stable region
    # Small magnitude
    #
    eventfile = os.path.join(datadir, 'event_oklahoma.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    np.testing.assert_allclose(W, -98.5)
    np.testing.assert_allclose(E, -96.28333333333333)
    np.testing.assert_allclose(S, 34.766666666666666)
    np.testing.assert_allclose(N, 36.583333333333336)
Example #16
0
def test_get_extent_stable_small():
    #
    # Do an event in a stable region
    # Small magnitude
    #
    eventfile = os.path.join(datadir, 'event_oklahoma.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    assert W == -98.5
    assert E == -96.28333333333333
    assert S == 34.766666666666666
    assert N == 36.583333333333336
Example #17
0
def test_get_extent_small_complex():
    #
    # Do a complex rupture
    #
    eventfile = os.path.join(datadir, 'event_wenchuan.xml')
    origin = Origin.fromFile(eventfile)
    faultfile = os.path.join(datadir, 'Hartzell11_fault.txt')
    rupture = get_rupture(origin, faultfile)
    W, E, S, N = get_extent(rupture)
    assert W == 100.03333333333333
    assert E == 108.93333333333334
    assert S == 27.9
    assert N == 35.55
Example #18
0
def test_get_extent_stable_small():
    #
    # Do an event in a stable region
    # Small magnitude
    #
    eventfile = os.path.join(datadir, 'event_oklahoma.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    assert W == -98.5
    assert E == -96.28333333333333
    assert S == 34.766666666666666
    assert N == 36.583333333333336
Example #19
0
def test_get_extent_small_point():
    #
    # Do a point rupture
    # Small magnitude
    #
    eventfile = os.path.join(datadir, 'event_wenchuan_small.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    assert W == 102.33333333333333
    assert E == 104.41666666666667
    assert S == 30.083333333333332
    assert N == 31.883333333333333
Example #20
0
def test_get_extent_stable_large():
    #
    # Do an event in a stable region
    # Large magnitude
    #
    eventfile = os.path.join(datadir, 'event_oklahoma_large.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    np.testing.assert_allclose(W, -107.45)
    np.testing.assert_allclose(E, -84.8)
    np.testing.assert_allclose(S, 26.166666666666668)
    np.testing.assert_allclose(N, 44.15)
Example #21
0
def test_get_extent_stable_large():
    #
    # Do an event in a stable region
    # Large magnitude
    #
    eventfile = os.path.join(datadir, 'event_oklahoma_large.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    assert W == -106.14999999999999
    assert E == -86.76666666666667
    assert S == 27.55
    assert N == 43.03333333333333
Example #22
0
def test_get_extent_small_point():
    #
    # Do a point rupture
    # Small magnitude
    #
    eventfile = os.path.join(datadir, 'event_wenchuan_small.xml')
    origin = Origin.fromFile(eventfile)
    rupture = get_rupture(origin)
    W, E, S, N = get_extent(rupture)
    assert W == 102.33333333333333
    assert E == 104.41666666666667
    assert S == 30.083333333333332
    assert N == 31.883333333333333
Example #23
0
def test_get_extent_small_complex():
    #
    # Do a complex rupture
    #
    eventfile = os.path.join(datadir, 'event_wenchuan.xml')
    origin = Origin.fromFile(eventfile)
    faultfile = os.path.join(datadir, 'Hartzell11_fault.txt')
    rupture = get_rupture(origin, faultfile)
    W, E, S, N = get_extent(rupture)
    assert W == 100.03333333333333
    assert E == 108.93333333333334
    assert S == 27.9
    assert N == 35.55
Example #24
0
def test_northridge():
    rupture_text = """# Source: Wald, D. J., T. H. Heaton, and K. W. Hudnut (1996). The Slip History of the 1994 Northridge, California, Earthquake Determined from Strong-Motion, Teleseismic, GPS, and Leveling Data, Bull. Seism. Soc. Am. 86, S49-S70.
    -118.421 34.315  5.000
    -118.587 34.401  5.000
    -118.693 34.261 20.427
    -118.527 34.175 20.427
    -118.421 34.315 5.000
    """  # noqa

    # Rupture requires an origin even when not used:
    origin = Origin({
        'id': 'test',
        'lon': 0,
        'lat': 0,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    cbuf = io.StringIO(rupture_text)
    rupture = get_rupture(origin, cbuf)
    strike = rupture.getStrike()
    np.testing.assert_allclose(strike, 122.06, atol=0.01)
    dip = rupture.getDip()
    np.testing.assert_allclose(dip, 40.21, atol=0.01)
    L = rupture.getLength()
    np.testing.assert_allclose(L, 17.99, atol=0.01)
    W = rupture.getWidth()
    np.testing.assert_allclose(W, 23.94, atol=0.01)
    nq = rupture.getNumQuads()
    np.testing.assert_allclose(nq, 1)
    ng = rupture.getNumGroups()
    np.testing.assert_allclose(ng, 1)
    sind = rupture._getGroupIndex()
    np.testing.assert_allclose(sind, [0])
    ztor = rupture.getDepthToTop()
    np.testing.assert_allclose(ztor, 5, atol=0.01)
    itl = rupture.getIndividualTopLengths()
    np.testing.assert_allclose(itl, 17.99, atol=0.01)
    iw = rupture.getIndividualWidths()
    np.testing.assert_allclose(iw, 23.94, atol=0.01)
    lats = rupture.lats
    lats_d = np.array([34.401, 34.315, 34.175, 34.261, 34.401, np.nan])
    np.testing.assert_allclose(lats, lats_d, atol=0.01)
    lons = rupture.lons
    lons_d = np.array(
        [-118.587, -118.421, -118.527, -118.693, -118.587, np.nan])
    np.testing.assert_allclose(lons, lons_d, atol=0.01)
Example #25
0
def test_rupture_from_dict():
    # Grab an EdgeRupture
    origin = Origin({'eventsourcecode': 'test', 'lat': 0, 'lon': 0,
                     'depth': 5.0, 'mag': 7.0})

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 0.5

    # Specify mesh_dx
    rup_original = get_rupture(origin, file, mesh_dx=1.0)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 1.0

    # Quad rupture
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.getArea() == rup_original.getArea()
    # Note, there's a bit of an inconsistency highlighted here because
    # magnitude has key 'magnitude' in the izmit file, but 'mag' in
    # the origin and both get retained.

    # Point rupture
    origin = Origin({'eventsourcecode': 'test',
                     'lon': -122.5, 'lat': 37.3,
                     'depth': 5.0, 'mag': 7.0})
    rup_original = get_rupture(origin)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.lats == 37.3
    assert rup_from_dict.lons == -122.5
Example #26
0
    def createFromInput(cls, filename, config, eventfile, version_history,
                        rupturefile=None, sourcefile=None, momentfile=None,
                        datafiles=None):
        """
        Instantiate an InputContainer from ShakeMap input data.

        Args:
            filename (str): Path to HDF5 file that will be created to
                encapsulate all input data.
            config (dict): Dictionary containing all configuration information
                necessary for ShakeMap ground motion and other calculations.
            eventfile (str): Path to ShakeMap event.xml file.
            rupturefile (str): Path to ShakeMap rupture text or JSON file.
            sourcefile (str): Path to ShakeMap source.txt file.
            momentfile (str): Path to ShakeMap moment.xml file.
            datafiles (list): List of ShakeMap data (DYFI, strong motion)
                files.
            version_history (dict): Dictionary containing version history.

        Returns:
            InputContainer: Instance of InputContainer.
        """
        container = cls.create(filename)
        container.setConfig(config)

        # create an origin from the event file
        origin = Origin.fromFile(eventfile, sourcefile=sourcefile,
                                 momentfile=momentfile)

        # create a rupture object from the origin and the rupture file
        # (if present).
        rupture = get_rupture(origin, file=rupturefile)

        # store the rupture object in the container
        container.setRupture(rupture)

        if datafiles is not None and len(datafiles) > 0:
            container.setStationData(datafiles)

        container.setVersionHistory(version_history)
        return container
Example #27
0
def test_northridge():
    rupture_text = """# Source: Wald, D. J., T. H. Heaton, and K. W. Hudnut (1996). The Slip History of the 1994 Northridge, California, Earthquake Determined from Strong-Motion, Teleseismic, GPS, and Leveling Data, Bull. Seism. Soc. Am. 86, S49-S70.
    34.315 -118.421 5.000
    34.401 -118.587 5.000
    34.261 -118.693 20.427
    34.175 -118.527 20.427
    34.315 -118.421 5.000
    """  # noqa

    # Rupture requires an origin even when not used:
    origin = Origin({'eventsourcecode': 'test', 'lat': 0, 'lon': 0,
                     'depth': 5.0, 'mag': 7.0})
    cbuf = io.StringIO(rupture_text)
    rupture = get_rupture(origin, cbuf)
    strike = rupture.getStrike()
    np.testing.assert_allclose(strike, 122.06, atol=0.01)
    dip = rupture.getDip()
    np.testing.assert_allclose(dip, 40.21, atol=0.01)
    L = rupture.getLength()
    np.testing.assert_allclose(L, 17.99, atol=0.01)
    W = rupture.getWidth()
    np.testing.assert_allclose(W, 23.94, atol=0.01)
    nq = rupture.getNumQuads()
    np.testing.assert_allclose(nq, 1)
    ng = rupture.getNumGroups()
    np.testing.assert_allclose(ng, 1)
    sind = rupture._getGroupIndex()
    np.testing.assert_allclose(sind, [0])
    ztor = rupture.getDepthToTop()
    np.testing.assert_allclose(ztor, 5, atol=0.01)
    itl = rupture.getIndividualTopLengths()
    np.testing.assert_allclose(itl, 17.99, atol=0.01)
    iw = rupture.getIndividualWidths()
    np.testing.assert_allclose(iw, 23.94, atol=0.01)
    lats = rupture.lats
    lats_d = np.array([34.401, 34.315, 34.175, 34.261, 34.401, np.nan])
    np.testing.assert_allclose(lats, lats_d, atol=0.01)
    lons = rupture.lons
    lons_d = np.array(
        [-118.587, -118.421, -118.527, -118.693, -118.587, np.nan])
    np.testing.assert_allclose(lons, lons_d, atol=0.01)
Example #28
0
    def createFromInput(cls, filename, config, eventfile, version_history, rupturefile=None,
                        datafiles=None):
        """
        Instantiate an InputContainer from ShakeMap input data.

        Args:
            filename (str): Path to HDF5 file that will be created to encapsulate all
                input data.
            config (dict): Dictionary containing all configuration information
                necessary for ShakeMap ground motion and other calculations.
            eventfile (str): Path to ShakeMap event.xml file.
            rupturefile (str): Path to ShakeMap rupture text or JSON file.
            datafiles (list): List of ShakeMap data (DYFI, strong motion) files.
            version_history (dict): Dictionary containing version history.

        Returns:
            InputContainer: Instance of InputContainer.
        """
        container = cls.create(filename)
        container.setConfig(config)

        # create an origin from the event file
        origin = Origin.fromFile(eventfile)

        # create a rupture object from the origin and the rupture file
        # (if present).
        rupture = get_rupture(origin,file=rupturefile)

        # store the rupture object in the container
        container.setRupture(rupture)

        if datafiles is not None:
            container.setStationData(datafiles)

        container.setVersionHistory(version_history)
        return container
Example #29
0
def test_EdgeRupture():
    # Rupture requires an origin even when not used:
    origin = Origin({'eventsourcecode': 'test', 'lat': 0, 'lon': 0,
                     'depth': 5.0, 'mag': 7.0})

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup = get_rupture(origin, file)
    np.testing.assert_allclose(rup.getArea(), 105635.92827547337)

    # Force read Northridge as EdgeRupture
    file = os.path.join(homedir, 'rupture_data/northridge_fault.txt')
    d = text_to_json(file)
    rupt = EdgeRupture(d, origin)
    strike = rupt.getStrike()
    np.testing.assert_allclose(strike, 121.97, atol=0.01)
    dip = rupt.getDip()
    np.testing.assert_allclose(dip, 40.12, atol=0.01)
    L = rupt.getLength()
    np.testing.assert_allclose(L, 17.99, atol=0.01)
    W = rupt.getWidth()
    np.testing.assert_allclose(W, 23.92, atol=0.01)
    ztor = rupt.getDepthToTop()
    np.testing.assert_allclose(ztor, 5, atol=0.01)

    # And again for the same vertices but reversed order
    file = os.path.join(homedir, 'rupture_data/northridge_fixed_fault.txt')
    d = text_to_json(file)
    rupt = EdgeRupture(d, origin)
    strike = rupt.getStrike()
    np.testing.assert_allclose(strike, 121.97, atol=0.01)
    dip = rupt.getDip()
    np.testing.assert_allclose(dip, 40.12, atol=0.01)
    L = rupt.getLength()
    np.testing.assert_allclose(L, 17.99, atol=0.01)
    W = rupt.getWidth()
    np.testing.assert_allclose(W, 23.92, atol=0.01)
    ztor = rupt.getDepthToTop()
    np.testing.assert_allclose(ztor, 5, atol=0.01)

    # Test for fromArrays method
    toplats = np.array([37.0, 38.0])
    toplons = np.array([-120.0, -120.0])
    topdeps = np.array([0.0, 0.0])
    botlats = copy.copy(toplats)
    botlons = copy.copy(toplons)
    botdeps = np.array([10.0, 10.0])
    erup = EdgeRupture.fromArrays(toplons, toplats, topdeps, botlons, botlats,
                                  botdeps, origin)
    qrup = QuadRupture.fromVertices(
        [toplons[0]], [toplats[0]], [topdeps[0]],
        [toplons[1]], [toplats[1]], [topdeps[1]],
        [botlons[1]], [botlats[1]], [botdeps[1]],
        [botlons[0]], [botlats[0]], [botdeps[0]],
        origin)
    np.testing.assert_allclose(erup.getArea(), 1108.9414759967776)
    np.testing.assert_allclose(erup.getDepthToTop(), 0)
    np.testing.assert_allclose(erup.getLength(), 111.19492664455889)
    np.testing.assert_allclose(
        erup.lats, np.array([37.,  38.,  38.,  37.,  37.,  np.nan]))
    np.testing.assert_allclose(
        erup.lons, np.array([-120., -120., -120., -120., -120.,  np.nan]))
    np.testing.assert_allclose(
        erup.depths, np.array([0.,   0.,  10.,  10.,   0.,  np.nan]))
    np.testing.assert_allclose(
        erup._getGroupIndex(), np.array([0.,   0.]))
    quads = erup.getQuadrilaterals()
    np.testing.assert_allclose(quads[0][0].x, -120.0)

    # Need to also test the distances with EdgeRupture
    lons = np.linspace(-120.1, -121.0, 10)
    lats = np.linspace(37.0, 38, 10)
    deps = np.zeros_like(lons)
    rrup1 = qrup.computeRrup(lons, lats, deps)
    rrup2 = erup.computeRrup(lons, lats, deps)
    np.testing.assert_allclose(rrup1, rrup2, atol=2e-2)
    rjb1 = qrup.computeRjb(lons, lats, deps)
    rjb2 = erup.computeRjb(lons, lats, deps)
    np.testing.assert_allclose(rjb1, rjb2, atol=2e-2)
    gc2 = erup.computeGC2(lons, lats, deps)
    targetRy0 = np.array(
      [0., 0.,  0., 0.,  0.,
       0., 0.,  0., 0.,  0.67335931])
    targetRx = np.array(
      [-8.88024949, -17.73390996, -26.56167797, -35.3634266,
       -44.13902929, -52.88835984, -61.61129242, -70.30770154,
       -78.97746209, -87.6204493])
    np.testing.assert_allclose(gc2['ry0'], targetRy0)
    np.testing.assert_allclose(gc2['rx'], targetRx)
Example #30
0
def test_parse_complicated_rupture():
    rupture_text = """# SOURCE: Barka, A., H. S. Akyz, E. Altunel, G. Sunal, Z. Akir, A. Dikbas, B. Yerli, R. Armijo, B. Meyer, J. B. d. Chabalier, T. Rockwell, J. R. Dolan, R. Hartleb, T. Dawson, S. Christofferson, A. Tucker, T. Fumal, R. Langridge, H. Stenner, W. Lettis, J. Bachhuber, and W. Page (2002). The Surface Rupture and Slip Distribution of the 17 August 1999 Izmit Earthquake (M 7.4), North Anatolian Fault, Bull. Seism. Soc. Am. 92, 43-60.
    40.70985 29.33760 0
    40.72733 29.51528 0
    40.72933 29.51528 20
    40.71185 29.33760 20
    40.70985 29.33760 0
    >
    40.70513 29.61152 0
    40.74903 29.87519 0
    40.75103 29.87519 20
    40.70713 29.61152 20
    40.70513 29.61152 0
    >
    40.72582 29.88662 0
    40.72336 30.11126 0
    40.73432 30.19265 0
    40.73632 30.19265 20
    40.72536 30.11126 20
    40.72782 29.88662 20
    40.72582 29.88662 0
    >
    40.71210 30.30494 0
    40.71081 30.46540 0
    40.70739 30.56511 0
    40.70939 30.56511 20
    40.71281 30.46540 20
    40.71410 30.30494 20
    40.71210 30.30494 0
    >
    40.71621 30.57658 0
    40.70068 30.63731 0
    40.70268 30.63731 20
    40.71821 30.57658 20
    40.71621 30.57658 0
    >
    40.69947 30.72900 0
    40.79654 30.93655 0
    40.79854 30.93655 20
    40.70147 30.72900 20
    40.69947 30.72900 0
    >
    40.80199 30.94688 0
    40.84501 31.01799 0
    40.84701 31.01799 20
    40.80399 30.94688 20
    40.80199 30.94688 0"""  # noqa

    # Rupture requires an origin even when not used:
    origin = Origin({'eventsourcecode': 'test', 'lat': 0, 'lon': 0,
                     'depth': 5.0, 'mag': 7.0})
    cbuf = io.StringIO(rupture_text)
    rupture = get_rupture(origin, cbuf)
    strike = rupture.getStrike()
    np.testing.assert_allclose(strike, -100.46, atol=0.01)
    dip = rupture.getDip()
    np.testing.assert_allclose(dip, 89.40, atol=0.01)
    L = rupture.getLength()
    np.testing.assert_allclose(L, 119.56, atol=0.01)
    W = rupture.getWidth()
    np.testing.assert_allclose(W, 20.0, atol=0.01)
    nq = rupture.getNumQuads()
    np.testing.assert_allclose(nq, 9)
    ng = rupture.getNumGroups()
    np.testing.assert_allclose(ng, 7)
    sind = rupture._getGroupIndex()
    np.testing.assert_allclose(sind, [0, 1, 2, 2, 3, 3, 4, 5, 6])
    ztor = rupture.getDepthToTop()
    np.testing.assert_allclose(ztor, 0, atol=0.01)
    itl = rupture.getIndividualTopLengths()
    itl_d = np.array([15.13750778,  22.80237887,  18.98053425,   6.98263853,
                      13.55978731,   8.43444811,   5.41399812,  20.57788056,
                      7.66869463])
    np.testing.assert_allclose(itl, itl_d, atol=0.01)
    iw = rupture.getIndividualWidths()
    iw_d = np.array([20.00122876,  20.00122608,  20.00120173,  20.00121028,
                     20.00121513,  20.00121568,  20.00107293,  20.00105498,
                     20.00083348])
    np.testing.assert_allclose(iw, iw_d, atol=0.01)
    lats = rupture.lats
    lats_d = np.array([40.72733,  40.70985,  40.71185,  40.72932969,
                       40.72733,          np.nan,  40.74903,  40.70513,
                       40.70713,  40.75102924,  40.74903,          np.nan,
                       40.72336,  40.72582,  40.72336,  40.72536,
                       40.72782,  40.72536004,  40.72336,          np.nan,
                       40.71081,  40.7121,  40.71081,  40.71281,
                       40.7141,  40.71281002,  40.71081,          np.nan,
                       40.70068,  40.71621,  40.71821,  40.70268025,
                       40.70068,          np.nan,  40.79654,  40.69947,
                       40.70147,  40.79853872,  40.79654,          np.nan,
                       40.84501,  40.80199,  40.80399,  40.84700952,
                       40.84501,          np.nan])
    np.testing.assert_allclose(lats, lats_d, atol=0.001)
    lons = rupture.lons
    lons_d = np.array([29.51528,  29.3376,  29.3376,  29.51528005,
                       29.51528,          np.nan,  29.87519,  29.61152,
                       29.61152,  29.87519021,  29.87519,          np.nan,
                       30.11126,  29.88662,  30.11126,  30.11126,
                       29.88662,  30.11126,  30.11126,          np.nan,
                       30.4654,  30.30494,  30.4654,  30.4654,
                       30.30494,  30.4654,  30.4654,          np.nan,
                       30.63731,  30.57658,  30.57658,  30.63731011,
                       30.63731,          np.nan,  30.93655,  30.729,
                       30.729,  30.93655103,  30.93655,          np.nan,
                       31.01799,  30.94688,  30.94688,  31.0179905,
                       31.01799,          np.nan])

    np.testing.assert_allclose(lons, lons_d, atol=0.001)
Example #31
0
        filepath = os.path.join(rupt_dir, rupture_file[0])

        # need a dummy origin
        origin = Origin({
            'id': '',
            'netid': '',
            'network': '',
            'lat': 0,
            'lon': 0,
            'depth': 0,
            'locstring': '',
            'mag': 0,
            'time': ''
        })

        rupt = get_rupture(origin, filepath, new_format=False)

        rx.width = rupt.getWidth()
        rx.ztor = rupt.getDepthToTop()

    # If there is no fault file, use hypocentral dist for rrup.
    else:
        rx.width = 10**(-0.76 + 0.27 * rx.mag)
        rx.ztor = rx.hypo_depth

    # Evaluate the GMPE.
    for i in range(len(imts)):
        gmpe_imt_mean, gmpe_imt_sd = gmpe.get_mean_and_stddevs(
            sx, rx, dx, imts[i], sd_types)
        spectrals[i].append(gmpe_imt_mean)
        stds[i].append(gmpe_imt_sd)
Example #32
0
def test_incorrect():
    # Number of points in polyon is even
    rupture_text = """# Source: Ji, C., D. V. Helmberger, D. J. Wald, and \
K.-F. Ma (2003). Slip history and dynamic implications of the 1999 Chi-Chi, \
Taiwan, earthquake, J. Geophys. Res. 108, 2412, doi:10.1029/2002JB001764.
    120.72300 24.27980 	0
    121.00000 24.05000	17
    121.09300 24.07190	17
    121.04300 24.33120	17
    121.04300 24.33120	17
    120.72300 24.27980	0
    >
    120.72300 24.27980	0
    120.68000 23.70000	0
    120.97200 23.60400	17
    121.00000 24.05000	17
    120.72300 24.27980	0
    >
    120.97200 23.60400	17
    120.68000 23.70000	0
    120.58600 23.58850	0
    120.78900 23.40240	17
    120.97200 23.60400	17"""  # noqa

    # Rupture requires an origin even when not used:
    origin = Origin({'id': 'test',
                     'lon': 0, 'lat': 0,
                     'depth': 5.0, 'mag': 7.0, 'netid': 'us',
                     'network': '', 'locstring': '',
                     'time': HistoricTime.utcfromtimestamp(time.time())})
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf)

    # Top points must be first
    rupture_text = """# Test
    120.72300 24.27980 	0
    121.00000 24.05000	17
    121.09300 24.07190	17
    121.04300 24.33120	17
    120.72300 24.27980	0"""  # noqa
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf)

    # Wrong order of lat/lon
    rupture_text = """# Test
    -118.421 34.315  5.000
    -118.587 34.401  5.000
    -118.693 34.261 20.427
    -118.527 34.175 20.427
    -118.421 34.315 5.000
    """  # noqa
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf, new_format=False)

    # Wrong order of lat/lon
    rupture_text = """# Test
    34.315 -118.421  5.000
    34.401 -118.587  5.000
    34.261 -118.693 20.427
    34.175 -118.527 20.427
    34.315 -118.421  5.000
    """  # noqa
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf, new_format=True)

    # Unclosed segments
    rupture_text = """# Test
    34.315 -118.421  5.000
    34.401 -118.587  5.000
    34.261 -118.693 20.427
    34.175 -118.527 20.427
    34.315 -118.6    5.000
    """  # noqa
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf, new_format=False)

    # incorrect delimiter
    rupture_text = """#Test
    34.315;-118.421;5.000
    34.401;-118.587;5.000
    34.261;-118.693;20.427
    34.175;-118.527;20.427
    34.315;-118.421;5.000
    """  # noqa
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf, new_format=False)

    # incorrect delimiter, new format
    rupture_text = """#Test
    34.315;-118.421;5.000
    34.401;-118.587;5.000
    34.261;-118.693;20.427
    34.175;-118.527;20.427
    34.315;-118.421;5.000
    """  # noqa
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf, new_format=True)

    # Not 3 columns
    rupture_text = """#Test
    34.315 -118.421;5.000
    34.401 -118.587;5.000
    34.261 -118.693;20.427
    34.175 -118.527;20.427
    34.315 -118.421;5.000
    """  # noqa
    cbuf = io.StringIO(rupture_text)
    with pytest.raises(Exception):
        get_rupture(origin, cbuf, new_format=False)

    # Json incorrect
    test = {
        "metadata": {
            "id": "test",
            "mag": 7.0,
            "lon": 0,
            "mech": "ALL",
            "depth": 5.0,
            "time": "2018-07-02T22:50:03Z",
            "netid": "us",
            "rake": 0.0,
            "lat": 0,
            "network": "",
            "locstring": "",
            "reference": "Test"
        },
        "features": [{
            "type": "Feature",
            "geometry": {
                "coordinates": [[
                    [[-118.421, 34.315, 5.0],
                     [-118.587, 34.401, 5.0],
                     [-118.693, 34.261, 20.427],
                     [-118.527, 34.175, 20.427],
                     [-118.421, 34.315, 5.0]]]],
                "type": "MultiPolygon"
            },
            "properties":{
                "rupture type": "rupture extent"
            }
        }],
        "type": "FeatureCollection"
    }

    # incorrect type
    test_incorrect = copy.deepcopy(test)
    test_incorrect['type'] = 'Feature'
    with pytest.raises(Exception) as e:
        validate_json(test_incorrect)
    print(str(e))

    # Incorrect number of features
    test_incorrect = copy.deepcopy(test)
    test_incorrect['features'].append(['wrong'])
    with pytest.raises(Exception) as e:
        validate_json(test_incorrect)
    print(str(e))

    # no reference
    test_incorrect = copy.deepcopy(test)
    test_incorrect['metadata'].pop('reference', None)
    with pytest.raises(Exception) as e:
        validate_json(test_incorrect)
    print(str(e))

    # incorrect feature type
    test_incorrect = copy.deepcopy(test)
    test_incorrect['features'][0]['type'] = 'fred'
    with pytest.raises(Exception) as e:
        validate_json(test_incorrect)
    print(str(e))

    # incorrect feature geometry type
    test_incorrect = copy.deepcopy(test)
    test_incorrect['features'][0]['geometry']['type'] = 'fred'
    with pytest.raises(Exception) as e:
        validate_json(test_incorrect)
    print(str(e))

    # no coordinates
    test_incorrect = copy.deepcopy(test)
    test_incorrect['features'][0]['geometry'].pop('coordinates', None)
    with pytest.raises(Exception) as e:
        validate_json(test_incorrect)
    print(str(e))
Example #33
0
def test_parse_complicated_rupture():
    rupture_text = """# SOURCE: Barka, A., H. S. Akyz, E. Altunel, G. Sunal, \
Z. Akir, A. Dikbas, B. Yerli, R. Armijo, B. Meyer, J. B. d. Chabalier, \
T. Rockwell, J. R. Dolan, R. Hartleb, T. Dawson, S. Christofferson, \
A. Tucker, T. Fumal, R. Langridge, H. Stenner, W. Lettis, J. Bachhuber, \
and W. Page (2002). The Surface Rupture and Slip Distribution of the \
17 August 1999 Izmit Earthquake (M 7.4), North Anatolian Fault, Bull. \
Seism. Soc. Am. 92, 43-60.
    29.33760 40.70985 0
    29.51528 40.72733 0
    29.51528 40.72933 20
    29.33760 40.71185 20
    29.33760 40.70985 0
    >
    29.61152 40.70513 0
    29.87519 40.74903 0
    29.87519 40.75103 20
    29.61152 40.70713 20
    29.61152 40.70513 0
    >
    29.88662 40.72582 0
    30.11126 40.72336 0
    30.19265 40.73432 0
    30.19265 40.73632 20
    30.11126 40.72536 20
    29.88662 40.72782 20
    29.88662 40.72582 0
    >
    30.30494 40.71210 0
    30.46540 40.71081 0
    30.56511 40.70739 0
    30.56511 40.70939 20
    30.46540 40.71281 20
    30.30494 40.71410 20
    30.30494 40.71210 0
    >
    30.57658 40.71621 0
    30.63731 40.70068 0
    30.63731 40.70268 20
    30.57658 40.71821 20
    30.57658 40.71621 0
    >
    30.72900 40.69947 0
    30.93655 40.79654 0
    30.93655 40.79854 20
    30.72900 40.70147 20
    30.72900 40.69947 0
    >
    30.94688 40.80199 0
    31.01799 40.84501 0
    31.01799 40.84701 20
    30.94688 40.80399 20
    30.94688 40.80199 0"""  # noqa

    # Rupture requires an origin even when not used:
    origin = Origin({'id': 'test',
                     'lon': 0, 'lat': 0,
                     'depth': 5.0, 'mag': 7.0, 'netid': 'us',
                     'network': '', 'locstring': '',
                     'time': HistoricTime.utcfromtimestamp(time.time())})
    cbuf = io.StringIO(rupture_text)
    rupture = get_rupture(origin, cbuf)
    strike = rupture.getStrike()
    np.testing.assert_allclose(strike, -100.46, atol=0.01)
    dip = rupture.getDip()
    np.testing.assert_allclose(dip, 89.40, atol=0.01)
    L = rupture.getLength()
    np.testing.assert_allclose(L, 119.56, atol=0.01)
    W = rupture.getWidth()
    np.testing.assert_allclose(W, 20.0, atol=0.01)
    nq = rupture.getNumQuads()
    np.testing.assert_allclose(nq, 9)
    ng = rupture.getNumGroups()
    np.testing.assert_allclose(ng, 7)
    sind = rupture._getGroupIndex()
    np.testing.assert_allclose(sind, [0, 1, 2, 2, 3, 3, 4, 5, 6])
    ztor = rupture.getDepthToTop()
    np.testing.assert_allclose(ztor, 0, atol=0.01)
    itl = rupture.getIndividualTopLengths()
    itl_d = np.array([15.13750778,  22.80237887,  18.98053425,   6.98263853,
                      13.55978731,   8.43444811,   5.41399812,  20.57788056,
                      7.66869463])
    np.testing.assert_allclose(itl, itl_d, atol=0.01)
    iw = rupture.getIndividualWidths()
    iw_d = np.array([20.00122876,  20.00122608,  20.00120173,  20.00121028,
                     20.00121513,  20.00121568,  20.00107293,  20.00105498,
                     20.00083348])
    np.testing.assert_allclose(iw, iw_d, atol=0.01)
    lats = rupture.lats
    lats_d = np.array([40.72733,  40.70985,  40.71185,  40.72932969,
                       40.72733,          np.nan,  40.74903,  40.70513,
                       40.70713,  40.75102924,  40.74903,          np.nan,
                       40.72336,  40.72582,  40.72336,  40.72536,
                       40.72782,  40.72536004,  40.72336,          np.nan,
                       40.71081,  40.7121,  40.71081,  40.71281,
                       40.7141,  40.71281002,  40.71081,          np.nan,
                       40.70068,  40.71621,  40.71821,  40.70268025,
                       40.70068,          np.nan,  40.79654,  40.69947,
                       40.70147,  40.79853872,  40.79654,          np.nan,
                       40.84501,  40.80199,  40.80399,  40.84700952,
                       40.84501,          np.nan])
    np.testing.assert_allclose(lats, lats_d, atol=0.001)
    lons = rupture.lons
    lons_d = np.array([29.51528,  29.3376,  29.3376,  29.51528005,
                       29.51528,          np.nan,  29.87519,  29.61152,
                       29.61152,  29.87519021,  29.87519,          np.nan,
                       30.11126,  29.88662,  30.11126,  30.11126,
                       29.88662,  30.11126,  30.11126,          np.nan,
                       30.4654,  30.30494,  30.4654,  30.4654,
                       30.30494,  30.4654,  30.4654,          np.nan,
                       30.63731,  30.57658,  30.57658,  30.63731011,
                       30.63731,          np.nan,  30.93655,  30.729,
                       30.729,  30.93655103,  30.93655,          np.nan,
                       31.01799,  30.94688,  30.94688,  31.0179905,
                       31.01799,          np.nan])

    np.testing.assert_allclose(lons, lons_d, atol=0.001)
Example #34
0
def test_QuadRupture():

    # Rupture requires an origin even when not used:
    origin = Origin({'id': 'test',
                     'lon': 0, 'lat': 0,
                     'depth': 5.0, 'mag': 7.0, 'netid': 'us',
                     'network': '', 'locstring': '',
                     'time': HistoricTime.utcfromtimestamp(time.time())})

    # First with json file
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rupj = get_rupture(origin, file)
    # Then with text file:
    file = os.path.join(homedir, 'rupture_data/Barkaetal02_fault.txt')
    rupt = get_rupture(origin, file)

    np.testing.assert_allclose(rupj.lats, rupt.lats, atol=1e-5)
    np.testing.assert_allclose(rupj.lons, rupt.lons, atol=1e-5)
    np.testing.assert_allclose(rupj._depth, rupt._depth, atol=1e-5)
    np.testing.assert_allclose(rupt.getArea(), 2391.2822653900268, atol=1e-5)

    target = np.array(
        [29.51528,  29.3376,  29.3376,  29.51528005,
         29.51528,       np.nan,  29.87519,  29.61152,
         29.61152,  29.87519021,  29.87519,       np.nan,
         30.11126,  29.88662,  30.11126,  30.11126,
         29.88662,  30.11126,  30.11126,       np.nan,
         30.4654,  30.30494,  30.4654,  30.4654,
         30.30494,  30.4654,  30.4654,       np.nan,
         30.63731,  30.57658,  30.57658,  30.63731011,
         30.63731,       np.nan,  30.93655,  30.729,
         30.729,  30.93655103,  30.93655,       np.nan,
         31.01799,  30.94688,  30.94688,  31.0179905,
         31.01799,       np.nan]
    )
    np.testing.assert_allclose(rupj.lons, target, atol=1e-5)
    target = np.array(
        [40.72733,  40.70985,  40.71185,  40.72932969,
         40.72733,       np.nan,  40.74903,  40.70513,
         40.70713,  40.75102924,  40.74903,       np.nan,
         40.72336,  40.72582,  40.72336,  40.72536,
         40.72782,  40.72536004,  40.72336,       np.nan,
         40.71081,  40.7121,  40.71081,  40.71281,
         40.7141,  40.71281002,  40.71081,       np.nan,
         40.70068,  40.71621,  40.71821,  40.70268025,
         40.70068,       np.nan,  40.79654,  40.69947,
         40.70147,  40.79853872,  40.79654,       np.nan,
         40.84501,  40.80199,  40.80399,  40.84700952,
         40.84501,       np.nan]
    )
    np.testing.assert_allclose(rupj.lats, target, atol=1e-5)
    target = np.array(
        [-0.00000000e+00,  -0.00000000e+00,   2.00000000e+01,
         1.99999325e+01,  -0.00000000e+00,           np.nan,
         -9.31322575e-13,  -0.00000000e+00,   2.00000000e+01,
         1.99998304e+01,  -9.31322575e-13,           np.nan,
         9.31322575e-13,  -0.00000000e+00,   9.31322575e-13,
         2.00000000e+01,   2.00000000e+01,   2.00000095e+01,
         9.31322575e-13,           np.nan,  -0.00000000e+00,
         -0.00000000e+00,  -0.00000000e+00,   2.00000000e+01,
         2.00000000e+01,   2.00000050e+01,  -0.00000000e+00,
         np.nan,  -0.00000000e+00,  -0.00000000e+00,
         2.00000000e+01,   2.00000600e+01,  -0.00000000e+00,
         np.nan,  -0.00000000e+00,  -0.00000000e+00,
         2.00000000e+01,   1.99996249e+01,  -0.00000000e+00,
         np.nan,  -0.00000000e+00,  -0.00000000e+00,
         2.00000000e+01,   1.99998338e+01,  -0.00000000e+00,
         np.nan])
    np.testing.assert_allclose(rupj.depths, target, atol=1e-5)
Example #35
0
def test_EdgeRupture():

    # Rupture requires an origin even when not used:
    origin = Origin({'id': 'test',
                     'lon': 0, 'lat': 0,
                     'depth': 5.0, 'mag': 7.0, 'netid': 'us',
                     'network': '', 'locstring': '',
                     'time': HistoricTime.utcfromtimestamp(time.time())})

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup = get_rupture(origin, file)
    np.testing.assert_allclose(rup.getArea(), 105635.92827547337)

    # Force read Northridge as EdgeRupture
    file = os.path.join(homedir, 'rupture_data/northridge_fault.txt')
    d = text_to_json(file, new_format=True)
    rupt = EdgeRupture(d, origin)
    strike = rupt.getStrike()
    np.testing.assert_allclose(strike, 121.97, atol=0.01)
    dip = rupt.getDip()
    np.testing.assert_allclose(dip, 40.12, atol=0.01)
    L = rupt.getLength()
    np.testing.assert_allclose(L, 17.99, atol=0.01)
    W = rupt.getWidth()
    np.testing.assert_allclose(W, 23.92, atol=0.01)
    ztor = rupt.getDepthToTop()
    np.testing.assert_allclose(ztor, 5, atol=0.01)

    # And again for the same vertices but reversed order
    file = os.path.join(homedir, 'rupture_data/northridge_fixed_fault.txt')
    d = text_to_json(file, new_format=True)
    rupt = EdgeRupture(d, origin)
    strike = rupt.getStrike()
    np.testing.assert_allclose(strike, 121.97, atol=0.01)
    dip = rupt.getDip()
    np.testing.assert_allclose(dip, 40.12, atol=0.01)
    L = rupt.getLength()
    np.testing.assert_allclose(L, 17.99, atol=0.01)
    W = rupt.getWidth()
    np.testing.assert_allclose(W, 23.92, atol=0.01)
    ztor = rupt.getDepthToTop()
    np.testing.assert_allclose(ztor, 5, atol=0.01)

    # Test for fromArrays method
    toplats = np.array([37.0, 38.0])
    toplons = np.array([-120.0, -120.0])
    topdeps = np.array([0.0, 0.0])
    botlats = copy.copy(toplats)
    botlons = copy.copy(toplons)
    botdeps = np.array([10.0, 10.0])
    erup = EdgeRupture.fromArrays(toplons, toplats, topdeps, botlons, botlats,
                                  botdeps, origin)
    # Error: array lengths differ
    with pytest.raises(ShakeLibException) as e:
        qrup = QuadRupture.fromVertices(
            [toplons[0]], [toplats[0]], [topdeps[0]],
            [toplons[1]], [toplats[1]], [topdeps[1]],
            [botlons[1]], [botlats[1]], [botdeps[1]],
            [botlons[0]], [botlats[0]], [botdeps[0]][:-1],
            origin)
    print(str(e))

    # Error: group index too long
    with pytest.raises(ShakeLibException) as e:
        qrup = QuadRupture.fromVertices(
            [toplons[0]], [toplats[0]], [topdeps[0]],
            [toplons[1]], [toplats[1]], [topdeps[1]],
            [botlons[1]], [botlats[1]], [botdeps[1]],
            [botlons[0]], [botlats[0]], [botdeps[0]],
            origin, group_index=[0, 0, 0, 0, 0, 0])
    print(str(e))

    qrup = QuadRupture.fromVertices(
        [toplons[0]], [toplats[0]], [topdeps[0]],
        [toplons[1]], [toplats[1]], [topdeps[1]],
        [botlons[1]], [botlats[1]], [botdeps[1]],
        [botlons[0]], [botlats[0]], [botdeps[0]],
        origin)
    np.testing.assert_allclose(erup.getArea(), 1108.9414759967776)
    np.testing.assert_allclose(erup.getDepthToTop(), 0)
    np.testing.assert_allclose(erup.getLength(), 111.19492664455889)
    np.testing.assert_allclose(
        erup.lats, np.array([37.,  38.,  38.,  37.,  37.,  np.nan]))
    np.testing.assert_allclose(
        erup.lons, np.array([-120., -120., -120., -120., -120.,  np.nan]))
    np.testing.assert_allclose(
        erup.depths, np.array([0.,   0.,  10.,  10.,   0.,  np.nan]))
    np.testing.assert_allclose(
        erup._getGroupIndex(), np.array([0.,   0.]))
    quads = erup.getQuadrilaterals()
    np.testing.assert_allclose(quads[0][0].x, -120.0)

    # Need to also test the distances with EdgeRupture
    lons = np.linspace(-120.1, -121.0, 10)
    lats = np.linspace(37.0, 38, 10)
    deps = np.zeros_like(lons)
    rrup1, _ = qrup.computeRrup(lons, lats, deps)
    rrup2, _ = erup.computeRrup(lons, lats, deps)
    np.testing.assert_allclose(rrup1, rrup2, atol=2e-2)
    rjb1, _ = qrup.computeRjb(lons, lats, deps)
    rjb2, _ = erup.computeRjb(lons, lats, deps)
    np.testing.assert_allclose(rjb1, rjb2, atol=2e-2)
    gc2 = erup.computeGC2(lons, lats, deps)
    targetRy0 = np.array(
        [0., 0.,  0., 0.,  0.,
         0., 0.,  0., 0.,  0.67335931])
    targetRx = np.array(
        [-8.88024949, -17.73390996, -26.56167797, -35.3634266,
         -44.13902929, -52.88835984, -61.61129242, -70.30770154,
         -78.97746209, -87.6204493])
    np.testing.assert_allclose(gc2['ry0'], targetRy0)
    np.testing.assert_allclose(gc2['rx'], targetRx)
Example #36
0
def test_rupture_from_dict():

    # Grab an EdgeRupture
    origin = Origin({'id': 'test', 'lat': 0, 'lon': 0, 'depth': 5.0,
                     'mag': 7.0, 'netid': 'us', 'network': '',
                     'locstring': '', 'time':
                     HistoricTime.utcfromtimestamp(time.time())})

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 0.5

    # Specify mesh_dx
    rup_original = get_rupture(origin, file, mesh_dx=1.0)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 1.0

    # Quad rupture
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.getArea() == rup_original.getArea()
    # Note, there's a bit of an inconsistency highlighted here because
    # magnitude has key 'magnitude' in the izmit file, but 'mag' in
    # the origin and both get retained.

    # Point rupture from json
    file = os.path.join(homedir, 'rupture_data/point.json')
    rup = get_rupture(origin, file)
    assert rup.lats == 0
    assert rup.lons == 0

    # Point rupture
    origin = Origin({
        'id': 'test',
        'lon': -122.5, 'lat': 37.3,
        'depth': 5.0, 'mag': 7.0, 'netid': 'us',
        'network': '', 'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    rup_original = get_rupture(origin)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.lats == 37.3
    assert rup_from_dict.lons == -122.5

    assert rup_original.getLength() is None
    assert rup_original.getWidth() == constants.DEFAULT_WIDTH
    assert rup_original.getArea() is None
    assert rup_original.getStrike() == constants.DEFAULT_STRIKE
    assert rup_original.getDip() == constants.DEFAULT_DIP
    assert rup_original.getDepthToTop() == constants.DEFAULT_ZTOR
    assert rup_original.getQuadrilaterals() is None
    assert rup_original.depths == 5.0
    # No mech, no tectonic region
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [42.757296, 46.614723])
    else:
        print(rjb[0], rrup[0])
    # Various combinations of mech and tectonic region...
    rup_original._origin._tectonic_region = 'Active Shallow Crust'
    rup_original._origin.mech = 'ALL'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [42.757296, 46.614723])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'RS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [39.779893, 44.033556])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'NM'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [40.937772, 45.254891])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'SS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [46.750567, 48.108934])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin._tectonic_region = 'Stable Shallow Crust'
    rup_original._origin.mech = 'ALL'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [43.676648, 48.008276])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'RS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [42.445057, 46.865434])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'NM'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [43.233314, 47.563079])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin.mech = 'SS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [47.829729, 50.087485])
    else:
        print(rjb[0], rrup[0])
    rup_original._origin._tectonic_region = 'Somewhere Else'
    rup_original._origin.mech = 'ALL'
    rjb, var = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    rrup, var = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                         np.array([0.0]))
    if do_tests is True:
        np.testing.assert_allclose([rjb[0], rrup[0]],
                                   [42.757296, 46.614723])
    else:
        print(rjb[0], rrup[0])

    # This is just zeroes now, so there's not much to check
    gc2 = rup_original.computeGC2(np.array([-122.0]), np.array([37.0]),
                                  np.array([0.0]))
    assert gc2['rx'][0] == 0
def main():
    """
    Read in data and add comcat IDs, download rupture file if available.
    """
    eq_df = pd.read_csv(EVENT_FILE, sep=" ", header=None, names=EVENT_COLS)
    eq_df['comcat_id'] = ''
    nrows = eq_df.shape[0]

    for i in range(nrows):
        print('i = %i' % i)

        eqmag = float(eq_df['mag'][i])
        dmag = 0.3
        min_mag = eqmag - dmag
        max_mag = eqmag + dmag

        edate = eq_df['date'][i]
        etime = eq_df['time'][i]
        edatetime = edate + ' ' + etime

        eqdatetime = datetime.datetime.strptime(edatetime, '%Y/%m/%d %H:%M:%S')
        start_time = eqdatetime - datetime.timedelta(1)  # -1 day
        end_time = eqdatetime + datetime.timedelta(1)  # +1 day

        dll = 0.1
        eq_lat = float(eq_df['lat'][i])
        min_latitude = eq_lat - dll
        max_latitude = eq_lat + dll

        eq_lon = float(eq_df['lon'][i])
        min_longitude = eq_lon - dll
        max_longitude = eq_lon + dll

        summary_list = search(starttime=start_time,
                              endtime=end_time,
                              minlatitude=min_latitude,
                              maxlatitude=max_latitude,
                              minlongitude=min_longitude,
                              maxlongitude=max_longitude,
                              minmagnitude=min_mag,
                              maxmagnitude=max_mag)

        if len(summary_list):
            summary_event = summary_list[0]
            detail = summary_event.getDetailEvent()
            eq_df.at[i, 'comcat_id'] = detail.id

            if (eqmag >= 5.5) & (detail.hasProduct('shakemap')):
                outdir = os.path.join('..', 'data', 'ruptures', detail.id)
                if not os.path.exists(outdir):
                    os.makedirs(outdir)
                shake = detail.getProducts('shakemap', source='preferred')[0]
                outfile = os.path.join(outdir, 'rupture.json')
                shake.getContent('rupture.json', outfile)

                # If it is a point source, no need for it so remove it.
                rup = get_rupture(origin, outfile)
                if isinstance(rup, PointRupture):
                    shutil.rmtree(outdir)

        new_file = 'events_comcat.csv'
        eq_df.to_csv(new_file, index=True)
Example #38
0
def test_QuadRupture():
    # Rupture requires an origin even when not used:
    origin = Origin({'eventsourcecode': 'test', 'lat': 0, 'lon': 0,
                     'depth': 5.0, 'mag': 7.0})

    # First with json file
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rupj = get_rupture(origin, file)
    # Then with text file:
    file = os.path.join(homedir, 'rupture_data/Barkaetal02_fault.txt')
    rupt = get_rupture(origin, file)

    np.testing.assert_allclose(rupj.lats, rupt.lats, atol=1e-5)
    np.testing.assert_allclose(rupj.lons, rupt.lons, atol=1e-5)
    np.testing.assert_allclose(rupj._depth, rupt._depth, atol=1e-5)
    np.testing.assert_allclose(rupt.getArea(), 2391282.2653900268, atol=1e-5)

    target = np.array(
        [29.51528,  29.3376,  29.3376,  29.51528005,
         29.51528,       np.nan,  29.87519,  29.61152,
         29.61152,  29.87519021,  29.87519,       np.nan,
         30.11126,  29.88662,  30.11126,  30.11126,
         29.88662,  30.11126,  30.11126,       np.nan,
         30.4654,  30.30494,  30.4654,  30.4654,
         30.30494,  30.4654,  30.4654,       np.nan,
         30.63731,  30.57658,  30.57658,  30.63731011,
         30.63731,       np.nan,  30.93655,  30.729,
         30.729,  30.93655103,  30.93655,       np.nan,
         31.01799,  30.94688,  30.94688,  31.0179905,
         31.01799,       np.nan]
    )
    np.testing.assert_allclose(rupj.lons, target, atol=1e-5)
    target = np.array(
        [40.72733,  40.70985,  40.71185,  40.72932969,
         40.72733,       np.nan,  40.74903,  40.70513,
         40.70713,  40.75102924,  40.74903,       np.nan,
         40.72336,  40.72582,  40.72336,  40.72536,
         40.72782,  40.72536004,  40.72336,       np.nan,
         40.71081,  40.7121,  40.71081,  40.71281,
         40.7141,  40.71281002,  40.71081,       np.nan,
         40.70068,  40.71621,  40.71821,  40.70268025,
         40.70068,       np.nan,  40.79654,  40.69947,
         40.70147,  40.79853872,  40.79654,       np.nan,
         40.84501,  40.80199,  40.80399,  40.84700952,
         40.84501,       np.nan]
    )
    np.testing.assert_allclose(rupj.lats, target, atol=1e-5)
    target = np.array(
        [-0.00000000e+00,  -0.00000000e+00,   2.00000000e+01,
         1.99999325e+01,  -0.00000000e+00,           np.nan,
         -9.31322575e-13,  -0.00000000e+00,   2.00000000e+01,
         1.99998304e+01,  -9.31322575e-13,           np.nan,
         9.31322575e-13,  -0.00000000e+00,   9.31322575e-13,
         2.00000000e+01,   2.00000000e+01,   2.00000095e+01,
         9.31322575e-13,           np.nan,  -0.00000000e+00,
         -0.00000000e+00,  -0.00000000e+00,   2.00000000e+01,
         2.00000000e+01,   2.00000050e+01,  -0.00000000e+00,
         np.nan,  -0.00000000e+00,  -0.00000000e+00,
         2.00000000e+01,   2.00000600e+01,  -0.00000000e+00,
         np.nan,  -0.00000000e+00,  -0.00000000e+00,
         2.00000000e+01,   1.99996249e+01,  -0.00000000e+00,
         np.nan,  -0.00000000e+00,  -0.00000000e+00,
         2.00000000e+01,   1.99998338e+01,  -0.00000000e+00,
         np.nan])
    np.testing.assert_allclose(rupj.depths, target, atol=1e-5)
Example #39
0
def append_rup_info(shake_df):
    # Add columns for things we will populate
    shake_df['ztor'] = np.nan
    shake_df['dip'] = np.nan
    shake_df['width'] = np.nan
    shake_df['r_rup'] = np.nan
    shake_df['r_rup_var'] = np.nan
    shake_df['r_jb'] = np.nan
    shake_df['r_jb_var'] = np.nan
    shake_df['r_x'] = np.nan
    shake_df['r_y'] = np.nan
    shake_df['r_y0'] = np.nan

    eq_df = pd.read_csv(EVENT_FILE)
    hist_eq_df = pd.read_csv(
        HIST_FILE, sep=' ', header=None, names=HIST_COLS)

    # Event dictionary template
    edict = {
        'mag': np.nan,
        'id': 'dummy',
        'locstring': 'dummy',
        'mech': 'ALL',
        'lon': np.nan,
        'lat': np.nan,
        'depth': np.nan,
        'netid': "",
        'network': "",
        'time': ""
    }

    # -------------------------------------------------------------------------
    # First do historic events
    print('Historic events...')
    n_hist = hist_eq_df.shape[0]
    for i in range(n_hist):
        print('    i = %s of %s' % (i, n_hist))
        ref_id = hist_eq_df['id'][i]
        com_id = hist_eq_df['comcat_id'][i]

        # Make an origin
        edict['mag'] = hist_eq_df['magnitude'][i]
        edict['lon'] = hist_eq_df['lon'][i]
        edict['lat'] = hist_eq_df['lat'][i]
        edict['depth'] = hist_eq_df['dep'][i]
        origin = Origin(edict)

        # Is there a comcat id?
        if isinstance(com_id, str):
            # Is there a rupture?
            rup_dir = os.path.abspath(os.path.join('ruptures', com_id))
            if os.path.exists(rup_dir):
                rup_file = os.path.join(rup_dir, 'rupture.json')
                rup = get_rupture(origin, rup_file)
            else:
                # No rupture file, so make a point rupture:
                rup = get_rupture(origin)

            # Things that don't need sites
            ztor = rup.getDepthToTop()
            dip = rup.getDip()
            width = rup.getWidth()

            # Get site lat/lons for this eqk
            idx = np.where(shake_df['event_id'] == ref_id)[0]
            if len(idx):
                sta_lat = np.array(shake_df['sta_lat'][idx])
                sta_lon = np.array(shake_df['sta_lon'][idx])
                rjb, rjb_var = rup.computeRjb(
                    sta_lon, sta_lat, np.zeros_like(sta_lat))
                rrup, rrup_var = rup.computeRrup(
                    sta_lon, sta_lat, np.zeros_like(sta_lat))
                gc2_dict = rup.computeGC2(
                    sta_lon, sta_lat, np.zeros_like(sta_lat))

                shake_df.at[idx, 'ztor'] = ztor
                shake_df.at[idx, 'dip'] = dip
                shake_df.at[idx, 'width'] = width
                shake_df.at[idx, 'r_rup'] = rrup
                shake_df.at[idx, 'r_rup_var'] = rrup_var
                shake_df.at[idx, 'r_jb'] = rjb
                shake_df.at[idx, 'r_jb_var'] = rjb_var
                shake_df.at[idx, 'r_x'] = gc2_dict['rx']
                shake_df.at[idx, 'r_y'] = gc2_dict['ry']
                shake_df.at[idx, 'r_y0'] = gc2_dict['ry0']

    # -------------------------------------------------------------------------
    # Now do the rest
    print('Non-historic events...')
    n_events = eq_df.shape[0]
    for i in range(n_events):
        print('    i = %s of %s' % (i, n_events))
        ref_id = eq_df['id'][i]
        com_id = eq_df['comcat_id'][i]

        # Make an origin
        edict['mag'] = eq_df['mag'][i]
        edict['lon'] = eq_df['lon'][i]
        edict['lat'] = eq_df['lat'][i]
        edict['depth'] = eq_df['dep'][i]
        origin = Origin(edict)

        # Is there a comcat id?
        if isinstance(com_id, str):
            # Is there a rupture?
            rup_dir = os.path.abspath(os.path.join('ruptures', com_id))
            if os.path.exists(rup_dir):
                rup_file = os.path.join(rup_dir, 'rupture.json')
                rup = get_rupture(origin, rup_file)
            else:
                # No rupture file, so make a point rupture:
                rup = get_rupture(origin)

            # Things that don't need sites
            ztor = rup.getDepthToTop()
            dip = rup.getDip()
            width = rup.getWidth()

            # Get site lat/lons for this eqk
            idx = np.where(shake_df['event_id'] == ref_id)[0]
            if len(idx):
                sta_lat = np.array(shake_df['sta_lat'][idx])
                sta_lon = np.array(shake_df['sta_lon'][idx])
                rjb, rjb_var = rup.computeRjb(
                    sta_lon, sta_lat, np.zeros_like(sta_lat))
                rrup, rrup_var = rup.computeRrup(
                    sta_lon, sta_lat, np.zeros_like(sta_lat))
                gc2_dict = rup.computeGC2(
                    sta_lon, sta_lat, np.zeros_like(sta_lat))

                shake_df.at[idx, 'ztor'] = ztor
                shake_df.at[idx, 'dip'] = dip
                shake_df.at[idx, 'width'] = width
                shake_df.at[idx, 'r_rup'] = rrup
                shake_df.at[idx, 'r_rup_var'] = rrup_var
                shake_df.at[idx, 'r_jb'] = rjb
                shake_df.at[idx, 'r_jb_var'] = rjb_var
                shake_df.at[idx, 'r_x'] = gc2_dict['rx']
                shake_df.at[idx, 'r_y'] = gc2_dict['ry']
                shake_df.at[idx, 'r_y0'] = gc2_dict['ry0']

    return shake_df
Example #40
0
def test_virtualipe():

    #
    # Set up the GMPE, IPE, and GMICE
    #
    gmpe_cy14 = ChiouYoungs2014()
    gmpe = MultiGMPE.from_list([gmpe_cy14], [1.0])
    gmice = WGRW12()
    ipe = VirtualIPE.fromFuncs(gmpe, gmice)

    #
    # Use the Calexico event info
    #
    homedir = os.path.dirname(os.path.abspath(__file__))
    datadir = os.path.abspath(
        os.path.join(homedir, 'virtualipe_data', 'Calexico', 'input'))

    #
    # Read the event, origin, and rupture files and produce Rupture and Origin
    # objects
    #
    # inputfile = os.path.join(datadir, 'stationlist_dat.xml')
    # dyfifile = os.path.join(datadir, 'ciim3_dat.xml')
    eventfile = os.path.join(datadir, 'event.xml')
    rupturefile = os.path.join(datadir, 'wei_fault.txt')

    origin_obj = Origin.fromFile(eventfile)
    rupture_obj = get_rupture(origin_obj, rupturefile)
    rx = rupture_obj.getRuptureContext([gmpe])
    rx.rake = 45.

    smdx = 0.0083333333
    smdy = 0.0083333333
    lonspan = 6.0
    latspan = 4.0
    vs30filename = os.path.join(datadir, '..', 'vs30', 'vs30.grd')

    sites_obj_grid = Sites.fromCenter(rx.hypo_lon,
                                      rx.hypo_lat,
                                      lonspan,
                                      latspan,
                                      smdx,
                                      smdy,
                                      defaultVs30=760.0,
                                      vs30File=vs30filename,
                                      vs30measured_grid=None,
                                      padding=False,
                                      resample=False)

    npts = 200
    lats = np.empty(npts)
    lons = np.empty(npts)
    depths = np.zeros(npts)
    for i in range(npts):
        lats[i] = rx.hypo_lat
        lons[i] = rx.hypo_lon + i * 0.01
    lldict = {'lats': lats, 'lons': lons}

    sx = sites_obj_grid.getSitesContext(lldict=lldict, rock_vs30=760.0)

    dobj = Distance(gmpe, lons, lats, depths, rupture_obj)
    dx = dobj.getDistanceContext()

    sd_types = [oqconst.StdDev.TOTAL]
    mmi_const_vs30, mmi_sd_const_vs30 = \
        ipe.get_mean_and_stddevs(sx, rx, dx, MMI(), sd_types)

    # These prints are just so a human can examine the outputs
    #    print(mmi_const_vs30)
    #    print(mmi_sd_const_vs30)

    sx = sites_obj_grid.getSitesContext(lldict=lldict)
    mmi_variable_vs30, mmi_sd_variable_vs30 = \
        ipe.get_mean_and_stddevs(sx, rx, dx, MMI(), sd_types)

    #    print(mmi_variable_vs30)
    #    print(mmi_sd_variable_vs30)

    sd_types = [
        oqconst.StdDev.TOTAL, oqconst.StdDev.INTRA_EVENT,
        oqconst.StdDev.INTER_EVENT
    ]
    mmi_variable_vs30_intra, mmi_sd_variable_vs30_intra = \
        ipe.get_mean_and_stddevs(sx, rx, dx, MMI(), sd_types)

    #    print(mmi_variable_vs30_intra)
    #    print(mmi_sd_variable_vs30_intra)
    #    assert(0)      # Assert causes test to fail and prints to be displayed

    #
    # Try with PGA
    #
    gmpe.DEFINED_FOR_INTENSITY_MEASURE_TYPES.remove(PGV)
    gmpe.ALL_GMPES_HAVE_PGV = False
    ipe = VirtualIPE.fromFuncs(gmpe, gmice)
    mmi_pga, mmi_sd_pga = \
        ipe.get_mean_and_stddevs(sx, rx, dx, MMI(), sd_types)
    #
    # Try with SA(1.0)
    #
    gmpe.DEFINED_FOR_INTENSITY_MEASURE_TYPES.remove(PGA)
    ipe = VirtualIPE.fromFuncs(gmpe, gmice)
    mmi_psa, mmi_sd_psa = \
        ipe.get_mean_and_stddevs(sx, rx, dx, MMI(), sd_types)

    #
    # This should raise an exception because the IMT isn't MMI
    #
    with pytest.raises(ValueError) as e:
        mmi_psa, mmi_sd_psa = \
            ipe.get_mean_and_stddevs(sx, rx, dx, PGA(), sd_types)
    #
    # This should raise an exception because no valid IMTs are available
    #
    gmpe.DEFINED_FOR_INTENSITY_MEASURE_TYPES.remove(SA)
    with pytest.raises(ShakeLibException) as e:  # noqa
        ipe = VirtualIPE.fromFuncs(gmpe, gmice)

    #
    # Now do a GMPE that uses Rjb instead of Rrup
    #
    gmpe_ba14 = BooreEtAl2014()
    gmpe = MultiGMPE.from_list([gmpe_ba14], [1.0])
    ipe = VirtualIPE.fromFuncs(gmpe, gmice)
    rx = rupture_obj.getRuptureContext([gmpe])
    rx.rake = 45.
    dobj = Distance(gmpe, lons, lats, depths, rupture_obj)
    dx = dobj.getDistanceContext()

    mmi_rjb, mmi_sd_rjb = \
        ipe.get_mean_and_stddevs(sx, rx, dx, MMI(), sd_types)

    #
    # Test the results against a known standard
    #
    savefile = os.path.abspath(
        os.path.join(homedir, 'virtualipe_data', 'Calexico', 'virtualipe_test',
                     'savefile.npz'))

    #
    # If things change, set remake_save to True, and it will rebuild the
    # saved data file against which the comparisons are done
    # Remember to set this back to False once you've remade the test datafile
    #
    remake_save = False
    if remake_save:
        np.savez_compressed(
            savefile,
            mmi_const_vs30=mmi_const_vs30,
            mmi_sd_const_vs30=mmi_sd_const_vs30[0],
            mmi_variable_vs30=mmi_variable_vs30,
            mmi_sd_variable_vs30=mmi_sd_variable_vs30[0],
            mmi_variable_vs30_intra=mmi_variable_vs30_intra,
            mmi_sd_variable_vs30_total=mmi_sd_variable_vs30_intra[0],
            mmi_sd_variable_vs30_intra=mmi_sd_variable_vs30_intra[1],
            mmi_sd_variable_vs30_inter=mmi_sd_variable_vs30_intra[2],
            mmi_pga=mmi_pga,
            mmi_sd_pga=mmi_sd_pga[0],
            mmi_psa=mmi_psa,
            mmi_sd_psa=mmi_sd_psa[0],
            mmi_rjb=mmi_rjb,
            mmi_sd_rjb=mmi_sd_rjb[0])

    td = np.load(savefile)

    assert (np.allclose(td['mmi_const_vs30'], mmi_const_vs30))
    assert (np.allclose(td['mmi_sd_const_vs30'], mmi_sd_const_vs30[0]))
    assert (np.allclose(td['mmi_variable_vs30'], mmi_variable_vs30))
    assert (np.allclose(td['mmi_sd_variable_vs30'], mmi_sd_variable_vs30[0]))
    assert (np.allclose(td['mmi_variable_vs30_intra'],
                        mmi_variable_vs30_intra))
    assert (np.allclose(td['mmi_sd_variable_vs30_total'],
                        mmi_sd_variable_vs30_intra[0]))
    assert (np.allclose(td['mmi_sd_variable_vs30_intra'],
                        mmi_sd_variable_vs30_intra[1]))
    assert (np.allclose(td['mmi_sd_variable_vs30_inter'],
                        mmi_sd_variable_vs30_intra[2]))
    assert (np.allclose(td['mmi_pga'], mmi_pga))
    assert (np.allclose(td['mmi_sd_pga'], mmi_sd_pga[0]))
    assert (np.allclose(td['mmi_psa'], mmi_psa))
    assert (np.allclose(td['mmi_sd_psa'], mmi_sd_psa[0]))
    assert (np.allclose(td['mmi_rjb'], mmi_rjb))
    assert (np.allclose(td['mmi_sd_rjb'], mmi_sd_rjb[0]))

    # The total uncertainties should be greater than the intra-event
    assert (np.all(mmi_sd_variable_vs30[0] > mmi_sd_variable_vs30_intra[1]))

    # The combined intra and inter-event uncertainty should be equal
    # to the total
    tot = np.sqrt(mmi_sd_variable_vs30_intra[1]**2 +
                  mmi_sd_variable_vs30_intra[2]**2)
    assert (np.allclose(tot, mmi_sd_variable_vs30_intra[0], rtol=1e-2))
Example #41
0
def test_rupture_from_dict():

    # Grab an EdgeRupture
    origin = Origin({
        'id': 'test',
        'lat': 0,
        'lon': 0,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    file = os.path.join(homedir, 'rupture_data/cascadia.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 0.5

    # Specify mesh_dx
    rup_original = get_rupture(origin, file, mesh_dx=1.0)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict._mesh_dx == 1.0

    # Quad rupture
    file = os.path.join(homedir, 'rupture_data/izmit.json')
    rup_original = get_rupture(origin, file)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.getArea() == rup_original.getArea()
    # Note, there's a bit of an inconsistency highlighted here because
    # magnitude has key 'magnitude' in the izmit file, but 'mag' in
    # the origin and both get retained.

    # Point rupture from json
    file = os.path.join(homedir, 'rupture_data/point.json')
    rup = get_rupture(origin, file)
    assert rup.lats == 0
    assert rup.lons == 0

    # Point rupture
    origin = Origin({
        'id': 'test',
        'lon': -122.5,
        'lat': 37.3,
        'depth': 5.0,
        'mag': 7.0,
        'netid': 'us',
        'network': '',
        'locstring': '',
        'time': HistoricTime.utcfromtimestamp(time.time())
    })

    rup_original = get_rupture(origin)
    d = rup_original._geojson
    rup_from_dict = rupture_from_dict(d)
    assert rup_from_dict.lats == 37.3
    assert rup_from_dict.lons == -122.5

    assert rup_original.getLength() is None
    assert rup_original.getWidth() == constants.DEFAULT_WIDTH
    assert rup_original.getArea() is None
    assert rup_original.getStrike() == constants.DEFAULT_STRIKE
    assert rup_original.getDip() == constants.DEFAULT_DIP
    assert rup_original.getDepthToTop() == constants.DEFAULT_ZTOR
    assert rup_original.getQuadrilaterals() is None
    assert rup_original.depths == 5.0
    # No mech, no tectonic region
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [41.11182253, 42.73956168])
    # Various combinations of mech and tectonic region...
    rup_original._origin._tectonic_region = 'Active Shallow Crust'
    rup_original._origin.mech = 'ALL'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [41.11182253, 42.73956168])
    rup_original._origin.mech = 'RS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [39.17479645, 41.20916362])
    rup_original._origin.mech = 'NM'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [39.85641875, 41.89222387])
    rup_original._origin.mech = 'SS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [43.21392667, 44.04215406])
    rup_original._origin._tectonic_region = 'Stable Shallow Crust'
    rup_original._origin.mech = 'ALL'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [42.68382206, 43.71213495])
    rup_original._origin.mech = 'RS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [42.29766584, 43.51422441])
    rup_original._origin.mech = 'NM'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [42.57075149, 43.7987126])
    rup_original._origin.mech = 'SS'
    rjb, _ = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                     np.array([0.0]))
    rrup, _ = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [44.19126409, 45.02525107])
    rup_original._origin._tectonic_region = 'Somewhere Else'
    rup_original._origin.mech = 'ALL'
    rjb, var = rup_original.computeRjb(np.array([-122.0]), np.array([37.0]),
                                       np.array([0.0]))
    rrup, var = rup_original.computeRrup(np.array([-122.0]), np.array([37.0]),
                                         np.array([0.0]))
    np.testing.assert_allclose([rjb[0], rrup[0]], [41.11182253, 42.73956168])

    # This is just zeroes now, so there's not much to check
    gc2 = rup_original.computeGC2(np.array([-122.0]), np.array([37.0]),
                                  np.array([0.0]))
    assert gc2['rx'][0] == 0