Esempio n. 1
0
def main():
    ## Post - Processing [processing the results from inversion]
    result = Post_processing_sdr()

    directory = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Euler_data'
    path_to_file = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Euler_data/Trials/Trial_close_GOOD/close_small_spread.txt'
    # path_to_stream = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Blindtest/bw_reject.mseed'
    # path= '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Additional_scripts/Iteration_runs/Together'

    savename = 'Trials'
    show = False  # Choose True for direct show, choose False for saving
    skiprows = 70
    column_names = [
        "Epi", "Depth", "Strike", "Dip", "Rake", "Total_misfit", "S_z", "S_r",
        "S_t", "P_z", "P_r", "BW_misfit", "Rtot", "Ltot"
    ]
    # column_names= ["Epi", "Depth", "Strike", "Dip", "Rake","Total_misfit","S_z","S_r","S_t"]
    # path_to_file, save = result.convert_txt_folder_to_yaml(path, savename)
    # result.get_stereonets(filepath=path_to_file, savename=savename, directory=directory, show=show)

    # result.plot_streams(stream_filepath=path_to_stream,filepath=path_to_file,savename=savename, directory=directory,skiprows=skiprows ,column_names=column_names)

    par = Get_Paramters()
    REAL = par.get_unkown()
    PRIOR = par.get_prior()
    result.event_plot(PRIOR['la_r'], PRIOR['lo_r'], REAL['la_s'], REAL['lo_s'])
