示例#1
0
 def test_flinnengdahl(self):
     """
     Tests calculation of Flinn-Engdahl region code or name.
     """
     client = Client()
     # code
     result = client.flinnengdahl(lat=-20.5, lon=-100.6, rtype="code")
     self.assertEqual(result, 683)
     # w/o kwargs
     result = client.flinnengdahl(-20.5, -100.6, "code")
     self.assertEqual(result, 683)
     # region
     result = client.flinnengdahl(lat=42, lon=-122.24, rtype="region")
     self.assertEqual(result, 'OREGON')
     # w/o kwargs
     result = client.flinnengdahl(42, -122.24, "region")
     self.assertEqual(result, 'OREGON')
     # both
     result = client.flinnengdahl(lat=-20.5, lon=-100.6, rtype="both")
     self.assertEqual(result, (683, 'SOUTHEAST CENTRAL PACIFIC OCEAN'))
     # w/o kwargs
     result = client.flinnengdahl(-20.5, -100.6, "both")
     self.assertEqual(result, (683, 'SOUTHEAST CENTRAL PACIFIC OCEAN'))
     # default rtype
     result = client.flinnengdahl(lat=42, lon=-122.24)
     self.assertEqual(result, (32, 'OREGON'))
     # w/o kwargs
     # outside boundaries
     self.assertRaises(Exception, client.flinnengdahl, lat=-90.1, lon=0)
     self.assertRaises(Exception, client.flinnengdahl, lat=90.1, lon=0)
     self.assertRaises(Exception, client.flinnengdahl, lat=0, lon=-180.1)
     self.assertRaises(Exception, client.flinnengdahl, lat=0, lon=180.1)
示例#2
0
 def test_sacpz(self):
     """
     Fetches SAC poles and zeros information.
     """
     client = Client()
     # 1
     t1 = UTCDateTime("2005-01-01")
     t2 = UTCDateTime("2008-01-01")
     result = client.sacpz("IU", "ANMO", "00", "BHZ", t1, t2)
     # drop lines with creation date (current time during request)
     result = result.splitlines()
     sacpz_file = os.path.join(self.path, 'data', 'IU.ANMO.00.BHZ.sacpz')
     with open(sacpz_file, 'rb') as fp:
         expected = fp.read().splitlines()
     result.pop(5)
     expected.pop(5)
     self.assertEqual(result, expected)
     # 2 - empty location code
     dt = UTCDateTime("2002-11-01")
     result = client.sacpz('UW', 'LON', '', 'BHZ', dt)
     self.assertIn(b"* STATION    (KSTNM): LON", result)
     self.assertIn(b"* LOCATION   (KHOLE):   ", result)
     # 3 - empty location code via '--'
     result = client.sacpz('UW', 'LON', '--', 'BHZ', dt)
     self.assertIn(b"* STATION    (KSTNM): LON", result)
     self.assertIn(b"* LOCATION   (KHOLE):   ", result)
示例#3
0
    def test_timeseries(self):
        """
        Tests timeseries Web service interface.

        Examples are inspired by https://service.iris.edu/irisws/timeseries/1/.
        """
        client = Client()
        # 1
        t1 = UTCDateTime("2005-001T00:00:00")
        t2 = UTCDateTime("2005-001T00:01:00")
        # no filter
        st1 = client.timeseries("IU", "ANMO", "00", "BHZ", t1, t2)
        # instrument corrected
        st2 = client.timeseries("IU",
                                "ANMO",
                                "00",
                                "BHZ",
                                t1,
                                t2,
                                filter=["correct"])
        # compare results
        self.assertEqual(st1[0].stats.starttime, st2[0].stats.starttime)
        self.assertEqual(st1[0].stats.endtime, st2[0].stats.endtime)
        self.assertEqual(st1[0].data[0], 24)
        self.assertAlmostEqual(st2[0].data[0], -2.8373747e-06)
