def main():
    # === Read input file ===
    param = toml.load(toml_path, _dict=dict)

    # === Read the mSEED file ===
    get_parameters = Get_Parameters()
    mSEED_path = get_parameters.Get_Path(param['directory'],
                                         param['mSEED_file'])
    stream = obspy.read(mSEED_path)
    PRIOR = get_parameters.PRIOR(stream, param['PRIOR'])

    import numpy as np
    len_trace = len(stream.traces[0].data)
    test__data = np.hstack(
        (np.zeros(56279 - 100), np.hanning(100) * 0.2, np.zeros(56280)))
    stream.traces[0].data = test__data
    stream.traces[1].data = test__data
    stream.traces[2].data = test__data

    # === Process the data ===
    # Process = Process_mSEED(stream)
    # st = Process.remove_instrument() # Remove instrument response
    # stream = Process.automatic_rotate(PRIOR['baz']) # Rotate your Traces

    # === GET PRIOR ===
    PRIOR = get_parameters.Get_ranges(PRIOR)  # WHEN RUN IS NOT YET DONE

    sample_path = get_parameters.Start_sample_path(PRIOR)

    # === Cut the BW windows (P&S) ===
    BW_obs = Cut_windows(PRIOR['VELOC_taup'],
                         P_HP=PRIOR['P_HP'],
                         P_LP=PRIOR['P_LP'],
                         S_HP=PRIOR['S_HP'],
                         S_LP=PRIOR['S_LP'],
                         Pre_P=PRIOR['Pre_P'],
                         Pre_S=PRIOR['Pre_S'],
                         Post_P=PRIOR['Post_P'],
                         Post_S=PRIOR['Post_S'],
                         zero_phase=PRIOR['Zero_Phase'],
                         Order=PRIOR['Order'],
                         Taper=PRIOR['Taper_obs'])
    if PRIOR['P_pick'] == None or PRIOR['S_pick'] == None:
        BW_obs.Get_bw_windows(stream, PRIOR['epi_s'], PRIOR['depth_s'],
                              PRIOR['origin_time'])
    else:
        P_pick = obspy.UTCDateTime(2019, 7, 26, 12, 46, 8)
        BW_obs.Get_bw_windows_MANUAL(stream, P_pick, P_pick,
                                     PRIOR['origin_time'])

    # === Start Grid Search ===
    depth = 58691.9  #           #5000
    epi = 24.7437  #            #PRIOR['epi_s']
    M0 = 135943762646494.86  #      #PRIOR['M0']
    GS = Grid_Search(PRIOR)
    GS.start_GS(BW_obs, depth, epi, M0)
Exemplo n.º 2
0
def main():
    # === Read the mSEED file ===
    get_parameters = Get_Parameters()
    mSEED_path = get_parameters.Get_Path()
    stream = obspy.read(mSEED_path)
    # stream.resample(sampling_rate = 20.)
    # stream.plot()

    # Stream for only BFO station
    # st = Stream()
    # st.append(stream[2])
    # st.append(stream[0])
    # st.append(stream[1])

    PRIOR = get_parameters.PRIOR(stream, inventory=False)

    # === Process the data ===
    # Process = Process_mSEED(stream)
    # st = Process.remove_instrument() # Remove instrument response
    # st = Process.automatic_rotate(PRIOR['baz']) # Rotate your Traces

    PRIOR = get_parameters.Get_ranges(PRIOR)

    sample_path = get_parameters.Start_sample_path(PRIOR)

    # === Cut the BW windows (P&S) ===
    BW_obs = Cut_windows(PRIOR['VELOC_taup'],
                         P_HP=PRIOR['P_HP'],
                         P_LP=PRIOR['P_LP'],
                         S_HP=PRIOR['S_HP'],
                         S_LP=PRIOR['S_LP'])

    npts = stream.traces[0].stats.npts
    BW_obs.Get_bw_windows(stream,
                          PRIOR['epi_s'],
                          PRIOR['depth_s'],
                          PRIOR['origin_time'],
                          npts=PRIOR['npts'])
    # tt_P = obspy.UTCDateTime(2019, 1, 3, 15, 9, 54.9)
    # tt_S = obspy.UTCDateTime(2019, 1, 3, 15, 18, 34.6)
    # BW_obs.Get_bw_windows_MANUAL_OLD(stream, tt_P, tt_S, PRIOR['origin_time'], npts=npts)

    # === Start the MCMC ===
    # mcmc = MCMC(PRIOR['origin_time'], PRIOR, sample_path=sample_path)
    # mcmc.start_BW(BW_obs)

    # === Plot waveforms from a previous run ===
    PRIOR['VELOC'] = PRIOR['VELOC']
    path_txt = '/home/nienke/Documents/Master/Data/MSS/Output/MAAK_7J_SYNT4_02_MHZ.txt'
    savedir = '/home/nienke/Documents/Master/Data/MSS/Output/'
    plot = Plot_waveforms(BW_obs, path_txt, savedir, PRIOR,
                          PRIOR['origin_time'])
    plot.get_waveforms()
Exemplo n.º 3
0
    def __init__(self, or_time, PRIOR, sample_path=None):
        self.or_time = or_time
        self.prior = PRIOR
        self.sample_path = sample_path

        self.model = Model_samples(self.prior)
        self.BW_syn = Cut_windows(self.prior['VELOC_taup'], P_HP=PRIOR['P_HP'], P_LP=PRIOR['P_LP'], S_HP=PRIOR['S_HP'],
                                  S_LP=PRIOR['S_LP'], Pre_P=PRIOR['Pre_P'], Pre_S=PRIOR['Pre_S'],
                                  Post_P=PRIOR['Post_P'], Post_S=PRIOR['Post_S'], Taper_len=PRIOR['Taper_len'],
                                  Zero_len=PRIOR['Zero_len'])
        self.seis = Get_Seismogram(self.prior)
        self.mis = Misfit()