def Normal_check():
    # Initiate Parameters:

    get_parameters = Get_Paramters()
    PARAMETERS = get_parameters.get_unkown()
    PRIOR = get_parameters.get_prior()
    VALUES = get_parameters.specifications()
    VALUES['blind'] = False
    VALUES[
        'directory'] = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Final/check_waveforms'

    ## DISCUSS THIS!!!!
    PRIOR['az'] = PARAMETERS['az']
    PRIOR['baz'] = PARAMETERS['baz']

    # Initiate the databases from instaseis:
    db = instaseis.open_db(PRIOR['VELOC'])
    create = Create_observed(PRIOR, db)

    d_obs, tr_obs, source = create.get_seis_automatic(
        parameters=PARAMETERS,
        prior=PRIOR,
        noise_model=VALUES['noise'],
        sdr=VALUES['sdr'])
    traces_obs, p_obs, s_obs, p_time_obs, s_time_obs = create.get_window_obspy(
        tr_obs, PARAMETERS['epi'], PARAMETERS['depth_s'],
        PARAMETERS['origin_time'], VALUES['npts'])
    time_at_receiver = create.get_receiver_time(PARAMETERS['epi'],
                                                PARAMETERS['depth_s'],
                                                PARAMETERS['origin_time'])

    PRIOR['var_est'] = create.get_var_data(p_time_obs, tr_obs)

    sw = Surface_waves(PRIOR)
    R_env_obs = sw.rayleigh_pick(tr_obs.traces[0],
                                 PARAMETERS['la_s'],
                                 PARAMETERS['lo_s'],
                                 PARAMETERS['depth_s'],
                                 VALUES['directory'],
                                 PARAMETERS['origin_time'],
                                 VALUES['npts'],
                                 plot_modus=False)
    L_env_obs = sw.love_pick(tr_obs.traces[2],
                             PARAMETERS['la_s'],
                             PARAMETERS['lo_s'],
                             PARAMETERS['depth_s'],
                             VALUES['directory'],
                             PARAMETERS['origin_time'],
                             VALUES['npts'],
                             plot_modus=False)
    # tr_obs.plot()
    # ------------------------------------------------------------------

    seis = Seismogram(PRIOR, db)
    window_code = Source_code(PRIOR['VELOC_taup'])
    misfit = Misfit(VALUES['directory'])

    epi = PARAMETERS['epi']
    depth = PARAMETERS['depth_s']
    strike = PARAMETERS['strike']
    dip = PARAMETERS['dip']
    rake = PARAMETERS['rake']
    time = PARAMETERS['origin_time']

    # ---------------------------------------------------------------------------------------------------------------  #
    dict = geo.Geodesic(a=PRIOR['radius'], f=0).ArcDirect(lat1=PRIOR['la_r'],
                                                          lon1=PRIOR['lo_r'],
                                                          azi1=PRIOR['baz'],
                                                          a12=epi,
                                                          outmask=1929)
    d_syn, traces_syn, sources = seis.get_seis_manual(la_s=dict['lat2'],
                                                      lo_s=dict['lon2'],
                                                      depth=depth,
                                                      strike=strike,
                                                      dip=dip,
                                                      rake=rake,
                                                      time=time,
                                                      M0=PRIOR['M0'],
                                                      sdr=VALUES['sdr'])

    R_env_syn = sw.rayleigh_pick(Z_trace=traces_syn.traces[0],
                                 la_s=dict['lat2'],
                                 lo_s=dict['lon2'],
                                 depth=depth,
                                 save_directory=VALUES['directory'],
                                 time_at_rec=time,
                                 npts=VALUES['npts'],
                                 plot_modus=True)
    L_env_syn = sw.love_pick(T_trace=traces_syn.traces[2],
                             la_s=dict['lat2'],
                             lo_s=dict['lon2'],
                             depth=depth,
                             save_directory=VALUES['directory'],
                             time_at_rec=time,
                             npts=VALUES['npts'],
                             plot_modus=False)

    traces_syn.plot(outfile=VALUES['directory'] + '/syntethic')
    total_syn, p_syn, s_syn, p_time_syn, s_time_syn = window_code.get_window_obspy(
        traces_syn, epi, depth, time, VALUES['npts'])

    ax1 = plt.subplot2grid((5, 1), (0, 0))
    ax1.plot(zero_to_nan(p_syn.traces[0].data), c='r', linewidth=0.3)
    ax1.plot(zero_to_nan(p_obs.traces[0].data),
             c='k',
             linestyle=':',
             linewidth=0.3)
    plt.tight_layout()
    ax2 = plt.subplot2grid((5, 1), (1, 0))
    ax2.plot(zero_to_nan(p_syn.traces[1].data), c='r', linewidth=0.3)
    ax2.plot(zero_to_nan(p_obs.traces[1].data),
             c='k',
             linestyle=':',
             linewidth=0.3)
    plt.tight_layout()
    ax3 = plt.subplot2grid((5, 1), (2, 0))
    ax3.plot(zero_to_nan(s_syn.traces[0].data), c='r', linewidth=0.3)
    ax3.plot(zero_to_nan(s_obs.traces[0].data), c='k', linewidth=0.3)
    plt.tight_layout()
    ax4 = plt.subplot2grid((5, 1), (3, 0))
    ax4.plot(zero_to_nan(s_syn.traces[1].data), c='r', linewidth=0.3)
    ax4.plot(zero_to_nan(s_obs.traces[1].data), c='k', linewidth=0.3)
    plt.tight_layout()
    ax5 = plt.subplot2grid((5, 1), (4, 0))
    ax5.plot(zero_to_nan(s_syn.traces[2].data), c='r', linewidth=0.3)
    ax5.plot(zero_to_nan(s_obs.traces[2].data), c='k', linewidth=0.3)
    plt.tight_layout()

    plt.savefig(VALUES['directory'] + '/%.2f_%.2f.pdf' % (epi, depth))
    plt.close()

    ax1 = plt.subplot2grid((3, 1), (0, 0))
    ax1.plot(zero_to_nan(total_syn.traces[0].data), c='r', linewidth=0.5)
    ax1.plot(zero_to_nan(traces_obs.traces[0].data),
             c='k',
             linestyle=':',
             linewidth=0.5)
    ax1.set_title('SYNTHETIC: = epi: %.2f  REAL: epi = %.2f (depth fixed' %
                  (epi, epi))
    plt.tight_layout()
    ax2 = plt.subplot2grid((3, 1), (1, 0))
    ax2.plot(zero_to_nan(total_syn.traces[1].data), c='r', linewidth=0.5)
    ax2.plot(zero_to_nan(traces_obs.traces[1].data),
             c='k',
             linestyle=':',
             linewidth=0.5)
    plt.tight_layout()
    ax3 = plt.subplot2grid((3, 1), (2, 0))
    ax3.plot(zero_to_nan(total_syn.traces[2].data), c='r', linewidth=0.5)
    ax3.plot(zero_to_nan(traces_obs.traces[2].data),
             c='k',
             linestyle=':',
             linewidth=0.5)
    plt.tight_layout()

    plt.savefig(VALUES['directory'] + '/PS_%.2f_%.2f.pdf' % (epi, depth))
    plt.close()

    Xi_bw_new, time_shift_new, amplitude = misfit.CC_stream(
        p_obs, p_syn, s_obs, s_syn, p_time_obs, p_time_syn)
    s_z_new = 0.1 * Xi_bw_new[0]
    s_r_new = 0.1 * Xi_bw_new[1]
    s_t_new = 1 * Xi_bw_new[2]
    p_z_new = 5 * Xi_bw_new[3]
    p_r_new = 5 * Xi_bw_new[4]
    bw_new = s_z_new + s_r_new + s_t_new + p_z_new + p_r_new
    Xi_R_new = misfit.SW_L2(R_env_obs, R_env_syn, PRIOR['var_est'], amplitude)
    Xi_L_new = misfit.SW_L2(L_env_obs, L_env_syn, PRIOR['var_est'], amplitude)

    R_dict_new = {}
    rw_new = 0
    for j, v in enumerate(Xi_R_new):
        R_dict_new.update({'R_%i_new' % j: v})
        rw_new += v

    L_dict_new = {}
    lw_new = 0
    for j, v in enumerate(Xi_L_new):
        L_dict_new.update({'L_%i_new' % j: v})
        lw_new += v
    Xi_new = bw_new + rw_new + lw_new
    a = 1
