コード例 #1
0
ファイル: spec_func.py プロジェクト: taranye96/site_spectra
def cut_swave(infile, cutfile, t1, t2):
    #reads in a sac file
    #full path to output file
    #cuts at t1 sec before s arrival and t2 seconds after
    from obspy import read
    import dread
    import datetime
    from obspy.core.utcdatetime import UTCDateTime

    velocity = 3.5  #km/s

    stream = read(infile)
    tr = stream[0]

    origin_hour = tr.stats.sac.nzhour
    origin_min = tr.stats.sac.nzmin
    origin_sec = tr.stats.sac.nzsec
    origin_msec = tr.stats.sac.nzmsec

    trace_starttime = tr.stats.starttime

    origin_time = (origin_hour * 60 * 60 + origin_min * 60 + origin_sec +
                   origin_msec / 1000.)  # in seconds after start of day
    trace_starttime_sec = trace_starttime.hour * 60 * 60 + trace_starttime.minute * 60 + trace_starttime.second

    delta = origin_time - trace_starttime_sec  # in sec
    #    print(delta)
    origin_time_UTC = trace_starttime + datetime.timedelta(
        seconds=delta)  #convert origin time to UTC

    evlon = tr.stats.sac.evlo  #deg
    evlat = tr.stats.sac.evla  #deg
    evdepth = tr.stats.sac.evdp  #km
    stlon = tr.stats.sac.stlo  #deg
    stlat = tr.stats.sac.stla  #deg
    stdepth = tr.stats.sac.stdp  #km

    #find distance between event and station
    dist = dread.compute_rrup(evlon, evlat, evdepth, stlon, stlat,
                              stdepth)  #in km

    s_travel_time = dist / velocity  # in sec
    #    print(s_travel_time)
    cuttime = origin_time_UTC + datetime.timedelta(
        seconds=s_travel_time)  #add travel time or utc origin time
    #    print(cuttime)
    start = cuttime - datetime.timedelta(seconds=t1)
    end = cuttime + datetime.timedelta(seconds=t2)
    start = str(start)
    end = str(end)
    #    print(start, end)
    #    print(cuttime - datetime.timedelta(seconds = t1),cuttime + datetime.timedelta(seconds = t2))
    #    print(tr.slice(cuttime - datetime.timedelta(seconds = t1),cuttime + datetime.timedelta(seconds = t2), nearest_sample=True))
    #    cut_trace = tr.slice(cuttime - datetime.timedelta(seconds = t1),cuttime + datetime.timedelta(seconds = t2), nearest_sample=True)#make a new trace by slicing
    cut_trace = tr.slice(UTCDateTime(start),
                         UTCDateTime(end),
                         nearest_sample=True)  #make a new trace by slicing
    #    print(tr.data)
    #    print(cut_trace)
    cut_trace.write(cutfile, format='SAC')