Exemplo n.º 4
0
    def __init__(self, PRIOR):
        self.or_time = PRIOR['origin_time']
        self.prior = PRIOR

        self.model = Model_samples(self.prior)
        self.BW_syn = Cut_windows(self.prior['VELOC_taup'], P_HP=PRIOR['P_HP'], P_LP=PRIOR['P_LP'], S_HP=PRIOR['S_HP'],
                                  S_LP=PRIOR['S_LP'], Pre_P=PRIOR['Pre_P'], Pre_S=PRIOR['Pre_S'],
                                  Post_P=PRIOR['Post_P'], Post_S=PRIOR['Post_S'],
                                  global_P_shift=PRIOR['Global_P_shift'], global_S_shift=PRIOR['Global_S_shift'],
                                  zero_phase=PRIOR['Zero_Phase'],
                                  Order=PRIOR['Order'], Taper=PRIOR['Taper_syn'], Taper_len=PRIOR['Taper_len'],
                                  Zero_len=PRIOR['Zero_len'])
        self.seis = Get_Seismogram(self.prior)
        self.mis = Misfit()
Exemplo n.º 5
0
def main():
    # === Read input file ===
    param = toml.load(toml_path, _dict=dict)

    # === Read the mSEED file ===
    get_parameters = Get_Parameters()
    mSEED_path = get_parameters.Get_Path(param['directory'],
                                         param['mSEED_file'])
    stream = obspy.read(mSEED_path)
    PRIOR = get_parameters.PRIOR(stream, param['PRIOR'])

    # === GET PRIOR ===
    PRIOR = get_parameters.Get_ranges(PRIOR)  # WHEN RUN IS NOT YET DONE

    # === Cut the BW windows (P&S) ===
    BW_obs = Cut_windows(PRIOR['VELOC_taup'],
                         P_HP=PRIOR['P_HP'],
                         P_LP=PRIOR['P_LP'],
                         S_HP=PRIOR['S_HP'],
                         S_LP=PRIOR['S_LP'],
                         Pre_P=PRIOR['Pre_P'],
                         Pre_S=PRIOR['Pre_S'],
                         Post_P=PRIOR['Post_P'],
                         Post_S=PRIOR['Post_S'],
                         global_P_shift=PRIOR['Global_P_shift'],
                         global_S_shift=PRIOR['Global_S_shift'],
                         zero_phase=PRIOR['Zero_Phase'],
                         Order=PRIOR['Order'],
                         Taper=PRIOR['Taper_obs'],
                         Taper_len=PRIOR['Taper_len'],
                         Zero_len=PRIOR['Zero_len'])
    if PRIOR['P_pick'] == None or PRIOR['S_pick'] == None:
        BW_obs.Get_bw_windows(stream,
                              PRIOR['epi_s'],
                              PRIOR['depth_s'],
                              PRIOR['origin_time'],
                              MANUAL=False)
    else:
        BW_obs.Get_bw_windows(stream,
                              PRIOR['P_pick'],
                              PRIOR['S_pick'],
                              PRIOR['origin_time'],
                              MANUAL=True)

    ## === 2. Get Green's Functions ===
    db = instaseis.open_db(PRIOR['VELOC'])
    depth = 58691.9

    a = 1
