Beispiel #1
0
# Execute sonic
arguments = 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 propertieds
        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, verbose=True, timestamp='mlabhour',
        stime=UTCDateTime("20080217110515"),
    etime=UTCDateTime("20080217110545")
)
# Perform beamforming with previously set arguments.
out = sonic(stream, **arguments)

#import matplotlib.pyplot as plt
#
#labels = 'rel.power abs.power baz slow'.split()
#
#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')
#        ax.set_ylabel(lab)
#        ax.xaxis_date()
#
#fig.autofmt_xdate()
#fig.subplots_adjust(top=0.95, right=0.95, bottom=0.2, hspace=0)
Beispiel #2
0
    # sliding window propertieds
    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,
    verbose=True,
    timestamp='mlabhour',
    stime=UTCDateTime("20080217110515"),
    etime=UTCDateTime("20080217110545"))
# Perform beamforming with previously set arguments.
out = sonic(stream, **arguments)

#import matplotlib.pyplot as plt
#
#labels = 'rel.power abs.power baz slow'.split()
#
#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')
#        ax.set_ylabel(lab)
#        ax.xaxis_date()
#
#fig.autofmt_xdate()
#fig.subplots_adjust(top=0.95, right=0.95, bottom=0.2, hspace=0)
paz1hz = cornFreq2Paz(1.0, damp=0.707)
st.simulate(paz_remove='self', paz_simulate=paz1hz)

# Execute sonic
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, verbose=True, timestamp='mlabday',
    stime=UTCDateTime("20080217110515"), etime=UTCDateTime("20080217110545")
)
out = sonic(st, **kwargs)

# Plot
from matplotlib.colorbar import ColorbarBase
from matplotlib.colors import Normalize
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np

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
Beispiel #4
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))
    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,
    verbose=True,
    timestamp='mlabday',
    stime=UTCDateTime("20080217110515"),
    etime=UTCDateTime("20080217110545"))
out = sonic(st, **kwargs)

# Plot
from matplotlib.colorbar import ColorbarBase
from matplotlib.colors import Normalize
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np

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
    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))
Beispiel #7
0
    # sliding window propertieds
    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,
    verbose=True,
    timestamp='mlabhour',
    stime=UTCDateTime("20080217110515"),
    etime=UTCDateTime("20080217110545"))
# Perform beamforming with previously set arguments.
out = sonic(stream, **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/N is an integer!)
N = 30
abins = np.arange(N + 1) * 360. / N
sbins = np.linspace(0, 3, N + 1)

# sum rel power in bins given by abins and sbins
Beispiel #8
0
    def test_sonic(self):
#        for i in xrange(100):
        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
        prewhiten = 0

        semb_thres = -1e99
        vel_thres = -1e99

        # out returns: rel. power, abs. power, backazimuth, slowness
        out = sonic(st, win_len, step_frac, sll_x, slm_x, sll_y, slm_y, sl_s,
                    semb_thres, vel_thres, frqlow, frqhigh, stime, etime,
                    prewhiten, coordsys='xy', verbose=False)

        # returns baz
        np.testing.assert_almost_equal(out[:, 3].mean(), 18.434948822922024)
        # slowness ~= 1.3
        np.testing.assert_almost_equal(out[:, 4].mean(), 1.26491106407)
Beispiel #9
0
# Execute sonic
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 propertieds
        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, verbose=True, timestamp='mlabhour',
        stime=UTCDateTime("20080217110515"),
    etime=UTCDateTime("20080217110545")
)
# Perform beamforming with previously set arguments.
out = sonic(stream, **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/N is an integer!) 
N = 30
abins = np.arange(N+1)*360./N 
sbins = np.linspace(0, 3, N+1)

# sum rel power in bins given by abins and sbins
Beispiel #10
0
    def test_sonic(self):
        #        for i in xrange(100):
        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.0
        df = 100  # samplerate
        # SNR = 100.         # signal to noise ratio
        amp = 0.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.0)
            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.0
        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
        prewhiten = 0

        semb_thres = -1e99
        vel_thres = -1e99

        # out returns: rel. power, abs. power, backazimuth, slowness
        out = sonic(
            st,
            win_len,
            step_frac,
            sll_x,
            slm_x,
            sll_y,
            slm_y,
            sl_s,
            semb_thres,
            vel_thres,
            frqlow,
            frqhigh,
            stime,
            etime,
            prewhiten,
            coordsys="xy",
            verbose=False,
        )

        # returns baz
        np.testing.assert_almost_equal(out[:, 3].mean(), 18.434948822922024)
        # slowness ~= 1.3
        np.testing.assert_almost_equal(out[:, 4].mean(), 1.26491106407)