Ejemplo n.º 1
0
 def test_undefined_b(self):
     """
     Test that an undefined B value (-12345.0) is not messing up the
     starttime
     """
     # read in the test file an see that sac reference time and
     # starttime of seismogram are correct
     tr = read(self.file)[0]
     self.assertEqual(tr.stats.starttime.timestamp, 269596810.0)
     self.assertEqual(tr.stats.sac.b, 10.0)
     with open(self.file, 'rb') as fh:
         sac_ref_time = SACTrace.read(fh).reftime
     self.assertEqual(sac_ref_time.timestamp, 269596800.0)
     # change b to undefined and write (same case as if b == 0.0)
     # now sac reference time and reftime of seismogram must be the
     # same
     tr.stats.sac.b = -12345.0
     with NamedTemporaryFile() as tf:
         tmpfile = tf.name
         tr.write(tmpfile, format="SAC")
         tr2 = read(tmpfile)[0]
         self.assertEqual(tr2.stats.starttime.timestamp, 269596810.0)
         self.assertEqual(tr2.stats.sac.b, 10.0)
         with open(tmpfile, "rb") as fh:
             sac_ref_time2 = SACTrace.read(fh).reftime
     self.assertEqual(sac_ref_time2.timestamp, 269596800.0)
Ejemplo n.º 2
0
 def test_undefined_b(self):
     """
     Test that an undefined B value (-12345.0) is not messing up the
     starttime
     """
     # read in the test file an see that sac reference time and
     # starttime of seismogram are correct
     tr = read(self.file)[0]
     self.assertEqual(tr.stats.starttime.timestamp, 269596810.0)
     self.assertEqual(tr.stats.sac.b, 10.0)
     with open(self.file, 'rb') as fh:
         sac_ref_time = SACTrace.read(fh).reftime
     self.assertEqual(sac_ref_time.timestamp, 269596800.0)
     # change b to undefined and write (same case as if b == 0.0)
     # now sac reference time and reftime of seismogram must be the
     # same
     tr.stats.sac.b = -12345.0
     with NamedTemporaryFile() as tf:
         tmpfile = tf.name
         tr.write(tmpfile, format="SAC")
         tr2 = read(tmpfile)[0]
         self.assertEqual(tr2.stats.starttime.timestamp, 269596810.0)
         self.assertEqual(tr2.stats.sac.b, 10.0)
         with open(tmpfile, "rb") as fh:
             sac_ref_time2 = SACTrace.read(fh).reftime
     self.assertEqual(sac_ref_time2.timestamp, 269596800.0)
