示例#1
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)
示例#2
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)
示例#3
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")
示例#4
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)
示例#5
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)
示例#6
0
            sta1 = part[1]
            sta2 = part[2] + '_1'
    else:
        sta1 = part[1] + '_1'
        sta2 = part[3] + '_1'

    # if (sta1[0] in ['A','C','J'] or (sta1[0]=='D' and sta1 != 'DOC')) \
    # and (sta2[0] in ['A','C','J'] or (sta2[0]=='D' and sta2 != 'DOC')):

    if (sta1[0] == 'B' or sta1 == 'KMI' or sta1 == 'DOC') and (sta2[0] == 'B' or sta2 == 'KMI' or sta2 == 'DOC'):
        sac_num = sac_num + 1
        p1 = st_names.index(sta1)
        p2 = st_names.index(sta2)
        st_lo1, st_la1, st_lo2, st_la2 = st_los[p1], st_las[p1], st_los[p2], st_las[p2]
        client = Client()
        result = client.distaz(stalat=st_la1, stalon=st_lo1, evtlat=st_la2, evtlon=st_lo2)
        dist = int(result['distancemeters']) / 10 ** 3
        dists.append(dist)
        sta1s.append(sta1)
        sta2s.append(sta2)

for i in range(sac_num - 1):
    for j in range(i + 1, sac_num):
        if dists[i] > dists[j]:
            td, t1, t2 = dists[i], sta1s[i], sta2s[i]
            dists[i], sta1s[i], sta2s[i] = dists[j], sta1s[j], sta2s[j]
            dists[j], sta1s[j], sta2s[j] = td, t1, t2

dist_file = open('dist_s.dat', 'w')
for i in range(sac_num):
    dist_file.write(str(dists[i]) + ' ' + sta1s[i] + ' ' + sta2s[i] + '\n')