Esempio n. 1
0
    def FK(self, st, inv, stime, etime, fmin, fmax, slim, sres, win_len,
           win_frac):

        n = len(st)
        for i in range(n):
            coords = inv.get_coordinates(st[i].id)
            st[i].stats.coordinates = AttribDict({
                'latitude':
                coords['latitude'],
                'elevation':
                coords['elevation'],
                'longitude':
                coords['longitude']
            })

        kwargs = dict(
            # slowness grid: X min, X max, Y min, Y max, Slow Step
            sll_x=-1 * slim,
            slm_x=slim,
            sll_y=-1 * slim,
            slm_y=slim,
            sl_s=sres,
            # sliding open_main_window properties
            win_len=win_len,
            win_frac=win_frac,
            # frequency properties
            frqlow=fmin,
            frqhigh=fmax,
            prewhiten=0,
            # restrict output
            semb_thres=-1e9,
            vel_thres=-1e9,
            timestamp='mlabday',
            stime=stime + 0.1,
            etime=etime - 0.1)

        try:
            out = array_processing(st, **kwargs)

            T = out[:, 0]
            relpower = out[:, 1]
            abspower = out[:, 2]
            AZ = out[:, 3]
            AZ[AZ < 0.0] += 360
            Slowness = out[:, 4]

        except:
            print("Check Parameters and Starttime/Endtime")

            relpower = []
            abspower = []
            AZ = []
            Slowness = []
            T = []

        return relpower, abspower, AZ, Slowness, T
Esempio n. 2
0
def _colormap_plot_beamforming_time(cmaps):
    """
    Plot for illustrating colormaps: beamforming.

    :param cmaps: list of :class:`~matplotlib.colors.Colormap`
    :rtype: None
    """
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates

    from obspy import UTCDateTime
    from obspy.signal.array_analysis import array_processing

    # Execute array_processing
    stime = UTCDateTime("20080217110515")
    etime = UTCDateTime("20080217110545")
    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll_x=-3.0, slm_x=3.0, sll_y=-3.0, slm_y=3.0, sl_s=0.03,
        # sliding window properties
        win_len=1.0, win_frac=0.05,
        # frequency properties
        frqlow=1.0, frqhigh=8.0, prewhiten=0,
        # restrict output
        semb_thres=-1e9, vel_thres=-1e9, timestamp='mlabday',
        stime=stime, etime=etime
    )
    st = _get_beamforming_example_stream()
    out = array_processing(st, **kwargs)
    # Plot
    labels = ['rel.power', 'abs.power', 'baz', 'slow']
    xlocator = mdates.AutoDateLocator()
    for cmap in cmaps:
        fig = plt.figure()
        for i, lab in enumerate(labels):
            ax = fig.add_subplot(4, 1, i + 1)
            ax.scatter(out[:, 0], out[:, i + 1], c=out[:, 1], alpha=0.6,
                       edgecolors='none', cmap=cmap)
            ax.set_ylabel(lab)
            ax.set_xlim(out[0, 0], out[-1, 0])
            ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())
            ax.xaxis.set_major_locator(xlocator)
            ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(xlocator))
        fig.suptitle('AGFA skyscraper blasting in Munich %s' % (
            stime.strftime('%Y-%m-%d'), ))
        fig.autofmt_xdate()
        fig.subplots_adjust(left=0.15, top=0.95, right=0.95, bottom=0.2,
                            hspace=0)
    plt.show()
Esempio n. 3
0
def beamform_spherical(st, slim, sstep, freqlow, freqhigh, win_len, minbeampow, percdiv, stepdiv, Dmin, Dmax, Dstep, stime=None, etime=None, win_frac=0.05, outfolder=None, coordsys='xy', verbose=False):
    """
    Uses plane wave beamforming to approximate answer, then searches in finer grid around answer from that for spherical wave best solution
    Almendros et al 1999 methods
    """
    if outfolder is None:
        outfolder = os.getcwd()

    def dump(pow_map, apow_map, i):
        """Example function to use with `store` kwarg in
        :func:`~obspy.signal.array_analysis.array_processing`.
        """
        np.savez(outfolder+'/pow_map_%d.npz' % i, pow_map)

    if stime is None:
        stime = st[0].stats.starttime
    if etime is None:
        etime = st[0].stats.endtime

    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll_x=-slim, slm_x=slim, sll_y=-slim, slm_y=slim, sl_s=sstep,
        # sliding window properties
        win_len=win_len, win_frac=win_frac,
        # frequency properties
        frqlow=freqlow, frqhigh=freqhigh, prewhiten=0,
        # restrict output
        semb_thres=-1e9, vel_thres=-1e9,
        stime=stime,
        etime=etime, coordsys=coordsys, store=None)

    t, rel_power, abs_power, baz, slow = array_processing(st, **kwargs)

    # Will need this for next step
    geometry = get_geometry(st, coordsys=coordsys)

    # Initiate zero result matrix for entire possible area (sparse?) - Will be

    # Generate time shift table for entire area for all stations (This would be 4D)

    # Filter seismograms to freqlims

    # Pull out just the data from the stream into an array

    for i, t1 in enumerate(t):
        pass
Esempio n. 4
0
# Execute array_processing
stime = obspy.UTCDateTime("20080217110515")
etime = obspy.UTCDateTime("20080217110545")
kwargs = dict(
    # slowness grid: X min, X max, Y min, Y max, Slow Step
    sll_x=-3.0, slm_x=3.0, sll_y=-3.0, slm_y=3.0, sl_s=0.03,
    # sliding window properties
    win_len=1.0, win_frac=0.05,
    # frequency properties
    frqlow=1.0, frqhigh=8.0, prewhiten=0,
    # restrict output
    semb_thres=-1e9, vel_thres=-1e9, timestamp='mlabday',
    stime=stime, etime=etime
)
out = array_processing(st, **kwargs)

# Plot
labels = ['rel.power', 'abs.power', 'baz', 'slow']

xlocator = mdates.AutoDateLocator()
fig = plt.figure()
for i, lab in enumerate(labels):
    ax = fig.add_subplot(4, 1, i + 1)
    ax.scatter(out[:, 0], out[:, i + 1], c=out[:, 1], alpha=0.6,
               edgecolors='none', cmap=obspy_sequential)
    ax.set_ylabel(lab)
    ax.set_xlim(out[0, 0], out[-1, 0])
    ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())
    ax.xaxis.set_major_locator(xlocator)
    ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(xlocator))
Esempio n. 5
0
    def arrayProcessing(self, prewhiten, method):
        np.random.seed(2348)

        geometry = np.array([[0.0, 0.0, 0.0], [-5.0, 7.0,
                                               0.0], [5.0, 7.0, 0.0],
                             [10.0, 0.0, 0.0], [5.0, -7.0, 0.0],
                             [-5.0, -7.0, 0.0], [-10.0, 0.0, 0.0]])

        geometry /= 100  # in km
        slowness = 1.3  # in s/km
        baz_degree = 20.0  # 0.0 > source in x direction
        baz = baz_degree * np.pi / 180.
        df = 100  # samplerate
        # SNR = 100.         # signal to noise ratio
        amp = .00001  # amplitude of coherent wave
        length = 500  # signal length in samples

        coherent_wave = amp * np.random.randn(length)

        # time offsets in samples
        dt = df * slowness * (np.cos(baz) * geometry[:, 1] +
                              np.sin(baz) * geometry[:, 0])
        dt = np.round(dt)
        dt = dt.astype('int32')
        max_dt = np.max(dt) + 1
        min_dt = np.min(dt) - 1
        trl = list()
        for i in xrange(len(geometry)):
            tr = Trace(coherent_wave[-min_dt + dt[i]:-max_dt + dt[i]].copy())
            # + amp / SNR * \
            # np.random.randn(length - abs(min_dt) - abs(max_dt)))
            tr.stats.sampling_rate = df
            tr.stats.coordinates = AttribDict()
            tr.stats.coordinates.x = geometry[i, 0]
            tr.stats.coordinates.y = geometry[i, 1]
            tr.stats.coordinates.elevation = geometry[i, 2]
            # lowpass random signal to f_nyquist / 2
            tr.filter("lowpass", freq=df / 4.)
            trl.append(tr)

        st = Stream(trl)

        stime = UTCDateTime(1970, 1, 1, 0, 0)
        etime = UTCDateTime(1970, 1, 1, 0, 0) + \
            (length - abs(min_dt) - abs(max_dt)) / df

        win_len = 2.
        step_frac = 0.2
        sll_x = -3.0
        slm_x = 3.0
        sll_y = -3.0
        slm_y = 3.0
        sl_s = 0.1

        frqlow = 1.0
        frqhigh = 8.0

        semb_thres = -1e99
        vel_thres = -1e99

        args = (st, win_len, step_frac, sll_x, slm_x, sll_y, slm_y, sl_s,
                semb_thres, vel_thres, frqlow, frqhigh, stime, etime)
        kwargs = dict(prewhiten=prewhiten,
                      coordsys='xy',
                      verbose=False,
                      method=method)
        out = array_processing(*args, **kwargs)
        if 0:  # 1 for debugging
            print '\n', out[:, 1:]
        return out
Esempio n. 6
0
    sll_y=-3.0,
    slm_y=3.0,
    sl_s=0.03,
    # sliding window properties
    win_len=1.0,
    win_frac=0.05,
    # frequency properties
    frqlow=1.0,
    frqhigh=8.0,
    prewhiten=0,
    # restrict output
    semb_thres=-1e9,
    vel_thres=-1e9,
    stime=obspy.UTCDateTime("20080217110515"),
    etime=obspy.UTCDateTime("20080217110545"))
out = array_processing(st, **kwargs)

# Plot

cmap = obspy_sequential

# make output human readable, adjust backazimuth to values between 0 and 360
t, rel_power, abs_power, baz, slow = out.T
baz[baz < 0.0] += 360