def Acces_Normal():
    # Initiate Parameters:

    get_parameters = Get_Paramters()
    PARAMETERS = get_parameters.get_unkown()
    PRIOR = get_parameters.get_prior()
    VALUES = get_parameters.specifications()

    VALUES[
        'directory'] = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Final'

    ## DISCUSS THIS!!!!
    PRIOR['az'] = PARAMETERS['az']
    PRIOR['baz'] = PARAMETERS['baz']

    # Initiate the databases from instaseis:
    db = instaseis.open_db(PRIOR['VELOC'])
    create = Create_observed(PRIOR, db)

    d_obs, tr_obs, source = create.get_seis_automatic(
        parameters=PARAMETERS,
        prior=PRIOR,
        noise_model=VALUES['noise'],
        sdr=VALUES['sdr'])
    time_at_receiver = create.get_receiver_time(PARAMETERS['epi'],
                                                PARAMETERS['depth_s'],
                                                PARAMETERS['origin_time'])
    traces_obs, p_obs, s_obs, start_time_p, start_time_s = create.get_window_obspy(
        tr_obs, PARAMETERS['epi'], PARAMETERS['depth_s'],
        PARAMETERS['origin_time'], VALUES['npts'])

    PRIOR['var_est'] = create.get_var_data(start_time_p, tr_obs)
    # PRIOR['var_est'] =1

    sw = Surface_waves(PRIOR)
    R_env_obs = sw.rayleigh_pick(tr_obs.traces[0],
                                 PARAMETERS['la_s'],
                                 PARAMETERS['lo_s'],
                                 PARAMETERS['depth_s'],
                                 VALUES['directory'],
                                 PARAMETERS['origin_time'],
                                 VALUES['npts'],
                                 plot_modus=False)
    L_env_obs = sw.love_pick(tr_obs.traces[2],
                             PARAMETERS['la_s'],
                             PARAMETERS['lo_s'],
                             PARAMETERS['depth_s'],
                             VALUES['directory'],
                             PARAMETERS['origin_time'],
                             VALUES['npts'],
                             plot_modus=False)
    # tr_obs.plot()
    # ------------------------------------------------------------------

    seis = Seismogram(PRIOR, db)
    window_code = Source_code(PRIOR['VELOC_taup'])
    misfit = Misfit(VALUES['directory'])

    # start_sample_path = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Final/close_sample.txt'
    start_sample_path = None

    m = MCMC_stream(R_env_obs,
                    L_env_obs,
                    traces_obs,
                    p_obs,
                    s_obs,
                    PRIOR,
                    db,
                    VALUES,
                    PARAMETERS['origin_time'],
                    start_time_p,
                    start_time_s,
                    start_sample_path,
                    None,
                    full_obs_trace=tr_obs)
    m.start_MCMC(VALUES['directory'] + '/Exploring.txt')