コード例 #2
0
def L1norm(record_paths):
    import os.path as path
    import dread
    from obspy import read
    import numpy as np

    N = len(record_paths)
    L1 = np.zeros((N, 50))  #50 bands, number of recordings
    for i in range(N):
        #for the list of records compute L2 norm in each f band
        base = path.basename(record_paths[i])
        eventid, network, station, channel, extn = base.split('.')
        raw_file = '/Users/escuser/Documents/Alexis_Data/cut_sac_files/rawdata/' + eventid + '.' + network + '.' + station + '.HHN.sac'
        event_dir = '/Users/escuser/Documents/Alexis_Data/cut_sac_files/event_site_spectra/'
        station_dir = '/Users/escuser/Documents/Alexis_Data/cut_sac_files/event_site_spectra/'
        stream = read(raw_file)
        tr = stream[0]

        evlon = tr.stats.sac.evlo  #deg
        evlat = tr.stats.sac.evla  #deg
        evdepth = tr.stats.sac.evdp  #km
        stlon = tr.stats.sac.stlo  #deg
        stlat = tr.stats.sac.stla  #deg
        stdepth = tr.stats.sac.stdp  #km

        #find distance between event and station
        dist = dread.compute_rrup(evlon, evlat, evdepth, stlon, stlat,
                                  stdepth)  #in km
        #km to cm
        dist = dist * 100000
        #record spectra
        record_data = np.genfromtxt(record_paths[i],
                                    dtype=float,
                                    comments='#',
                                    delimiter=None,
                                    usecols=(0,
                                             1))  #only read in first two cols
        record_spec = record_data[:, 1] * dist

        #event spectra
        event_data = np.genfromtxt(event_dir + eventid + '.out',
                                   dtype=float,
                                   comments='#',
                                   delimiter=None,
                                   usecols=(0, 1))
        event_spec = event_data[:, 1]
        #station spectra
        station_data = np.genfromtxt(station_dir + station + '.out',
                                     dtype=float,
                                     comments='#',
                                     delimiter=None,
                                     usecols=(0, 1))
        station_spec = station_data[:, 1]

        calc_record_spec = station_spec * event_spec
        residual = (record_spec - calc_record_spec)
        #set recording row equal to residual array
        L1[i:, ] = residual
    return L1
コード例 #3
0
def match_residuals(evid, mcat, slon, slat, sd, s, rlon, rlat, rdepth, eresid):
    from scipy.stats import pearsonr
    import statsmodels
    import statsmodels.stats.power
    
    
    eventid = []
    stressdrop = []
    residual = []
    for i in range(len(evid)):
        d = []
        print (evid[i])
        for j in range(len(rlat)):
            dist = dread.compute_rrup(slon[i], slat[i], sd[i], rlon[j], rlat[j], -1*rdepth[j]) #in km
            d.append(dist)
        if min(d) < 20:
            ind = d.index(min(d))
            eventid.append(evid[i])
            stressdrop.append(s[i])
            residual.append(eresid[ind])
    cmap = mpl.cm.get_cmap('viridis')
    
    normalize = mpl.colors.Normalize(vmin=min(mcat), vmax=max(mcat))
    colors = [cmap(normalize(value)) for value in mcat]
    s_m = mpl.cm.ScalarMappable(cmap = cmap, norm=normalize)
    s_m.set_array([])
    
    fig = plt.figure(figsize = (16,14))
    plt.subplot(111)
    plt.tick_params(axis='both', which='major', labelsize=18)
    plt.tick_params(axis='both', which='both', length = 5, width = 1)
    plt.scatter(x= stressdrop, y=residual, c = colors, edgecolors = colors)
    plt.xlabel('log stress drop (MPa)', fontsize = 28)
    plt.ylabel('GMPE event residual', fontsize = 28)
    plt.gca().xaxis.set_major_formatter(mtick.FormatStrFormatter('%.2f'))
    
    
    rval, pval = pearsonr(x= stressdrop, y=residual)
    power = statsmodels.stats.power.tt_solve_power(effect_size = rval, nobs = len(stressdrop), alpha = 0.05)
    label1 = 'Pearson R : ' + "{:.4f}".format(rval)
    label3 = 'power : ' + "{:.4f}".format(power)
    label2 = 'pvalue: ' + "{:.4f}".format(pval)
    
    plt.annotate(label1 + '\n' + label2 + '\n' + label3, xy=(0.72, 0.02), xycoords='axes fraction', bbox=dict(facecolor='white', edgecolor='black', boxstyle='square,pad=0.2'))

    
    fig.subplots_adjust(right=0.9)
    cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.75])
    cbar = plt.colorbar(s_m, cax=cbar_ax)
    cbar.set_label(ur"magnitude", fontsize = 22)#"$azimuth$ (\u00b0)"
    cbar.ax.tick_params(labelsize = 18)
    
    
    
    plt.show()
    plt.savefig(top_dir + '/source_params/residual_vs_stressdrop_match_events.png')