示例#4
0
    def test_resp(self):
        """
        Tests resp Web service interface.

        Examples are inspired by https://service.iris.edu/irisws/resp/1/.
        """
        client = Client()
        # 1
        t1 = UTCDateTime("2005-001T00:00:00")
        t2 = UTCDateTime("2008-001T00:00:00")
        result = client.resp("IU", "ANMO", "00", "BHZ", t1, t2)
        self.assertIn(b'B050F03     Station:     ANMO', result)
        # Exception: No response data available
        # 2 - empty location code
        # result = client.resp("UW", "LON", "", "EHZ")
        # self.assertIn(b'B050F03     Station:     LON', result)
        # self.assertIn(b'B052F03     Location:    ??', result)
        # 3 - empty location code via '--'
        # result = client.resp("UW", "LON", "--", "EHZ")
        # self.assertIn(b'B050F03     Station:     LON', result)
        # self.assertIn(b'B052F03     Location:    ??', result)
        # 4
        dt = UTCDateTime("2010-02-27T06:30:00.000")
        result = client.resp("IU", "ANMO", "*", "*", dt)
        self.assertIn(b'B050F03     Station:     ANMO', result)

        dt = UTCDateTime("2005-001T00:00:00")
        result = client.resp("AK", "RIDG", "--", "LH?", dt)
        self.assertIn(b'B050F03     Station:     RIDG', result)
示例#5
0
 def test_distaz(self):
     """
     Tests distance and azimuth calculation between two points on a sphere.
     """
     client = Client()
     # normal request
     result = client.distaz(stalat=1.1, stalon=1.2, evtlat=3.2, evtlon=1.4)
     self.assertAlmostEqual(result['distance'], 2.10256)
     self.assertAlmostEqual(result['distancemeters'], 233272.79028)
     self.assertAlmostEqual(result['backazimuth'], 5.46944)
     self.assertAlmostEqual(result['azimuth'], 185.47695)
     self.assertEqual(result['ellipsoidname'], 'WGS84')
     self.assertTrue(isinstance(result['distance'], float))
     self.assertTrue(isinstance(result['distancemeters'], float))
     self.assertTrue(isinstance(result['backazimuth'], float))
     self.assertTrue(isinstance(result['azimuth'], float))
     self.assertTrue(isinstance(result['ellipsoidname'], str))
     # w/o kwargs
     result = client.distaz(1.1, 1.2, 3.2, 1.4)
     self.assertAlmostEqual(result['distance'], 2.10256)
     self.assertAlmostEqual(result['distancemeters'], 233272.79028)
     self.assertAlmostEqual(result['backazimuth'], 5.46944)
     self.assertAlmostEqual(result['azimuth'], 185.47695)
     self.assertEqual(result['ellipsoidname'], 'WGS84')
     # missing parameters
     self.assertRaises(Exception, client.distaz, stalat=1.1)
     self.assertRaises(Exception, client.distaz, 1.1)
     self.assertRaises(Exception, client.distaz, stalat=1.1, stalon=1.2)
     self.assertRaises(Exception, client.distaz, 1.1, 1.2)
示例#6
0
 def test_traveltime(self):
     """
     Tests calculation of travel-times for seismic phases.
     """
     client = Client()
     result = client.traveltime(evloc=(-36.122, -72.898),
                                evdepth=22.9,
                                staloc=[(-33.45, -70.67), (47.61, -122.33),
                                        (35.69, 139.69)])
     self.assertTrue(result.startswith(b'Model: iasp91'))
示例#7
0
def rotate_traces(event_code, database):
    data_path = f"{database}/{event_code}/synthetics/point_source/"
    filelist = glob.glob(f"{data_path}/*MXZ*.sac")

    cmt_finite_fault = f"{database}/{event_code}/{event_code}"
    cmt_lines = open(cmt_finite_fault).readlines()
    for line in cmt_lines:
        if line.split()[0] == "latitude":
            ev_lat = float(line.split()[1])
        elif line.split()[0] == "longitude":
            ev_lon = float(line.split()[1])
        else:
            continue

    client = Client()
    for Zfile in filelist:
        print(Zfile)
        Nfile = Zfile.replace("MXZ", "MXN")
        Efile = Zfile.replace("MXZ", "MXE")
        Rfile = Zfile.replace("MXZ", "MXR")
        Tfile = Zfile.replace("MXZ", "MXT")

        if os.path.isfile(Nfile) and os.path.isfile(Efile):
            st = read(Zfile)
            st += read(Nfile)
            st += read(Efile)

            Ztr = st[0]
            st_lat = Ztr.stats["sac"]["stla"]
            st_lon = Ztr.stats["sac"]["stlo"]
            station = Ztr.stats.station
            channel = Ztr.stats.channel

            result = client.distaz(stalat=st_lat,
                                   stalon=st_lon,
                                   evtlat=ev_lat,
                                   evtlon=ev_lon)
            baz = result["backazimuth"]
            az = result["azimuth"]
            dist_km = result["distancemeters"] / 1000.0
            dist_deg = result["distance"]
            print(station, channel, st_lat, st_lon, dist_km, dist_deg, baz, az)

            os.system(
                f"sac > macro {_lib}/rotate.macro {Nfile} {Efile} {baz} {Rfile} {Tfile}"
            )

            Rtr = read(Rfile)[0]
            Rtr.stats["channel"] = "MXR"
            Rtr.write(Rfile, format="SAC")

            Ttr = read(Tfile)[0]
            Ttr.stats["channel"] = "MXT"
            Ttr.write(Tfile, format="SAC")