Exemplo n.º 6
0
class Grid_Search:
    def __init__(self, PRIOR):
        self.or_time = PRIOR['origin_time']
        self.prior = PRIOR

        self.model = Model_samples(self.prior)
        self.BW_syn = Cut_windows(self.prior['VELOC_taup'], P_HP=PRIOR['P_HP'], P_LP=PRIOR['P_LP'], S_HP=PRIOR['S_HP'],
                                  S_LP=PRIOR['S_LP'], Pre_P=PRIOR['Pre_P'], Pre_S=PRIOR['Pre_S'],
                                  Post_P=PRIOR['Post_P'], Post_S=PRIOR['Post_S'],
                                  global_P_shift=PRIOR['Global_P_shift'], global_S_shift=PRIOR['Global_S_shift'],
                                  zero_phase=PRIOR['Zero_Phase'],
                                  Order=PRIOR['Order'], Taper=PRIOR['Taper_syn'], Taper_len=PRIOR['Taper_len'],
                                  Zero_len=PRIOR['Zero_len'])
        self.seis = Get_Seismogram(self.prior)
        self.mis = Misfit()

    def start_GS(self, BW_obs, depth, epi, M0):
        savepath = self.prior['save_dir'] + '/%s.txt' % self.prior['save_name']
        color = 'b'
        # self.plot_original_vs_filter(BW_obs,color,self.prior['save_dir'],"OBS")

        strike_len = np.linspace(0, 360, int(360 / 15) + 1, endpoint=True)
        dip_len = np.linspace(0, 90, int(90 / 5) + 1, endpoint=True)
        rake_len = np.linspace(-180, 180, int(360 / 15) + 1, endpoint=True)

        with open(savepath, 'w') as save_file:
            self.write_par(save_file)
            i = 0
            print('Iteration: %i' % i)
            for i_s, strike in enumerate(strike_len):
                for i_d, dip in enumerate(dip_len):
                    for i_r, rake in enumerate(rake_len):

                        ## Get the synthetic Data:
                        dict = geo.Geodesic(a=self.prior['radius'], f=self.prior['f']).ArcDirect(
                            lat1=self.prior['la_r'],
                            lon1=self.prior['lo_r'],
                            azi1=self.prior['baz'],
                            a12=epi, outmask=1929)
                        st_syn = self.seis.get_seis_manual(la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth,
                                                           strike=strike, dip=dip, rake=rake,
                                                           time=self.or_time, M0=M0)

                        self.BW_syn.Get_bw_windows(st_syn, epi, depth, self.or_time, self.prior['Full_P_shift'],self.prior['Full_S_shift'])
                        # color = 'r'
                        # self.plot_original_vs_filter(self.BW_syn,color, self.prior['save_dir'], str(i))



                        ## Determine the misfit:
                        Xi_bw, Norms, amplitude, time_shift, fig = self.mis.CC_BW(BW_obs, self.BW_syn,
                                                                                  self.prior['Full_P_shift'],
                                                                                  self.prior['Full_S_shift'],
                                                                                  self.prior['PLOT'])

                        M0_New = M0 / np.mean(amplitude)  # Only Based on PZ
                        if self.prior['PLOT'] == True:
                            # self.plot()
                            if not os.path.exists(self.prior['save_dir'] + '/plots/'):
                                os.makedirs(self.prior['save_dir'] + '/plots/')
                            fig.savefig(
                                self.prior['save_dir'] + '/plots/%.3f_%.3f_%.3f_%05i.png' % (strike, dip, rake, i))
                            plt.close("all")

                        self.write_sample(save_file, epi, depth, strike, dip, rake, M0_New, Xi_bw, Norms, amplitude[0],
                                          time_shift, i, accept=1)
                        i += 1
                        print('Iteration: %i' % i)
            save_file.close()

    # def Full_shift(self, st_syn, st_obs, Full_shift):
    #     zeros_int =
    #
    #     tr_syn = self.shift(tr_syn, Full_shift)
    #     if Full_shift < 0:
    #         tr_obs[-time_shift:] = np_array[:time_shift]
    #     elif Full_shift == 0:
    #         new_array[:] = np_array[:]
    #     else:
    #         new_array[:-time_shift] = np_array[time_shift:]

    def write_sample(self, file_name, epi, depth, strike, dip, rake, M0, Xi_bw, Norms, PZ_Amplitude, time_shift,
                     iteration,
                     accept=0):
        s_z = Xi_bw[0]  # * 0.1 #* 0.14
        s_r = Xi_bw[1]  # * 0.1#* 0.35
        s_t = Xi_bw[2]  # * 1
        p_z = Xi_bw[3]  # * 5
        p_r = Xi_bw[4]  # * 5#* 0.1
        Xi = s_z + s_r + s_t + p_z + p_r

        Ns_z = Norms[0]  # * 0.1 #* 0.14
        Ns_r = Norms[1]  # * 0.1#* 0.35
        Ns_t = Norms[2]  # * 1
        Np_z = Norms[3]  # * 5
        Np_r = Norms[4]  # * 5#* 0.1

        file_name.write("%.5e, %.5e, %.5e, %.5e, %.5e, %.5e, %.5e, " % (
            epi, depth, strike, dip, rake, M0, Xi))
        file_name.write("%.5e, %.5e, %.5e, %.5e, %.5e, %.5e,%.5e,%.5e,%.5e,%.5e,%.5e, " % (
            p_z, p_r, s_z, s_r, s_t, Np_z, Np_r, Ns_z, Ns_r, Ns_t, PZ_Amplitude))
        file_name.write("%i, %i, %i\n\r" % (time_shift[0], time_shift[1], iteration))

    def write_par(self, file_name):

        file_name.write(
            "epi, depth, strike, dip, rake, M0, Total-misfit, p_z, p_r, s_z, s_r, s_t, Npz,Npr,Nsz,Nsr,Nst,PZ_Amplitude, shift_S, shift-P, Iteration\n\r")
        file_name.write("Velocity Model:%s\n\r" % self.prior['VELOC'])
        file_name.write("Station:%s\n\r" % self.prior['station'])
        file_name.write("Sampling rate:%.2f\n\r" % self.prior['sampling_rate'])
        file_name.write("la_r:%.4f\n\r" % self.prior['la_r'])
        file_name.write("lo_r:%.4f\n\r" % self.prior['lo_r'])
        file_name.write("kind:%s\n\r" % self.prior['kind'])  #
        file_name.write("Pre_P:%.2f\n\r" % self.prior['Pre_P'])  #
        file_name.write("Pre_S:%.2f\n\r" % self.prior['Pre_S'])  #
        file_name.write("Post_P:%.2f\n\r" % self.prior['Post_P'])  #
        file_name.write("Post_S:%.2f\n\r" % self.prior['Post_S'])  #
        file_name.write("P_LP:%.2f\n\r" % self.prior['P_LP'])  #
        file_name.write("P_HP:%.2f\n\r" % self.prior['P_HP'])  #
        file_name.write("S_LP:%.2f\n\r" % self.prior['S_LP'])  #
        file_name.write("S_HP:%.2f\n\r" % self.prior['S_HP'])  #
        file_name.write("Taper_obs:%5i\n\r" % self.prior['Taper_obs'])  #
        file_name.write("Taper_syn:%5i\n\r" % self.prior['Taper_syn'])  #
        file_name.write("Zero_phase:%5i\n\r" % self.prior['Zero_Phase'])  #
        file_name.write("Order:%5i\n\r" % self.prior['Order'])  #
        file_name.write("Taper Length:%.2f\n\r" % self.prior['Taper_len'])  #
        file_name.write("Zero Length:%.2f\n\r" % self.prior['Zero_len'])  #
        file_name.write("Global P Shift:%.2f\n\r" % self.prior['Global_P_shift'])  #
        file_name.write("Global S Shift:%.2f\n\r" % self.prior['Global_S_shift'])  #
        file_name.write("Full P Shift:%i\n\r" % self.prior['Full_P_shift'])  #
        file_name.write("Full S Shift:%i\n\r" % self.prior['Full_S_shift'])  #
        file_name.write("amount samples:%i\n\r" % self.prior['sample_number'])  #
        file_name.write("Temperature:%i\n\r" % self.prior['Temperature'])  #
        file_name.write("Radius:%.4f\n\r" % self.prior['radius'])  #
        file_name.write("Flattening:%.4f\n\r" % self.prior['f'])  #
        file_name.write("Azimuth:%.4f\n\r" % self.prior['az'])  #

    def plot_original_vs_filter(self, stream, color, savepath, save_name):
        stream.original.trim(self.prior['origin_time'])

        plt.figure(figsize=(8, 10))
        ax1 = plt.subplot(321)
        x = np.arange(len(stream.original.traces[0]))
        x_cut = x[stream.or_P_len - 500:stream.or_P_len + stream.P_len + 500]
        plt.plot(stream.original.traces[0], 'g')
        # plt.plot(x,self.BW_syn.original.traces[0], 'r')
        plt.plot(x_cut, stream.P_stream.traces[0], color)
        ymin, ymax = ax1.get_ylim()
        plt.vlines(stream.or_P_len, ymin=ymin, ymax=ymax, colors=color, linewidth=3, label='Obs_P')
        plt.vlines(stream.or_P_len + self.prior['Pre_P'] * 20 + self.prior['Post_P'] * 20, ymin=ymin, ymax=ymax,
                   colors=color, linewidth=3, label='Obs_P')
        plt.xlim(stream.or_P_len - 100, stream.or_P_len + 200)
        min_ = min(np.hstack((stream.original.traces[0].data[stream.or_P_len - 100:stream.or_P_len + 400],
                              stream.P_stream.traces[0].data)))
        max_ = max(np.hstack((stream.original.traces[0].data[stream.or_P_len - 100:stream.or_P_len + 400],
                              stream.P_stream.traces[0].data)))
        plt.ylim(min_, max_)
        plt.grid(True)
        plt.title('PZ')

        ax2 = plt.subplot(323)
        x = np.arange(len(stream.original.traces[1]))
        x_cut = x[stream.or_P_len - 500:stream.or_P_len + stream.P_len + 500]
        plt.plot(stream.original.traces[1], 'g')
        # plt.plot(x,self.BW_syn.original.traces[0], 'r')
        plt.plot(x_cut, stream.P_stream.traces[1], color)
        ymin, ymax = ax2.get_ylim()
        plt.vlines(stream.or_P_len, ymin=ymin, ymax=ymax, colors=color, linewidth=3, label='Obs_P')
        plt.vlines(stream.or_P_len + self.prior['Pre_P'] * 20 + self.prior['Post_P'] * 20, ymin=ymin, ymax=ymax,
                   colors=color, linewidth=3, label='Obs_P')
        plt.xlim(stream.or_P_len - 100, stream.or_P_len + 200)
        min_ = min(np.hstack((stream.original.traces[1].data[stream.or_P_len - 100:stream.or_P_len + 400],
                              stream.P_stream.traces[1].data)))
        max_ = max(np.hstack((stream.original.traces[1].data[stream.or_P_len - 100:stream.or_P_len + 400],
                              stream.P_stream.traces[1].data)))
        plt.ylim(min_, max_)
        plt.grid(True)
        plt.title('PR')

        ax3 = plt.subplot(322)
        x = np.arange(len(stream.original.traces[0]))
        x_cut = x[stream.or_S_len - 500:stream.or_S_len + stream.S_len + 500]
        plt.plot(stream.original.traces[0], 'g')
        # plt.plot(x,self.BW_syn.original.traces[0], 'r')
        plt.plot(x_cut, stream.S_stream.traces[0], color)
        ymin, ymax = ax3.get_ylim()
        plt.vlines(stream.or_S_len, ymin=ymin, ymax=ymax, colors=color, linewidth=3, label='Obs_S')
        plt.vlines(stream.or_S_len + self.prior['Pre_S'] * 20 + self.prior['Post_S'] * 20, ymin=ymin, ymax=ymax,
                   colors=color, linewidth=3, label='Obs_S')
        plt.xlim(stream.or_S_len - 100, stream.or_S_len + 400)
        min_ = min(np.hstack((stream.original.traces[0].data[stream.or_S_len - 100:stream.or_S_len + 400],
                              stream.S_stream.traces[0].data)))
        max_ = max(np.hstack((stream.original.traces[0].data[stream.or_S_len - 100:stream.or_S_len + 400],
                              stream.S_stream.traces[0].data)))
        plt.ylim(min_, max_)
        plt.grid(True)
        plt.title('SZ')

        ax4 = plt.subplot(324)
        x = np.arange(len(stream.original.traces[1]))
        x_cut = x[stream.or_S_len - 500:stream.or_S_len + stream.S_len + 500]
        plt.plot(stream.original.traces[1], 'g')
        # plt.plot(x,self.BW_syn.original.traces[0], 'r')
        plt.plot(x_cut, stream.S_stream.traces[1], color)
        ymin, ymax = ax4.get_ylim()
        plt.vlines(stream.or_S_len, ymin=ymin, ymax=ymax, colors=color, linewidth=3, label='Obs_S')
        plt.vlines(stream.or_S_len + self.prior['Pre_S'] * 20 + self.prior['Post_S'] * 20, ymin=ymin, ymax=ymax,
                   colors=color, linewidth=3, label='Obs_S')
        plt.xlim(stream.or_S_len - 100, stream.or_S_len + 400)
        min_ = min(np.hstack((stream.original.traces[1].data[stream.or_S_len - 100:stream.or_S_len + 400],
                              stream.S_stream.traces[1].data)))
        max_ = max(np.hstack((stream.original.traces[1].data[stream.or_S_len - 100:stream.or_S_len + 400],
                              stream.S_stream.traces[1].data)))
        plt.ylim(min_, max_)
        plt.grid(True)
        plt.title('SR')

        ax5 = plt.subplot(326)
        x = np.arange(len(stream.original.traces[2]))
        x_cut = x[stream.or_S_len - 500:stream.or_S_len + stream.S_len + 500]
        plt.plot(stream.original.traces[2], 'g')
        # plt.plot(x,self.BW_syn.original.traces[0], 'r')
        plt.plot(x_cut, stream.S_stream.traces[2], color)
        ymin, ymax = ax5.get_ylim()
        plt.vlines(stream.or_S_len, ymin=ymin, ymax=ymax, colors=color, linewidth=3, label='Obs_S')
        plt.vlines(stream.or_S_len + self.prior['Pre_S'] * 20 + self.prior['Post_S'] * 20, ymin=ymin, ymax=ymax,
                   colors=color, linewidth=3, label='Obs_S')
        plt.xlim(stream.or_S_len - 100, stream.or_S_len + 400)
        min_ = min(np.hstack((stream.original.traces[2].data[stream.or_S_len - 100:stream.or_S_len + 400],
                              stream.S_stream.traces[2].data)))
        max_ = max(np.hstack((stream.original.traces[2].data[stream.or_S_len - 100:stream.or_S_len + 400],
                              stream.S_stream.traces[2].data)))
        plt.ylim(min_, max_)
        plt.grid(True)
        plt.title('ST')

        plt.tight_layout()
        savepath = savepath + '/plots/'
        if not os.path.exists(savepath):
            os.makedirs(savepath)
        plt.savefig(savepath + '/Waveforms_%s.png' % save_name)
        plt.close("all")
