Ejemplo n.º 1
0
def event_magnitude(sfile, min_sta=3):
    """
    Function to generate the magnitude of a single event from a seisan s-file
    with amplitude picks in it

    :type sfile: String
    :param sfile: Nordic type s-file name, with full path

    :return: Local magnitude, standard deviation of magnitude
    """
    from pro import Sfile_util
    from par import mag_conv_par as mag_par
    # Check that the s-file exists
    import glob
    if not glob.glob(sfile):
        raise NameError('Sfile does not exist: '+sfile)

    picks=Sfile_util.readpicks(sfile)
    Mag_out=[]
    for pick in picks:
        if pick.phase=='IAML':
            if 'sta_cor' in locals():
                del sta_cor
            for station in mag_par.station_corrections:
                if pick.station==station[0]:
                    sta_cor=station[1]
            if not 'sta_cor' in locals():
                sta_cor=1.0
                # print '\nStation correction not found for station '+pick.station
            # try:
            # Note, seisan stores half amplitudes
            Magnitude=mag_conv(pick.amplitude*2, pick.distance, sta_cor,\
                              mag_par.frequency_dependent,\
                              pick.peri)
            if not np.isnan(Magnitude):
               Mag_out.append(Magnitude)
            # except (ValueError):
                # print 'Either earthquake too far away, or frequency is not set'
                # print pick.peri
                # pass
    if len(Mag_out) > min_sta:
        Mag_std=np.std(Mag_out)
        Mag_out=np.mean(Mag_out) # Take the mean magnitude
        print Mag_out
        return Mag_out, Mag_std
    else:
        return np.nan, np.nan
Ejemplo n.º 2
0
def plot_residuals(path):
    """
    Function to read in S-files and make a histogram of the pick residuals for
    each station

    :type path: Str
    """
    import glob, sys
    import matplotlib.pyplot as plt
    from pro import Sfile_util
    import numpy as np
    sfilelist=glob.glob(path+'/*/*/*.S*')
    if 'stachan_list' in locals():
        del stachan_list
    for sfile in sfilelist:
        picks=Sfile_util.readpicks(sfile)
        for pick in picks:
            match=0
            if not 'stachan_list' in locals():
                if abs(pick.timeres) <=4.0 and pick.channel != 'HT':
                    if pick.phase=='P':
                        stachan_list=[[pick.station, pick.channel, [pick.timeres],[]]]
                    elif pick.phase=='S':
                        stachan_list=[[pick.station, pick.channel, [], [pick.timeres]]]
            else:
                for stachan in stachan_list:
                    if pick.station == stachan[0] and \
                            pick.channel == stachan[1] and not np.isnan(pick.timeres)\
                            and abs(pick.timeres) <= 4.0:
                        if pick.phase=='P':
                            stachan[2].append(pick.timeres)
                        elif pick.phase=='S':
                            stachan[3].append(pick.timeres)
                        match=1
                if match == 0 and not np.isnan(pick.timeres)\
                        and abs(pick.timeres) <= 4.0 and pick.channel != 'HT':
                    print 'Found picks for: '+pick.station+' '+pick.channel
                    if pick.phase=='P':
                        stachan_list.append([pick.station, pick.channel, [pick.timeres], []])
                    elif pick.phase=='S':
                        stachan_list.append([pick.station, pick.channel, [], [pick.timeres]])
    # Print out some useful stats
    ppicks=0
    spicks=0
    presidual=0
    sresidual=0
    for stachan in stachan_list:
        ppicks+=len(stachan[2])
        spicks+=len(stachan[3])
        presidual+=sum(stachan[2])
        sresidual+=sum(stachan[3])
    print 'Total P-picks: '+str(ppicks)
    print 'Total S-picks: '+str(spicks)
    print 'P RMS mean: '+str(presidual/ppicks)
    print 'S RMS mean: '+str(sresidual/spicks)
    # Plot the results
    i=0
    # Get unique list of stations, make one plot for each station
    stations=[]
    for stachan in stachan_list:
        stations+=[stachan[0]]
    stations=list(set(stations))
    # Concatenate all the picks for each station
    stachan_list.sort()
    for stachan in stachan_list:
        if not 'sta_list' in locals():
            sta_list=[[stachan[0], 'all', stachan[2], stachan[3]]]
            station=stachan[0]
            i=0
        else:
            if station==stachan[0]:
                sta_list[i][3]+=stachan[3]
                sta_list[i][2]+=stachan[2]
            else:
                sta_list.append(stachan)
                i+=1
                station=stachan[0]
    fig, axes = plt.subplots((len(sta_list)), 1, sharex=True)#, sharey=True)
    print 'I have picks for '+str(len(sta_list))+' stations'
    axes=axes.ravel()
    i=0
    for stachan in sta_list:
        print 'Plotting for station: '+stachan[0]
        if len(stachan[2]) != 0:
            n, bins, patches=axes[i].hist(stachan[2], bins=np.arange(-4.0, 4.0, 0.025)\
                                          , facecolor='Black', alpha=0.5)
            axes[i].text(0.85, 0.8, r'$\ P:\ \mu='+str(np.mean(stachan[2]))[0:4]+\
                         ',\ \sigma='+str(np.std(stachan[2]))[0:4]+\
                         ',\ n='+str(len(stachan[2]))+'$',\
                         horizontalalignment='center', verticalalignment='center',
                         transform=axes[i].transAxes)
        if len(stachan[3]) != 0:
            n, bins, patches=axes[i].hist(stachan[3],bins=np.arange(-4.0, 4.0, 0.025)\
                                          , facecolor='Red', alpha=0.75)
            axes[i].text(0.15, 0.8, r'$\ S:\ \mu='+str(np.mean(stachan[3]))[0:4]+\
                         ',\ \sigma='+str(np.std(stachan[3]))[0:4]+\
                         ',\ n='+str(len(stachan[3]))+'$',\
                         horizontalalignment='center', verticalalignment='center',
                         transform=axes[i].transAxes, color='Red')
        axes[i].set_ylabel(stachan[0])
        # axes[i].yaxis.set_label_position("right")
        axes[i].yaxis.tick_right()
        axes[i].locator_params(axis='y', nbins=2)
        i+=1
    axes[i-1].set_xlabel('RMS residual (s)')
    plt.xlim(-2.0, 2.0)
    # plt.ylim(0,40)
    fig.subplots_adjust(hspace=0.25)
    fig.subplots_adjust(wspace=0)
    fig.text(0.94, 0.5, 'Number of picks', ha='center', va='center', rotation=270)
    plt.show()
    # plt.savefig('residuals.eps')
    return stachan_list