# choose number of fractions in plot (desirably 360 degree/N is an integer!)
N = 36
N2 = 30
abins = np.arange(N + 1) * 360. / N
sbins = np.linspace(0, 3, N2 + 1)
Esempio n. 7
0
    def array_processing(self, prewhiten, method):
        np.random.seed(2348)

        geometry = np.array([[0.0, 0.0, 0.0],
                             [-5.0, 7.0, 0.0],
                             [5.0, 7.0, 0.0],
                             [10.0, 0.0, 0.0],
                             [5.0, -7.0, 0.0],
                             [-5.0, -7.0, 0.0],
                             [-10.0, 0.0, 0.0]])

        geometry /= 100      # in km
        slowness = 1.3       # in s/km
        baz_degree = 20.0    # 0.0 > source in x direction
        baz = baz_degree * np.pi / 180.
        df = 100             # samplerate
        # SNR = 100.         # signal to noise ratio
        amp = .00001         # amplitude of coherent wave
        length = 500         # signal length in samples

        coherent_wave = amp * np.random.randn(length)

        # time offsets in samples
        dt = df * slowness * (np.cos(baz) * geometry[:, 1] + np.sin(baz) *
                              geometry[:, 0])
        dt = np.round(dt)
        dt = dt.astype(np.int32)
        max_dt = np.max(dt) + 1
        min_dt = np.min(dt) - 1
        trl = list()
        for i in range(len(geometry)):
            tr = Trace(coherent_wave[-min_dt + dt[i]:-max_dt + dt[i]].copy())
            # + amp / SNR * \
            # np.random.randn(length - abs(min_dt) - abs(max_dt)))
            tr.stats.sampling_rate = df
            tr.stats.coordinates = AttribDict()
            tr.stats.coordinates.x = geometry[i, 0]
            tr.stats.coordinates.y = geometry[i, 1]
            tr.stats.coordinates.elevation = geometry[i, 2]
            # lowpass random signal to f_nyquist / 2
            tr.filter("lowpass", freq=df / 4.)
            trl.append(tr)

        st = Stream(trl)

        stime = UTCDateTime(1970, 1, 1, 0, 0)
        etime = UTCDateTime(1970, 1, 1, 0, 0) + 4.0
        # TODO: check why this does not work any more
        #    (length - abs(min_dt) - abs(max_dt)) / df

        win_len = 2.
        step_frac = 0.2
        sll_x = -3.0
        slm_x = 3.0
        sll_y = -3.0
        slm_y = 3.0
        sl_s = 0.1

        frqlow = 1.0
        frqhigh = 8.0

        semb_thres = -1e99
        vel_thres = -1e99

        args = (st, win_len, step_frac, sll_x, slm_x, sll_y, slm_y, sl_s,
                semb_thres, vel_thres, frqlow, frqhigh, stime, etime)
        kwargs = dict(prewhiten=prewhiten, coordsys='xy', verbose=False,
                      method=method)
        out = array_processing(*args, **kwargs)
        if False:  # 1 for debugging
            print('\n', out[:, 1:])
        return out
Esempio n. 8
0
def _colormap_plot_beamforming_polar(cmaps):
    """
    Plot for illustrating colormaps: beamforming.

    :param cmaps: list of :class:`~matplotlib.colors.Colormap`
    :rtype: None
    """
    import matplotlib.pyplot as plt
    from matplotlib.colorbar import ColorbarBase
    from matplotlib.colors import Normalize

    from obspy import UTCDateTime
    from obspy.signal.array_analysis import array_processing
    # Execute array_processing
    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll_x=-3.0, slm_x=3.0, sll_y=-3.0, slm_y=3.0, sl_s=0.03,
        # sliding window properties
        win_len=1.0, win_frac=0.05,
        # frequency properties
        frqlow=1.0, frqhigh=8.0, prewhiten=0,
        # restrict output
        semb_thres=-1e9, vel_thres=-1e9,
        stime=UTCDateTime("20080217110515"),
        etime=UTCDateTime("20080217110545")
    )
    st = _get_beamforming_example_stream()
    out = array_processing(st, **kwargs)
    # make output human readable, adjust backazimuth to values between 0 and
    # 360
    t, rel_power, abs_power, baz, slow = out.T
    baz[baz < 0.0] += 360
    # choose number of fractions in plot (desirably 360 degree/N is an
    # integer!)
    num = 36
    num2 = 30
    abins = np.arange(num + 1) * 360. / num
    sbins = np.linspace(0, 3, num2 + 1)
    # sum rel power in bins given by abins and sbins
    hist, baz_edges, sl_edges = \
        np.histogram2d(baz, slow, bins=[abins, sbins], weights=rel_power)
    # transform to radian
    baz_edges = np.radians(baz_edges)
    dh = abs(sl_edges[1] - sl_edges[0])
    dw = abs(baz_edges[1] - baz_edges[0])
    for cmap in cmaps:
        # add polar and colorbar axes
        fig = plt.figure(figsize=(8, 8))
        cax = fig.add_axes([0.85, 0.2, 0.05, 0.5])
        ax = fig.add_axes([0.10, 0.1, 0.70, 0.7], polar=True)
        ax.set_theta_direction(-1)
        ax.set_theta_zero_location("N")
        # circle through backazimuth
        for i, row in enumerate(hist):
            ax.bar(left=(i * dw) * np.ones(num2),
                   height=dh * np.ones(num2),
                   width=dw, bottom=dh * np.arange(num2),
                   color=cmap(row / hist.max()))
        ax.set_xticks(np.linspace(0, 2 * np.pi, 4, endpoint=False))
        ax.set_xticklabels(['N', 'E', 'S', 'W'])
        # set slowness limits
        ax.set_ylim(0, 3)
        [i.set_color('grey') for i in ax.get_yticklabels()]
        ColorbarBase(cax, cmap=cmap,
                     norm=Normalize(vmin=hist.min(), vmax=hist.max()))
    plt.show()
Esempio n. 9
0
def beamform_plane(st, sll_x, slm_x, sll_y, slm_y, sstep, freqlow, freqhigh, win_len, stime=None, etime=None, win_frac=0.05, coordsys='xy', outfolder=None, movie=True, savemovieimg=False, plottype='slowaz', showplots=True, saveplots=False, plotlabel=''):
    """
    MAKE CHOICE TO USE Sx Sy or S A in PLOTTING
    plotype = 'slowaz' or 'wavenum'
    NEED ffmpeg for movie making to work, otherwise will just get the images
    """
    if outfolder is None:
        outfolder = os.getcwd()

    def dump(pow_map, apow_map, i):
        """Example function to use with `store` kwarg in
        :func:`~obspy.signal.array_analysis.array_processing`.
        """
        np.savez(outfolder+'/pow_map_%d.npz' % i, pow_map)

    if stime is None:
        stime = st[0].stats.starttime
    if etime is None:
        etime = st[0].stats.endtime
    if movie:
        store = dump
    else:
        store = None

    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll_x=sll_x, slm_x=slm_x, sll_y=sll_y, slm_y=slm_y, sl_s=sstep,
        # sliding window properties
        win_len=win_len, win_frac=win_frac,
        # frequency properties
        frqlow=freqlow, frqhigh=freqhigh, prewhiten=0,
        # restrict output
        semb_thres=-1e9, vel_thres=-1e9,
        stime=stime,
        etime=etime, coordsys=coordsys, store=store)

    out = array_processing(st, **kwargs)

    # make output human readable, adjust backazimuth to values between 0 and 360
    t, rel_power, abs_power, baz, slow = out.T
    baz[baz < 0.0] += 360

    # Plot 1
    labels = ['rel.power', 'abs.power', 'baz', 'slow']

    xlocator = mdates.AutoDateLocator()
    fig1 = plt.figure()
    for i, lab in enumerate(labels):
        ax = fig1.add_subplot(4, 1, i + 1)
        ax.scatter(out[:, 0], out[:, i + 1], c=out[:, 1], alpha=0.6,
                   edgecolors='none')
        ax.set_ylabel(lab)
        ax.set_xlim(out[0, 0], out[-1, 0])
        ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())
        ax.xaxis.set_major_locator(xlocator)
        ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(xlocator))

    fig1.autofmt_xdate()
    fig1.subplots_adjust(left=0.15, top=0.95, right=0.95, bottom=0.2, hspace=0)

    # Plot 2

    cmap = cm.hot_r

    # choose number of fractions in plot (desirably 360 degree/N is an integer!)
    N = 36
    N2 = 30
    abins = np.arange(N + 1) * 360. / N
    sbins = np.linspace(0, np.sqrt(slm_x**2 + slm_y**2), N2 + 1)

    # sum rel power in bins given by abins and sbins
    hist, baz_edges, sl_edges = np.histogram2d(baz, slow, bins=[abins, sbins], weights=rel_power)

    # transform to radian
    baz_edges = np.radians(baz_edges)

    # add polar and colorbar axes
    fig2 = plt.figure(figsize=(8, 8))
    cax = fig2.add_axes([0.85, 0.2, 0.05, 0.5])
    ax = fig2.add_axes([0.10, 0.1, 0.70, 0.7], polar=True)
    ax.set_theta_direction(-1)
    ax.set_theta_zero_location('N')

    dh = abs(sl_edges[1] - sl_edges[0])
    dw = abs(baz_edges[1] - baz_edges[0])

    # circle through backazimuth
    for i, row in enumerate(hist):
        bars = ax.bar(left=(i * dw) * np.ones(N2),
                      height=dh * np.ones(N2),
                      width=dw, bottom=dh * np.arange(N2), color=cmap(row / hist.max()))

    ax.set_xticks(np.linspace(0, 2 * np.pi, np.sqrt(slm_x**2 + slm_y**2), endpoint=False))
    ax.set_xticklabels(['N', 'E', 'S', 'W'])

    # set slowness limits
    ax.set_ylim(0, np.sqrt(slm_x**2 + slm_y**2))
    [i.set_color('grey') for i in ax.get_yticklabels()]
    ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=hist.min(), vmax=hist.max()))

    if showplots is True:
        plt.show()
    if saveplots is True:
        fig1.savefig('%s/%s-%s.png' % (outfolder, 'timeplot', plotlabel))
        fig2.savefig('%s/%s-%s.png' % (outfolder, 'overallplot', plotlabel))

    if movie:
        cmap = cm.RdYlBu
        xgrid = np.arange(sll_x, slm_x+sstep, sstep)
        ygrid = np.arange(sll_y, slm_y+sstep, sstep)
        slow2 = np.empty((len(xgrid), len(ygrid)))
        baz2 = slow2.copy()
        for i in np.arange(len(xgrid)):
            for j in np.arange(len(ygrid)):
                # compute baz, slow
                slow_x = xgrid[i]
                slow_y = ygrid[j]
                slow2[i, j] = np.sqrt(slow_x ** 2 + slow_y ** 2)
                if slow2[i, j] < 1e-8:
                    slow2[i, j] = 1e-8
                azimut = 180 * math.atan2(slow_x, slow_y) / math.pi
                baz2[i, j] = azimut % -360 + 180
        baz2[baz2 < 0.0] += 360
        # transform to radian
        baz2 = np.radians(baz2)

        x, y = np.meshgrid(xgrid, ygrid)

        #pow_map_mean = np.array((x, y))
        findind = 0

        stfilt = st.copy()
        stfilt.filter('bandpass', freqmin=freqlow, freqmax=freqhigh)
        stfilt.trim(stime-5., etime+5., pad=True, fill_value=0.)

        for i, t1 in enumerate(t):
            filen = glob.glob(outfolder+'/pow_map_%i.npz' % findind)
            f = np.load(filen[0])
            pow_map = f['arr_0']
            fig = plt.figure(figsize=(18, 6))
            ax = fig.add_axes([0.05, 0.05, 0.25, 0.9], polar=True)
            ax.pcolormesh(baz2, slow2, pow_map, vmin=0., vmax=1., cmap=cmap)
            ax.set_theta_direction(-1)
            ax.set_theta_zero_location('N')
            #ax.set_ylim(0, np.sqrt(slm_x**2 + slm_y**2))
            ax.set_ylim(0, np.max([slm_x, slm_y]))

            ix, iy = np.unravel_index(pow_map.argmax(), pow_map.shape)
            az = 180 * math.atan2(xgrid[ix], ygrid[iy]) / math.pi
            bazimut = az % -360 + 180
            if bazimut < 0.0:
                bazimut += 360
            slow1 = np.sqrt(xgrid[ix]**2 + ygrid[iy]**2)
            ax.plot(np.radians(bazimut), slow1, 'xk')
            ax.text(np.radians(bazimut), slow1, '  %1.1f km/s\\n %1.0f deg' % (1./slow1, bazimut))
            ax.grid()
            plt.draw()

            cax = fig.add_axes([0.32, 0.15, 0.01, 0.7])
            ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=0.0, vmax=1.))
            ax1 = fig.add_axes([0.37, 0.05, 0.58, 0.9])
            tvec = sigproc.maketvec(stfilt[0])
            #import pdb; pdb.set_trace()
            ax1.plot(tvec, stfilt[0].data/max(stfilt[0].data), 'k', label=stfilt[0].stats.station)
            ax1.plot(tvec, stfilt[1].data/max(stfilt[1].data) + 1.5, 'k', label=stfilt[1].stats.station)
            ax1.plot(tvec, stfilt[2].data/max(stfilt[2].data) + 3., 'k', label=stfilt[2].stats.station)
            sec = UTCDateTime(mdates.num2date(t1))-stfilt[0].stats.starttime
            ax1.vlines(sec, -1, 4, color='r')
            ax1.vlines(sec + win_len, -1, 4, color='r')
            plt.title('Max at %3.0f degrees, speed of %1.1f km/s - tstart %1.0f' % (baz[i], 1/slow[i], sec))
            ax1.set_ylim(-1, 4)
            plt.savefig(('%s/img%03d.png') % (outfolder, i))
            findind += int(win_len*st[0].stats.sampling_rate*win_frac)
            #plt.draw()
            plt.show()
            plt.close(fig)

        #turn into mpg
        origdir = os.getcwd()
        os.chdir(outfolder)
        os.system('ffmpeg -f image2 -start_number 0 -r 4 -i img%03d.png -y -c:v libx264 -vf "format=yuv420p" beammovie.mp4')
        # Clean up
        delfiles = glob.glob(outfolder+'/pow_map_*.npz')
        for df in delfiles:
            os.remove(df)
        if savemovieimg is False:
            delfiles = glob.glob(outfolder+'/img*png')
            for df in delfiles:
                os.remove(df)
        os.chdir(origdir)

    return t, rel_power, abs_power, baz, slow