示例#8
0
def download_response(network, station, location, channel, start, end,
                      respfile):
    '''
    Download instrument response file from IRIS and save to .resp
    Input:
        network:            String with network name
        station:            String with station name
        location:           String with location - can have * for wildcards
        channel:            String with channel - can have * for wildcards
        start:              String with start date and time: yyy-mm-ddThh:mm.sss
        end:                String with end date and time: yyy-mm-ddThh:mm.sss
    Output: 
        respfile:           Prints instrument response to respfile
    '''

    from obspy.clients.iris import Client
    from obspy import UTCDateTime

    # Set up client
    client = Client()

    # Define start and end date for resp file
    startdt = UTCDateTime(start)
    enddt = UTCDateTime(end)

    # Download resp data
    dlstring = 'downloading resp data for network ' + network + ', station ' \
        + station + ', location and channel ' + location + ' ' + channel \
        + ', \n for time ' + start + ' to ' + end
    print dlstring

    respdata = client.resp(network,
                           station,
                           location,
                           channel,
                           starttime=startdt,
                           endtime=enddt)

    # Save to file:
    respf = open(respfile, 'w')
    respf.write(respdata)
    respf.close()

    # Print statement:
    print 'Saved resp to file ' + respfile
示例#9
0
 def test_distaz(self):
     """
     Tests distance and azimuth calculation between two points on a sphere.
     """
     client = Client()
     # normal request
     result = client.distaz(stalat=1.1, stalon=1.2, evtlat=3.2, evtlon=1.4)
     self.assertAlmostEqual(result['distance'], 2.09554)
     self.assertAlmostEqual(result['backazimuth'], 5.46946)
     self.assertAlmostEqual(result['azimuth'], 185.47692)
     # w/o kwargs
     result = client.distaz(1.1, 1.2, 3.2, 1.4)
     self.assertAlmostEqual(result['distance'], 2.09554)
     self.assertAlmostEqual(result['backazimuth'], 5.46946)
     self.assertAlmostEqual(result['azimuth'], 185.47692)
     # missing parameters
     self.assertRaises(Exception, client.distaz, stalat=1.1)
     self.assertRaises(Exception, client.distaz, 1.1)
     self.assertRaises(Exception, client.distaz, stalat=1.1, stalon=1.2)
     self.assertRaises(Exception, client.distaz, 1.1, 1.2)
示例#10
0
    def test_resp(self):
        """
        Tests resp Web service interface.

        Examples are inspired by http://www.iris.edu/ws/resp/.
        """
        client = Client()
        # 1
        t1 = UTCDateTime("2005-001T00:00:00")
        t2 = UTCDateTime("2008-001T00:00:00")
        result = client.resp("IU", "ANMO", "00", "BHZ", t1, t2)
        self.assertIn(b'B050F03     Station:     ANMO', result)
        # 2 - empty location code
        result = client.resp("UW", "LON", "", "EHZ")
        self.assertIn(b'B050F03     Station:     LON', result)
        self.assertIn(b'B052F03     Location:    ??', result)
        # 3 - empty location code via '--'
        result = client.resp("UW", "LON", "--", "EHZ")
        self.assertIn(b'B050F03     Station:     LON', result)
        self.assertIn(b'B052F03     Location:    ??', result)
        # 4
        dt = UTCDateTime("2010-02-27T06:30:00.000")
        result = client.resp("IU", "ANMO", "*", "*", dt)
        self.assertIn(b'B050F03     Station:     ANMO', result)