def Acces_Blindtest_check():
    BLINDTEST_MSEED = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Database/data_Nienke/M5.0_3914855_deg_2019-09-22.mseed'
    BLINDTEST_XML = BLINDTEST_MSEED.replace(".mseed", ".xml")

    # Initiate Parameters:
    get_parameters = Get_Paramters()
    PRIOR = get_parameters.get_prior()
    VALUES = get_parameters.specifications()
    VALUES['npts'] = 2000
    VALUES[
        'directory'] = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Blindtest/check_waveforms'
    VALUES['blind'] = True

    # st = read(VALUES['directory'] + '/bw.mseed')
    # st_reject = read(VALUES['directory'] + '/bw_reject.mseed')

    # Initiate the databases from instaseis:
    db = instaseis.open_db(PRIOR['VELOC'])
    tr_obs = obspy.read(BLINDTEST_MSEED)
    # tr_obs.plot(outfile=VALUES['directory'] + '/Observed')
    tr_obs.integrate()
    tr_obs.plot(outfile=VALUES['directory'] + '/Observed_integrated')
    source = instaseis.Source.parse(BLINDTEST_XML)
    blindtest = Blindtest()
    events = blindtest.get_events(BLINDTEST_XML)
    # get_parameters.get_prior_blindtest(events[0])
    time, depth, la_s, lo_s = blindtest.get_pref_origin(events[0])

    dist, az, baz = gps2dist_azimuth(lat1=la_s,
                                     lon1=lo_s,
                                     lat2=PRIOR['la_r'],
                                     lon2=PRIOR['lo_r'],
                                     a=PRIOR['radius'],
                                     f=0)
    epi = kilometer2degrees(dist, radius=PRIOR['radius'])
    PRIOR['az'] = az
    PRIOR['baz'] = baz
    PRIOR['epi']['range_min'] = epi - 5
    PRIOR['epi']['range_max'] = epi + 5
    PRIOR['epi']['spread'] = 1
    PRIOR['depth']['range_min'] = depth - 10000
    PRIOR['depth']['range_max'] = depth + 10000
    PRIOR['network'] = tr_obs.traces[0].meta.network
    PRIOR['location'] = tr_obs.traces[0].meta.location
    PRIOR['station'] = tr_obs.traces[0].meta.station
    est_noise = Create_observed(PRIOR, db)
    create = Source_code(PRIOR['VELOC_taup'])
    traces_obs, p_obs, s_obs, p_time_obs, s_time_obs = create.get_window_obspy(
        tr_obs, epi, depth, time, VALUES['npts'])
    PRIOR['var_est'] = est_noise.get_var_data(p_time_obs, tr_obs)
    obs_time = Create_observed(PRIOR, db)
    time_at_receiver = obs_time.get_receiver_time(epi, depth, time)
    plt.figure()

    catalog_path = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Additional_scripts/MQScatalog_withFrequencies/MQS_absolute_withFrequencyInfo.xml'

    events_catalog = blindtest.get_events(catalog_path)

    for v in events_catalog:
        t, d, lat_ev, lo_ev = blindtest.get_pref_origin(v)
        if time.date == t.date:
            Pick_event = v
            break
    PRIOR['M0'] = blindtest.get_pref_scalarmoment(Pick_event)
    picks_surface = get_phase_picks(Pick_event, pick_type='surface')
    R_env_obs, L_env_obs = blindtest.pick_sw(tr_obs,
                                             picks_surface,
                                             epi,
                                             PRIOR,
                                             VALUES['npts'],
                                             VALUES['directory'],
                                             plot_modus=True)

    start_sample = create_starting_sample()
    strike = 243.423396191
    dip = 34.436087773
    rake = 164.912874159

    from Seismogram import Seismogram
    from Misfit import Misfit
    misfit = Misfit(VALUES['directory'])
    seis = Seismogram(PRIOR, db)
    epi = epi - 3
    depth = depth

    # ---------------------------------------------------------------------------------------------------------------  #
    dict = geo.Geodesic(a=PRIOR['radius'], f=0).ArcDirect(lat1=PRIOR['la_r'],
                                                          lon1=PRIOR['lo_r'],
                                                          azi1=PRIOR['baz'],
                                                          a12=epi,
                                                          outmask=1929)
    d_syn, traces_syn, sources = seis.get_seis_manual(la_s=dict['lat2'],
                                                      lo_s=dict['lon2'],
                                                      depth=depth,
                                                      strike=strike,
                                                      dip=dip,
                                                      rake=rake,
                                                      time=time,
                                                      M0=PRIOR['M0'],
                                                      sdr=VALUES['sdr'])

    R_env_syn, L_env_syn = blindtest.pick_sw(traces_syn,
                                             picks_surface,
                                             epi,
                                             PRIOR,
                                             VALUES['npts'],
                                             VALUES['directory'],
                                             plot_modus=False)

    traces_syn.plot(outfile=VALUES['directory'] + '/syntethic')
    total_syn, p_syn, s_syn, p_time_syn, s_time_syn = create.get_window_obspy(
        traces_syn, epi, depth, time, VALUES['npts'])

    ax1 = plt.subplot2grid((5, 1), (0, 0))
    ax1.plot(zero_to_nan(p_syn.traces[0].data), c='r', linewidth=0.3)
    ax1.plot(zero_to_nan(p_obs.traces[0].data),
             c='k',
             linestyle=':',
             linewidth=0.3)
    plt.tight_layout()
    ax2 = plt.subplot2grid((5, 1), (1, 0))
    ax2.plot(zero_to_nan(p_syn.traces[1].data), c='r', linewidth=0.3)
    ax2.plot(zero_to_nan(p_obs.traces[1].data),
             c='k',
             linestyle=':',
             linewidth=0.3)
    plt.tight_layout()
    ax3 = plt.subplot2grid((5, 1), (2, 0))
    ax3.plot(zero_to_nan(s_syn.traces[0].data), c='r', linewidth=0.3)
    ax3.plot(zero_to_nan(s_obs.traces[0].data), c='k', linewidth=0.3)
    plt.tight_layout()
    ax4 = plt.subplot2grid((5, 1), (3, 0))
    ax4.plot(zero_to_nan(s_syn.traces[1].data), c='r', linewidth=0.3)
    ax4.plot(zero_to_nan(s_obs.traces[1].data), c='k', linewidth=0.3)
    plt.tight_layout()
    ax5 = plt.subplot2grid((5, 1), (4, 0))
    ax5.plot(zero_to_nan(s_syn.traces[2].data), c='r', linewidth=0.3)
    ax5.plot(zero_to_nan(s_obs.traces[2].data), c='k', linewidth=0.3)
    plt.tight_layout()

    plt.savefig(VALUES['directory'] + '/%.2f_%.2f.pdf' % (epi, depth))
    plt.close()

    # time =

    ax1 = plt.subplot2grid((3, 1), (0, 0))
    ax1.plot(zero_to_nan(total_syn.traces[0].data), c='r', linewidth=0.5)
    ax1.plot(zero_to_nan(traces_obs.traces[0].data),
             c='k',
             linestyle=':',
             linewidth=0.5)
    ax1.set_title('SYNTHETIC: = epi: %.2f  REAL: epi = %.2f (depth fixed' %
                  (epi, epi + 3))
    plt.tight_layout()
    ax2 = plt.subplot2grid((3, 1), (1, 0))
    ax2.plot(zero_to_nan(total_syn.traces[1].data), c='r', linewidth=0.5)
    ax2.plot(zero_to_nan(traces_obs.traces[1].data),
             c='k',
             linestyle=':',
             linewidth=0.5)
    plt.tight_layout()
    ax3 = plt.subplot2grid((3, 1), (2, 0))
    ax3.plot(zero_to_nan(total_syn.traces[2].data), c='r', linewidth=0.5)
    ax3.plot(zero_to_nan(traces_obs.traces[2].data),
             c='k',
             linestyle=':',
             linewidth=0.5)
    plt.tight_layout()

    plt.savefig(VALUES['directory'] + '/PS_%.2f_%.2f.pdf' % (epi, depth))
    plt.close()

    Xi_bw_new, time_shift_new, amplitude = misfit.CC_stream(
        p_obs, p_syn, s_obs, s_syn, p_time_obs, p_time_syn)
    s_z_new = 0.1 * Xi_bw_new[0]
    s_r_new = 0.1 * Xi_bw_new[1]
    s_t_new = 1 * Xi_bw_new[2]
    p_z_new = 5 * Xi_bw_new[3]
    p_r_new = 5 * Xi_bw_new[4]
    bw_new = s_z_new + s_r_new + s_t_new + p_z_new + p_r_new
    Xi_R_new = misfit.SW_L2(R_env_obs, R_env_syn, PRIOR['var_est'], amplitude)
    Xi_L_new = misfit.SW_L2(L_env_obs, L_env_syn, PRIOR['var_est'], amplitude)

    R_dict_new = {}
    rw_new = 0
    for j, v in enumerate(Xi_R_new):
        R_dict_new.update({'R_%i_new' % j: v})
        rw_new += v

    L_dict_new = {}
    lw_new = 0
    for j, v in enumerate(Xi_L_new):
        L_dict_new.update({'L_%i_new' % j: v})
        lw_new += v
    Xi_new = bw_new + rw_new + lw_new
    a = 1