Esempio n. 10
0
def array_analysis_helper(stream, inventory, method, frqlow, frqhigh,
                          filter=True, baz_plot=True, static3D=False,
                          vel_corr=4.8, wlen=-1, slx=(-10, 10),
                          sly=(-10, 10), sls=0.5, array_response=True):
    """
    Array analysis wrapper routine for MESS 2014.

    :param stream: Waveforms for the array processing.
    :type stream: :class:`obspy.core.stream.Stream`
    :param inventory: Station metadata for waveforms
    :type inventory: :class:`obspy.station.inventory.Inventory`
    :param method: Method used for the array analysis
     (one of "FK": Frequnecy Wavenumber, "DLS": Delay and Sum,
     "PWS": Phase Weighted Stack, "SWP": Slowness Whitened Power).
    :type method: str
    :param filter: Whether to bandpass data to selected frequency range
    :type filter: bool
    :param frqlow: Low corner of frequency range for array analysis
    :type frqlow: float
    :param frqhigh: High corner of frequency range for array analysis
    :type frqhigh: float
    :param baz_plot: Whether to show backazimuth-slowness map (True) or
     slowness x-y map (False).
    :type baz_plot: str
    :param static3D: static correction of topography using `vel_corr` as
     velocity (slow!)
    :type static3D: bool
    :param vel_corr: Correction velocity for static topography correction in
     km/s.
    :type vel_corr: float
    :param wlen: sliding window for analysis in seconds, use -1 to use the
     whole trace without windowing.
    :type wlen: float
    :param slx: Min/Max slowness for analysis in x direction.
    :type slx: (float, float)
    :param sly: Min/Max slowness for analysis in y direction.
    :type sly: (float, float)
    :param sls: step width of slowness grid
    :type sls: float
    :param array_response: superimpose array reponse function in plot (slow!)
    :type array_response: bool
    """

    if method not in ("FK", "DLS", "PWS", "SWP"):
        raise ValueError("Invalid method: ''" % method)

    sllx, slmx = slx
    slly, slmy = sly

    starttime = max([tr.stats.starttime for tr in stream])
    endtime = min([tr.stats.endtime for tr in stream])
    stream.trim(starttime, endtime)

    #stream.attach_response(inventory)
    stream.merge()
    for tr in stream:
        for station in inventory[0].stations:
            if tr.stats.station == station.code:
                tr.stats.coordinates = \
                    AttribDict(dict(latitude=station.latitude,
                                    longitude=station.longitude,
                                    elevation=station.elevation))
                break

    if filter:
        stream.filter('bandpass', freqmin=frqlow, freqmax=frqhigh,
                      zerophase=True)

    print stream
    spl = stream.copy()

    tmpdir = tempfile.mkdtemp(prefix="obspy-")
    filename_patterns = (os.path.join(tmpdir, 'pow_map_%03d.npy'),
                         os.path.join(tmpdir, 'apow_map_%03d.npy'))

    def dump(pow_map, apow_map, i):
        np.save(filename_patterns[0] % i, pow_map)
        np.save(filename_patterns[1] % i, apow_map)

    try:
        # next step would be needed if the correction velocity needs to be
        # estimated
        #
        sllx /= KM_PER_DEG
        slmx /= KM_PER_DEG
        slly /= KM_PER_DEG
        slmy /= KM_PER_DEG
        sls /= KM_PER_DEG
        vc = vel_corr
        if method == 'FK':
            kwargs = dict(
                #slowness grid: X min, X max, Y min, Y max, Slow Step
                sll_x=sllx, slm_x=slmx, sll_y=slly, slm_y=slmy, sl_s=sls,
                # sliding window properties
                win_len=wlen, win_frac=0.8,
                # frequency properties
                frqlow=frqlow, frqhigh=frqhigh, prewhiten=0,
                # restrict output
                store=dump,
                semb_thres=-1e9, vel_thres=-1e9, verbose=False,
                timestamp='julsec', stime=starttime, etime=endtime,
                method=0, correct_3dplane=False, vel_cor=vc,
                static_3D=static3D)

            # here we do the array processing
            start = UTCDateTime()
            out = AA.array_processing(stream, **kwargs)
            print "Total time in routine: %f\n" % (UTCDateTime() - start)

            # make output human readable, adjust backazimuth to values
            # between 0 and 360
            t, rel_power, abs_power, baz, slow = out.T

        else:
            kwargs = dict(
                # slowness grid: X min, X max, Y min, Y max, Slow Step
                sll_x=sllx, slm_x=slmx, sll_y=slly, slm_y=slmy, sl_s=sls,
                # sliding window properties
                # frequency properties
                frqlow=frqlow, frqhigh=frqhigh,
                # restrict output
                store=dump,
                win_len=wlen, win_frac=0.5,
                nthroot=4, method=method,
                verbose=False, timestamp='julsec',
                stime=starttime, etime=endtime, vel_cor=vc,
                static_3D=False)

            # here we do the array processing
            start = UTCDateTime()
            out = AA.beamforming(stream, **kwargs)
            print "Total time in routine: %f\n" % (UTCDateTime() - start)

            # make output human readable, adjust backazimuth to values
            # between 0 and 360
            trace = []
            t, rel_power, baz, slow_x, slow_y, slow = out.T

            # calculating array response
        if array_response:
            stepsfreq = (frqhigh - frqlow) / 10.
            tf_slx = sllx
            tf_smx = slmx
            tf_sly = slly
            tf_smy = slmy
            transff = AA.array_transff_freqslowness(
                stream, (tf_slx, tf_smx, tf_sly, tf_smy), sls, frqlow,
                frqhigh, stepsfreq, coordsys='lonlat',
                correct_3dplane=False, static_3D=False, vel_cor=vc)

        # now let's do the plotting
        cmap = cm.rainbow

        #
        # we will plot everything in s/deg
        slow *= KM_PER_DEG
        sllx *= KM_PER_DEG
        slmx *= KM_PER_DEG
        slly *= KM_PER_DEG
        slmy *= KM_PER_DEG
        sls *= KM_PER_DEG

        numslice = len(t)
        powmap = []
        slx = np.arange(sllx-sls, slmx, sls)
        sly = np.arange(slly-sls, slmy, sls)
        if baz_plot:
            maxslowg = np.sqrt(slmx*slmx + slmy*slmy)
            bzs = np.arctan2(sls, np.sqrt(slmx*slmx + slmy*slmy))*180/np.pi
            xi = np.arange(0., maxslowg, sls)
            yi = np.arange(-180., 180., bzs)
            grid_x, grid_y = np.meshgrid(xi, yi)
        # reading in the rel-power maps
        for i in xrange(numslice):
            powmap.append(np.load(filename_patterns[0] % i))
            if method != 'FK':
                trace.append(np.load(filename_patterns[1] % i))

        npts = stream[0].stats.npts
        df = stream[0].stats.sampling_rate
        T = np.arange(0, npts / df, 1 / df)

        # if we choose windowlen > 0. we now move through our slices
        for i in xrange(numslice):
            slow_x = np.sin((baz[i]+180.)*np.pi/180.)*slow[i]
            slow_y = np.cos((baz[i]+180.)*np.pi/180.)*slow[i]
            st = UTCDateTime(t[i]) - starttime
            if wlen <= 0:
                en = endtime
            else:
                en = st + wlen
            print UTCDateTime(t[i])
            # add polar and colorbar axes
            fig = plt.figure(figsize=(12, 12))
            ax1 = fig.add_axes([0.1, 0.87, 0.7, 0.10])
            # here we plot the first trace on top of the slowness map
            # and indicate the possibiton of the lsiding window as green box
            if method == 'FK':
                ax1.plot(T, spl[0].data, 'k')
                if wlen > 0.:
                    try:
                        ax1.axvspan(st, en, facecolor='g', alpha=0.3)
                    except IndexError:
                        pass
            else:
                T = np.arange(0, len(trace[i])/df, 1 / df)
                ax1.plot(T, trace[i], 'k')

            ax1.yaxis.set_major_locator(MaxNLocator(3))

            ax = fig.add_axes([0.10, 0.1, 0.70, 0.7])

            # if we have chosen the baz_plot option a re-griding
            # of the sx,sy slowness map is needed
            if baz_plot:
                slowgrid = []
                transgrid = []
                pow = np.asarray(powmap[i])
                for ix, sx in enumerate(slx):
                    for iy, sy in enumerate(sly):
                        bbaz = np.arctan2(sx, sy)*180/np.pi+180.
                        if bbaz > 180.:
                            bbaz = -180. + (bbaz-180.)
                        slowgrid.append((np.sqrt(sx*sx+sy*sy), bbaz,
                                         pow[ix, iy]))
                        if array_response:
                            tslow = (np.sqrt((sx+slow_x) *
                                     (sx+slow_x)+(sy+slow_y) *
                                     (sy+slow_y)))
                            tbaz = (np.arctan2(sx+slow_x, sy+slow_y) *
                                    180 / np.pi + 180.)
                            if tbaz > 180.:
                                tbaz = -180. + (tbaz-180.)
                            transgrid.append((tslow, tbaz,
                                              transff[ix, iy]))

                slowgrid = np.asarray(slowgrid)
                sl = slowgrid[:, 0]
                bz = slowgrid[:, 1]
                slowg = slowgrid[:, 2]
                grid = spi.griddata((sl, bz), slowg, (grid_x, grid_y),
                                    method='nearest')
                ax.pcolormesh(xi, yi, grid, cmap=cmap)

                if array_response:
                    level = np.arange(0.1, 0.5, 0.1)
                    transgrid = np.asarray(transgrid)
                    tsl = transgrid[:, 0]
                    tbz = transgrid[:, 1]
                    transg = transgrid[:, 2]
                    trans = spi.griddata((tsl, tbz), transg,
                                         (grid_x, grid_y),
                                         method='nearest')
                    ax.contour(xi, yi, trans, level, colors='k',
                               linewidth=0.2)

                ax.set_xlabel('slowness [s/deg]')
                ax.set_ylabel('backazimuth [deg]')
                ax.set_xlim(xi[0], xi[-1])
                ax.set_ylim(yi[0], yi[-1])
            else:
                ax.set_xlabel('slowness [s/deg]')
                ax.set_ylabel('slowness [s/deg]')
                slow_x = np.cos((baz[i]+180.)*np.pi/180.)*slow[i]
                slow_y = np.sin((baz[i]+180.)*np.pi/180.)*slow[i]
                ax.pcolormesh(slx, sly, powmap[i].T)
                ax.arrow(0, 0, slow_y, slow_x, head_width=0.005,
                         head_length=0.01, fc='k', ec='k')
                if array_response:
                    tslx = np.arange(sllx+slow_x, slmx+slow_x+sls, sls)
                    tsly = np.arange(slly+slow_y, slmy+slow_y+sls, sls)
                    try:
                        ax.contour(tsly, tslx, transff.T, 5, colors='k',
                                   linewidth=0.5)
                    except:
                        pass
                ax.set_ylim(slx[0], slx[-1])
                ax.set_xlim(sly[0], sly[-1])
            new_time = t[i]

            result = "BAZ: %.2f, Slow: %.2f s/deg, Time %s" % (
                baz[i], slow[i], UTCDateTime(new_time))
            ax.set_title(result)

            plt.show()
    finally:
        shutil.rmtree(tmpdir)