コード例 #4
0
ファイル: spec_func.py プロジェクト: Elias-King/turtle-kappa
def L1norm(record_paths):
    import os.path as path
    import dread
    from obspy import read
    import numpy as np

    N = len(record_paths)
    L1  = np.zeros((N, 50)) #50 bands, number of recordings
    for i in range(N):
    #for the list of records compute L1 norm in each f band
        base = path.basename(record_paths[i])
        print(record_paths[i])
        box = record_paths[i].split('/')[5]
        network, station, channel, loc = base.split('_')[0:4]
        yyyy, month, day, hh, mm, ss = base.split('_')[4:]
        ss = ss.split('.')[0]
        eventid = yyyy + '_' + month + '_' + day + '_' + hh + '_' + mm + '_' + ss    

        raw_file = '/Users/escuser/project/boxes/' + box + '/uncorrected/Event_' + eventid + '/' + network + '_' +  station + '_HHN_' + loc + '_' + eventid + '.SAC'
        event_dir =  '/Users/escuser/project/boxes/' + box + '/secondo/'
        station_dir =  '/Users/escuser/project/boxes/' + box + '/secondo/'
        
        stream = read(raw_file)
        tr = stream[0]

        evlon =  tr.stats.sac.evlo #deg
        evlat =  tr.stats.sac.evla #deg
        evdepth = tr.stats.sac.evdp #km
        stlon = tr.stats.sac.stlo #deg
        stlat = tr.stats.sac.stla #deg
        stdepth = tr.stats.sac.stdp #km

        #find distance between event and station
        dist =  dread.compute_rrup(evlon, evlat, evdepth, stlon, stlat, stdepth) #in km
        #km to cm
        dist = dist*100000
        #record spectra
        record_data = np.genfromtxt(record_paths[i], dtype = float, comments = '#', delimiter = None, usecols = (0,1))#only read in first two cols
        record_spec = record_data[:,1]*dist

        #event spectra
        event_data = np.genfromtxt(event_dir + eventid + '.out', dtype = float, comments = '#', delimiter = None, usecols = (0,1))
        event_spec = event_data[:,1]
        #station spectra
        station_data = np.genfromtxt(station_dir + station + '.out', dtype = float, comments = '#', delimiter = None, usecols = (0,1))
        station_spec = station_data[:,1]
        
        calc_record_spec = station_spec*event_spec
        residual = (record_spec - calc_record_spec)
        #set recording row equal to residual array
        L1[i:,] = residual
    return L1
コード例 #5
0
def dist_to_elMayor(vertices, lon, lat, m, s, sig, d):
    points = zip(sobj.lon, sobj.lat)
    path = mpltPath.Path(vertices)
    inside = path.contains_points(points)
    
    t = []
    s = []
    m = []
    sig = []
    d = []
    lat = []
    lon = []
    elMayor_dist = []
    
    for i in range(len(inside)):
        if inside[i] == True:
            x = (sobj.evid[i]).split('_')
            t.append(datetime(int(x[0]), int(x[1]), int(x[2]), int(x[3]), int(x[4]), int(x[5])))
            #t.append(points_t[i])
            s.append(sobj.log_stressdrop[i])
            m.append(sobj.m_cat[i])
            sig.append(sobj.log_stressdrop_sig[i])
            d.append(sobj.depth[i])
            lat.append(sobj.lat[i])
            lon.append(sobj.lon[i])
            dist = dread.compute_rrup(elMayorlon, elMayorlat,elMayordepth, sobj.lon[i], sobj.lat[i], -1*sobj.depth[i])
            elMayor_dist.append(dist)
    
    cmap = mpl.cm.get_cmap('viridis')
    normalize = mpl.colors.Normalize(vmin=min(m), vmax=max(m))
    colors = [cmap(normalize(value)) for value in m]
    s_m = mpl.cm.ScalarMappable(cmap = cmap, norm=normalize)
    s_m.set_array([])
    
    fig = plt.figure(figsize = (18,16))
    plt.scatter(elMayor_dist, s, marker='o', s=25, c = colors, edgecolors = colors)   
    for i in range(len(s)):
            plt.errorbar(x=elMayor_dist[i], y=s[i], yerr = sig[i], marker = '.', c = colors[i])
    plt.xlabel('distance to elMayor event (km)')
    plt.ylabel('log stressdrop')
    
    fig.subplots_adjust(right=0.88)
    cbar_ax = fig.add_axes([0.92, 0.1, 0.02, 0.8])
    cbar = plt.colorbar(s_m, cax=cbar_ax)
    cbar.set_label(ur"magnitude", fontsize = 22)#"$azimuth$ (\u00b0)"
    cbar.ax.tick_params(labelsize = 18)
    
    plt.show()
    plt.savefig(top_dir + '/source_params/dist_to_elMayor_polygon1.png')