示例#11
0
 def test_evalresp(self):
     """
     Tests evaluating instrument response information.
     """
     client = Client()
     dt = UTCDateTime("2005-01-01")
     # plot as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='plot',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # plot-amp as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='plot-amp',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # plot-phase as PNG file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='plot-phase',
                         filename=tempfile)
         with open(tempfile, 'rb') as fp:
             self.assertEqual(fp.read(4)[1:4], b'PNG')
     # fap as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # cs as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='cs',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05 -1.055896E+04 1.473054E+02\n')
     # fap & def as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         units='def',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # fap & dis as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         units='dis',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  6.635035E-01  2.692007E+02\n')
     # fap & vel as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         units='vel',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.055999E+04  1.792007E+02\n')
     # fap & acc as ASCII file
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         client.evalresp(network="IU",
                         station="ANMO",
                         location="00",
                         channel="BHZ",
                         time=dt,
                         output='fap',
                         units='acc',
                         filename=tempfile)
         with open(tempfile, 'rt') as fp:
             self.assertEqual(fp.readline(),
                              '1.000000E-05  1.680674E+08  8.920073E+01\n')
     # fap as NumPy ndarray
     data = client.evalresp(network="IU",
                            station="ANMO",
                            location="00",
                            channel="BHZ",
                            time=dt,
                            output='fap')
     np.testing.assert_array_equal(
         data[0], [1.00000000e-05, 1.05599900e+04, 1.79200700e+02])
     # cs as NumPy ndarray
     data = client.evalresp(network="IU",
                            station="ANMO",
                            location="00",
                            channel="BHZ",
                            time=dt,
                            output='cs')
     np.testing.assert_array_equal(
         data[0], [1.00000000e-05, -1.05589600e+04, 1.47305400e+02])
示例#12
0
文件: mail.py 项目: xumi1993/bqmail
from bqmail.query import Query
from obspy import UTCDateTime
from obspy.taup import TauPyModel
from obspy.clients.iris import Client
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from .distaz import distaz
model = TauPyModel()
cld = Client()


def connectsmtp(server, port, sender, password):
    smtpObj = smtplib.SMTP_SSL(server, port)
    smtpObj.login(sender, password)
    return smtpObj


def loginmail(sender, server='localhost', password='', port=465, test_num=5):
    test_it = 1
    while test_it <= test_num:
        if test_it > 1:
            print('Try to link to {} in {} times'.format(server, test_it))
        try:
            smtpObj = connectsmtp(server, port, sender, password)
        except:
            test_it += 1
            continue
        else:
            break
    if test_it > test_num:
from utilities_Array import deg_km_az_baz

# To dictate headers
from obspy.core.util import AttribDict

## Web service packages
from obspy.clients.iris import Client

# TauP
from obspy.taup import TauPyModel

# my model of choice is prem :D
model = TauPyModel(model="prem")

# Make client - just for giggles
client = Client()

import shutil
import numpy

import matplotlib.pyplot as plt

import argparse

parser = argparse.ArgumentParser(
    description='Preprocessing script for data retrieved from obspy DMT')