Esempio n. 11
0
def beamform_spherical(st,
                       slim,
                       sstep,
                       freqlow,
                       freqhigh,
                       win_len,
                       minbeampow,
                       percdiv,
                       stepdiv,
                       Dmin,
                       Dmax,
                       Dstep,
                       stime=None,
                       etime=None,
                       win_frac=0.05,
                       outfolder=None,
                       coordsys='xy',
                       verbose=False):
    """
    Uses plane wave beamforming to approximate answer, then searches in finer grid around answer from that for spherical wave best solution
    Almendros et al 1999 methods
    """
    if outfolder is None:
        outfolder = os.getcwd()

    def dump(pow_map, apow_map, i):
        """Example function to use with `store` kwarg in
        :func:`~obspy.signal.array_analysis.array_processing`.
        """
        np.savez(outfolder + '/pow_map_%d.npz' % i, pow_map)

    if stime is None:
        stime = st[0].stats.starttime
    if etime is None:
        etime = st[0].stats.endtime

    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll_x=-slim,
        slm_x=slim,
        sll_y=-slim,
        slm_y=slim,
        sl_s=sstep,
        # sliding window properties
        win_len=win_len,
        win_frac=win_frac,
        # frequency properties
        frqlow=freqlow,
        frqhigh=freqhigh,
        prewhiten=0,
        # restrict output
        semb_thres=-1e9,
        vel_thres=-1e9,
        stime=stime,
        etime=etime,
        coordsys=coordsys,
        store=None)

    t, rel_power, abs_power, baz, slow = array_processing(st, **kwargs)

    # Will need this for next step
    geometry = get_geometry(st, coordsys=coordsys)

    # Initiate zero result matrix for entire possible area (sparse?) - Will be

    # Generate time shift table for entire area for all stations (This would be 4D)

    # Filter seismograms to freqlims

    # Pull out just the data from the stream into an array

    for i, t1 in enumerate(t):
        pass