コード例 #6
0
def cut_swave(infile, cutfile, t1, t2):
    #reads in a sac file
    #full path to output file
    #cuts at t1 sec before s arrival and t2 seconds after
    from obspy import read
    import dread
    import datetime

    velocity = 3.5  #km/s

    stream = read(infile)
    tr = stream[0]

    origin_hour = tr.stats.sac.nzhour
    origin_min = tr.stats.sac.nzmin
    origin_sec = tr.stats.sac.nzsec
    origin_msec = tr.stats.sac.nzmsec

    trace_starttime = tr.stats.starttime

    origin_time = (origin_hour * 60 * 60 + origin_min * 60 + origin_sec +
                   origin_msec / 1000.)  # in seconds after start of day
    trace_starttime_sec = tr.stats.sac.b  #sec

    #difference between origin time and when the trace starts
    delta = origin_time - trace_starttime_sec  # in sec
    origin_time_UTC = trace_starttime + datetime.timedelta(
        seconds=delta)  #convert origin time to UTC

    evlon = tr.stats.sac.evlo  #deg
    evlat = tr.stats.sac.evla  #deg
    evdepth = tr.stats.sac.evdp  #km
    stlon = tr.stats.sac.stlo  #deg
    stlat = tr.stats.sac.stla  #deg
    stdepth = tr.stats.sac.stdp  #km

    #find distance between event and station
    dist = dread.compute_rrup(evlon, evlat, evdepth, stlon, stlat,
                              stdepth)  #in km

    s_travel_time = dist / velocity  # in sec
    cuttime = origin_time_UTC + datetime.timedelta(
        seconds=s_travel_time)  #add travel time or utc origin time

    cut_trace = tr.slice(cuttime - datetime.timedelta(seconds=t1),
                         cuttime + datetime.timedelta(seconds=t2),
                         nearest_sample=True)  #make a new trace by slicing

    cut_trace.write(cutfile, format='sac')
コード例 #7
0
    #read in uncorrected data for header info
    raw_file = boxpath + '/uncorrected/Event_'+ eventid + '/' + network + '_' + station + '_HHN_' + loc + '_' + eventid + '.SAC'
    stream = read(raw_file)
    tr = stream[0]
    
#    print('doing record: ' +  base)
    
    evlon =  tr.stats.sac.evlo #deg
    evlat =  tr.stats.sac.evla #deg
    evdepth = tr.stats.sac.evdp #km
    stlon = tr.stats.sac.stlo #deg
    stlat = tr.stats.sac.stla #deg
    stdepth = tr.stats.sac.stdp #km
    
    #find distance between event and station
    dist =  dread.compute_rrup(evlon, evlat, evdepth, stlon, stlat, stdepth) #in km
    #km to cm
    dist = dist*100000.
    record_dist.append(dist)
    #read in file
    data = np.genfromtxt(record_path[i], dtype = float, comments = '#', delimiter = None, usecols = (0,1))#only read in first two cols
    record_freq.append(data[:,0])
    #data is NE spectra
    #square for power spectra
    record_spec.append((data[:,1]*dist)**2.)
    #if network and station not part of the list yet add
    if station not in stationlist:
        stationlist.append(station)
        stn_lat.append(stlat)
        stn_lon.append(stlon)