def Acces_Blindtest():
    # BLINDTEST_MSEED = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Database/data_Nienke/M3.5_8213363_deg_2019-02-15.mseed'
    BLINDTEST_MSEED = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Database/data_Nienke/M5.0_3914855_deg_2019-09-22.mseed'
    BLINDTEST_XML = BLINDTEST_MSEED.replace(".mseed", ".xml")

    # Initiate Parameters:
    get_parameters = Get_Paramters()
    PRIOR = get_parameters.get_prior()
    VALUES = get_parameters.specifications()
    VALUES['npts'] = 30000
    VALUES[
        'directory'] = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Blindtest'

    # st = read(VALUES['directory'] + '/bw.mseed')
    # st_reject = read(VALUES['directory'] + '/bw_reject.mseed')

    # Initiate the databases from instaseis:
    db = instaseis.open_db(PRIOR['VELOC'])
    tr_obs = obspy.read(BLINDTEST_MSEED)
    # tr_obs.plot(outfile=VALUES['directory'] + '/Observed')
    tr_obs.integrate()
    # tr_obs.plot(outfile=VALUES['directory'] + '/Observed_integrated')
    # source = instaseis.Source.parse(BLINDTEST_XML)
    blindtest = Blindtest()
    events = blindtest.get_events(BLINDTEST_XML)
    # get_parameters.get_prior_blindtest(events[0])
    time, depth, la_s, lo_s = blindtest.get_pref_origin(events[0])

    dist, az, baz = gps2dist_azimuth(lat1=la_s,
                                     lon1=lo_s,
                                     lat2=PRIOR['la_r'],
                                     lon2=PRIOR['lo_r'],
                                     a=PRIOR['radius'],
                                     f=0)
    epi = kilometer2degrees(dist, radius=PRIOR['radius'])
    PRIOR['az'] = az
    PRIOR['baz'] = baz
    PRIOR['epi']['range_min'] = epi - 5
    PRIOR['epi']['range_max'] = epi + 5
    PRIOR['epi']['spread'] = 1
    PRIOR['depth']['range_min'] = depth - 10000
    PRIOR['depth']['range_max'] = depth + 10000
    PRIOR['network'] = tr_obs.traces[0].meta.network
    PRIOR['location'] = tr_obs.traces[0].meta.location
    PRIOR['station'] = tr_obs.traces[0].meta.station
    est_noise = Create_observed(PRIOR, db)
    create = Source_code(PRIOR['VELOC_taup'])
    traces_obs, p_obs, s_obs, start_time_p, start_time_s = create.get_window_obspy(
        tr_obs, epi, depth, time, VALUES['npts'])
    PRIOR['var_est'] = est_noise.get_var_data(start_time_p, tr_obs)
    # time_at_receiver = create.get_receiver_time(epi,depth, time)
    plt.figure()

    catalog_path = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Additional_scripts/MQScatalog_withFrequencies/MQS_absolute_withFrequencyInfo.xml'
    catalog = Blindtest()
    events_catalog = catalog.get_events(catalog_path)

    for v in events_catalog:
        t, d, lat_ev, lo_ev = catalog.get_pref_origin(v)
        if time.date == t.date:
            Pick_event = v
            break
    PRIOR['M0'] = catalog.get_pref_scalarmoment(Pick_event)
    picks_surface = get_phase_picks(Pick_event, pick_type='surface')
    R_env_obs, L_env_obs = blindtest.pick_sw(tr_obs,
                                             picks_surface,
                                             epi,
                                             PRIOR,
                                             30000,
                                             VALUES['directory'],
                                             plot_modus=False)

    start_sample = create_starting_sample()
    strike = np.random.uniform(PRIOR['strike']['range_min'],
                               PRIOR['strike']['range_max'])
    dip = np.random.uniform(PRIOR['dip']['range_min'],
                            PRIOR['dip']['range_max'])
    rake = np.random.uniform(PRIOR['rake']['range_min'],
                             PRIOR['rake']['range_max'])
    sample_path = start_sample.get_sample_manual(
        epi, depth, strike, dip, rake,
        VALUES['directory'] + '/Blindtest_trialrun_sample.txt')
    # sample_path = '/home/nienke/Documents/Applied_geophysics/Thesis/anaconda/Blindtest/Blindtest_trialrun_sample.txt'
    mcmc = MCMC_stream(R_env_obs=R_env_obs,
                       L_env_obs=L_env_obs,
                       total_traces_obs=traces_obs,
                       P_traces_obs=p_obs,
                       S_traces_obs=s_obs,
                       PRIOR=PRIOR,
                       db=db,
                       specification_values=VALUES,
                       time_at_receiver=time,
                       start_sample_path=sample_path,
                       picked_events=picks_surface,
                       full_obs_trace=tr_obs,
                       P_start=start_time_p,
                       S_start=start_time_s)

    mcmc.start_MCMC(VALUES['directory'] + '/Blindtest_trialrun.txt')