Exemplo n.º 7
0
class MCMC:
    def __init__(self, or_time, PRIOR, sample_path=None):
        self.or_time = or_time
        self.prior = PRIOR
        self.sample_path = sample_path

        self.model = Model_samples(self.prior)
        self.BW_syn = Cut_windows(self.prior['VELOC_taup'], P_HP=PRIOR['P_HP'], P_LP=PRIOR['P_LP'], S_HP=PRIOR['S_HP'],
                                  S_LP=PRIOR['S_LP'], Pre_P=PRIOR['Pre_P'], Pre_S=PRIOR['Pre_S'],
                                  Post_P=PRIOR['Post_P'], Post_S=PRIOR['Post_S'], Taper_len=PRIOR['Taper_len'],
                                  Zero_len=PRIOR['Zero_len'])
        self.seis = Get_Seismogram(self.prior)
        self.mis = Misfit()

    def start_BW(self, BW_obs):
        self.BW_obs = BW_obs
        self.start_MCMC(self.prior['save_dir'] + '/%s.txt' % self.prior['save_name'], BW=True)

    def start_SW(self):
        raise ValueError('Surface waves Not implemented yet')

    def start_Bw_and_SW(self):
        raise ValueError('Surface waves Not implemented yet')

    def start_MCMC(self, savepath, BW=False, SW=False):
        if BW == False and SW == False:
            raise ValueError('Run either: start_SW (Surface waves) or start_BW (Body waves)')

        with open(savepath, 'w') as save_file:
            self.write_par(save_file, BW, SW)
            accepted = 0
            rejected = 0
            for self.i in range(self.prior['sample_number']):
                if self.i % 10 == 0:
                    print("proposal: %i, accepted: %i" % (self.i, accepted))
                    print("proposal: %i, rejected: %i" % (self.i, rejected))

                if self.i == 0:
                    if self.sample_path == None:
                        update = None
                        # epi, depth = self.model.model_samples()
                        # M0_old = self.prior['M0']
                        depth = 58691.9
                        epi = 24.7437
                        M0_old = 135943762646494.86

                        strike, dip, rake = self.model.model_samples_sdr()
                        moment_old = moment_old = np.array([strike, dip, rake])
                    else:
                        data = np.loadtxt(self.sample_path, delimiter=',')
                        # epi = data[0]
                        # depth = data[1]
                        strike = data[2]
                        dip = data[3]
                        rake = data[4]
                        # M0_old = data[5]
                        depth = 58691.9
                        epi = 24.7437
                        M0_old = 135943762646494.86

                else:
                    # update = np.random.choice(['epi', 'depth', 'moment'], 1)[0]
                    # epi, depth = self.model.model_samples(update, epi_old, depth_old)
                    # if epi < self.prior['epi']['range_min'] or epi > self.prior['epi']['range_max'] or depth < \
                    #         self.prior['depth']['range_min'] or depth > self.prior['depth']['range_max']:
                    #     continue
                    update = np.array(['moment'])
                    strike, dip, rake = self.model.model_samples_sdr(update, strike_old, dip_old, rake_old)

                self.G_function(epi, depth, M0_old, strike, dip, rake)

                if BW == True:
                    Xi_bw_new, amplitude, time_shift_new, fig = self.mis.CC_BW(self.BW_obs, self.BW_syn, self.or_time,
                                                                               self.prior['PLOT'])

                    s_z_new = Xi_bw_new[0]  # 1 *
                    s_r_new = Xi_bw_new[1]  # 1 *
                    s_t_new = Xi_bw_new[2]  # 5 *
                    p_z_new = Xi_bw_new[3]  # 5 *
                    p_r_new = Xi_bw_new[4]  # 2 *
                    bw_new = s_z_new + s_r_new + s_t_new + p_z_new + p_r_new
                    Xi_new = bw_new
                if SW == True:
                    # sw_new =
                    raise ValueError('Surface waves Not implemented yet')
                if BW == True and SW == True:
                    raise ValueError('Surface waves Not implemented yet')

                # M0 = M0_old / np.mean(amplitude)
                M0 = M0_old

                if self.i == 0:
                    if self.prior['PLOT'] == True and self.i % 1 == 0:
                        # self.plot()
                        if not os.path.exists(self.prior['save_dir'] + '/plots/'):
                            os.makedirs(self.prior['save_dir'] + '/plots/')
                        fig.savefig(
                            self.prior['save_dir'] + '/plots/SHIFT_%s_%05i.png' % (self.prior['save_name'], self.i))
                        plt.close("all")
                    if BW == True:
                        self.s_z_old = s_z_new
                        self.s_r_old = s_r_new
                        self.s_t_old = s_t_new
                        self.p_z_old = p_z_new
                        self.p_r_old = p_r_new
                        self.bw_old = bw_new
                    if SW == True:
                        raise ValueError('Surface waves Not implemented yet')
                    if BW == True and SW == True:
                        raise ValueError('Surface waves Not implemented yet')
                    Xi_old = Xi_new
                    epi_old = epi
                    depth_old = depth
                    strike_old = strike
                    dip_old = dip
                    rake_old = rake
                    M0_old = M0
                    time_shift_old = time_shift_new

                    self.write_sample(save_file, epi_old, depth_old, strike_old, dip_old, rake_old, M0_old, Xi_old, BW,
                                      SW, time_shift_old, accept=1)

                    continue
                random = np.random.random_sample((1,))
                if (Xi_new < Xi_old) or (np.exp((Xi_old - Xi_new) / self.prior['Temperature']) > random):
                    if self.prior['PLOT'] == True and self.i % 1 == 0:
                        # self.plot()
                        fig.savefig(
                            self.prior['save_dir'] + '/plots/SHIFT_%s_%05i.png' % (self.prior['save_name'], self.i))
                        plt.close("all")
                    print(Xi_new)
                    if BW == True:
                        self.s_z_old = s_z_new
                        self.s_r_old = s_r_new
                        self.s_t_old = s_t_new
                        self.p_z_old = p_z_new
                        self.p_r_old = p_r_new
                        self.bw_old = bw_new
                    if SW == True:
                        raise ValueError('Surface waves Not implemented yet')
                    if BW == True and SW == True:
                        raise ValueError('Surface waves Not implemented yet')
                    Xi_old = Xi_new
                    epi_old = epi
                    depth_old = depth
                    strike_old = strike
                    dip_old = dip
                    rake_old = rake
                    M0_old = M0
                    time_shift_old = time_shift_new
                    accepted = accepted + 1
                    if self.i % 10 == 0:
                        self.write_sample(save_file, epi_old, depth_old, strike_old, dip_old, rake_old, M0_old, Xi_old,
                                          BW, SW, time_shift_old, accept=1)
                else:
                    if self.prior['PLOT']:
                        plt.close("all")
                    rejected += 1
                    if self.i % 10 == 0:
                        self.write_sample(save_file, epi_old, depth_old, strike_old, dip_old, rake_old, M0_old, Xi_old,
                                          BW, SW, time_shift_old, accept=0)
            save_file.close()

    def G_function(self, epi, depth, M0, strike, dip, rake):
        dict = geo.Geodesic(a=self.prior['radius'], f=self.prior['f']).ArcDirect(lat1=self.prior['la_r'],
                                                                                 lon1=self.prior['lo_r'],
                                                                                 azi1=self.prior['baz'],
                                                                                 a12=epi, outmask=1929)

        st_syn = self.seis.get_seis_manual(la_s=dict['lat2'], lo_s=dict['lon2'], depth=depth,
                                           strike=strike, dip=dip, rake=rake,
                                           time=self.or_time, M0=M0)

        self.BW_syn.Get_bw_windows(st_syn, epi, depth, self.or_time)

        # self.BW_obs.original.filter('highpass', freq = 1.0/8.0 , zerophase = True)
        # self.BW_syn.original.filter('highpass', freq = 1.0/8.0 , zerophase = True)
        #
        # self.BW_obs.original.filter('lowpass', freq = 1.0/2.0 , zerophase = True)
        # self.BW_syn.original.filter('lowpass', freq = 1.0/2.0 , zerophase = True)
        #
        # self.BW_obs.original.trim(self.prior['origin_time'])
        # self.BW_syn.original.trim(self.prior['origin_time'])
        #
        # ax1 = plt.subplot(111)
        # plt.plot(self.BW_obs.original.traces[2], 'b')
        # plt.plot(self.BW_syn.original.traces[2], 'r')
        # ymin, ymax = ax1.get_ylim()
        # plt.vlines(self.BW_obs.or_P_len , ymin=ymin, ymax=ymax, colors='b', linewidth=3, label='Obs_P')
        # plt.vlines(self.BW_syn.or_P_len, ymin=ymin, ymax=ymax, colors='r', linewidth=3, label = 'Syn_P')
        # plt.vlines(self.BW_obs.or_S_len , ymin=ymin, ymax=ymax, colors='b', linewidth=3, label='Obs_S')
        # plt.vlines(self.BW_syn.or_S_len, ymin=ymin, ymax=ymax, colors='r', linewidth=3, label = 'Syn_S')
        # plt.title('Depth: %.2f' % depth)
        # plt.show()

        # plt.figure()
        # ax1 = plt.subplot(121)
        # plt.plot(self.BW_obs.P_stream.traces[0], 'b')
        # plt.plot(self.BW_syn.P_stream.traces[0], 'r')
        # ax1 = plt.subplot(122)
        # plt.plot(self.BW_obs.S_stream.traces[2], 'b')
        # plt.plot(self.BW_syn.S_stream.traces[2], 'r')
        #
        # plt.show()
        # a=1

    def write_par(self, file_name, BW, SW):
        if BW == True and SW == True:
            raise ValueError('Surface waves Not implemented yet')
        elif BW == True:
            file_name.write(
                "epi, depth, strike, dip, rake, M0, Total-misfit, p_z, p_r, s_z, s_r, s_t, bw_tot, shift_S, shift-P, Iteration\n\r")
            file_name.write("Velocity Model:%s\n\r" % self.prior['VELOC'])
            file_name.write("Station:%s\n\r" % self.BW_obs.P_stream.traces[0].stats.station)
            file_name.write("Sampling rate:%.2f\n\r" % self.BW_obs.P_stream.traces[0].stats.sampling_rate)
            file_name.write("la_r:%.4f\n\r" % self.prior['la_r'])
            file_name.write("lo_r:%.4f\n\r" % self.prior['lo_r'])
            file_name.write("kind:%s\n\r" % self.prior['kind'])  #
            file_name.write("Pre_P:%.2f\n\r" % self.prior['Pre_P'])  #
            file_name.write("Pre_S:%.2f\n\r" % self.prior['Pre_S'])  #
            file_name.write("Post_P:%.2f\n\r" % self.prior['Post_P'])  #
            file_name.write("Post_S:%.2f\n\r" % self.prior['Post_S'])  #
            file_name.write("P_LP:%.2f\n\r" % self.prior['P_LP'])  #
            file_name.write("P_HP:%.2f\n\r" % self.prior['P_HP'])  #
            file_name.write("S_LP:%.2f\n\r" % self.prior['S_LP'])  #
            file_name.write("S_HP:%.2f\n\r" % self.prior['S_HP'])  #
            file_name.write("Taper_obs:%5i\n\r" % self.prior['Taper_obs'])  #
            file_name.write("Taper_syn:%5i\n\r" % self.prior['Taper_syn'])  #
            file_name.write("Zero_phase:%%5i\n\r" % self.prior['Zero_phase'])  #
            file_name.write("Order:%5i\n\r" % self.prior['Order'])  #
            file_name.write("amount samples:%i\n\r" % self.prior['sample_number'])  #
            file_name.write("Temperature:%i\n\r" % self.prior['Temperature'])  #
            file_name.write("Radius:%.4f\n\r" % self.prior['radius'])  #
            file_name.write("Flattening:%.4f\n\r" % self.prior['f'])  #
            file_name.write("Azimuth:%.4f\n\r" % self.prior['az'])  #

        elif SW == True:
            raise ValueError('Surface waves Not implemented yet')

    def write_sample(self, file_name, epi, depth, strike, dip, rake, M0, Xi_old, BW, SW, time_shift, accept=0):
        file_name.write("%.4f, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f, " % (epi, depth, strike, dip, rake, M0, Xi_old))
        if BW == True:
            file_name.write("%.4f, %.4f, %.4f, %.4f, %.4f, %.4f, " % (
            self.p_z_old, self.p_r_old, self.s_z_old, self.s_r_old, self.s_t_old, self.bw_old))
        if SW == True:
            raise ValueError('Surface waves Not implemented yet')
        file_name.write("%i, %i, %i\n\r" % (time_shift[0], time_shift[1], self.i))

    def plot(self):
        stream = Stream()
        stream += self.BW_obs.BW_stream.traces[0]
        # stream += self.BW_obs.S_stream.traces[1]
        # stream += self.BW_obs.S_stream.traces[2]
        #
        #
        stream += self.BW_syn.BW_stream.traces[0]
        # stream += self.BW_syn.S_stream.traces[1]
        # stream += self.BW_syn.S_stream.traces[2]
        #
        stream.plot()

        fig = plt.figure(figsize=(10, 12))
        delta = self.BW_obs.P_stream.traces[0].meta.delta
        p_time_array = np.arange(len(self.BW_obs.P_stream.traces[0].data)) * delta
        s_time_array = np.arange(len(self.BW_obs.S_stream.traces[0].data)) * delta

        start_P = int((self.BW_obs.start_P.timestamp - self.or_time.timestamp - 10) / delta)
        end_P = int((self.BW_obs.start_P.timestamp - self.or_time.timestamp + 30) / delta)

        start_S = int((self.BW_obs.start_S.timestamp - self.or_time.timestamp - 20) / delta)
        end_S = int((self.BW_obs.start_S.timestamp - self.or_time.timestamp + 100) / delta)

        ax1 = plt.subplot2grid((5, 1), (0, 0))
        plt.plot(p_time_array[start_P:end_P], self.BW_obs.P_stream.traces[0].data[start_P:end_P], 'b', label='Observed')
        plt.plot(p_time_array[start_P:end_P], self.BW_syn.P_stream.traces[0].data[start_P:end_P], 'r',
                 label='Synthetic')
        ymin, ymax = ax1.get_ylim()
        xmin, xmax = ax1.get_xlim()
        plt.text(xmax - 5, ymax / 1.7, "P-Z", fontsize=20, color='b')
        ax1.ticklabel_format(style="sci", axis='y', scilimits=(-2, 2))
        ax1.tick_params(axis='x', labelsize=18)
        ax1.tick_params(axis='y', labelsize=18)
        plt.tight_layout()
        plt.legend(loc='lower left', fontsize=15)

        ax2 = plt.subplot2grid((5, 1), (1, 0))
        plt.plot(p_time_array[start_P:end_P], self.BW_obs.P_stream.traces[1].data[start_P:end_P], 'b')
        plt.plot(p_time_array[start_P:end_P], self.BW_syn.P_stream.traces[1].data[start_P:end_P], 'r')
        ymin, ymax = ax2.get_ylim()
        xmin, xmax = ax2.get_xlim()
        plt.text(xmax - 5, ymax / 1.7, "P-R", fontsize=20, color='b')
        ax2.ticklabel_format(style="sci", axis='y', scilimits=(-2, 2))
        ax2.tick_params(axis='x', labelsize=18)
        ax2.tick_params(axis='y', labelsize=18)
        plt.tight_layout()

        ax3 = plt.subplot2grid((5, 1), (2, 0))
        plt.plot(s_time_array[start_S:end_S], self.BW_obs.S_stream.traces[0].data[start_S:end_S], 'b')
        plt.plot(s_time_array[start_S:end_S], self.BW_syn.S_stream.traces[0].data[start_S:end_S], 'r')
        ymin, ymax = ax3.get_ylim()
        xmin, xmax = ax3.get_xlim()
        plt.text(xmax - 10, ymax / 1.7, "S-Z", fontsize=20, color='b')
        ax3.ticklabel_format(style="sci", axis='y', scilimits=(-2, 2))
        ax3.tick_params(axis='x', labelsize=18)
        ax3.tick_params(axis='y', labelsize=18)
        plt.tight_layout()

        ax4 = plt.subplot2grid((5, 1), (3, 0))
        plt.plot(s_time_array[start_S:end_S], self.BW_obs.S_stream.traces[1].data[start_S:end_S], 'b')
        plt.plot(s_time_array[start_S:end_S], self.BW_syn.S_stream.traces[1].data[start_S:end_S], 'r')
        ymin, ymax = ax4.get_ylim()
        xmin, xmax = ax4.get_xlim()
        plt.text(xmax - 10, ymax / 1.7, "S-R", fontsize=20, color='b')
        ax4.ticklabel_format(style="sci", axis='y', scilimits=(-2, 2))
        ax4.tick_params(axis='x', labelsize=18)
        ax4.tick_params(axis='y', labelsize=18)
        plt.tight_layout()

        ax5 = plt.subplot2grid((5, 1), (4, 0))
        plt.plot(s_time_array[start_S:end_S], self.BW_obs.S_stream.traces[2].data[start_S:end_S], 'b')
        plt.plot(s_time_array[start_S:end_S], self.BW_syn.S_stream.traces[2].data[start_S:end_S], 'r')
        ymin, ymax = ax5.get_ylim()
        xmin, xmax = ax5.get_xlim()
        plt.text(xmax - 10, ymax / 1.9, "S-T", fontsize=20, color='b')
        ax5.ticklabel_format(style="sci", axis='y', scilimits=(-2, 2))
        ax5.tick_params(axis='x', labelsize=18)
        ax5.tick_params(axis='y', labelsize=18)
        ax5.set_xlabel(self.BW_obs.start_P.strftime('From P arrival: %Y-%m-%dT%H:%M:%S + [sec]'), fontsize=18)
        plt.tight_layout()
        # plt.show()
        plt.savefig(self.prior['save_dir'] + '/plots/%s_%i.png' % (self.prior['save_name'], self.i))
        # plt.show()
        plt.close()
