Example #1
0
 def on_data(self, trace):
     global i
     global traces
     global fn
     global day
     if i == 1:
         print('Received traces. Checking for existing data...')
         if (os.path.isfile(fn)):
             print('Found %s, reading...' % fn)
             traces = read(fn)
             print('Done.')
         else:
             print('No data found. Creating new blank trace to write to...')
             traces = Trace()
         traces = trace
         print('Trace %s: %s' % (i, trace))
     else:
         print('Trace %s: %s' % (i, trace))
         traces += trace
         traces.__add__(trace)
         if (float(i) / 10. == int(float(i) / 10.)):
             print('Saving %s traces to %s...' % (i, fn))
             traces.write(fn, format='MSEED')
             print('Done.')
     i += 1
     if (day != UTCDateTime.now().strftime('%Y.%j')):
         day = UTCDateTime.now().strftime('%Y.%j')
         fn = fn = '%s.%s.%s.%s.D.%s' % (net, sta, loc, cha, day)
         i = 1
    def love_pick(self,
                  T_trace,
                  la_s,
                  lo_s,
                  depth,
                  save_directory,
                  time_at_rec,
                  npts,
                  filter=True,
                  plot_modus=False):
        if plot_modus == True:
            dir_L = save_directory + '/Love_waves'
            if not os.path.exists(dir_L):
                os.makedirs(dir_L)
        Love_st = Stream()

        evla = la_s
        evlo = lo_s

        rec = instaseis.Receiver(latitude=self.prior['la_r'],
                                 longitude=self.prior['lo_r'])

        dist, az, baz = gps2dist_azimuth(lat1=evla,
                                         lon1=evlo,
                                         lat2=self.prior['la_r'],
                                         lon2=self.prior['lo_r'],
                                         a=self.prior['radius'],
                                         f=0)

        # For now I am just using the Z-component, because this will have the strongest Rayleigh signal:
        T_comp = T_trace.copy()

        if plot_modus == True:
            T_comp.plot(outfile=dir_L + '/sw_entire_waveform.pdf')
        phases = self.get_L_phases(time_at_rec)

        for i in range(len(phases)):
            if plot_modus == True:
                dir_phases = dir_L + '/%s' % phases[i]['name']
                if not os.path.exists(dir_phases):
                    os.makedirs(dir_phases)
            trial = T_trace.copy()
            if filter == True:
                trial.detrend(type="demean")
                trial.filter('highpass',
                             freq=phases[i]['fmin'],
                             zerophase=True)
                trial.filter('lowpass', freq=phases[i]['fmax'], zerophase=True)
                trial.detrend()

            if plot_modus == True:
                start_vline = int(
                    (phases[i]['starttime'](dist, depth).timestamp -
                     time_at_rec.timestamp) / trial.stats.delta)
                end_vline = int((phases[i]['endtime'](dist, depth).timestamp -
                                 time_at_rec.timestamp) / trial.stats.delta)
                plt.figure(1)
                ax = plt.subplot(111)
                plt.plot(trial.data, alpha=0.5)
                ymin, ymax = ax.get_ylim()
                # plt.plot(trial.data)
                plt.vlines([start_vline, end_vline], ymin, ymax)
                plt.xlabel(time_at_rec.strftime('%Y-%m-%dT%H:%M:%S + sec'))
                plt.savefig(dir_phases + '/sw_with_Love_windows.pdf')
                plt.tight_layout()
                plt.close()

            if filter == True:
                trial.detrend(type="demean")
                env = envelope(trial.data)
                trial.data = env
                trial.trim(starttime=phases[i]['starttime'](dist, depth),
                           endtime=phases[i]['endtime'](dist, depth))
            else:
                env = trial.data
            if plot_modus == True:
                plt.figure(2)
                plt.plot(trial, label='%s' % phases[i]['name'])
                plt.legend()
                plt.tight_layout()
                plt.savefig(dir_phases +
                            '/Love_envelope_filter_%s.pdf' % phases[i]['name'])
                plt.close()

            zero_trace = Trace(np.zeros(npts),
                               header={
                                   "starttime": phases[i]['starttime'](dist,
                                                                       depth),
                                   'delta': trial.meta.delta,
                                   "station": trial.meta.station,
                                   "network": trial.meta.network,
                                   "location": trial.meta.location,
                                   "channel": phases[i]['name']
                               })

            total_trace = zero_trace.__add__(trial,
                                             method=0,
                                             interpolation_samples=0,
                                             fill_value=trial.data,
                                             sanity_checks=False)

            Love_st.append(total_trace)
        if plot_modus == True:
            plt.figure(3)
            plt.plot(Love_st.traces[0].data,
                     label='%s' % Love_st.traces[0].meta.channel)
            plt.plot(Love_st.traces[1].data,
                     label='%s' % Love_st.traces[1].meta.channel)
            plt.plot(Love_st.traces[2].data,
                     label='%s' % Love_st.traces[2].meta.channel)
            plt.plot(Love_st.traces[3].data,
                     label='%s' % Love_st.traces[3].meta.channel)
            plt.legend()
            plt.tight_layout()
            plt.savefig(dir_L + '/diff_Love_freq.pdf')
            plt.close()
        return Love_st