# IMPORTANT: in Get_Parameters --> sdr = False !!!!!!!

import instaseis
import numpy as np
import matplotlib.pylab as plt

## All different classes:
from Create_observed import Create_observed
from Get_Parameters import Get_Paramters
from Green_functions import Green_functions
from Inversion_problems import Inversion_problem
from Forward_problem import Forward_problem
from Misfit import Misfit

# Getting parameters to create the observed data:
get_parameters = Get_Paramters()
PARAMETERS = get_parameters.get_unkown(
)  # These values can only be used to create d_obs
PRIOR = get_parameters.get_prior(PARAMETERS['epi'])
VALUES = get_parameters.specifications()
PRIOR['az'] = PARAMETERS['az']
PRIOR['baz'] = PARAMETERS['baz']

# Initiate the databases from instaseis:
db = instaseis.open_db(PRIOR['VELOC'])

## Step 1 - Create the observed data:
create = Create_observed(PRIOR, PARAMETERS, db)
# FUll seismogram:
# d_obs = stacked numpy array of the seismogram
# traces = obspy stream with 3 traces [Z,R,T]
Esempio n. 7
0
    def trace_density(self,
                      filepath,
                      savename,
                      directory,
                      skiprows,
                      column_names,
                      show=True):
        dir = directory + '/%s' % (savename.strip('.yaml'))
        if not os.path.exists(dir):
            os.makedirs(dir)

        if filepath.endswith('.yaml') == True:
            with open(filepath, 'r') as stream:
                data_file = yaml.load(stream)
                stream.close()
                data = data_file['data']
                # parameters = data_file['parameters']
        else:
            # parameters = open(filepath, "r").readlines()[:33]
            data = np.loadtxt(filepath, delimiter=',', skiprows=skiprows)

        length = len(data[0]) - (len(column_names) + 3)
        L_length = 4  #int(data[0][-1])
        R_length = 4  #int(data[0][-2])

        for i in range(R_length):
            column_names = np.append(column_names, "R_%i" % (i + 1))
        for i in range(L_length):
            column_names = np.append(column_names, "L_%i" % (i + 1))
        column_names = np.append(column_names, "Accepted")
        # column_names = np.append(column_names,"Rayleigh_length")
        # column_names = np.append(column_names,"Love_length")

        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)
        #
        df = pd.DataFrame(data, columns=column_names)
        df_select = df[["Epi", "Depth", "Strike", "Dip", "Rake"]]
        par = Get_Paramters()
        REAL = par.get_unkown()
        real_v = np.array([
            REAL['epi'], REAL['depth_s'], REAL['strike'], REAL['dip'],
            REAL['rake']
        ])
        # real_v=np.array([35.2068855191,16848.1405882,99.88000245897199, 77.02994881296266,68.80551508147109])
        # real_v=np.array([73.8059395565,26247.7456326,158.92744919732135, 47.46909146946276,-45.69139707143311])
        strike, dip, rake = aux_plane(REAL['strike'], REAL['dip'],
                                      REAL['rake'])
        # strike,dip,rake = aux_plane(99.88000245897199,77.02994881296266,68.80551508147109)
        # strike,dip,rake = aux_plane(158.92744919732135, 47.46909146946276,-45.69139707143311)

        fig = plt.figure(figsize=(20, 20))
        row = 0

        for i in df_select:
            ax1 = plt.subplot2grid((5, 2), (row, 0))
            ax1.plot(df_select[i], label=i)
            # ax1.axhline(y=REAL[df_select], linewidth=0.3, linestyle=':')
            ax1.set_title("Trace %s" % i, color='b', fontsize=20)
            ax1.set_xlabel("Iteration")
            # ax1.set_ylabel("Epicentral ")
            plt.tight_layout()
            ax2 = plt.subplot2grid((5, 2), (row, 1))
            plt.hist(df_select[i], bins=100)
            ymin, ymax = ax2.get_ylim()
            plt.vlines(df_select[i][1],
                       ymin=ymin,
                       ymax=ymax,
                       colors='r',
                       linewidth=3)
            plt.vlines(real_v[row],
                       ymin=ymin,
                       ymax=ymax,
                       colors='k',
                       linewidth=3)
            if i == 'Strike':
                plt.vlines(strike,
                           ymin=ymin,
                           ymax=ymax,
                           colors='g',
                           linewidth=3)
            if i == 'Dip':
                plt.vlines(dip, ymin=ymin, ymax=ymax, colors='g', linewidth=3)
            if i == 'Rake':
                plt.vlines(rake, ymin=ymin, ymax=ymax, colors='g', linewidth=3)

            # y, binEdges = np.histogram(df_select[i], bins=100)
            # bincenters = 0.5 * (binEdges[1:] + binEdges[:-1])
            # pylab.plot(bincenters, y, '-',label = "%s" % i)
            ax2.set_title("Density %s" % i, color='b', fontsize=20)
            ax2.set_xlabel("N=%i" % (len(df_select[i])))
            plt.tight_layout()
            row += 1
        plt.savefig(dir + '/Trace_density.pdf')
