Example #1
0
def get_local_magnitude(st,
                        stations,
                        stlons,
                        stlats,
                        evtime,
                        evlon,
                        evlat,
                        evdep,
                        freqmin=1,
                        freqmax=10,
                        max_epicenter_dist=100):

    allmags = []
    for station in stations:
        st1 = st.copy().select(station=station)
        for tr in st1:
            try:
                tr.detrend('demean')
                tr.detrend('linear')
                tr.taper(max_percentage=0.005, type='hann')
                tr.filter("bandpass",
                          freqmin=freqmin,
                          freqmax=freqmax,
                          corners=2)

                amp_min = tr.data.min()
                amp_max = tr.data.max()
                ind1 = np.where(amp_min == tr.data)[0][0]
                ind2 = np.where(amp_max == tr.data)[0][0]
                amplitude = abs(amp_max) + abs(amp_min)
                timespan = tr.times("utcdatetime")[ind2] - tr.times(
                    "utcdatetime")[ind1]

                ind = np.where(station == stations)[0][0]
                h_dist = calc_vincenty_inverse(evlat, evlon, stlats[ind],
                                               stlons[ind])[0] / 1000.

                PYGEMA_PATH = "%s/pygema" % (site.getsitepackages()[0])
                dataless_file = glob.glob(
                    "%s/src/dataless/%s_%s.dataless" %
                    (PYGEMA_PATH, tr.stats.network, tr.stats.station))[0]
                parser = Parser(dataless_file)
                paz = parser.get_paz(tr.id)

                mag = estimate_magnitude(paz, amplitude, timespan, h_dist)
                if h_dist <= max_epicenter_dist:
                    allmags.append(mag)

            except:
                continue

    # calculate mean of magnitudes
    if len(allmags) > 0:
        evmag = np.nanmean(allmags)
    else:
        evmag = 0.0

    return evmag
Example #2
0
def getrij(latlist, lonlist):
    r''' Calculate rij from lat-lon.

    Returns the projected geographic positions in X-Y.
    Points are calculated with the Vicenty inverse
    and will have a zero-mean.

    @ authors: Jordan W. Bishop and David Fee

    Args:
        1. latlist - [list] A list of latitude points.
        2. lonlist - [list] A list of longitude points.

    Returns:
        1. rij - [array] A numpy array with the first row corresponding to
            cartesian "X" - coordinates and the second row
            corresponding to cartesian "Y" - coordinates.

    Date Last Modified: 8/29/19
    '''

    getrij.__version__ = '1.00'

    # Basic error checking
    latsize = len(latlist)
    lonsize = len(lonlist)

    if (latsize != lonsize):
        raise ValueError('latsize != lonsize')

    # Now to calculate
    xnew = np.zeros((latsize, ))
    ynew = np.zeros((lonsize, ))

    # azes = [0]
    for jj in range(1, lonsize):
        # Obspy defaults are set as: a = 6378137.0, f = 0.0033528106647474805
        # This is apparently the WGS84 ellipsoid.
        delta, az, baz = calc_vincenty_inverse(latlist[0], lonlist[0],
                                               latlist[jj], lonlist[jj])
        # Converting azimuth to radians
        az = (450 - az) % 360
        # azes.append(az)
        xnew[jj] = delta / 1000 * np.cos(az * np.pi / 180)
        ynew[jj] = delta / 1000 * np.sin(az * np.pi / 180)

    # Removing the mean
    xnew = xnew - np.mean(xnew)
    ynew = ynew - np.mean(ynew)

    # rij
    rij = np.array([xnew.tolist(), ynew.tolist()])

    return rij
Example #3
0
def dist_az(lat_source, long_source, depth_source, lat_station, long_station,
            depth_station):
    """
    dist_az(lat_source, long_source, lat_station, long_station)\n
    Compute the epicentral distance and the azimuth from source to station.
    """
    dist, az, baz = calc_vincenty_inverse(lat_source, long_source, lat_station,
                                          long_station)
    dist /= 1000.  # from m to km
    dist = np.sqrt(dist**2 + (depth_station - depth_source)**2)
    return dist, az
Example #4
0
def plot_record_section(st, stations, stlons, stlats, evtime, evlon, evlat, freqmin=2, freqmax=10, dark_background=False, show_plot=False, savedir=None):

  if dark_background:
    plt.style.use(['dark_background'])
  else:
    plt.style.use(['default'])

  for tr in st:
    try:
      #tr.detrend('demean')
      #tr.detrend('linear')
      #tr.taper(max_percentage=0.005,type='hann')
      tr = remove_instrument_response(tr, pre_filt=(0.01, 0.02, 50, 100), detrend=True, taper=True, dataless_file=None)
      tr.filter("bandpass", freqmin=freqmin, freqmax=freqmax, corners=2)
      ind = np.where( tr.stats.station == stations )[0][0]
      tr.stats.distance = calc_vincenty_inverse( stlats[ind], stlons[ind], evlat, evlon )[0]
    except:
      st.remove(tr)
      continue


  fig = plt.figure()
  st.plot(type='section', method='full', orientation='vertical', time_down=True, linewidth=.25, grid_linewidth=.25, show=False, fig=fig )
  ax = fig.axes[0]
  fig.suptitle("Origin Time: %s" % (evtime.strftime("%Y-%m-%d %H:%M:%S")), fontsize=10)
  transform = blended_transform_factory(ax.transData, ax.transAxes)
  for tr in st:
    ax.text(tr.stats.distance / 1e3, 1.0, tr.stats.station, fontsize=6, rotation=45, va="bottom", ha="center", transform=transform, zorder=10)


  if dark_background:
    ax.patch.set_facecolor('k')
  else:
    ax.patch.set_facecolor('w')

  if savedir:
    outdir = "%s" % (savedir)
    if not os.path.isdir(outdir):
      os.makedirs(outdir)

    figname = "%s/record_section.jpg" % (outdir)
    plt.savefig(figname, dpi=300, bbox_inches='tight', transparent=False)
    if not show_plot:
      plt.close('all')

  if show_plot:
    plt.show()
    plt.close('all')