Example #3
0
    def pick_sw(self,
                stream,
                pick_info,
                epi,
                prior,
                npts,
                directory,
                plot_modus=False):
        if plot_modus == True:
            dir_SW = directory + '/Blind_rayleigh'
            if not os.path.exists(dir_SW):
                os.makedirs(dir_SW)
        Rayleigh_st = Stream()
        Love_st = Stream()

        dist = degrees2kilometers(epi, prior['radius'])
        phase = 0
        for pick in pick_info:
            if pick['phase_name'] == 'R1':
                if plot_modus == True:
                    dir_phases = dir_SW + '/Rayleigh_%.2f_%.2f' % (
                        pick['lower_frequency'], pick['upper_frequency'])
                    if not os.path.exists(dir_phases):
                        os.makedirs(dir_phases)
                Z_trace = stream.traces[0].copy()
                if plot_modus == True:
                    Z_trace.plot(outfile=dir_SW + '/Z_comp.pdf')
                Z_trace.detrend(type="demean")
                if (pick['lower_frequency']
                        == float(0.0)) and (pick['upper_frequency']
                                            == float(0.0)):
                    pass
                else:
                    Z_trace.filter('highpass',
                                   freq=pick['lower_frequency'],
                                   zerophase=True)
                    Z_trace.filter('lowpass',
                                   freq=pick['upper_frequency'],
                                   zerophase=True)
                Z_trace.detrend()
                Z_trace.detrend(type="demean")

                if plot_modus == True:
                    start_vline = int(
                        ((pick['time'].timestamp - pick['lower_uncertainty']) -
                         Z_trace.meta.starttime.timestamp) /
                        Z_trace.stats.delta)
                    end_vline = int(
                        ((pick['time'].timestamp + pick['lower_uncertainty']) -
                         Z_trace.meta.starttime.timestamp) /
                        Z_trace.stats.delta)
                    plt.figure()
                    ax = plt.subplot(111)
                    plt.plot(Z_trace.data, alpha=0.5)
                    ymin, ymax = ax.get_ylim()
                    plt.plot(Z_trace.data)
                    plt.vlines([start_vline, end_vline], ymin, ymax)
                    plt.xlabel(
                        Z_trace.meta.starttime.strftime(
                            '%Y-%m-%dT%H:%M:%S + sec'))
                    plt.tight_layout()
                    plt.savefig(dir_phases + '/sw_with_Rayleigh_windows.pdf')
                    # plt.show()
                    plt.close()
                Period = 1.0 / pick['frequency']
                Z_trace.trim(starttime=pick['time'] - Period,
                             endtime=pick['time'] + Period)
                zero_trace = Trace(np.zeros(npts),
                                   header={
                                       "starttime": pick['time'] - Period,
                                       'delta': Z_trace.meta.delta,
                                       "station": Z_trace.meta.station,
                                       "network": Z_trace.meta.network,
                                       "location": Z_trace.meta.location,
                                       "channel": Z_trace.meta.channel
                                   })
                total_trace = zero_trace.__add__(Z_trace,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=Z_trace.data,
                                                 sanity_checks=False)
                Rayleigh_st.append(total_trace)
                if plot_modus == True:
                    plt.figure()
                    plt.plot(
                        Z_trace.data,
                        label='%.2f_%.2f' %
                        (pick['lower_frequency'], pick['upper_frequency']))
                    plt.legend()
                    plt.tight_layout()
                    plt.savefig(dir_phases + '/diff_Love_freq.pdf')
                    plt.close()

            elif pick['phase_name'] == 'G1':
                if plot_modus == True:
                    dir_phases = dir_SW + '/Love_%.2f_%.2f' % (
                        pick['lower_frequency'], pick['upper_frequency'])
                    if not os.path.exists(dir_phases):
                        os.makedirs(dir_phases)
                T_trace = stream.traces[2].copy()
                if plot_modus == True:
                    T_trace.plot(outfile=dir_SW + '/T_comp.pdf')
                T_trace.detrend(type="demean")
                if (pick['lower_frequency']
                        == float(0.0)) and (pick['upper_frequency']
                                            == float(0.0)):
                    pass
                else:
                    T_trace.filter('highpass',
                                   freq=pick['lower_frequency'],
                                   zerophase=True)
                    T_trace.filter('lowpass',
                                   freq=pick['upper_frequency'],
                                   zerophase=True)
                T_trace.detrend()
                T_trace.detrend(type="demean")

                if plot_modus == True:
                    start_vline = int(
                        ((pick['time'].timestamp - pick['lower_uncertainty']) -
                         T_trace.meta.starttime.timestamp) /
                        T_trace.stats.delta)
                    end_vline = int(
                        ((pick['time'].timestamp + pick['lower_uncertainty']) -
                         T_trace.meta.starttime.timestamp) /
                        T_trace.stats.delta)
                    plt.figure()
                    ax = plt.subplot(111)
                    plt.plot(T_trace.data, alpha=0.5)
                    ymin, ymax = ax.get_ylim()
                    plt.plot(T_trace.data)
                    plt.vlines([start_vline, end_vline], ymin, ymax)
                    plt.xlabel(
                        T_trace.meta.starttime.strftime(
                            '%Y-%m-%dT%H:%M:%S + sec'))
                    plt.tight_layout()
                    plt.savefig(dir_phases + '/sw_with_Love_windows.pdf')
                    # plt.show()
                    plt.close()
                Period = 1.0 / pick['frequency']
                T_trace.trim(starttime=pick['time'] - Period,
                             endtime=pick['time'] + Period)
                zero_trace = Trace(np.zeros(npts),
                                   header={
                                       "starttime": pick['time'] - Period,
                                       'delta': T_trace.meta.delta,
                                       "station": T_trace.meta.station,
                                       "network": T_trace.meta.network,
                                       "location": T_trace.meta.location,
                                       "channel": T_trace.meta.channel
                                   })
                total_trace = zero_trace.__add__(T_trace,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=T_trace.data,
                                                 sanity_checks=False)
                Love_st.append(total_trace)
                if plot_modus == True:
                    plt.figure()
                    plt.plot(
                        T_trace.data,
                        label='%.2f_%.2f' %
                        (pick['lower_frequency'], pick['upper_frequency']))
                    plt.legend()
                    plt.tight_layout()
                    plt.savefig(dir_phases + '/diff_Love_freq.pdf')
                    plt.close()
        return Rayleigh_st, Love_st