Esempio n. 8
0
    def combine_all(self,
                    filepath,
                    savename,
                    directory,
                    skiprows,
                    column_names,
                    show=True):
        dir = directory + '/%s' % (savename.strip('.yaml'))
        if not os.path.exists(dir):
            os.makedirs(dir)

        if filepath.endswith('.yaml') == True:
            with open(filepath, 'r') as stream:
                data_file = yaml.load(stream)
                stream.close()
                data = data_file['data']
                # parameters = data_file['parameters']
        else:
            # parameters = open(filepath, "r").readlines()[:33]
            data = np.loadtxt(filepath, delimiter=',', skiprows=skiprows)
        length = len(data[0]) - (len(column_names) + 3)
        L_length = int(data[0][-1])
        R_length = int(data[0][-2])

        for i in range(R_length):
            column_names = np.append(column_names, "R_%i" % (i + 1))
        for i in range(L_length):
            column_names = np.append(column_names, "L_%i" % (i + 1))
        column_names = np.append(column_names, "Accepted")
        column_names = np.append(column_names, "Rayleigh_length")
        column_names = np.append(column_names, "Love_length")

        par = Get_Paramters()
        REAL = par.get_unkown()

        df = pd.DataFrame(data, columns=column_names)
        df_select = df[["Epi", "Depth", "Strike", "Dip", "Rake", "M0"]]
        fig = plt.figure(figsize=(20, 20))
        ax1 = plt.subplot2grid((5, 2), (0, 0), colspan=2)
        # ax1.axhline(y = REAL['epi'] ,linewidth = 0.3 , linestyle =':', color = 'b')
        ax1.plot(df_select['Epi'], label="Epi", c='b')
        ax1.tick_params("y", colors='b')
        ax1.set_ylabel('Epicentral distance [degree]', color='b')
        ax2 = ax1.twinx()
        ax2.plot(df_select['Depth'], label="Depth", c='r')
        # ax2.axhline(y=REAL['depth_s'], linewidth=0.3, linestyle=':', color='r')
        ax2.tick_params('y', colors='r')
        ax2.set_ylabel('Depth [m]', color='r')
        plt.tight_layout()
        ax3 = plt.subplot2grid((5, 2), (1, 0), colspan=2)
        ax3.plot(df_select['Strike'], label="Strike", color="b")
        # ax3.axhline(y=REAL['strike'], linewidth=0.3, linestyle=':', color='b')
        # ax3.axhline(y=REAL['dip'], linewidth=0.3, linestyle=':', color='g')
        # ax3.axhline(y=REAL['rake'], linewidth=0.3, linestyle=':', color='r')
        ax3.plot(df_select['Dip'], label="Dip", color='g')
        ax3.plot(df_select['Rake'], label="Rake", color='r')
        ax3.set_ylabel('Moment tensor angle [degree]', color='k')
        plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
        plt.tight_layout()
        axes = ax3.twinx()
        axes.plot(df_select['M0'], label="M0", c='m')
        # ax2.axhline(y=REAL['depth_s'], linewidth=0.3, linestyle=':', color='r')
        axes.tick_params('y', colors='m')
        axes.set_ylabel('M0', color='r')
        plt.yscale('log')
        plt.tight_layout()

        R_select = df.filter(like='R_')
        L_select = df.filter(like='L_')
        df_select_xi = df[[
            "Total_misfit", "S_z", "S_r", "S_t", "P_z", "P_r", "BW_misfit",
            "Rtot", "Ltot"
        ]]
        ax4 = plt.subplot2grid((5, 2), (2, 0), colspan=2)
        ax4.plot(df_select_xi['Total_misfit'], label="Total_misfit", c='r')
        # ax4.plot(df_select_xi['S_z'], label = "S_z")
        # ax4.plot(df_select_xi['S_r'], label = "S_r")
        # ax4.plot(df_select_xi['S_t'], label = "S_t")
        # ax4.plot(df_select_xi['P_z'], label = "P_z")
        # ax4.plot(df_select_xi['P_r'], label = "P_r")
        ax4.plot(df_select_xi['BW_misfit'], label="BW_tot")
        ymin, ymax = ax4.get_ylim()
        plt.yscale('log')
        # plt.ylim((pow(10, 0), pow(10, 3)))
        plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
        plt.tight_layout()
        ax5 = plt.subplot2grid((5, 2), (3, 0), colspan=2)
        # for i in R_select:
        #     ax5.plot(R_select[i],label = i)
        ax5.plot(df_select_xi['Rtot'], label="Rtot")
        plt.yscale('log')
        # plt.ylim((pow(10, 0), pow(10, 4)))
        plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
        plt.tight_layout()
        ax6 = plt.subplot2grid((5, 2), (4, 0), colspan=2)
        # for i in L_select:
        #     ax6.plot(L_select[i],label = i)
        ax6.plot(df_select_xi['Ltot'], label="Ltot")
        plt.yscale('log')

        # plt.ylim((pow(10, 0), pow(10, 4)))
        plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
        plt.tight_layout()
        plt.savefig(dir + '/combined_all_par.pdf')
        plt.close()