Esempio n. 12
0
def beamform_plane(st,
                   sll_x,
                   slm_x,
                   sll_y,
                   slm_y,
                   sstep,
                   freqlow,
                   freqhigh,
                   win_len,
                   stime=None,
                   etime=None,
                   win_frac=0.05,
                   coordsys='xy',
                   outfolder=None,
                   movie=True,
                   savemovieimg=False,
                   plottype='slowaz',
                   showplots=True,
                   saveplots=False,
                   plotlabel=''):
    """
    MAKE CHOICE TO USE Sx Sy or S A in PLOTTING
    plotype = 'slowaz' or 'wavenum'
    NEED ffmpeg for movie making to work, otherwise will just get the images
    """
    if outfolder is None:
        outfolder = os.getcwd()

    def dump(pow_map, apow_map, i):
        """Example function to use with `store` kwarg in
        :func:`~obspy.signal.array_analysis.array_processing`.
        """
        np.savez(outfolder + '/pow_map_%d.npz' % i, pow_map)

    if stime is None:
        stime = st[0].stats.starttime
    if etime is None:
        etime = st[0].stats.endtime
    if movie:
        store = dump
    else:
        store = None

    kwargs = dict(
        # slowness grid: X min, X max, Y min, Y max, Slow Step
        sll_x=sll_x,
        slm_x=slm_x,
        sll_y=sll_y,
        slm_y=slm_y,
        sl_s=sstep,
        # sliding window properties
        win_len=win_len,
        win_frac=win_frac,
        # frequency properties
        frqlow=freqlow,
        frqhigh=freqhigh,
        prewhiten=0,
        # restrict output
        semb_thres=-1e9,
        vel_thres=-1e9,
        stime=stime,
        etime=etime,
        coordsys=coordsys,
        store=store)

    out = array_processing(st, **kwargs)

    # make output human readable, adjust backazimuth to values between 0 and 360
    t, rel_power, abs_power, baz, slow = out.T
    baz[baz < 0.0] += 360

    # Plot 1
    labels = ['rel.power', 'abs.power', 'baz', 'slow']

    xlocator = mdates.AutoDateLocator()
    fig1 = plt.figure()
    for i, lab in enumerate(labels):
        ax = fig1.add_subplot(4, 1, i + 1)
        ax.scatter(out[:, 0],
                   out[:, i + 1],
                   c=out[:, 1],
                   alpha=0.6,
                   edgecolors='none')
        ax.set_ylabel(lab)
        ax.set_xlim(out[0, 0], out[-1, 0])
        ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())
        ax.xaxis.set_major_locator(xlocator)
        ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(xlocator))

    fig1.autofmt_xdate()
    fig1.subplots_adjust(left=0.15, top=0.95, right=0.95, bottom=0.2, hspace=0)

    # Plot 2

    cmap = cm.hot_r

    # choose number of fractions in plot (desirably 360 degree/N is an integer!)
    N = 36
    N2 = 30
    abins = np.arange(N + 1) * 360. / N
    sbins = np.linspace(0, np.sqrt(slm_x**2 + slm_y**2), N2 + 1)

    # sum rel power in bins given by abins and sbins
    hist, baz_edges, sl_edges = np.histogram2d(baz,
                                               slow,
                                               bins=[abins, sbins],
                                               weights=rel_power)

    # transform to radian
    baz_edges = np.radians(baz_edges)

    # add polar and colorbar axes
    fig2 = plt.figure(figsize=(8, 8))
    cax = fig2.add_axes([0.85, 0.2, 0.05, 0.5])
    ax = fig2.add_axes([0.10, 0.1, 0.70, 0.7], polar=True)
    ax.set_theta_direction(-1)
    ax.set_theta_zero_location('N')

    dh = abs(sl_edges[1] - sl_edges[0])
    dw = abs(baz_edges[1] - baz_edges[0])

    # circle through backazimuth
    for i, row in enumerate(hist):
        bars = ax.bar(left=(i * dw) * np.ones(N2),
                      height=dh * np.ones(N2),
                      width=dw,
                      bottom=dh * np.arange(N2),
                      color=cmap(row / hist.max()))

    ax.set_xticks(
        np.linspace(0, 2 * np.pi, np.sqrt(slm_x**2 + slm_y**2),
                    endpoint=False))
    ax.set_xticklabels(['N', 'E', 'S', 'W'])

    # set slowness limits
    ax.set_ylim(0, np.sqrt(slm_x**2 + slm_y**2))
    [i.set_color('grey') for i in ax.get_yticklabels()]
    ColorbarBase(cax,
                 cmap=cmap,
                 norm=Normalize(vmin=hist.min(), vmax=hist.max()))

    if showplots is True:
        plt.show()
    if saveplots is True:
        fig1.savefig('%s/%s-%s.png' % (outfolder, 'timeplot', plotlabel))
        fig2.savefig('%s/%s-%s.png' % (outfolder, 'overallplot', plotlabel))

    if movie:
        cmap = cm.RdYlBu
        xgrid = np.arange(sll_x, slm_x + sstep, sstep)
        ygrid = np.arange(sll_y, slm_y + sstep, sstep)
        slow2 = np.empty((len(xgrid), len(ygrid)))
        baz2 = slow2.copy()
        for i in np.arange(len(xgrid)):
            for j in np.arange(len(ygrid)):
                # compute baz, slow
                slow_x = xgrid[i]
                slow_y = ygrid[j]
                slow2[i, j] = np.sqrt(slow_x**2 + slow_y**2)
                if slow2[i, j] < 1e-8:
                    slow2[i, j] = 1e-8
                azimut = 180 * math.atan2(slow_x, slow_y) / math.pi
                baz2[i, j] = azimut % -360 + 180
        baz2[baz2 < 0.0] += 360
        # transform to radian
        baz2 = np.radians(baz2)

        x, y = np.meshgrid(xgrid, ygrid)

        #pow_map_mean = np.array((x, y))
        findind = 0

        stfilt = st.copy()
        stfilt.filter('bandpass', freqmin=freqlow, freqmax=freqhigh)
        stfilt.trim(stime - 5., etime + 5., pad=True, fill_value=0.)

        for i, t1 in enumerate(t):
            filen = glob.glob(outfolder + '/pow_map_%i.npz' % findind)
            f = np.load(filen[0])
            pow_map = f['arr_0']
            fig = plt.figure(figsize=(18, 6))
            ax = fig.add_axes([0.05, 0.05, 0.25, 0.9], polar=True)
            ax.pcolormesh(baz2, slow2, pow_map, vmin=0., vmax=1., cmap=cmap)
            ax.set_theta_direction(-1)
            ax.set_theta_zero_location('N')
            #ax.set_ylim(0, np.sqrt(slm_x**2 + slm_y**2))
            ax.set_ylim(0, np.max([slm_x, slm_y]))

            ix, iy = np.unravel_index(pow_map.argmax(), pow_map.shape)
            az = 180 * math.atan2(xgrid[ix], ygrid[iy]) / math.pi
            bazimut = az % -360 + 180
            if bazimut < 0.0:
                bazimut += 360
            slow1 = np.sqrt(xgrid[ix]**2 + ygrid[iy]**2)
            ax.plot(np.radians(bazimut), slow1, 'xk')
            ax.text(np.radians(bazimut), slow1,
                    '  %1.1f km/s\\n %1.0f deg' % (1. / slow1, bazimut))
            ax.grid()
            plt.draw()

            cax = fig.add_axes([0.32, 0.15, 0.01, 0.7])
            ColorbarBase(cax, cmap=cmap, norm=Normalize(vmin=0.0, vmax=1.))
            ax1 = fig.add_axes([0.37, 0.05, 0.58, 0.9])
            tvec = sigproc.maketvec(stfilt[0])
            #import pdb; pdb.set_trace()
            ax1.plot(tvec,
                     stfilt[0].data / max(stfilt[0].data),
                     'k',
                     label=stfilt[0].stats.station)
            ax1.plot(tvec,
                     stfilt[1].data / max(stfilt[1].data) + 1.5,
                     'k',
                     label=stfilt[1].stats.station)
            ax1.plot(tvec,
                     stfilt[2].data / max(stfilt[2].data) + 3.,
                     'k',
                     label=stfilt[2].stats.station)
            sec = UTCDateTime(mdates.num2date(t1)) - stfilt[0].stats.starttime
            ax1.vlines(sec, -1, 4, color='r')
            ax1.vlines(sec + win_len, -1, 4, color='r')
            plt.title(
                'Max at %3.0f degrees, speed of %1.1f km/s - tstart %1.0f' %
                (baz[i], 1 / slow[i], sec))
            ax1.set_ylim(-1, 4)
            plt.savefig(('%s/img%03d.png') % (outfolder, i))
            findind += int(win_len * st[0].stats.sampling_rate * win_frac)
            #plt.draw()
            plt.show()
            plt.close(fig)

        #turn into mpg
        origdir = os.getcwd()
        os.chdir(outfolder)
        os.system(
            'ffmpeg -f image2 -start_number 0 -r 4 -i img%03d.png -y -c:v libx264 -vf "format=yuv420p" beammovie.mp4'
        )
        # Clean up
        delfiles = glob.glob(outfolder + '/pow_map_*.npz')
        for df in delfiles:
            os.remove(df)
        if savemovieimg is False:
            delfiles = glob.glob(outfolder + '/img*png')
            for df in delfiles:
                os.remove(df)
        os.chdir(origdir)

    return t, rel_power, abs_power, baz, slow
Esempio n. 13
0
    def call(self):
        try:
            from obspy.core import UTCDateTime, stream
            from obspy.signal import array_analysis
            from obspy.imaging.cm import obspy_sequential as cmap
        except ImportError as _import_error:
            self.fail('ImportError:\n%s' % _import_error)

        from matplotlib.colorbar import ColorbarBase
        from matplotlib.colors import Normalize
        import matplotlib.dates as mdates
        self.cleanup()
        viewer = self.get_viewer()

        if viewer.lowpass is None or viewer.highpass is None:
            self.fail('highpass and lowpass in viewer must be set!')

        traces = []
        for trs in self.chopper_selected_traces(fallback=True):
            for tr in trs:
                tr.lowpass(2, viewer.lowpass)
                tr.highpass(2, viewer.highpass)

            traces.extend(trs)

        if not traces:
            self.fail('no traces selected')

        if self.downresample == 'resample':
            dt_want = min([t.deltat for t in traces])
            for t in traces:
                t.resample(dt_want)

        elif self.downresample == 'downsample':
            dt_want = max([t.deltat for t in traces])
            for t in traces:
                t.downsample_to(dt_want)

        elif self.downresample == 'downsample to "target dt"':
            for t in traces:
                t.downsample_to(float(self.target_dt))

        tmin = max([t.tmin for t in traces])
        tmax = min([t.tmax for t in traces])
        try:
            obspy_traces = [
                p2o_trace(tr, viewer.get_station(viewer.station_key(tr)))
                for tr in traces
            ]

        except KeyError:
            self.fail('station information missing')

        st = stream.Stream(traces=obspy_traces)
        center = array_analysis.get_geometry(st, return_center=True)
        center_lon, center_lat, center_ele = center[len(center) - 1]

        # Execute sonic
        kwargs = dict(sll_x=-self.smax,
                      slm_x=self.smax,
                      sll_y=-self.smax,
                      slm_y=self.smax,
                      sl_s=self.smax / self.divisor,
                      win_len=self.window_lenth,
                      win_frac=self.win_frac,
                      frqlow=viewer.highpass,
                      frqhigh=viewer.lowpass,
                      prewhiten=0,
                      semb_thres=-1.0e9,
                      vel_thres=-1.0e9,
                      verbose=True,
                      timestamp='mlabday',
                      stime=UTCDateTime(tmin),
                      etime=UTCDateTime(tmax))

        try:
            out = array_analysis.array_processing(st, **kwargs)
        except AttributeError:
            from obspy.signal.array_analysis import sonic
            out = sonic(st, **kwargs)

        pi = num.pi

        # make output human readable, adjust backazimuth to values between 0
        # and 360
        t, rel_power, abs_power, baz, slow = out.T
        baz[baz < 0.0] += 360.

        # choose number of fractions in plot (desirably 360 degree/N is an
        # integer!)
        N = int(self.numberOfFraction)
        abins = num.arange(N + 1) * 360. / N
        sbins = num.linspace(0., self.smax, N + 1)

        # sum rel power in bins given by abins and sbins
        hist, baz_edges, sl_edges = num.histogram2d(baz,
                                                    slow,
                                                    bins=[abins, sbins],
                                                    weights=rel_power)

        # transform to gradient
        baz_edges = baz_edges / 180. * pi

        fig = self.pylab(get='figure')
        cax = fig.add_axes([0.85, 0.2, 0.05, 0.5])
        ax = fig.add_axes([0.10, 0.1, 0.70, 0.7], polar=True)
        ax.grid(False)

        dh = abs(sl_edges[1] - sl_edges[0])
        dw = abs(baz_edges[1] - baz_edges[0])

        # circle through backazimuth
        for i, row in enumerate(hist):
            ax.bar(left=(pi / 2 - (i + 1) * dw) * num.ones(N),
                   height=dh * num.ones(N),
                   width=dw,
                   bottom=dh * num.arange(N),
                   color=cmap(row / hist.max()))

        ax.set_xticks([pi / 2, 0, 3. / 2 * pi, pi])
        ax.set_xticklabels(['N', 'E', 'S', 'W'])
        ax.set_ylim(0., self.smax)
        ColorbarBase(cax,
                     cmap=cmap,
                     norm=Normalize(vmin=hist.min(), vmax=hist.max()))

        fig2 = self.pylab(get='figure')
        labels = ['rel.power', 'abs.power', 'baz', 'slow']
        xlocator = mdates.AutoDateLocator()
        ax = None
        for i, lab in enumerate(labels):
            ax = fig2.add_subplot(4, 1, i + 1, sharex=ax)
            ax.scatter(out[:, 0],
                       out[:, i + 1],
                       c=out[:, 1],
                       alpha=0.6,
                       edgecolors='none',
                       cmap=cmap)
            ax.set_ylabel(lab)
            ax.set_xlim(out[0, 0], out[-1, 0])
            ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())
            ax.xaxis.set_tick_params(which='both', direction='in')
            ax.xaxis.set_major_locator(xlocator)
            ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(xlocator))
            if i != 3:
                ax.set_xticklabels([])
        fig2.subplots_adjust(hspace=0.)
        fig2.canvas.draw()
        fig.canvas.draw()

        print('Center of Array at latitude %s and longitude %s' %
              (center_lat, center_lon))