Example #4
0
    def get_window_obspy(self, seis_traces, epi, depth, time, npts):
        tt_P = self.get_P(
            epi, depth
        )  # Estimated P-wave arrival, based on the known velocity model
        tt_S = self.get_S(
            epi, depth
        )  # Estimated S-wave arrival, based on the known velocity model
        sec_per_sample = 1 / (seis_traces[0].meta.sampling_rate)
        #
        total_stream = Stream()
        s_stream = Stream()
        p_stream = Stream()
        p_time = time.timestamp + tt_P
        s_time = time.timestamp + tt_S
        start_time_p = obspy.UTCDateTime(p_time - 5)
        start_time_s = obspy.UTCDateTime(s_time - 15)
        end_time_p = obspy.UTCDateTime(p_time + 20)
        end_time_s = obspy.UTCDateTime(s_time + 35)
        #
        for i, trace in enumerate(seis_traces.traces):
            P_trace = Trace.slice(trace, start_time_p, end_time_p)
            S_trace = Trace.slice(trace, start_time_s, end_time_s)
            #
            #     params = {'legend.fontsize': 'x-large',
            #               'figure.figsize': (15, 15),
            #               'axes.labelsize': 25,
            #               'axes.titlesize': 'x-large',
            #               'xtick.labelsize': 25,
            #               'ytick.labelsize': 25}
            #     pylab.rcParams.update(params)
            #     fig = plt.figure(figsize=(10, 10))
            #     time_array = np.arange(len(trace)) * trace.meta.delta
            #     Axes = plt.subplot()
            #     Axes.plot(time_array, trace, c='k', label = 'Z-component')
            #     ymin, ymax = Axes.get_ylim()
            #     x_cor = [start_time_p.timestamp - trace.meta.starttime.timestamp,
            #              end_time_p.timestamp - trace.meta.starttime.timestamp,
            #              end_time_p.timestamp - trace.meta.starttime.timestamp,
            #              start_time_p.timestamp - trace.meta.starttime.timestamp,
            #              start_time_p.timestamp - trace.meta.starttime.timestamp]
            #     y_cor = [ymax / 10.0, ymax / 10.0, ymin / 10.0, ymin / 10.0, ymax / 10.0]
            #     plt.plot(x_cor,y_cor,c='r')
            #     x_cor_s = [start_time_s.timestamp - trace.meta.starttime.timestamp,
            #              end_time_s.timestamp - trace.meta.starttime.timestamp,
            #              end_time_s.timestamp - trace.meta.starttime.timestamp,
            #              start_time_s.timestamp - trace.meta.starttime.timestamp,
            #              start_time_s.timestamp - trace.meta.starttime.timestamp]
            #     y_cor_s = [ymax / 10.0, ymax / 10.0, ymin / 10.0, ymin / 10.0, ymax / 10.0]
            #     plt.plot(x_cor_s,y_cor_s,c='r')
            #     # Axes.axhline(y=ymin,  color='r')
            #     # Axes.axhline(y=ymax,  color='r')
            #     # plt.vlines(start_time_p,ymin=ymin,ymax=ymax,colors='r',label='P pick')
            #     # plt.vlines(end_time_p,ymin=ymin,ymax=ymax,colors='r')
            #
            #
            #     phases = (dict(starttime=lambda dist, depth: time + dist / 2.8,
            #                    endtime=lambda dist, depth: time + dist / 2.6,
            #                    comp='Z',
            #                    fmin=1. / 20.,
            #                    fmax=1. / 10.,
            #                    dt=5.0,
            #                    name='R1_10_20'))
            #     # trace.detrend(type="demean")
            #     # trace.filter('highpass', freq=phases['fmin'], zerophase=True)
            #     # trace.filter('lowpass', freq=phases['fmax'], zerophase=True)
            #     # trace.detrend()
            #     start = phases['starttime'](2716.72921884, 10000)
            #     end = phases['endtime'](2716.72921884, 10000)
            #     start_vline = int(
            #         (phases['starttime'](2716.72921884, 10000).timestamp- time.timestamp))
            #     end_vline = int(
            #         (phases['endtime'](2716.72921884, 10000).timestamp - time.timestamp))
            #
            #     y_cor_R = [ymin,ymin,ymax,ymax,ymin]
            #     x_cor_R = [start_vline,end_vline,end_vline,start_vline,start_vline]
            #
            #     plt.plot(x_cor_R, y_cor_R, c='g')
            #     Axes.legend()
            #     Axes.ticklabel_format(style="sci", axis='y', scilimits=(-2, 2))
            #     Axes.set_xlabel(trace.meta.starttime.strftime('Time : %Y-%m-%dT%H:%M:%S + [sec]'))
            #     Axes.set_ylabel("Displacement [m]")
            #     plt.tight_layout()
            #     # plt.show()
            #     plt.savefig('/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Final/check_waveforms' + '/picks.pdf')
            #     plt.close()
            #
            #     # v_p_start = start_time_p

            stream_add = P_trace.__add__(S_trace,
                                         fill_value=0,
                                         sanity_checks=True)
            zero_trace = Trace(np.zeros(npts),
                               header={
                                   "starttime": start_time_p,
                                   'delta': trace.meta.delta,
                                   "station": trace.meta.station,
                                   "network": trace.meta.network,
                                   "location": trace.meta.location,
                                   "channel": trace.meta.channel
                               })
            if 'T' in trace.meta.channel:
                total_trace = zero_trace.__add__(S_trace,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=S_trace.data,
                                                 sanity_checks=True)
                total_s_trace = total_trace.copy()
            else:
                total_trace = zero_trace.__add__(stream_add,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=stream_add.data,
                                                 sanity_checks=True)
                total_s_trace = zero_trace.__add__(S_trace,
                                                   method=0,
                                                   interpolation_samples=0,
                                                   fill_value=S_trace.data,
                                                   sanity_checks=True)
                total_p_trace = zero_trace.__add__(P_trace,
                                                   method=0,
                                                   interpolation_samples=0,
                                                   fill_value=P_trace.data,
                                                   sanity_checks=True)
                p_stream.append(total_p_trace)
            s_stream.append(total_s_trace)
            total_stream.append(total_trace)
            s_stream = self.BW_filter(s_stream)
            p_stream = self.BW_filter(p_stream)
            total_stream = self.BW_filter(total_stream)
        return total_stream, p_stream, s_stream, start_time_p, start_time_s