#        print station, stlat, stlon
コード例 #8
0
def cut_swave(infile,
              cutfile):  #input an instrument corrected sac file, full path
    #reads in a sac file and cuts at the s wave arrival time and 120 s after
    #set up for HH sampling rate
    import matplotlib.pyplot as plt
    from obspy import read
    import dread
    import datetime

    # out = open(cutfile,'w')

    velocity = 3.5  #km/s, check and update with paper

    stream = read(infile)
    tr = stream[0]

    #df = tr.stats.sampling_rate
    origin_hour = tr.stats.sac.nzhour
    origin_min = tr.stats.sac.nzmin
    origin_sec = tr.stats.sac.nzsec
    origin_msec = tr.stats.sac.nzmsec

    trace_starttime = tr.stats.starttime
    #trace_endtime = tr.stats.endtime

    origin_time = (origin_hour * 60 * 60 + origin_min * 60 + origin_sec +
                   origin_msec / 1000.)  # in seconds after start of day
    trace_starttime_sec = tr.stats.sac.b  #sec

    #difference between origin time and when the trace starts
    delta = origin_time - trace_starttime_sec  # in sec
    origin_time_UTC = trace_starttime + datetime.timedelta(
        seconds=delta)  #convert origin time to UTC

    evlon = tr.stats.sac.evlo  #deg
    evlat = tr.stats.sac.evla  #deg
    evdepth = tr.stats.sac.evdp  #km
    stlon = tr.stats.sac.stlo  #deg
    stlat = tr.stats.sac.stla  #deg
    stdepth = tr.stats.sac.stdp  #km

    #find distance between event and station
    dist = dread.compute_rrup(evlon, evlat, evdepth, stlon, stlat,
                              stdepth)  #in km
    #print(tr.stats.sac.dist)

    s_travel_time = dist / velocity  # in sec
    #s_arrival_time = origin_time + s_travel_time
    cuttime = origin_time_UTC + datetime.timedelta(
        seconds=s_travel_time)  #add travel time or utc origin time

    cut_xval = (
        cuttime - trace_starttime
    ) / 0.01  #using HH sampling rate, convert cut time into x value on plot

    data = tr.data
    #    plt.figure(figsize = (25,6))
    #    plt.plot(data, color='black')
    #    plt.xlim(0, len(data))
    #    plt.axvline(x=cut_xval, c = 'r')#first cut
    #    plt.axvline(x=cut_xval + 120/0.01, c = 'r')#second cut
    #    plt.show()

    cut_trace = tr.slice(cuttime,
                         cuttime + datetime.timedelta(seconds=120),
                         nearest_sample=True)  #make a new trace by slicing
    data2 = cut_trace.data

    #    plt.figure(figsize = (25,6))
    #    plt.plot(data2, color='black')
    #    plt.xlim(0, len(data2))
    #    plt.show()

    cut_trace.write(cutfile, format='sac')

    return cuttime
コード例 #9
0
    t_evlat = [tobj.evlat[i] for i in t_index]
    t_evlon = [tobj.evlon[i] for i in t_index]
    t_evdep = [tobj.evdep[i] for i in t_index]
    t_tstar = [tobj.tstar[i] for i in t_index]
    
    r_evlat = [robj.elat[i] for i in r_index]
    r_evlon = [robj.elon[i] for i in r_index]
    r_evdep = [robj.edepth[i] for i in r_index]
    r_residual = [robj.path_terms[i] for i in r_index]
    
    #for each t* event, find the closest residual event
    for l in range(len(t_evlat)):