Esempio n. 14
0
def doCalc(flag, Config, WaveformDict, FilterMetaData, Gmint, Gmaxt,
           TTTGridMap, Folder, Origin, ntimes, switch, ev, arrayfolder,
           syn_in):
    '''
    method for calculating semblance of one station array
    '''
    Logfile.add('PROCESS %d %s' % (flag, ' Enters Semblance Calculation'))
    Logfile.add('MINT  : %f  MAXT: %f Traveltime' % (Gmint, Gmaxt))

    cfg = ConfigObj(dict=Config)
    cfg_f = FilterCfg(Config)

    timeev = util.str_to_time(ev.time)
    dimX = cfg.dimX()  #('dimx')
    dimY = cfg.dimY()  #('dimy')
    winlen = cfg.winlen()  #('winlen')
    step = cfg.step()  #('step')

    new_frequence = cfg.newFrequency()  #('new_frequence')
    forerun = cfg.Int('forerun')
    duration = cfg.Int('duration')

    nostat = len(WaveformDict)
    traveltimes = {}
    recordstarttime = ''
    minSampleCount = 999999999

    ntimes = int((forerun + duration) / step)
    nsamp = int(winlen * new_frequence)
    nstep = int(step * new_frequence)
    from pyrocko import obspy_compat
    from pyrocko import model
    obspy_compat.plant()

    ############################################################################
    calcStreamMap = WaveformDict

    stations = []
    py_trs = []
    lats = []
    lons = []
    for trace in calcStreamMap.iterkeys():
        py_tr = obspy_compat.to_pyrocko_trace(calcStreamMap[trace])
        py_trs.append(py_tr)
        for il in FilterMetaData:
            if str(il) == str(trace):
                szo = model.Station(lat=float(il.lat),
                                    lon=float(il.lon),
                                    station=il.sta,
                                    network=il.net,
                                    channels=py_tr.channel,
                                    elevation=il.ele,
                                    location=il.loc)
                stations.append(szo)
                lats.append(float(il.lat))
                lons.append(float(il.lon))
    array_center = [num.mean(lats), num.mean(lons)]

    #==================================synthetic BeamForming======================

    if cfg.Bool('synthetic_test') is True:
        store_id = syn_in.store()
        engine = LocalEngine(store_superdirs=[syn_in.store_superdirs()])
        recordstarttimes = []
        for tracex in calcStreamMap.iterkeys():
            recordstarttimes.append(
                calcStreamMap[tracex].stats.starttime.timestamp)
            tr_org = obspy_compat.to_pyrocko_trace(calcStreamMap[tracex])
            tmin = tr_org.tmin

        #tmin= num.min(recordstarttimes)
        targets = []
        sources = []
        for st in stations:
            target = Target(lat=st.lat,
                            lon=st.lon,
                            store_id=store_id,
                            codes=(st.network, st.station, st.location, 'BHZ'),
                            tmin=-6900,
                            tmax=6900,
                            interpolation='multilinear',
                            quantity=cfg.quantity())
            targets.append(target)

        if syn_in.nsources() == 1:
            if syn_in.use_specific_stf() is True:
                stf = syn_in.stf()
                exec(stf)
            else:
                stf = STF()
            if syn_in.source() == 'RectangularSource':
                sources.append(
                    RectangularSource(
                        lat=float(syn_in.lat_0()),
                        lon=float(syn_in.lon_0()),
                        east_shift=float(syn_in.east_shift_0()) * 1000.,
                        north_shift=float(syn_in.north_shift_0()) * 1000.,
                        depth=syn_in.depth_syn_0() * 1000.,
                        strike=syn_in.strike_0(),
                        dip=syn_in.dip_0(),
                        rake=syn_in.rake_0(),
                        width=syn_in.width_0() * 1000.,
                        length=syn_in.length_0() * 1000.,
                        nucleation_x=syn_in.nucleation_x_0(),
                        slip=syn_in.slip_0(),
                        nucleation_y=syn_in.nucleation_y_0(),
                        stf=stf,
                        time=util.str_to_time(syn_in.time_0())))
            if syn_in.source() == 'DCSource':
                sources.append(
                    DCSource(lat=float(syn_in.lat_0()),
                             lon=float(syn_in.lon_0()),
                             east_shift=float(syn_in.east_shift_0()) * 1000.,
                             north_shift=float(syn_in.north_shift_0()) * 1000.,
                             depth=syn_in.depth_syn_0() * 1000.,
                             strike=syn_in.strike_0(),
                             dip=syn_in.dip_0(),
                             rake=syn_in.rake_0(),
                             stf=stf,
                             time=util.str_to_time(syn_in.time_0()),
                             magnitude=syn_in.magnitude_0()))

        else:
            for i in range(syn_in.nsources()):
                if syn_in.use_specific_stf() is True:
                    stf = syn_in.stf()
                    exec(stf)

                else:
                    stf = STF()
                if syn_in.source() == 'RectangularSource':
                    sources.append(
                        RectangularSource(
                            lat=float(syn_in.lat_1(i)),
                            lon=float(syn_in.lon_1(i)),
                            east_shift=float(syn_in.east_shift_1(i)) * 1000.,
                            north_shift=float(syn_in.north_shift_1(i)) * 1000.,
                            depth=syn_in.depth_syn_1(i) * 1000.,
                            strike=syn_in.strike_1(i),
                            dip=syn_in.dip_1(i),
                            rake=syn_in.rake_1(i),
                            width=syn_in.width_1(i) * 1000.,
                            length=syn_in.length_1(i) * 1000.,
                            nucleation_x=syn_in.nucleation_x_1(i),
                            slip=syn_in.slip_1(i),
                            nucleation_y=syn_in.nucleation_y_1(i),
                            stf=stf,
                            time=util.str_to_time(syn_in.time_1(i))))

                if syn_in.source() == 'DCSource':
                    sources.append(
                        DCSource(
                            lat=float(syn_in.lat_1(i)),
                            lon=float(syn_in.lon_1(i)),
                            east_shift=float(syn_in.east_shift_1(i)) * 1000.,
                            north_shift=float(syn_in.north_shift_1(i)) * 1000.,
                            depth=syn_in.depth_syn_1(i) * 1000.,
                            strike=syn_in.strike_1(i),
                            dip=syn_in.dip_1(i),
                            rake=syn_in.rake_1(i),
                            stf=stf,
                            time=util.str_to_time(syn_in.time_1(i)),
                            magnitude=syn_in.magnitude_1(i)))
            #source = CombiSource(subsources=sources)
        synthetic_traces = []
        for source in sources:
            response = engine.process(source, targets)
            synthetic_traces_source = response.pyrocko_traces()
            if not synthetic_traces:
                synthetic_traces = synthetic_traces_source
            else:
                for trsource, tr in zip(synthetic_traces_source,
                                        synthetic_traces):
                    tr.add(trsource)
            from pyrocko import trace as trld
            #trld.snuffle(synthetic_traces)
        timeev = util.str_to_time(syn_in.time_0())
        if cfg.Bool('synthetic_test_add_noise') is True:
            from noise_addition import add_noise
            trs_orgs = []
            calcStreamMapsyn = calcStreamMap.copy()
            #from pyrocko import trace
            for tracex in calcStreamMapsyn.iterkeys():
                for trl in synthetic_traces:
                    if str(trl.name()[4:12]) == str(tracex[4:]) or str(
                            trl.name()[3:13]) == str(tracex[3:]) or str(
                                trl.name()[3:11]) == str(tracex[3:]) or str(
                                    trl.name()[3:14]) == str(tracex[3:]):
                        tr_org = obspy_compat.to_pyrocko_trace(
                            calcStreamMapsyn[tracex])
                        tr_org.downsample_to(2.0)
                        trs_orgs.append(tr_org)
            store_id = syn_in.store()
            engine = LocalEngine(store_superdirs=[syn_in.store_superdirs()])
            synthetic_traces = add_noise(trs_orgs,
                                         engine,
                                         source.pyrocko_event(),
                                         stations,
                                         store_id,
                                         phase_def='P')
        trs_org = []
        trs_orgs = []
        from pyrocko import trace
        fobj = os.path.join(arrayfolder, 'shift.dat')
        calcStreamMapsyn = calcStreamMap.copy()
        for tracex in calcStreamMapsyn.iterkeys():
            for trl in synthetic_traces:
                if str(trl.name()[4:12]) == str(tracex[4:]) or str(
                        trl.name()[3:13]) == str(tracex[3:]) or str(
                            trl.name()[3:11]) == str(tracex[3:]) or str(
                                trl.name()[3:14]) == str(tracex[3:]):
                    mod = trl
                    recordstarttime = calcStreamMapsyn[
                        tracex].stats.starttime.timestamp
                    recordendtime = calcStreamMapsyn[
                        tracex].stats.endtime.timestamp
                    tr_org = obspy_compat.to_pyrocko_trace(
                        calcStreamMapsyn[tracex])
                    if switch == 0:
                        tr_org.bandpass(4, cfg_f.flo(), cfg_f.fhi())
                    elif switch == 1:
                        tr_org.bandpass(4, cfg_f.flo2(), cfg_f.fhi2())
                    trs_orgs.append(tr_org)
                    tr_org_add = mod.chop(recordstarttime,
                                          recordendtime,
                                          inplace=False)
                    synthetic_obs_tr = obspy_compat.to_obspy_trace(tr_org_add)
                    calcStreamMapsyn[tracex] = synthetic_obs_tr
                    trs_org.append(tr_org_add)
        calcStreamMap = calcStreamMapsyn

    if cfg.Bool('shift_by_phase_pws') == True:
        calcStreamMapshifted = calcStreamMap.copy()
        from obspy.core import stream
        stream = stream.Stream()
        for trace in calcStreamMapshifted.iterkeys():
            stream.append(calcStreamMapshifted[trace])
        pws_stack = PWS_stack([stream], weight=2, normalize=True)
        for tr in pws_stack:
            for trace in calcStreamMapshifted.iterkeys():
                calcStreamMapshifted[trace] = tr
        calcStreamMap = calcStreamMapshifted

    if cfg.Bool('shift_by_phase_cc') is True:
        from stacking import align_traces
        calcStreamMapshifted = calcStreamMap.copy()
        list_tr = []
        for trace in calcStreamMapshifted.iterkeys():
            tr_org = calcStreamMapshifted[trace]
            list_tr.append(tr_org)
        shifts, ccs = align_traces(list_tr, 10, master=False)
        for shift in shifts:
            for trace in calcStreamMapshifted.iterkeys():
                tr_org = obspy_compat.to_pyrocko_trace(
                    calcStreamMapshifted[trace])
                tr_org.shift(shift)
                shifted = obspy_compat.to_obspy_trace(tr_org)
                calcStreamMapshifted[trace] = shifted
        calcStreamMap = calcStreamMapshifted

    if cfg.Bool('shift_by_phase_onset') is True:
        pjoin = os.path.join
        timeev = util.str_to_time(ev.time)
        trs_orgs = []
        calcStreamMapshifted = calcStreamMap.copy()
        for trace in calcStreamMapshifted.iterkeys():
            tr_org = obspy_compat.to_pyrocko_trace(calcStreamMapshifted[trace])
            trs_orgs.append(tr_org)

        timing = CakeTiming(
            phase_selection='first(p|P|PP|P(cmb)P(icb)P(icb)p(cmb)p)-20',
            fallback_time=100.)
        traces = trs_orgs

        event = model.Event(lat=float(ev.lat),
                            lon=float(ev.lon),
                            depth=ev.depth * 1000.,
                            time=timeev)
        directory = arrayfolder
        bf = BeamForming(stations, traces, normalize=True)
        shifted_traces = bf.process(event=event,
                                    timing=timing,
                                    fn_dump_center=pjoin(
                                        directory, 'array_center.pf'),
                                    fn_beam=pjoin(directory, 'beam.mseed'))
        i = 0
        store_id = syn_in.store()
        engine = LocalEngine(store_superdirs=[syn_in.store_superdirs()])
        for tracex in calcStreamMapshifted.iterkeys():
            for trl in shifted_traces:
                if str(trl.name()[4:12]) == str(tracex[4:]) or str(
                        trl.name()[3:13]) == str(tracex[3:]) or str(
                            trl.name()[3:11]) == str(tracex[3:]) or str(
                                trl.name()[3:14]) == str(tracex[3:]):
                    mod = trl
                    recordstarttime = calcStreamMapshifted[
                        tracex].stats.starttime.timestamp
                    recordendtime = calcStreamMapshifted[
                        tracex].stats.endtime.timestamp
                    tr_org = obspy_compat.to_pyrocko_trace(
                        calcStreamMapshifted[tracex])
                    tr_org_add = mod.chop(recordstarttime,
                                          recordendtime,
                                          inplace=False)
                    shifted_obs_tr = obspy_compat.to_obspy_trace(tr_org_add)
                    calcStreamMapshifted[tracex] = shifted_obs_tr
        calcStreamMap = calcStreamMapshifted

    weight = 1.
    if cfg.Bool('weight_by_noise') is True:
        from noise_analyser import analyse
        pjoin = os.path.join
        timeev = util.str_to_time(ev.time)
        trs_orgs = []
        calcStreamMapshifted = calcStreamMap.copy()
        for trace in calcStreamMapshifted.iterkeys():
            tr_org = obspy_compat.to_pyrocko_trace(calcStreamMapshifted[trace])
            trs_orgs.append(tr_org)

        timing = CakeTiming(
            phase_selection='first(p|P|PP|P(cmb)P(icb)P(icb)p(cmb)p)-20',
            fallback_time=100.)
        traces = trs_orgs
        event = model.Event(lat=float(ev.lat),
                            lon=float(ev.lon),
                            depth=ev.depth * 1000.,
                            time=timeev)
        directory = arrayfolder
        bf = BeamForming(stations, traces, normalize=True)
        shifted_traces = bf.process(event=event,
                                    timing=timing,
                                    fn_dump_center=pjoin(
                                        directory, 'array_center.pf'),
                                    fn_beam=pjoin(directory, 'beam.mseed'))
        i = 0
        store_id = syn_in.store()
        engine = LocalEngine(store_superdirs=[syn_in.store_superdirs()])
        weight = analyse(shifted_traces,
                         engine,
                         event,
                         stations,
                         100.,
                         store_id,
                         nwindows=1,
                         check_events=True,
                         phase_def='P')

    if cfg.Bool('array_response') is True:
        from obspy.signal import array_analysis
        from obspy.core import stream
        ntimesr = int((forerun + duration) / step)
        nsampr = int(winlen)
        nstepr = int(step)
        sll_x = -3.0
        slm_x = 3.0
        sll_y = -3.0
        slm_y = 3.0
        sl_s = 0.03,
        # sliding window properties

        # frequency properties
        frqlow = 1.0,
        frqhigh = 8.0
        prewhiten = 0
        # restrict output
        semb_thres = -1e9
        vel_thres = -1e9
        stime = stime
        etime = etime
        stream_arr = stream.Stream()
        for trace in calcStreamMapshifted.iterkeys():
            stream_arr.append(calcStreamMapshifted[trace])
        results = array_analysis.array_processing(stream_arr, nsamp, nstep,\
                                                  sll_x, slm_x, sll_y, slm_y,\
                                                   sl_s, semb_thres, vel_thres, \
                                                   frqlow, frqhigh, stime, \
                                                   etime, prewhiten)
        timestemp = results[0]
        relative_relpow = results[1]
        absolute_relpow = results[2]

    for trace in calcStreamMap.iterkeys():
        recordstarttime = calcStreamMap[trace].stats.starttime
        d = calcStreamMap[trace].stats.starttime
        d = d.timestamp

        if calcStreamMap[trace].stats.npts < minSampleCount:
            minSampleCount = calcStreamMap[trace].stats.npts

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

    traces = num.ndarray(shape=(len(calcStreamMap), minSampleCount),
                         dtype=float)
    traveltime = num.ndarray(shape=(len(calcStreamMap), dimX * dimY),
                             dtype=float)

    latv = num.ndarray(dimX * dimY, dtype=float)
    lonv = num.ndarray(dimX * dimY, dtype=float)
    ###########################################################################

    c = 0
    streamCounter = 0

    for key in calcStreamMap.iterkeys():
        streamID = key
        c2 = 0

        for o in calcStreamMap[key]:
            if c2 < minSampleCount:
                traces[c][c2] = o

                c2 += 1

        for key in TTTGridMap.iterkeys():

            if streamID == key:
                traveltimes[streamCounter] = TTTGridMap[key]
            else:
                "NEIN", streamID, key

        if not streamCounter in traveltimes:
            continue  #hs : thread crashed before

        g = traveltimes[streamCounter]
        dimZ = g.dimZ
        mint = g.mint
        gridElem = g.GridArray

        for x in range(dimX):
            for y in range(dimY):
                elem = gridElem[x, y]

                traveltime[c][x * dimY + y] = elem.tt
                latv[x * dimY + y] = elem.lat
                lonv[x * dimY + y] = elem.lon
        #endfor

        c += 1
        streamCounter += 1

    #endfor

    ################ CALCULATE PARAMETER FOR SEMBLANCE CALCULATION ########
    nsamp = winlen * new_frequence

    nstep = step * new_frequence
    migpoints = dimX * dimY

    dimZ = 0
    maxp = int(Config['ncore'])

    Logfile.add('PROCESS %d  NTIMES: %d' % (flag, ntimes))

    if False:
        print('nostat ', nostat, type(nostat))
        print('nsamp ', nsamp, type(nsamp))
        print('ntimes ', ntimes, type(ntimes))
        print('nstep ', nstep, type(nstep))
        print('dimX ', dimX, type(dimX))
        print('dimY ', dimY, type(dimY))
        print('mint ', Gmint, type(mint))
        print('new_freq ', new_frequence, type(new_frequence))
        print('minSampleCount ', minSampleCount, type(minSampleCount))
        print('latv ', latv, type(latv))
        print('traces', traces, type(traces))