Example #5
0
    def get_window_split_syn(self, splitted_syn, epi, depth, time_at_receiver,
                             npts):
        tt_P = self.get_P(
            epi, depth
        )  # Estimated P-wave arrival, based on the known velocity model
        tt_S = self.get_S(
            epi, depth
        )  # Estimated S-wave arrival, based on the known velocity model

        diff = tt_S - tt_P

        P_start = time_at_receiver
        P_end = obspy.UTCDateTime(P_start + 5 + 20)
        S_start = obspy.UTCDateTime(time_at_receiver.timestamp + diff)
        S_end = obspy.UTCDateTime(S_start + 5 + 20)

        p_stream = Stream()
        s_stream = Stream()
        total_stream = Stream()

        for i, trace in enumerate(splitted_syn.traces):
            P_trace = Trace.slice(trace, P_start, P_end)
            S_trace = Trace.slice(trace, S_start, S_end)
            stream_add = P_trace.__add__(S_trace,
                                         fill_value=0,
                                         sanity_checks=True)
            zero_trace = Trace(np.zeros(npts),
                               header={
                                   "starttime": P_start,
                                   'delta': trace.meta.delta,
                                   "station": trace.meta.station,
                                   "network": trace.meta.network,
                                   "location": trace.meta.location,
                                   "channel": trace.meta.channel,
                                   "instaseis": trace.meta.instaseis
                               })
            if 'T' in trace.meta.channel:
                total_trace = zero_trace.__add__(S_trace,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=S_trace.data,
                                                 sanity_checks=True)
                total_s_trace = total_trace.copy()
            else:
                total_trace = zero_trace.__add__(stream_add,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=stream_add.data,
                                                 sanity_checks=True)
                total_s_trace = zero_trace.__add__(S_trace,
                                                   method=0,
                                                   interpolation_samples=0,
                                                   fill_value=S_trace.data,
                                                   sanity_checks=True)
                total_p_trace = zero_trace.__add__(P_trace,
                                                   method=0,
                                                   interpolation_samples=0,
                                                   fill_value=P_trace.data,
                                                   sanity_checks=True)
                p_stream.append(total_p_trace)
            s_stream.append(total_s_trace)
            total_stream.append(total_trace)
        return total_stream, p_stream, s_stream
    def get_sw(self, time_at_rec, epi, depth, la_s, lo_s, npts_trace):
        gf = self.db.get_greens_function(epicentral_distance_in_degree=epi,
                                         source_depth_in_m=depth,
                                         origin_time=time_at_rec,
                                         kind=self.par['kind'],
                                         kernelwidth=self.par['kernelwidth'],
                                         definition=self.par['definition'])

        dist, az, baz = gps2dist_azimuth(lat1=la_s,
                                         lon1=lo_s,
                                         lat2=self.par['la_r'],
                                         lon2=self.par['lo_r'],
                                         a=self.par['radius'],
                                         f=0)

        Surface = Surface_waves(self.par)
        Phases_R = Surface.get_R_phases(time_at_rec)
        Phases_L = Surface.get_L_phases(time_at_rec)

        for j, R in enumerate(Phases_R):
            R_format_gf = Stream()
            run = gf.copy()
            for i in range(len(gf.traces)):
                if 'Z' not in gf.traces[i].id:
                    continue
                else:
                    R_trim = run.traces[i].trim(
                        starttime=R['starttime'](dist, depth),
                        endtime=R['endtime'](dist, depth))

                    zero_trace = Trace(np.zeros(npts_trace),
                                       header={
                                           "starttime": R['starttime'](dist,
                                                                       depth),
                                           'delta': gf.traces[0].meta.delta,
                                           'definition':
                                           self.par['definition'],
                                           'kernelwidth':
                                           self.par['kernelwidth'],
                                           'kind': self.par['kind'],
                                           "instaseis":
                                           gf.traces[0].meta.instaseis,
                                           'channel': gf.traces[i].id
                                       })
                    R_Trace = Trace(R_trim.data,
                                    header={
                                        "starttime": R['starttime'](dist,
                                                                    depth),
                                        'delta': gf.traces[0].meta.delta,
                                        'definition': self.par['definition'],
                                        'kernelwidth': self.par['kernelwidth'],
                                        'kind': self.par['kind'],
                                        "instaseis":
                                        gf.traces[0].meta.instaseis,
                                        'channel': gf.traces[i].id
                                    })
                    filled_trace = zero_trace.__add__(R_Trace,
                                                      method=0,
                                                      interpolation_samples=0,
                                                      fill_value=R_Trace.data,
                                                      sanity_checks=False)
                    R_format_gf.append(filled_trace)

            zss = R_format_gf.traces[0].data
            zds = R_format_gf.traces[1].data
            zdd = R_format_gf.traces[2].data
            zep = R_format_gf.traces[3].data

            G_R_Z = np.ones((npts_trace, 5))
            G_R_Z[:, 0] = zss * (0.5) * np.cos(
                2 * np.deg2rad(self.par['az'])) - zdd * 0.5
            G_R_Z[:, 1] = -zdd * 0.5 - zss * (0.5) * np.cos(
                2 * np.deg2rad(self.par['az']))
            # R_Zz G[0:G_z, 1] =  zdd * (1/3) + zep * (1/3)
            G_R_Z[:, 2] = zss * np.sin(2 * np.deg2rad(self.par['az']))
            G_R_Z[:, 3] = -zds * np.cos(np.deg2rad(self.par['az']))
            G_R_Z[:, 4] = -zds * np.sin(np.deg2rad(self.par['az']))

            R_new = np.vstack((G_R_Z)) if j == 0 else np.vstack((R_new, G_R_Z))

        for j, L in enumerate(Phases_L):
            L_format_gf = Stream()
            run = gf.copy()
            for i in range(len(gf.traces)):
                if 'T' not in gf.traces[i].id:
                    continue
                else:
                    L_trim = run.traces[i].trim(
                        starttime=L['starttime'](dist, depth),
                        endtime=L['endtime'](dist, depth))

                    zero_trace = Trace(np.zeros(npts_trace),
                                       header={
                                           "starttime": L['starttime'](dist,
                                                                       depth),
                                           'delta': gf.traces[0].meta.delta,
                                           'definition':
                                           self.par['definition'],
                                           'kernelwidth':
                                           self.par['kernelwidth'],
                                           'kind': self.par['kind'],
                                           "instaseis":
                                           gf.traces[0].meta.instaseis,
                                           'channel': gf.traces[i].id
                                       })
                    L_Trace = Trace(L_trim.data,
                                    header={
                                        "starttime": L['starttime'](dist,
                                                                    depth),
                                        'delta': gf.traces[0].meta.delta,
                                        'definition': self.par['definition'],
                                        'kernelwidth': self.par['kernelwidth'],
                                        'kind': self.par['kind'],
                                        "instaseis":
                                        gf.traces[0].meta.instaseis,
                                        'channel': gf.traces[i].id
                                    })
                    filled_trace = zero_trace.__add__(L_Trace,
                                                      method=0,
                                                      interpolation_samples=0,
                                                      fill_value=L_Trace.data,
                                                      sanity_checks=False)
                    L_format_gf.append(filled_trace)

            tss = L_format_gf.traces[0].data
            tds = L_format_gf.traces[1].data

            G_L_T = np.ones((npts_trace, 5))

            G_L_T[:, 0] = -tss * (0.5) * np.sin(2 * np.deg2rad(self.par['az']))
            G_L_T[:, 1] = tss * (0.5) * np.sin(2 * np.deg2rad(self.par['az']))
            # L_Tt G[G_r:G_t, 1] =   0
            G_L_T[:, 2] = tss * np.cos(2 * np.deg2rad(self.par['az']))
            G_L_T[:, 3] = tds * np.sin(np.deg2rad(self.par['az']))
            G_L_T[:, 4] = -tds * np.cos(np.deg2rad(self.par['az']))

            L_new = np.vstack((G_L_T)) if j == 0 else np.vstack((L_new, G_L_T))
        G_R_L = np.vstack((R_new, L_new))
        return G_R_L, R_new, L_new
    def get_bw(self, time_at_rec, epi, depth, npts_trace):
        gf = self.db.get_greens_function(epicentral_distance_in_degree=epi,
                                         source_depth_in_m=depth,
                                         origin_time=time_at_rec,
                                         kind=self.par['kind'],
                                         kernelwidth=self.par['kernelwidth'],
                                         definition=self.par['definition'])
        tt_P = self.window.get_P(epi, depth)
        tt_S = self.window.get_S(epi, depth)
        p_time = time_at_rec.timestamp + tt_P
        s_time = time_at_rec.timestamp + tt_S
        start_time_p = obspy.UTCDateTime(p_time - 10)
        start_time_s = obspy.UTCDateTime(s_time - 10)
        end_time_p = obspy.UTCDateTime(p_time + 44.2)
        end_time_s = obspy.UTCDateTime(s_time + 44.2)

        format_gf = Stream()
        for i in range(len(gf.traces)):
            if i == 0 or i == 3:
                stream_add = Trace.slice(gf.traces[i], start_time_s,
                                         end_time_s)
            else:
                P_trace = Trace.slice(gf.traces[i], start_time_p, end_time_p)
                S_trace = Trace.slice(gf.traces[i], start_time_s, end_time_s)
                stream_add = P_trace.__add__(S_trace,
                                             fill_value=0,
                                             sanity_checks=True)
            zero_trace = Trace(np.zeros(npts_trace),
                               header={
                                   "starttime": start_time_p,
                                   'delta': gf.traces[0].meta.delta,
                                   'definition': self.par['definition'],
                                   'kernelwidth': self.par['kernelwidth'],
                                   'kind': self.par['kind'],
                                   "instaseis": gf.traces[0].meta.instaseis,
                                   'channel': gf.traces[i].id
                               })
            filled_trace = zero_trace.__add__(stream_add,
                                              method=0,
                                              interpolation_samples=0,
                                              fill_value=stream_add.data,
                                              sanity_checks=False)
            format_gf.append(filled_trace)

        tss = format_gf.traces[0].data
        zss = format_gf.traces[1].data
        rss = format_gf.traces[2].data
        tds = format_gf.traces[3].data
        zds = format_gf.traces[4].data
        rds = format_gf.traces[5].data
        zdd = format_gf.traces[6].data
        rdd = format_gf.traces[7].data
        zep = format_gf.traces[8].data
        rep = format_gf.traces[9].data

        G_z = np.ones((npts_trace, 5))
        G_r = np.ones((npts_trace, 5))
        G_t = np.ones((npts_trace, 5))

        G_z[:, 0] = zss * (0.5) * np.cos(
            2 * np.deg2rad(self.par['az'])) - zdd * 0.5
        G_z[:, 1] = -zdd * 0.5 - zss * (0.5) * np.cos(
            2 * np.deg2rad(self.par['az']))
        # _z G[0:G_z, 1] =  zdd * (1/3) + zep * (1/3)
        G_z[:, 2] = zss * np.sin(2 * np.deg2rad(self.par['az']))
        G_z[:, 3] = -zds * np.cos(np.deg2rad(self.par['az']))
        G_z[:, 4] = -zds * np.sin(np.deg2rad(self.par['az']))

        G_r[:, 0] = rss * (0.5) * np.cos(
            2 * np.deg2rad(self.par['az'])) - rdd * 0.5
        G_r[:, 1] = -0.5 * rdd - rss * (0.5) * np.cos(
            2 * np.deg2rad(self.par['az']))
        # _r G[G_z:G_r, 1] =  rdd * (1/3) + rep * (1/3)
        G_r[:, 2] = rss * np.sin(2 * np.deg2rad(self.par['az']))
        G_r[:, 3] = -rds * np.cos(np.deg2rad(self.par['az']))
        G_r[:, 4] = -rds * np.sin(np.deg2rad(self.par['az']))

        G_t[:, 0] = -tss * (0.5) * np.sin(2 * np.deg2rad(self.par['az']))
        G_t[:, 1] = tss * (0.5) * np.sin(2 * np.deg2rad(self.par['az']))
        # _t G[G_r:G_t, 1] =   0
        G_t[:, 2] = tss * np.cos(2 * np.deg2rad(self.par['az']))
        G_t[:, 3] = tds * np.sin(np.deg2rad(self.par['az']))
        G_t[:, 4] = -tds * np.cos(np.deg2rad(self.par['az']))

        G_tot = np.vstack((np.vstack((G_z, G_r)), G_t))

        return G_tot, G_z, G_r, G_t
    def get_window_obspy(self, seis_traces, epi, depth, time, npts):
        self.origin = seis_traces
        tt_P = self.get_P(
            epi, depth
        )  # Estimated P-wave arrival, based on the known velocity model
        tt_S = self.get_S(
            epi, depth
        )  # Estimated S-wave arrival, based on the known velocity model
        sec_per_sample = 1 / (seis_traces[0].meta.sampling_rate)
        #
        self.BW_stream = Stream()
        self.S_stream = Stream()
        self.P_stream = Stream()
        p_time = time.timestamp + tt_P
        s_time = time.timestamp + tt_S
        self.start_P = obspy.UTCDateTime(p_time - 5)
        self.start_S = obspy.UTCDateTime(s_time - 15)
        self.or_S_len = int(
            (self.start_S - time) / seis_traces.traces[0].stats.delta)
        self.or_P_len = int(
            (self.start_P - time) / seis_traces.traces[0].stats.delta)
        end_time_p = obspy.UTCDateTime(p_time + 20)
        end_time_s = obspy.UTCDateTime(s_time + 35)

        for i, trace in enumerate(seis_traces.traces):
            P_trace = Trace.slice(trace, self.start_P, end_time_p)
            self.P_len = len(P_trace)
            S_trace = Trace.slice(trace, self.start_S, end_time_s)
            self.S_len = len(S_trace)
            stream_add = P_trace.__add__(S_trace,
                                         fill_value=0,
                                         sanity_checks=True)
            zero_trace = Trace(np.zeros(npts),
                               header={
                                   "starttime": self.start_P,
                                   'delta': trace.meta.delta,
                                   "station": trace.meta.station,
                                   "network": trace.meta.network,
                                   "location": trace.meta.location,
                                   "channel": trace.meta.channel
                               })
            if 'T' in trace.meta.channel:
                total_trace = zero_trace.__add__(S_trace,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=S_trace.data,
                                                 sanity_checks=True)
                total_s_trace = total_trace.copy()
            else:
                total_trace = zero_trace.__add__(stream_add,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=stream_add.data,
                                                 sanity_checks=True)
                total_s_trace = zero_trace.__add__(S_trace,
                                                   method=0,
                                                   interpolation_samples=0,
                                                   fill_value=S_trace.data,
                                                   sanity_checks=True)
                total_p_trace = zero_trace.__add__(P_trace,
                                                   method=0,
                                                   interpolation_samples=0,
                                                   fill_value=P_trace.data,
                                                   sanity_checks=True)
                self.P_stream.append(total_p_trace)
            self.S_stream.append(total_s_trace)
            self.BW_stream.append(total_trace)
            self.S_stream = self.BW_filter(self.S_stream)
            self.P_stream = self.BW_filter(self.P_stream)
            self.BW_stream = self.BW_filter(self.BW_stream)