Exemplo n.º 8
0
def main():
    # === Read the mSEED file ===
    get_parameters = Get_Parameters()
    mSEED_path = get_parameters.Get_Path()
    stream = obspy.read(mSEED_path)
    # stream.plot()
    #

    # Stream for only BFO station
    # st = Stream()
    # st.append(stream[2])
    # st.append(stream[0])
    # st.append(stream[1])

    # Get the inventory
    # Process = Process_mSEED(stream)

    # Process the data
    # st = Process.remove_instrument()

    PRIOR = get_parameters.PRIOR(stream)
    # PARAMETERS = get_parameters.Get_Unknown()

    la_s = PRIOR['la_s']
    lo_s = PRIOR['lo_s']
    la_r = PRIOR['la_r']
    lo_r = PRIOR['lo_r']
    dist, az, baz = gps2dist_azimuth(lat1=la_s,
                                     lon1=lo_s,
                                     lat2=la_r,
                                     lon2=lo_r,
                                     a=PRIOR['radius'],
                                     f=PRIOR['f'])
    # PRIOR['baz'] = 243
    # PRIOR['az'] = 84

    # st = Process.automatic_rotate(PRIOR['baz'])

    epi = kilometer2degrees(dist, radius=PRIOR['radius'])
    # epi = 86 # Uncertainty is 10 degrees
    # depth = PARAMETERS['depth_s']
    # depth = 36000 # 25000

    PRIOR = get_parameters.Get_ranges(epi, depth, PRIOR)
    sample_path = get_parameters.Start_sample_path(PRIOR)

    # === Cut the BW windows (P&S) ===
    BW_obs = Cut_windows(PRIOR['VELOC_taup'])

    npts = stream.traces[0].stats.npts
    # BW_obs.Get_bw_windows(stream,epi,depth,PARAMETERS['origin_time'], npts = npts)
    tt_P = obspy.UTCDateTime(2019, 1, 3, 15, 9, 54.9)
    tt_S = obspy.UTCDateTime(2019, 1, 3, 15, 18, 34.6)
    BW_obs.Get_bw_windows_MANUAL(stream,
                                 tt_P,
                                 tt_S,
                                 PARAMETERS['origin_time'],
                                 npts=npts)

    # === Start the MCMC ===
    mcmc = MCMC(PARAMETERS['origin_time'], PRIOR, sample_path=sample_path)
    mcmc.start_BW(BW_obs)