Example #5
0
def getrij(latlist, lonlist):
    r""" Calculate element r_{ij} from lat-lon.

    Return the projected geographic positions in X-Y (cartesian) coordinates.
    Points are calculated with the Vincenty inverse and will have a zero-mean.

    Args:
        latlist (list): A list of latitude points.
        lonlist (list): A list of longitude points.

    Returns:
        (array):
        ``rij``: A numpy array with the first row corresponding to
        cartesian "X" - coordinates and the second row
        corresponding to cartesian "Y" - coordinates.

    """

    # Check that the lat-lon arrays are the same size.
    latsize = len(latlist)
    lonsize = len(lonlist)
    if latsize != lonsize:
        raise ValueError('latsize != lonsize')

    # Pre-allocate "x" and "y" arrays.
    xnew = np.zeros((latsize, ))
    ynew = np.zeros((lonsize, ))

    for jj in range(1, lonsize):
        # Obspy defaults to the WGS84 ellipsoid.
        delta, az, baz = calc_vincenty_inverse(
            latlist[0], lonlist[0], latlist[jj], lonlist[jj])
        # Convert azimuth to radians.
        az = (450 - az) % 360
        xnew[jj] = delta/1000*np.cos(az*np.pi/180)
        ynew[jj] = delta/1000*np.sin(az*np.pi/180)

    # Remove the mean.
    xnew = xnew - np.mean(xnew)
    ynew = ynew - np.mean(ynew)

    # Package as rij.
    rij = np.array([xnew.tolist(), ynew.tolist()])

    return rij
Example #6
0
this_event, idxev, events_list = select_event_from_database(UTCDateTime(1970, 1,1), UTCDateTime().now(), table="LOC")

networks, stations, stlons, stlats, stalts = load_station_metadata()
outdir = build_event_directory_for_nonlinloc(this_event[0], networks, stations, freqmin=1, freqmax=10, deconvolve=False, only_vertical_channel=False, time_before=60, time_after=300)

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
# CHECK IF SEISMIC EVENT IS CONFIRMED OR REJECTED

sacfiles = glob.glob( outdir + "/*HZ*.sac" )  
st = Stream()
for sacfile in sacfiles:
  st1 = read(sacfile)
  for tr in st1:
    ind = np.where( tr.stats.station == stations )[0][0]
    tr.stats.distance = calc_vincenty_inverse( stlats[ind], stlons[ind], this_event[2], this_event[1] )[0]
    st += tr

fig = plt.figure()
st.plot(type='section', method='full', orientation='vertical', time_down=True, linewidth=.25, grid_linewidth=.25, show=False, fig=fig)
ax = fig.axes[0]
transform = blended_transform_factory(ax.transData, ax.transAxes)
for tr in st:
  ax.text(tr.stats.distance / 1e3, 1.0, tr.stats.station, rotation=270, va="bottom", ha="center", transform=transform, zorder=10)

figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.show()

flag = input("\n+ Is this a local earthquake? (yes/no): ")
while flag!="yes" and flag !="no":
Example #7
0
import automatic_detection as autodet
import numpy as np
import matplotlib.pyplot as plt
import h5py as h5
from obspy.core import UTCDateTime as udt
from scipy import stats as scistats

net = autodet.dataset.Network('network.in')
net.read()

#-----------------------------------------------
from obspy.geodetics.base import calc_vincenty_inverse
D = np.zeros((net.n_stations(), net.n_stations()), dtype=np.float32)
for s1 in range(D.shape[0]):
    for s2 in range(D.shape[0]):
        D[s1,s2], az, baz = calc_vincenty_inverse(net.latitude[s1], net.longitude[s1], net.latitude[s2], net.longitude[s2])
for s in range(D.shape[0]):
    D[s,s] += D[s, D[s,:] != 0.].min()/10.
#-----------------------------------------------

def feature_max_kurto(detections, sliding_window=1.):
    sliding_window = np.int32(sliding_window * autodet.cfg.sampling_rate)
    n_detections = detections['waveforms'].shape[0]
    n_stations   = detections['waveforms'].shape[1]
    n_components = detections['waveforms'].shape[2]
    max_kurto    = np.zeros((n_detections, n_stations, n_components, 1), dtype=np.float32)
    for d in range(n_detections):
            max_kurto[d, :, :, 0]  = np.max(autodet.clib.kurtosis(detections['waveforms'][d, :, :, :], W=sliding_window), axis=-1)
    return max_kurto

def feature_peaks_autocorr(detections, max_lag=1.):