#    for l in range(10):
        d = []
        for m in range(len(r_evlat)):
            dist = dread.compute_rrup(t_evlon[l], t_evlat[l], t_evdep[l], r_evlon[m], r_evlat[m], -1*r_evdep[m]) #in km
#            print(t_evlon[l], t_evlat[l], t_evdep[l], r_evlon[m], r_evlat[m], -1*r_evdep[m])
            d.append(dist)
        if min(d) < match_dist:
            #it's a match!!
            ind = d.index(min(d))
#            print '{0:23s} {1:6s} {2:15f} {3:12f} {4:12f} {5:12f} {6:12f} {7:12f} {8:12f} {9:12f} {10:12f}'.format(t_evid[l], sta_set[k], t_evlon[l], t_evlat[l], t_evdep[l], r_evlon[ind], r_evlat[ind], r_evdep[ind], d[ind], t_tstar[l], r_residual[ind])
            v1.append(t_evid[l])
            s.append(sta_set[k])
            v2.append(t_evlon[l])
            v3.append(t_evlat[l])
            v4.append(t_evdep[l])
            v5.append(r_evlon[ind])
            v6.append(r_evlat[ind])
            v7.append(r_evdep[ind])
            v8.append(d[ind])
コード例 #10
0
#Minimum number of stations for each event:
min_stations=5

print 'Will use a buffer of %f, and minimum number of stations as %f' % (buffer,min_stations)

#############
#############

print 'Reading in data'

#Read in the data:
evnum,evlat,evlon,evdep,sta,stlat,stlon,stelv,grcircle,ml,mw,pga_millig,source_i,receiver_i=dr.read_jsbfile(flatfile)

print 'Computing Rrup'
#Compute Rrup for the data:
rrup=dr.compute_rrup(evlon,evlat,evdep,stlon,stlat,stelv)

######################
print 'Acquiring Vs30 from grid file'
#Get Vs30:
#Find unique stations so it can be saved to a file later:
unique_stations=np.unique(sta)
sta_index=[]
for sta_i in range(len(unique_stations)):
    sta_index.append(int(np.where(sta==unique_stations[sta_i])[0][0]))

#Get the lat and lon of these points only:
stlon_unique=stlon[sta_index]
stlat_unique=stlat[sta_index]