Exemplo n.º 9
0
def main():
    # === Read input file ===
    param = toml.load(toml_path, _dict=dict)

    # === Read the mSEED file ===
    get_parameters = Get_Parameters()
    mSEED_path = get_parameters.Get_Path(param['directory'],
                                         param['mSEED_file'])
    stream = obspy.read(mSEED_path)
    PRIOR = get_parameters.PRIOR(stream, param['PRIOR'])

    # === Process the data ===
    # Process = Process_mSEED(stream)
    # st = Process.remove_instrument() # Remove instrument response
    # stream = Process.automatic_rotate(PRIOR['baz']) # Rotate your Traces

    # === GET PRIOR ===
    PRIOR = get_parameters.Get_ranges(PRIOR)  # WHEN RUN IS NOT YET DONE

    sample_path = get_parameters.Start_sample_path(PRIOR)

    # === Cut the BW windows (P&S) ===
    BW_obs = Cut_windows(PRIOR['VELOC_taup'],
                         P_HP=PRIOR['P_HP'],
                         P_LP=PRIOR['P_LP'],
                         S_HP=PRIOR['S_HP'],
                         S_LP=PRIOR['S_LP'],
                         Pre_P=PRIOR['Pre_P'],
                         Pre_S=PRIOR['Pre_S'],
                         Post_P=PRIOR['Post_P'],
                         Post_S=PRIOR['Post_S'],
                         global_P_shift=PRIOR['Global_P_shift'],
                         global_S_shift=PRIOR['Global_S_shift'],
                         zero_phase=PRIOR['Zero_Phase'],
                         Order=PRIOR['Order'],
                         Taper=PRIOR['Taper_obs'],
                         Taper_len=PRIOR['Taper_len'],
                         Zero_len=PRIOR['Zero_len'])
    if PRIOR['P_pick'] == None or PRIOR['S_pick'] == None:
        BW_obs.Get_bw_windows(stream,
                              PRIOR['epi_s'],
                              PRIOR['depth_s'],
                              PRIOR['origin_time'],
                              MANUAL=False)
    else:
        BW_obs.Get_bw_windows(stream,
                              PRIOR['P_pick'],
                              PRIOR['S_pick'],
                              PRIOR['origin_time'],
                              MANUAL=True)

    # === Start Grid Search ===
    # depth = 58691.9##           #5000
    # epi =    PRIOR['epi_s']#24.7437  #            #PRIOR['epi_s']
    # M0 = PRIOR['M0']# 135943762646494.86 #      #
    # GS = Grid_Search(PRIOR)
    # GS.start_GS(BW_obs,depth,epi,M0)

    # === Start the MCMC (Metropolis Hastings) ===
    # mcmc = MCMC(PRIOR['origin_time'], PRIOR, sample_path=sample_path)
    # mcmc.start_BW(BW_obs)

    # === Plot waveforms from a previous run ===
    PRIOR['VELOC'] = PRIOR['VELOC']
    path_txt = '/home/nienke/Documents/Master/Data/Mars/S0235b/waveforms/Output/DWTHot__.txt'
    # path_txt = '/home/nienke/Documents/Master/Data/Mars/S0235b/waveforms/Output/NEW_RUNS/1/EH45Tcold.txt'
    savedir = '/home/nienke/Documents/Master/Data/Mars/S0235b/waveforms/Output/'
    # path_txt = '/home/nienke/Documents/Master/Data/Mars/S0173a/waveforms/Output/DWTHot_173.txt'
    # savedir = '/home/nienke/Documents/Master/Data/Mars/S0173a/waveforms/Output/'
    skiprows = 60  #56
    plot = Plot_waveforms(BW_obs, path_txt, savedir, PRIOR, skiprows)
    # plot.get_Cut_waveforms()
    plot.get_waveforms(Norm=True)