Ejemplo n.º 3
0
def cgps_traces(files, tensor_info, data_prop):
    """Write json dictionary with specified properties for cGPS data
    
    :param files: list of waveform files in sac format
    :param tensor_info: dictionary with moment tensor information
    :param data_prop: dictionary with waveform properties
    :type files: list
    :type tensor_info: dict
    :type data_prop: dict
    
    .. warning::
        
        Make sure the filters of cGPS data agree with the values in
        sampling_filter.json!
    """
    if len(files) == 0:
        return
    event_lat = tensor_info['lat']
    event_lon = tensor_info['lon']
    depth = tensor_info['depth']
    origin_time = tensor_info['date_origin']
    headers = [SACTrace.read(file) for file in files]
    dt_cgps = headers[0].delta
    dt_cgps = round(dt_cgps, 1)
    values = [mng._distazbaz(header.stla, header.stlo, event_lat, event_lon)\
        for header in headers]
    distances = [value[0] for value in values]
    zipped = zip(distances, headers)
    arrivals = [np.sqrt(dist**2 + depth**2) / 5 + header.b for dist, header in zipped]
    duration = duration_strong_motion(distances, arrivals, tensor_info, dt_cgps)
    filter0 = data_prop['strong_filter']
    n0, n1 = data_prop['wavelet_scales']
    wavelet_weight = wavelets_strong_motion(
            duration, filter0, dt_cgps, n0, n1, cgps=True)
    info_traces = []
    vertical = ['LXZ', 'LHZ', 'LYZ']
    headers = [SACTrace.read(file) for file in files]
    streams = [read(file) for file in files]
    channels = [header.kcmpnm for header in headers]
    weights = [1.2 if not channel in vertical else 0.6 for file, channel in\
               zip(files, channels)]

    for file, header, stream, weight in zip(files, headers, streams, weights):
        start = origin_time - stream[0].stats.starttime
        distance, azimuth, back_azimuth = mng._distazbaz(
                header.stla, header.stlo, event_lat, event_lon)
        info = _dict_trace(
                file, header.kstnm, header.kcmpnm, azimuth, distance / 111.11,
                dt_cgps, duration, int(start // dt_cgps), weight,
                wavelet_weight, [], location=[header.stla, header.stlo])
        info_traces.append(info)
    with open('cgps_waves.json','w') as f:
         json.dump(
                 info_traces, f, sort_keys=True, indent=4,
                 separators=(',', ': '), ensure_ascii=False)
    return info_traces
Ejemplo n.º 4
0
def tele_body_traces(files, tensor_info, data_prop):
    """Write json dictionary with specified properties for teleseismic data
    
    :param files: list of waveform files in sac format
    :param tensor_info: dictionary with moment tensor information
    :param data_prop: dictionary with waveform properties
    :type files: list
    :type tensor_info: dict
    :type data_prop: dict
    
    .. warning::
        
        Make sure the filters of teleseismic data agree with the values in
        sampling_filter.json! 
    """
    if len(files) == 0:
        return
    origin_time = tensor_info['date_origin']
    headers = [SACTrace.read(file) for file in files]
    streams = [read(file) for file in files]
    dt = headers[0].delta
    dt = round(dt, 1)
    n0, n1 = data_prop['wavelet_scales']
    filter0 = data_prop['tele_filter']
    duration = duration_tele_waves(tensor_info, dt)
    wavelet_weight0, wavelet_weight1 = wavelets_body_waves(
            duration, filter0, dt, n0, n1)
    info_traces = []
    event_lat = tensor_info['lat']
    event_lon = tensor_info['lon']
    depth = tensor_info['depth']
    model = TauPyModel(model="ak135f_no_mud")
    
    for file, header, stream in zip(files, headers, streams):
        __failsafe(filter0, header)
        distance, azimuth, back_azimuth = mng._distazbaz(
                header.stla, header.stlo, event_lat, event_lon)
        arrivals = mng.theoretic_arrivals(model, distance / 111.11, depth)
        if header.kcmpnm == 'BHZ':
            arrival = arrivals['p_arrival'][0].time
            weight = 1.0
            wavelet_weight = wavelet_weight0
        elif header.kcmpnm == 'SH':
            arrival = arrivals['s_arrival'][0].time
            weight = 0.5
            wavelet_weight = wavelet_weight1
        starttime = stream[0].stats.starttime
        begin = starttime - origin_time
        n_start_obs = int((arrival - begin) / dt + 0.5)
        info = _dict_trace(
                file, header.kstnm, header.kcmpnm, azimuth, distance / 111.11,
                dt, duration, n_start_obs, weight, wavelet_weight, [],   ##!!!!!!!!!!
                location=[header.stla, header.stlo], derivative=False)
        info_traces.append(info)
    with open('tele_waves.json','w') as f:
         json.dump(
                 info_traces, f, sort_keys=True, indent=4,
                 separators=(',', ': '), ensure_ascii=False)
    return info_traces
Ejemplo n.º 5
0
Archivo: rf.py Proyecto: Ji-Cong/seispy
def load_station_info(pathname, ref_comp, suffix):
    try:
        ex_sac = glob.glob(join(pathname, '*{0}*{1}'.format(ref_comp,
                                                            suffix)))[0]
    except Exception:
        raise FileNotFoundError('no such SAC file in {0}'.format(pathname))
    ex_tr = SACTrace.read(ex_sac, headonly=True)
    return ex_tr.knetwk, ex_tr.kstnm, ex_tr.stla, ex_tr.stlo, ex_tr.stel
Ejemplo n.º 6
0
 def test_iztype11(self):
     # test that iztype 11 is read correctly
     sod_file = os.path.join(self.path, 'data', 'dis.G.SCZ.__.BHE_short')
     tr = read(sod_file)[0]
     with open(sod_file, "rb") as fh:
         sac = SACTrace.read(fh)
     t1 = tr.stats.starttime - float(tr.stats.sac.b)
     t2 = sac.reftime
     self.assertAlmostEqual(t1.timestamp, t2.timestamp, 5)
     # see that iztype is written correctly
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tr.write(tempfile, format="SAC")
         with open(tempfile, "rb") as fh:
             sac2 = SACTrace.read(fh)
     self.assertEqual(sac2._header['iztype'], 11)
     self.assertAlmostEqual(tr.stats.sac.b, sac2.b)
     self.assertAlmostEqual(t2.timestamp, sac2.reftime.timestamp, 5)
Ejemplo n.º 7
0
 def test_iztype11(self):
     # test that iztype 11 is read correctly
     sod_file = os.path.join(self.path, 'data', 'dis.G.SCZ.__.BHE_short')
     tr = read(sod_file)[0]
     with open(sod_file, "rb") as fh:
         sac = SACTrace.read(fh)
     t1 = tr.stats.starttime - float(tr.stats.sac.b)
     t2 = sac.reftime
     self.assertAlmostEqual(t1.timestamp, t2.timestamp, 5)
     # see that iztype is written correctly
     with NamedTemporaryFile() as tf:
         tempfile = tf.name
         tr.write(tempfile, format="SAC")
         with open(tempfile, "rb") as fh:
             sac2 = SACTrace.read(fh)
     self.assertEqual(sac2._header['iztype'], 11)
     self.assertAlmostEqual(tr.stats.sac.b, sac2.b)
     self.assertAlmostEqual(t2.timestamp, sac2.reftime.timestamp, 5)
Ejemplo n.º 8
0
def gen_list(para):
    with open(os.path.join(para.rfpath, "CB.NJ2finallist.dat"), 'w+') as fid:
        files = sorted(glob.glob(join(para.rfpath, '*R.sac')))
        for fname in files:
            sac = SACTrace.read(fname)
            evname = basename(fname).split('_')[0]
            fid.write('%s %s %6.3f %6.3f %6.3f %6.3f %6.3f %8.7f %6.3f %6.3f\n' % (
                evname, 'P', sac.evla, sac.evlo, sac.evdp, sac.gcarc, sac.baz, sac.user0, sac.mag, sac.user1
            ))
Ejemplo n.º 9
0
def load_station_info(pathname, ref_comp, suffix):
    try:
        ex_sac = glob.glob(join(pathname, '*{0}*{1}'.format(ref_comp,
                                                            suffix)))[0]
    except Exception:
        raise FileNotFoundError('no such SAC file in {0}'.format(pathname))
    ex_tr = SACTrace.read(ex_sac, headonly=True)
    if (ex_tr.stla is None or ex_tr.stlo is None):
        raise ValueError('The stlo and stla are not in the SACHeader')
    return ex_tr.knetwk, ex_tr.kstnm, ex_tr.stla, ex_tr.stlo, ex_tr.stel
Ejemplo n.º 10
0
def tele_surf_traces(files, tensor_info, data_prop):
    """Write json dictionary with specified properties for surface wave data
    
    :param files: list of waveform files in sac format
    :param tensor_info: dictionary with moment tensor information
    :param data_prop: dictionary with waveform properties
    :type files: list
    :type tensor_info: dict
    :type data_prop: dict
    """
    if len(files) == 0:
        return
    n0, n1 = data_prop['wavelet_scales']
    wavelet_weight = wavelets_surf_tele(n0, n1)
    info_traces = []
    headers = [SACTrace.read(file) for file in files]
    event_lat = tensor_info['lat']
    event_lon = tensor_info['lon']
    for file, header in zip(files, headers):
        npts = header.npts
        n_start = int(-header.b / 4.0)
        if npts < n_start:
            continue
        if npts + n_start < 0:
            continue
        length = 900
        if 900 >= (npts - n_start):
            length = npts - n_start if n_start > 0 else npts
        distance, azimuth, back_azimuth = mng._distazbaz(
            header.stla, header.stlo, event_lat, event_lon)
        info = _dict_trace(file,
                           header.kstnm,
                           header.kcmpnm,
                           azimuth,
                           distance / 111.11,
                           4.0,
                           length,
                           n_start,
                           1.0,
                           wavelet_weight, [],
                           location=[header.stla, header.stlo])
        info_traces.append(info)
    with open('surf_waves.json', 'w') as f:
        json.dump(info_traces,
                  f,
                  sort_keys=True,
                  indent=4,
                  separators=(',', ': '),
                  ensure_ascii=False)
    return info_traces
Ejemplo n.º 11
0
def initpara():
    h = np.arange(40, 80, 0.1)
    kappa = np.arange(1.6, 1.9, 0.01)
    path = join(dirname(__file__), 'benchmark')
    npts, dt, shift = readpara(path)
    baz, rayp = np.loadtxt(join(path, 'sample.geom'),
                           usecols=(0, 1),
                           unpack=True)
    rayp *= 1000
    ev_num = baz.shape[0]
    seis = np.empty([ev_num, npts])
    for _i, b in enumerate(baz):
        sac = SACTrace.read(
            join(path, 'tr_{:d}_{:.3f}.r'.format(int(b), rayp[0])))
        seis[_i] = sac.data
    return h, kappa, baz, rayp, npts, dt, shift, ev_num, seis
Ejemplo n.º 12
0
def tele_body_traces(files, tensor_info, data_prop):
    """Write json dictionary with specified properties for teleseismic data
    
    :param files: list of waveform files in sac format
    :param tensor_info: dictionary with moment tensor information
    :param data_prop: dictionary with waveform properties
    :type files: list
    :type tensor_info: dict
    :type data_prop: dict
    
    .. warning::
        
        Make sure the filters of teleseismic data agree with the values in
        sampling_filter.json! 
    """
    if len(files) == 0:
        return
    headers = [SACTrace.read(file) for file in files]
    dt = headers[0].delta
    dt = round(dt, 1)
    n0, n1 = data_prop['wavelet_scales']
    print('Wavelet: ', n0, n1)
    filter0 = data_prop['tele_filter']
    duration = duration_tele_waves(tensor_info, dt)
    wavelet_weight0, wavelet_weight1 = wavelets_body_waves(
        duration, filter0, dt, n0, n1)
    info_traces = []
    event_lat = tensor_info['lat']
    event_lon = tensor_info['lon']

    for file, header in zip(files, headers):
        if header.kcmpnm == 'BHZ':
            n_start_obs = int((header.t1 - header.b) / dt + 0.5)
            weight = 1.0
            wavelet_weight = wavelet_weight0
        elif header.kcmpnm == 'SH':
            n_start_obs = int((header.t5 - header.b) / dt + 0.5)
            weight = 0.5
            wavelet_weight = wavelet_weight1
        __failsafe(filter0, header)
        distance, azimuth, back_azimuth = mng._distazbaz(
            header.stla, header.stlo, event_lat, event_lon)
        info = _dict_trace(file,
                           header.kstnm,
                           header.kcmpnm,
                           azimuth,
                           distance / 111.11,
                           dt,
                           duration,
                           n_start_obs,
                           weight,
                           wavelet_weight, [],
                           location=[header.stla, header.stlo])
        info_traces.append(info)
    with open('tele_waves.json', 'w') as f:
        json.dump(info_traces,
                  f,
                  sort_keys=True,
                  indent=4,
                  separators=(',', ': '),
                  ensure_ascii=False)
    return info_traces
Ejemplo n.º 13
0
def strong_motion_traces(files, tensor_info, data_prop):
    """Write json dictionary with specified properties for strong motion data
    
    :param files: list of waveform files in sac format
    :param tensor_info: dictionary with moment tensor information
    :param data_prop: dictionary with waveform properties
    :type files: list
    :type tensor_info: dict
    :type data_prop: dict
    
    .. warning::
        
        Make sure the filters of strong motion data agree with the values in
        sampling_filter.json!
    """
    if len(files) == 0:
        return
    event_lat = tensor_info['lat']
    event_lon = tensor_info['lon']
    headers = [SACTrace.read(file) for file in files]
    dt_strong = headers[0].delta
    dt_strong = round(dt_strong, 1)
    starts = [header.o if header.o else 0 for header in headers]  #20
    values = [mng._distazbaz(header.stla, header.stlo, event_lat, event_lon)\
        for header in headers]
    distances = [value[0] for value in values]
    arrivals = [header.t1 if header.t1 else 0 for header in headers]
    filter0 = data_prop['strong_filter']
    seismic_moment = tensor_info['moment_mag']
    #    outliers = strong_outliers(files, tensor_info)
    if seismic_moment < 2 * 10**26:
        outliers = strong_outliers2(files, distances, tensor_info)
    else:
        outliers = strong_outliers(files, tensor_info)
    duration = duration_strong_motion(distances, arrivals, tensor_info,
                                      dt_strong)
    n0, n1 = data_prop['wavelet_scales']
    wavelet_weight = wavelets_strong_motion(duration, filter0, dt_strong, n0,
                                            n1)
    black_list = {'PB02': ['HNE', 'HNN', 'HLE', 'HLN'], 'PX02': ['HNE', 'HLE']}

    info_traces = []
    outlier_traces = []
    headers = [SACTrace.read(file) for file in files]
    streams = [read(file) for file in files]
    weights = [1.0 for st, file in zip(streams, files)]
    weights = [0 if header.kstnm in black_list\
        and header.kcmpnm in black_list[header.kstnm] else weight\
        for weight, header in zip(weights, headers)]
    #    weights = [0 if file in outliers else weight\
    #               for file, weight in zip(files, weights)]

    for file, header, start, weight, stream in zip(files, headers, starts,
                                                   weights, streams):
        # __failsafe(filter0, header)
        distance, azimuth, back_azimuth = mng._distazbaz(
            header.stla, header.stlo, event_lat, event_lon)
        info = _dict_trace(file,
                           header.kstnm,
                           header.kcmpnm,
                           azimuth,
                           distance / 111.11,
                           dt_strong,
                           duration,
                           int(start / dt_strong),
                           weight,
                           wavelet_weight, [],
                           location=[header.stla, header.stlo])
        info_traces.append(info)
    with open('strong_motion_waves.json', 'w') as f:
        json.dump(info_traces,
                  f,
                  sort_keys=True,
                  indent=4,
                  separators=(',', ': '),
                  ensure_ascii=False)
    with open('outlier_strong_motion_waves.json', 'w') as f:
        json.dump(outlier_traces,
                  f,
                  sort_keys=True,
                  indent=4,
                  separators=(',', ': '),
                  ensure_ascii=False)
    return info_traces
Ejemplo n.º 14
0
def strong_motion_traces(files, tensor_info, data_prop):
    """Write json dictionary with specified properties for strong motion data
    
    :param files: list of waveform files in sac format
    :param tensor_info: dictionary with moment tensor information
    :param data_prop: dictionary with waveform properties
    :type files: list
    :type tensor_info: dict
    :type data_prop: dict
    
    .. warning::
        
        Make sure the filters of strong motion data agree with the values in
        sampling_filter.json!
    """
    if len(files) == 0:
        return
    event_lat = tensor_info['lat']
    event_lon = tensor_info['lon']
    depth = tensor_info['depth']
    origin_time = tensor_info['date_origin']
    headers = [SACTrace.read(file) for file in files]
    dt_strong = headers[0].delta
    dt_strong = round(dt_strong, 1)
    values = [mng._distazbaz(header.stla, header.stlo, event_lat, event_lon)\
        for header in headers]
    distances = [value[0] for value in values]
    zipped = zip(distances, headers)
    arrivals = [np.sqrt(dist**2 + depth**2) / 5 + header.b for dist, header in zipped]
    filter0 = data_prop['strong_filter']
    seismic_moment = tensor_info['moment_mag']
#    outliers = strong_outliers(files, tensor_info)
    if seismic_moment < 2 * 10 ** 26:
        outliers = strong_outliers2(files, distances, tensor_info)
    else:
        outliers = strong_outliers(files, tensor_info)
    duration = duration_strong_motion(
            distances, arrivals, tensor_info, dt_strong)
    n0, n1 = data_prop['wavelet_scales']
    wavelet_weight = wavelets_strong_motion(
            duration, filter0, dt_strong, n0, n1)
    black_list = {
            'PB02': [
                    'HNE',
                    'HNN',
                    'HLE',
                    'HLN'
                    ],
            'PX02': [
                    'HNE',
                    'HLE'
                    ]
    }
    
    info_traces = []
    outlier_traces = []
    headers = [SACTrace.read(file) for file in files]
    streams = [read(file) for file in files]
    weights = [1.0 for st, file in zip(streams, files)]
    weights = [0 if header.kstnm in black_list\
        and header.kcmpnm in black_list[header.kstnm] else weight\
        for weight, header in zip(weights, headers)]
    
    zipped = zip(files, headers, weights, streams, arrivals)
    stat_list = ['KUSD', 'GMLD', 'CESE', 'DIDI', 'YKAV', 'FOCM', 'AKS', 'DATC',
                 'GOMA', 'KRBN']
        
    for file, header, weight, stream, arrival in zipped:
        # if not header.kstnm in stat_list:
        #     continue
        # weight = near_field_weight(tensor_info, header.stla, header.stlo)
        # weight = 0 if header.kstnm in black_list\
        # and header.kcmpnm in black_list[header.kstnm] else weight
        start = origin_time - stream[0].stats.starttime
        distance, azimuth, back_azimuth = mng._distazbaz(
                header.stla, header.stlo, event_lat, event_lon)
        info = _dict_trace(
                file, header.kstnm, header.kcmpnm, azimuth, distance / 111.11,
                dt_strong, duration, int(start / dt_strong), weight,
                wavelet_weight, [], location=[header.stla, header.stlo])
        info_traces.append(info)
    with open('strong_motion_waves.json','w') as f:
         json.dump(
                 info_traces, f, sort_keys=True, indent=4,
                 separators=(',', ': '), ensure_ascii=False)
    with open('outlier_strong_motion_waves.json','w') as f:
         json.dump(
                 outlier_traces, f, sort_keys=True, indent=4,
                 separators=(',', ': '), ensure_ascii=False)
    return info_traces
Ejemplo n.º 15
0
            spec_src = ffilt * spec_src * spec_src_conj / spec_src_water
            rf_src = ifft(spec_src, nfft)[:N]
            norm = 1 / max(rf_src)
            rf_src = norm * rf_src
        info = {'rf_src': rf_src, 'rf_src_conj': spec_src_conj,
                'spec_src_water': spec_src_water,
                'freq': np.fft.fftfreq(nfft, d=dt),
                'gauss': ffilt, 'norm': norm, 'N': N, 'nfft': nfft}
        return rf_list, info
    elif flag:
        return rf
    else:
        return rf_list


if __name__ == '__main__':
    ldata = SACTrace.read('data/syn_S.L')
    qdata = SACTrace.read('data/syn_S.Q')
    l = ldata.data
    q = qdata.data
    # l = np.flip(ldata.data, axis=0)
    # q = np.flip(qdata.data, axis=0)
    time_axis = np.linspace(qdata.b, qdata.npts*qdata.delta+qdata.b, qdata.npts)

    rf, rms, it = decovit(l, q, qdata.delta, tshift=-qdata.b, f0=2, itmax=20, phase='S')
    fig, axes = plt.subplots(3, 1, sharex=True, figsize=(10,6))
    axes[0].plot(time_axis, qdata.data)
    axes[1].plot(time_axis, ldata.data)
    axes[2].plot(time_axis, rf)
    plt.show()