# Write out the file to use for vs30 extraction: 
コード例 #11
0
def secondo(record_path, out_file_path):
    print 'Number of records: ', len(record_path)
    #read in all files to find networks and stations
    stationlist = []
    stn_lat = []
    stn_lon = []
    eventidlist = []
    event_lat = []
    event_lon = []
    event_depth = []
    record_freq = []
    record_spec = []
    record_std = []
    
    ##############################################################################
    ## read in the uncut sac files and get the distances between source and station
    
    t1 = time.time()

    
    for i in range(len(record_path)):
        record = (record_path[i].split('/')[-1])
        base = path.basename(record)
        network, station, channel, loc = base.split('_')[0:4]
        yyyy, month, day, hh, mm, ss = base.split('_')[4:]
        ss = ss.split('.')[0]
        eventid = yyyy + '_' + month + '_' + day + '_' + hh + '_' + mm + '_' + ss
        
        #read in uncorrected data for header info
        raw_file = working_dir + '/corrected/Event_'+ eventid + '/' + network + '_' + station + '_HHN_' + loc + '_' + eventid + '.SAC'
        stream = read(raw_file)
        tr = stream[0]
        
        evlon =  tr.stats.sac.evlo #deg
        evlat =  tr.stats.sac.evla #deg
        evdepth = tr.stats.sac.evdp #km
        stlon = tr.stats.sac.stlo #deg
        stlat = tr.stats.sac.stla #deg
        stdepth = tr.stats.sac.stdp #km
        
        #find distance between event and station
        dist =  dread.compute_rrup(evlon, evlat, evdepth, stlon, stlat, stdepth) #in km
        #km to m
        dist = dist*1000.
    
        #read in file
        data = np.genfromtxt(record_path[i], dtype = float, comments = '#', delimiter = None, usecols = (0,1,2))#only read in first two cols
        record_freq.append(data[:,0])##
        #data is NE spectra
        #square for power spectra
        ###########################################################################
        #propagation here for errors going lin to log power
        record_spec.append((data[:,1]*dist)**2.)
        std_prop = np.abs(2*(data[:,2])/(data[:,1]*np.log(10)))
        record_std.append(std_prop)#in log power here
        #if network and station not part of the list yet add
        if station not in stationlist:
            stationlist.append(station)
            stn_lat.append(stlat)
            stn_lon.append(stlon)
        if eventid not in eventidlist:
            eventidlist.append(eventid)
            event_lat.append(evlat)
            event_lon.append(evlon)
            event_depth.append(evdepth)
            
    t2 = time.time()
    
    print 'time to read and distance correct all records: ', (t2-t1)/60.
    print len(record_freq)
    print len(record_spec)

    freq_list = record_freq[0]
    print(freq_list)
    F_bins = len(freq_list)
    print(F_bins)
    
    rows = len(record_path) #testing first 10
    print(rows)
    
    index_matrix = [[0 for j in range(3)] for i in range(rows)]
    
    #for i in range(len(records)):
    for i in range(rows):
        record = record_path[i].split('/')[-1]
        base = path.basename(record)
        network, station, channel, loc = base.split('_')[0:4]
        yyyy, month, day, hh, mm, ss = base.split('_')[4:]
        ss = ss.split('.')[0]
        eventid = yyyy + '_' + month + '_' + day + '_' + hh + '_' + mm + '_' + ss
        #make a tuple of record, event, station so indices can be assigned
        index_matrix[i] = [base, eventidlist.index(eventid), stationlist.index(station)]
    
    print(eventidlist[0])
    print(stationlist)
    
    I = len(eventidlist)#events
    J = len(stationlist)#stations
    K = len(record_path)#records
    K = rows
    
    print 'Number of events: ', I, ' Number of stations: ', J
    print 'Number of rows (records): ', K, ' Number of cols (events+stations): ', I+J
    
    #make the G matrix of 1s and 0s and R matrix of records
    G1 = np.zeros((K,I))
    G2 = np.zeros((K,J))

    
    for k in range(K):#for all records
        G1[k][index_matrix[k][1]] = 1 #record row, eventid col
        G2[k][index_matrix[k][2]] = 1 #record row, station col
    
    
    G = np.concatenate((G1,G2), axis = 1)
    
    print(G)
    
    R = np.zeros((K,F_bins))
    cov = np.zeros((K,F_bins))
    
    #populate R matrix with the log of the record spectra (power record spectra)
    for k in range(K):#for all records
        #each row is a record, and col is a frequency band
        #set row equal to the that spectral array
        #here we take the log
        R[k:,] = np.log10(record_spec[k])
        cov[k:,] = record_std[k]
        
    m1 = np.zeros((I+J, F_bins))
    m_cov = np.zeros((I+J, F_bins))
    
    #do the inversion for each freq
    for f in range(F_bins):
        t1 = time.time()
        d = R[:,f]#record for given frequency col
        dT = d.T
        print 'inverting for frequency: ', f, freq_list[f]
        G_inv = np.linalg.pinv(G, rcond=1e-13)
        covd = np.diag(cov[:,f])

        covm = np.dot((np.dot(G_inv, covd)), G_inv.T)
        m1[:,f] = np.dot(G_inv,dT)
        m_cov[:,f]= covm.diagonal()
        t2 = time.time()
        print 'time for inversion: (min) ', round((t2-t1)/60., 4)
    
    
    print(m1.shape)
    #now split m into an event matrix and a station matrix
    event = m1[0:I,:] #take first I rows
    station = m1[I:I+J,:]
    event_cov = m_cov[0:I,:]
    station_cov = m_cov[I:I+J,:]
    print(event.shape, station.shape)
    print(event_cov.shape, station_cov.shape)

    for i in range(I):#for each event
        #go from the log of the power spectra to the regular spectra in m
        amp = np.sqrt(np.power(10.0, event[i,:]))

        std = (np.sqrt(np.abs(event_cov[i,:])/2.)*((amp)*(np.log(10))))
        
        outfile = open(outfile_path + '/' + eventidlist[i] + '.out', 'w')
        out = (np.array([freq_list, amp, std])).T
        outfile.write('#freq_bins \t vel_spec_NE_m \t stdev_m \n')
        np.savetxt(outfile, out, fmt=['%E', '%E', '%E'], delimiter='\t')
        outfile.close()


    print outfile_path
    for i in range(J):#for each station
        amp = np.sqrt(np.power(10.0, station[i,:]))

        std1 = np.sqrt((station_cov[i,:]))
        std = np.abs((std1/2.)*(amp)*(np.log(10)))
        outfile = open(outfile_path + '/' + stationlist[i] + '.out', 'w')
        out = (np.array([freq_list, amp, std])).T
        outfile.write('#freq_bins \t vel_spec_NE_m \t stdev_m \n')
        np.savetxt(outfile, out, fmt=['%E', '%E', '%E'], delimiter='\t')
        outfile.close()