# This code will run the MCMC algorithm

# IMPORTANT: in Get_Parameters --> MCMC = 'M' or MCMC = 'MH' (see Get_Parameters for further explanation)

import instaseis

## All different classes:
from Get_Parameters import Get_Paramters
from MCMC_stream import MCMC_stream
from Create_observed import Create_observed

# Initiate Parameters:
get_parameters = Get_Paramters()

PARAMETERS = get_parameters.get_unkown()
PRIOR = get_parameters.get_prior()
VALUES = get_parameters.specifications()

## DISCUSS THIS!!!!
PRIOR['az'] = PARAMETERS['az']
PRIOR['baz'] = PARAMETERS['baz']

# Initiate the databases from instaseis:
db = instaseis.open_db(PRIOR['VELOC'])
create = Create_observed(PRIOR, PARAMETERS, db)

d_obs, traces, source = create.get_seis_automatic(prior=PRIOR, noise_model=VALUES['noise'], sdr=VALUES['sdr'])
traces_obs, p_obs, s_obs = create.get_window_obspy(traces, PARAMETERS['epi'], PARAMETERS['depth_s'],
                                                   PARAMETERS['origin_time'], VALUES['npts'])
time_at_receiver = create.get_receiver_time(PARAMETERS['epi'], PARAMETERS['depth_s'], traces)
time_between_windows = create.time_between_windows(PARAMETERS['epi'], PARAMETERS['depth_s'], traces[0].meta.delta)