#===================compressed sensing=================================
    try:
        cs = cfg.cs()
    except:
        cs = 0
    if cs == 1:
        csmaxvaluev = num.ndarray(ntimes, dtype=float)
        csmaxlatv = num.ndarray(ntimes, dtype=float)
        csmaxlonv = num.ndarray(ntimes, dtype=float)
        folder = Folder['semb']
        fobjcsmax = open(os.path.join(folder, 'csmax_%s.txt' % (switch)), 'w')
        traveltimes = traveltime.reshape(1, nostat * dimX * dimY)
        traveltime2 = toMatrix(traveltimes, dimX * dimY)  # for relstart
        traveltime = traveltime.reshape(dimX * dimY, nostat)
        import matplotlib as mpl
        import scipy.optimize as spopt
        import scipy.fftpack as spfft
        import scipy.ndimage as spimg
        import cvxpy as cvx
        import matplotlib.pyplot as plt
        A = spfft.idct(traveltime, norm='ortho', axis=0)
        n = (nostat * dimX * dimY)
        vx = cvx.Variable(dimX * dimY)
        res = cvx.Variable(1)
        objective = cvx.Minimize(cvx.norm(res, 1))
        back2 = num.zeros([dimX, dimY])
        l = int(nsamp)
        fobj = open(
            os.path.join(folder,
                         '%s-%s_%03d.cs' % (switch, Origin['depth'], l)), 'w')
        for i in range(ntimes):
            ydata = []
            try:
                for tr in traces:
                    relstart = int((dimX * dimY - mint) * new_frequence +
                                   0.5) + i * nstep
                    tr = spfft.idct(tr[relstart + i:relstart + i +
                                       dimX * dimY],
                                    norm='ortho',
                                    axis=0)

                    ydata.append(tr)
                    ydata = num.asarray(ydata)
                    ydata = ydata.reshape(dimX * dimY, nostat)

                    constraints = [
                        res == cvx.sum_entries(0 + num.sum([
                            ydata[:, x] - A[:, x] * vx for x in range(nostat)
                        ]))
                    ]

                    prob = cvx.Problem(objective, constraints)
                    result = prob.solve(verbose=False, max_iters=200)

                    x = num.array(vx.value)
                    x = num.squeeze(x)
                    back1 = x.reshape(dimX, dimY)
                    sig = spfft.idct(x, norm='ortho', axis=0)
                    back2 = back2 + back1
                    xs = num.array(res.value)
                    xs = num.squeeze(xs)
                    max_cs = num.max(back1)
                    idx = num.where(back1 == back1.max())
                    csmaxvaluev[i] = max_cs
                    csmaxlatv[i] = latv[idx[0]]
                    csmaxlonv[i] = lonv[idx[1]]
                    fobj.write('%.5f %.5f %.20f\n' %
                               (latv[idx[0]], lonv[idx[1]], max_cs))
                    fobjcsmax.write('%.5f %.5f %.20f\n' %
                                    (latv[idx[0]], lonv[idx[1]], max_cs))
                fobj.close()
                fobjcsmax.close()

            except:
                pass