Example #9
0
    def get_window_obspy(self, seis_traces, epi, depth, or_time, npts):
        tt_P = self.get_P(
            epi, depth
        )  # Estimated P-wave arrival, based on the known velocity model
        tt_S = self.get_S(
            epi, depth
        )  # Estimated S-wave arrival, based on the known velocity model
        sec_per_sample = 1 / (seis_traces[0].meta.sampling_rate)

        total_stream = Stream()
        s_stream = Stream()
        p_stream = Stream()

        p_time = or_time.timestamp + tt_P
        s_time = or_time.timestamp + tt_S
        start_time_p = obspy.UTCDateTime(
            p_time - 5)  # -10 , + 44.2 --> PAPER: STAHLER & SIGLOCH
        end_time_p = obspy.UTCDateTime(p_time + 20)
        start_time_s = obspy.UTCDateTime(s_time - 15)
        end_time_s = obspy.UTCDateTime(s_time + 35)

        for i, trace in enumerate(seis_traces.traces):
            P_trace = Trace.slice(trace, start_time_p, end_time_p)
            # P_trace.detrend(type='demean')
            S_trace = Trace.slice(trace, start_time_s, end_time_s)
            # S_trace.detrend(type='demean')
            stream_add = P_trace.__add__(S_trace,
                                         fill_value=0,
                                         sanity_checks=True)
            zero_trace = Trace(np.zeros(npts),
                               header={
                                   "starttime": start_time_p,
                                   'delta': trace.meta.delta,
                                   "station": trace.meta.station,
                                   "network": trace.meta.network,
                                   "location": trace.meta.location,
                                   "channel": trace.meta.channel
                               })
            if 'T' in trace.meta.channel:
                total_trace = zero_trace.__add__(S_trace,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=S_trace.data,
                                                 sanity_checks=True)
                total_s_trace = total_trace.copy()
            else:
                total_trace = zero_trace.__add__(stream_add,
                                                 method=0,
                                                 interpolation_samples=0,
                                                 fill_value=stream_add.data,
                                                 sanity_checks=True)
                total_s_trace = zero_trace.__add__(S_trace,
                                                   method=0,
                                                   interpolation_samples=0,
                                                   fill_value=S_trace.data,
                                                   sanity_checks=True)
                total_p_trace = zero_trace.__add__(P_trace,
                                                   method=0,
                                                   interpolation_samples=0,
                                                   fill_value=P_trace.data,
                                                   sanity_checks=True)
                p_stream.append(total_p_trace)
            s_stream.append(total_s_trace)
            total_stream.append(total_trace)
            s_stream = self.BW_filter(s_stream)
            p_stream = self.BW_filter(p_stream)
            total_stream = self.BW_filter(total_stream)
        return total_stream, p_stream, s_stream, start_time_p, start_time_s