コード例 #12
0
#%%
#order stations by distance to the source
source_lat = 44.090  #N
source_lon = -122.831  #°W
source_dep = 4.0  #km

x = []
for i in range(len(test)):
    name_specfem = (test[i].split('/')[-1])[0:-4]
    nets, stas, chans, ns = name_specfem.split('.')
    print name_specfem
    for j in range(len(stnm)):
        if stnm[j] == stas and chan[j][2] == plotchan and chans[
                2] == plotchanspecfem:
            print stnm[j], stas, chans, ns
            dist = dread.compute_rrup(source_lon, source_lat, source_dep,
                                      lon[j], lat[j], 0.0)
            x.append([stnm[j], test[i], dist])

station_dist = sorted(x, key=lambda x: x[2])

n = len(station_dist)

##%%
##make a n x 2 figure of each station with data on left and specfem on right
#n = len(station_dist)
#fig, (axs) = plt.subplots(n,2, sharex=True,figsize = (16,10))
#
#for i in range(len(station_dist)):
#    print station_dist[i][0]
#    specfem =  station_dist[i][1]
#    r = round(station_dist[i][2],2)
コード例 #13
0
ファイル: compile_database.py プロジェクト: aklimase/GMM_ANN
                        if stns[j] == pcat[l][1]:
                            db_DA.append(pcat[l][2])
                            break

                db_sta.append(stns[j])
                db_stelv.append(data.stelv[k])
                db_stlat.append(data.stlat[k])
                db_stlon.append(data.stlon[k])
                db_vs30.append(data.vs30[k])
                db_vs30method.append(data.vs30_method[k])

                ind = np.where(tstarcat['site'] == (stns[j]))
                db_kappa.append(tstarcat['tstars'][ind])

                dist = dread.compute_rrup(cat[i][3], cat[i][2], cat[i][4],
                                          data.stlon[k], data.stlat[k],
                                          -1 * data.stelv[k])  #in km
                db_r.append(dist)

                print ev, stns[j], data.stelv[k], data.stlat[
                    k], dist, data.vs30[k], tstarcat['tstars'][ind], M, cat[i][
                        2]

                break

#make other things 0
db_N = np.zeros(len(db_evnum))
db_DV = np.zeros(len(db_evnum))
db_sourcei = np.zeros(len(db_evnum))
db_receiveri = np.zeros(len(db_evnum))
db_pga_snr = np.zeros(len(db_evnum))