#==================================semblance calculation========================================

    t1 = time.time()
    traces = traces.reshape(1, nostat * minSampleCount)

    traveltimes = traveltime.reshape(1, nostat * dimX * dimY)
    USE_C_CODE = False
    #try:
    if USE_C_CODE:
        import Cm
        import CTrig
        start_time = time.time()
        k = Cm.otest(maxp, nostat, nsamp, ntimes, nstep, dimX, dimY, Gmint,
                     new_frequence, minSampleCount, latv, lonv, traveltimes,
                     traces)
        print("--- %s seconds ---" % (time.time() - start_time))
    else:
        start_time = time.time()
        ntimes = int((forerun + duration) / step)
        nsamp = int(winlen)
        nstep = int(step)
        Gmint = cfg.Int('forerun')
        k = otest(maxp, nostat, nsamp, ntimes, nstep, dimX, dimY, Gmint,
                  new_frequence, minSampleCount, latv, lonv, traveltimes,
                  traces, calcStreamMap, timeev)
        print("--- %s seconds ---" % (time.time() - start_time))
    #except ValueError:
    #        k  = Cm.otest(maxp,nostat,nsamp,ntimes,nstep,dimX,dimY,Gmint,new_frequence,
    #                      minSampleCount,latv,lonv,traveltimes,traces)
    #    print "loaded tttgrid has probably wrong dimensions or stations,\
    #                delete ttgrid or exchange is recommended"

    t2 = time.time()

    Logfile.add('%s took %0.3f s' % ('CALC:', (t2 - t1)))

    partSemb = k
    partSemb = partSemb.reshape(ntimes, migpoints)

    return partSemb, weight, array_center
    def call(self):
        try:
            from obspy.core import UTCDateTime, stream
            from obspy.signal import array_analysis
            from obspy.imaging.cm import obspy_sequential as cmap
        except ImportError as _import_error:
            self.fail('ImportError:\n%s' % _import_error)

        from matplotlib.colorbar import ColorbarBase
        from matplotlib.colors import Normalize
        import matplotlib.dates as mdates
        self.cleanup()
        viewer = self.get_viewer()

        if viewer.lowpass is None or viewer.highpass is None:
            self.fail('highpass and lowpass in viewer must be set!')

        traces = []
        for trs in self.chopper_selected_traces(fallback=True):
            for tr in trs:
                tr.lowpass(2, viewer.lowpass)
                tr.highpass(2, viewer.highpass)

            traces.extend(trs)

        if not traces:
            self.fail('no traces selected')

        if self.downresample == 'resample':
            dt_want = min([t.deltat for t in traces])
            for t in traces:
                t.resample(dt_want)

        elif self.downresample == 'downsample':
            dt_want = max([t.deltat for t in traces])
            for t in traces:
                t.downsample_to(dt_want)

        elif self.downresample == 'downsample to "target dt"':
            for t in traces:
                t.downsample_to(float(self.target_dt))

        tmin = max([t.tmin for t in traces])
        tmax = min([t.tmax for t in traces])
        try:
            obspy_traces = [p2o_trace(
                tr, viewer.get_station(viewer.station_key(tr)))
                            for tr in traces]

        except KeyError:
            self.fail('station information missing')

        st = stream.Stream(traces=obspy_traces)
        center = array_analysis.get_geometry(st, return_center=True)
        center_lon, center_lat, center_ele = center[len(center)-1]

        # Execute sonic
        kwargs = dict(
            sll_x=-self.smax, slm_x=self.smax, sll_y=-self.smax,
            slm_y=self.smax, sl_s=self.smax/self.divisor,
            win_len=self.window_lenth, win_frac=self.win_frac,
            frqlow=viewer.highpass, frqhigh=viewer.lowpass, prewhiten=0,
            semb_thres=-1.0e9, vel_thres=-1.0e9, verbose=True,
            timestamp='mlabday', stime=UTCDateTime(tmin),
            etime=UTCDateTime(tmax)
        )

        try:
            out = array_analysis.array_processing(st, **kwargs)
        except AttributeError:
            from obspy.signal.array_analysis import sonic
            out = sonic(st, **kwargs)

        pi = num.pi

        # make output human readable, adjust backazimuth to values between 0
        # and 360
        t, rel_power, abs_power, baz, slow = out.T
        baz[baz < 0.0] += 360.

        # choose number of fractions in plot (desirably 360 degree/N is an
        # integer!)
        N = int(self.numberOfFraction)
        abins = num.arange(N + 1) * 360. / N
        sbins = num.linspace(0., self.smax, N + 1)

        # sum rel power in bins given by abins and sbins
        hist, baz_edges, sl_edges = num.histogram2d(
            baz, slow, bins=[abins, sbins], weights=rel_power)

        # transform to gradient
        baz_edges = baz_edges / 180. * pi

        fig = self.pylab(get='figure')
        cax = fig.add_axes([0.85, 0.2, 0.05, 0.5])
        ax = fig.add_axes([0.10, 0.1, 0.70, 0.7], polar=True)
        ax.grid(False)

        dh = abs(sl_edges[1] - sl_edges[0])
        dw = abs(baz_edges[1] - baz_edges[0])

        # circle through backazimuth
        for i, row in enumerate(hist):
            ax.bar(left=(pi / 2 - (i + 1) * dw) * num.ones(N),
                   height=dh * num.ones(N), width=dw,
                   bottom=dh * num.arange(N), color=cmap(row / hist.max()))

        ax.set_xticks([pi / 2, 0, 3. / 2 * pi, pi])
        ax.set_xticklabels(['N', 'E', 'S', 'W'])
        ax.set_ylim(0., self.smax)
        ColorbarBase(cax, cmap=cmap,
                     norm=Normalize(vmin=hist.min(), vmax=hist.max()))

        fig2 = self.pylab(get='figure')
        labels = ['rel.power', 'abs.power', 'baz', 'slow']
        xlocator = mdates.AutoDateLocator()
        ax = None
        for i, lab in enumerate(labels):
            ax = fig2.add_subplot(4, 1, i + 1, sharex=ax)
            ax.scatter(out[:, 0], out[:, i + 1], c=out[:, 1], alpha=0.6,
                       edgecolors='none', cmap=cmap)
            ax.set_ylabel(lab)
            ax.set_xlim(out[0, 0], out[-1, 0])
            ax.set_ylim(out[:, i + 1].min(), out[:, i + 1].max())
            ax.xaxis.set_tick_params(which='both', direction='in')
            ax.xaxis.set_major_locator(xlocator)
            ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(xlocator))
            if i != 3:
                ax.set_xticklabels([])
        fig2.subplots_adjust(hspace=0.)
        fig2.canvas.draw()
        fig.canvas.draw()

        print('Center of Array at latitude %s and longitude %s' %
              (center_lat, center_lon))
Esempio n. 16
0
    def call(self):
        self.cleanup()
        viewer = self.get_viewer()

        if viewer.lowpass is None or viewer.highpass is None:
            self.fail('highpass and lowpass in viewer must be set!')

        traces = []
        for trs in self.chopper_selected_traces(fallback=True):
            for tr in trs:
                tr.downsample_to(1/20.)
                tr.lowpass(4, viewer.lowpass)
                tr.highpass(4, viewer.highpass)

            traces.extend(trs)

        if not traces:
            self.fail('no traces selected')

        tmin, tmax = trace.minmaxtime(traces, key=lambda x: None)[None]

        try:
            obspy_traces = [ p2o_trace(tr, viewer.get_station(viewer.station_key(tr)) ) for tr in traces ]
        except KeyError:
            self.fail('station information missing')

        st = stream.Stream(traces=obspy_traces)

        smax = 0.5

        # Execute sonic
        kwargs = dict(
            # slowness grid: X min, X max, Y min, Y max, Slow Step
            sll_x=-smax, slm_x=smax, sll_y=-smax, slm_y=smax, sl_s=smax/20.,
            # sliding window properties
            win_len=5.0, win_frac=0.1,
            # frequency properties
            frqlow=viewer.highpass, frqhigh=viewer.lowpass, prewhiten=0,
            # restrict output
            semb_thres=-1.0e9, vel_thres=-1.0e9, verbose=True, timestamp='mlabday',
            stime=UTCDateTime(tmin), etime=UTCDateTime(tmax)
        )
        #out = sonic(st, **kwargs)
        out = array_analysis.array_processing(st, **kwargs)

        cmap = cm.hot_r
        pi = np.pi

        #
        # make output human readable, adjust backazimuth to values between 0 and 360
        t, rel_power, abs_power, baz, slow = out.T
        baz[baz < 0.0] += 360.

        # choose number of fractions in plot (desirably 360 degree/N is an integer!)
        N = int(self.numberOfFraction)
        abins = np.arange(N + 1) * 360. / N
        sbins = np.linspace(0., smax, N + 1)

        # sum rel power in bins given by abins and sbins
        hist, baz_edges, sl_edges = np.histogram2d(baz, slow,
                bins=[abins, sbins], weights=rel_power)

        # transform to gradient
        baz_edges = baz_edges / 180 * np.pi

        # add polar and colorbar axes
        fig = self.pylab(get='figure')
        cax = fig.add_axes([0.85, 0.2, 0.05, 0.5])
        ax = fig.add_axes([0.10, 0.1, 0.70, 0.7], polar=True)

        dh = abs(sl_edges[1] - sl_edges[0])
        dw = abs(baz_edges[1] - baz_edges[0])

        # circle through backazimuth
        for i, row in enumerate(hist):
            bars = ax.bar(left=(pi / 2 - (i + 1) * dw) * np.ones(N),
                          height=dh * np.ones(N),
                          width=dw, bottom=dh * np.arange(N),
                          color=cmap(row / hist.max()))
                            

        ax.set_xticks([pi / 2, 0, 3. / 2 * pi, pi])
        ax.set_xticklabels(['N', 'E', 'S', 'W'])

        # set slowness limits
        ax.set_ylim(0., smax)
        ColorbarBase(cax, cmap=cmap,
                     norm=Normalize(vmin=hist.min(), vmax=hist.max()))