parser.add_argument("-fmin",
                    "--minimuum_frequency",
                    help="Enter the lowest frequency to be bandpass filtered.",
                    type=float,
示例#14
0
#!/usr/bin/env python

#from obspy.core import read
from obspy.clients.iris import Client
from obspy import core

stat = 'AAM'  # Station Code
net = 'US'  # Station Network
ch = ['BHZ', 'BH1', 'BH2']  # Channel
loc = '00'  # Location
# These 4 parameter identify the trace to download

start = core.UTCDateTime("2017-09-19T18:14:38")
end = core.UTCDateTime(start + 1800)

client = Client(
)  # Not sure what this does but its gets rid of the "self" error message
str = core.stream.Stream()
for x in range(0, 3):
    str += client.timeseries(network=net,
                             station=stat,
                             channel=ch[x],
                             location=loc,
                             starttime=start,
                             endtime=end)
## Plot Traces
start_plot = start + 222  #Manipulate starttime to get a nicer plot
end_plot = start_plot + 960
str.plot(size=[800, 600],
         starttime=start_plot,
         endtime=end_plot,
         type='relative')
示例#15
0
def rate(network,
         phase,
         preproloc,
         station=None,
         review=False,
         retained=False,
         decon_meth='it',
         test_tt_calculation=False):
    """
    Module to rate and review the quality of Sp or Ps waveforms from the given
    station. Shows the automatic rating from qc. Tapers can be controlled with
    the mouse. Rating is done with the keyboard. Makes only sense if the
    files in preproloc have not been quality controlled (the script is a
    reminant from an earlier alpha version).

    Parameters
    ----------
    network : STRING
        Network code (two letters).
    phase : STRING
        Either "P" for Ps or "S" Sp. The default is "S".
    preproloc : string
        Directory that contains the preprocessed files (not quality controlled)
    station : str or list, optional
        Station code (three letters).
    review : INTEGER, optional
        If true, already rated waveforms are shown.
        Can also be an integer between 1 and 4. Then, only waveforms rated
        with the respected rating are shown. The default is False.
    retained : Bool, optional
        Show only waveforms retained by qcp or qcs. The default is False.
    decon_meth : STRING, optional
        Deconvolution method, "waterlevel", 'dampedf' for constant
        damping level, 'it' for iterative time domain deconvoltuion, 'multit'
        for multitaper or 'fqd' for frequency dependently damped spectral
        division. The default is 'it'

    Raises
    ------
    Exception
        For Typing mistakes.

    Returns
    -------
    None.

    """
    if phase == 'P':
        onset = 30
    elif phase[-1] == 'S':
        onset = 120

    inloc = os.path.join(preproloc, phase, 'by_station', network)

    infiles = []  # List of all files in folder
    pattern = []  # List of input constraints
    streams = []  # List of files filtered for input criteria

    for root, dirs, files in os.walk(inloc):
        for name in files:
            infiles.append(os.path.join(root, name))

    # Set filter patterns

    if station:
        if type(station) == str:
            pattern.append('*%s*%s*.mseed' % (network, station))
        elif type(station) == list:
            for stat in station:
                pattern.append('*%s*%s*.mseed' % (network, stat))
    else:
        pattern.append('*%s*.mseed' % (network))

    # Do filtering
    for pat in pattern:
        streams.extend(fnmatch.filter(infiles, pat))

    # clear memory
    del pattern, infiles

    # For TauPy lookup
    model = TauPyModel()

    if test_tt_calculation:
        client = Client()

    for f in streams:
        # if file[:4] == "info":  # Skip the info files
        #     continue
        # try:
        #     st = read(inloc + file)
        # except IsADirectoryError as e:
        #     print(e)
        #     continue

        st = read(f)
        # List for taper coordinates
        if "taper" in rating:
            del rating["taper"]
        rating["taper"] = []
        st.normalize()

        # Additional filter "test"
        if phase == "S":
            st.filter("lowpass", freq=1.0, zerophase=True, corners=2)
        elif phase == "P":
            st.filter("lowpass", freq=1.0, zerophase=True, corners=2)

        y = []
        ch = []
        starttime = str(st[0].stats.starttime)
        dt = st[0].stats.delta
        sampling_f = st[0].stats.sampling_rate
        old = __r_file(network, st[0].stats.station, starttime)  # old

        # read info file
        # location info file
        infof = os.path.join(inloc, st[0].stats.station, 'info')
        with shelve.open(infof) as info:
            ii = info["starttime"].index(st[0].stats.starttime)
            rdelta = info["rdelta"][ii]  # epicentral distance
            mag = info["magnitude"][ii]
            statlat = info["statlat"]
            statlon = info["statlon"]
            rayp = info["rayp_s_deg"][ii] / 111319.9
            evt_depth = info["evt_depth"][ii] / 1000
            ot = info["ot_ret"][ii]
            evtlat = info['evtlat'][ii]
            evtlon = info['evtlon'][ii]

        if old and not review:  # skip already rated files
            continue
        if type(review) == int:
            if review > 4:
                raise Exception("review has to be between 0 and 4")
            if review != int(old):
                continue

        # check automatic rating
        if phase == "S":
            st_f, crit, hf, noisemat = qcs(st, dt, sampling_f, onset=onset)
        elif phase == "P":
            st_f, crit, hf, noisemat = qcp(st, dt, sampling_f, onset=onset)

        # skip files that have not been retained
        if retained and not crit:
            continue

        # create RF
        if not test_tt_calculation:
            _, _, PSV = rotate_PSV(statlat, statlon, rayp, st_f)
        else:
            PSV = st_f  # to see correlation at theoretical arrival

        try:
            RF = createRF(PSV, phase, method=decon_meth, shift=onset)
        except ValueError as e:  # There were some problematic events
            print(e)
            continue

        # TauPy lookup
        ph_name = []
        ph_time = []

        if not test_tt_calculation:
            arrivals = model.get_travel_times(evt_depth,
                                              distance_in_degree=rdelta)

            primary_time = model.get_travel_times(evt_depth,
                                                  distance_in_degree=rdelta,
                                                  phase_list=phase)[0].time

            for arr in arrivals:
                if arr.time < primary_time - onset or arr.time > \
                        primary_time + 120 or arr.name == phase:
                    continue
                ph_name.append(arr.name)
                ph_time.append(arr.time - primary_time)

        else:
            # Caluclate travel times with different methods
            ph_time.append(
                model.get_travel_times_geo(evt_depth,
                                           evtlat,
                                           evtlon,
                                           statlat,
                                           statlon,
                                           phase_list=phase)[0].time)

            d = []
            d.append(
                client.distaz(statlat, statlon, evtlat, evtlon)['distance'])

            d.append(
                kilometer2degrees(
                    gps2dist_azimuth(statlat, statlon, evtlat, evtlon)[0] /
                    1000))

            for dis in d:
                ph_time.append(
                    model.get_travel_times(evt_depth, dis,
                                           phase_list=phase)[0].time)
            ph_name = ['taup', 'iris', 'geodetics']
            ph_time = np.array(ph_time) - (st[0].stats.starttime + onset -
                                           UTCDateTime(ot))

        # waveform data
        st.sort()
        for tr in st:
            y.append(tr.data)
            ch.append(tr.stats.channel[2])

        # create time vector
        t = np.linspace(0 - onset, tr.stats.npts * tr.stats.delta - onset,
                        len(y[0]))

        # plot
        fig, ax = __draw_plot(starttime, t, y, ph_time, ph_name, ch, noisemat,
                              RF, old, rdelta, mag, crit, ot, evt_depth, phase,
                              test_tt_calculation)
        while not plt.waitforbuttonpress(30):
            # Taper when input is there
            if len(rating["taper"]) == 2:
                if rating["taper"][0] < rating["taper"][1]:
                    trim = [rating["taper"][0], rating["taper"][1]]
                else:
                    trim = [rating["taper"][1], rating["taper"][0]]
                trim[0] = trim[0] - t[0]
                trim[1] = t[-1] - trim[1]

                RF = createRF(PSV,
                              phase,
                              method=decon_meth,
                              shift=onset,
                              trim=trim)

                __draw_plot(starttime, t, y, ph_time, ph_name, ch, noisemat,
                            RF, old, rdelta, mag, crit, ot, evt_depth, phase,
                            test_tt_calculation)
                rating["taper"].clear()
        # fig.canvas.mpl_connect('key_press_event', ontype)
        if rating["k"] == "q":
            break
        elif "k" in rating:
            __w_file(network, st[0].stats.station, starttime)
示例#16
0
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 12 15:10:29 2018

@author: jfarrugia
"""

#%% Get some raw data from IRIS to pass through our new stationXML file
from obspy import read_inventory
inv = read_inventory('NV_ONC.xml', format="STATIONXML")
plotting_flag = 1

if plotting_flag == 1:
    from obspy.clients.iris import Client
    client = Client(timeout=100)
    from obspy import UTCDateTime
    import pandas as pd
    import matplotlib.pyplot as plt

    start_t = UTCDateTime("2018-01-10T03:00:00")
    end_t = start_t + 60 * 30
    st_e = client.timeseries(network='NV',
                             station='NC89',
                             location=None,
                             channel='HHE',
                             starttime=start_t,
                             endtime=end_t,
                             filter=['decimate=5.0'])
    st_e_noresponse = st_e.remove_response(inventory=inv, output='ACC')
    st_e_noresponse.write('E_honduras_correct_response.dat', format='TSPAIR')