Example #1
0
    def _off_test_synthetic(self):

        from pyrocko import gf

        km = 1000.
        nstations = 10
        edepth = 5 * km
        store_id = 'crust2_d0'

        swin = 2.
        lwin = 9. * swin
        ks = 1.0
        kl = 1.0
        kd = 3.0

        engine = gf.get_engine()
        snorths = (num.random.random(nstations) - 1.0) * 50 * km
        seasts = (num.random.random(nstations) - 1.0) * 50 * km
        targets = []
        for istation, (snorths, seasts) in enumerate(zip(snorths, seasts)):
            targets.append(
                gf.Target(quantity='displacement',
                          codes=('', 's%03i' % istation, '', 'Z'),
                          north_shift=float(snorths),
                          east_shift=float(seasts),
                          store_id=store_id,
                          interpolation='multilinear'))

        source = gf.DCSource(north_shift=50 * km,
                             east_shift=50 * km,
                             depth=edepth)

        store = engine.get_store(store_id)

        response = engine.process(source, targets)
        trs = []

        station_traces = defaultdict(list)
        station_targets = defaultdict(list)
        for source, target, tr in response.iter_results():
            tp = store.t('any_P', source, target)
            t = tp - 5 * tr.deltat + num.arange(11) * tr.deltat
            if False:
                gauss = trace.Trace(tmin=t[0],
                                    deltat=tr.deltat,
                                    ydata=num.exp(-((t - tp)**2) /
                                                  ((2 * tr.deltat)**2)))

                tr.ydata[:] = 0.0
                tr.add(gauss)

            trs.append(tr)
            station_traces[target.codes[:3]].append(tr)
            station_targets[target.codes[:3]].append(target)

        station_stalta_traces = {}
        for nsl, traces in station_traces.items():
            etr = None
            for tr in traces:
                sqr_tr = tr.copy(data=False)
                sqr_tr.ydata = tr.ydata**2
                if etr is None:
                    etr = sqr_tr
                else:
                    etr += sqr_tr

            autopick.recursive_stalta(swin, lwin, ks, kl, kd, etr)
            etr.set_codes(channel='C')

            station_stalta_traces[nsl] = etr

        trace.snuffle(trs + list(station_stalta_traces.values()))
        deltat = trs[0].deltat

        nnorth = 50
        neast = 50

        size = 200 * km

        north = num.linspace(-size, size, nnorth)
        north2 = num.repeat(north, neast)
        east = num.linspace(-size, size, neast)
        east2 = num.tile(east, nnorth)
        depth = 5 * km

        def tcal(target, i):
            try:
                return store.t(
                    'any_P',
                    gf.Location(north_shift=north2[i],
                                east_shift=east2[i],
                                depth=depth), target)

            except gf.OutOfBounds:
                return 0.0

        nsls = sorted(station_stalta_traces.keys())

        tts = num.fromiter((tcal(station_targets[nsl][0], i)
                            for i in range(nnorth * neast) for nsl in nsls),
                           dtype=num.float)

        arrays = [
            station_stalta_traces[nsl].ydata.astype(num.float) for nsl in nsls
        ]
        offsets = num.array([
            int(round(station_stalta_traces[nsl].tmin / deltat))
            for nsl in nsls
        ],
                            dtype=num.int32)
        shifts = -num.array([int(round(tt / deltat)) for tt in tts],
                            dtype=num.int32).reshape(nnorth * neast, nstations)
        weights = num.ones((nnorth * neast, nstations))

        print(shifts[25 * neast + 25] * deltat)

        print(offsets.dtype, shifts.dtype, weights.dtype)

        print('stack start')
        mat, ioff = parstack(arrays, offsets, shifts, weights, 1)
        print('stack stop')

        mat = num.reshape(mat, (nnorth, neast))

        from matplotlib import pyplot as plt

        fig = plt.figure()

        axes = fig.add_subplot(1, 1, 1, aspect=1.0)

        axes.contourf(east / km, north / km, mat)

        axes.plot(
            g(targets, 'east_shift') / km,
            g(targets, 'north_shift') / km, '^')
        axes.plot(source.east_shift / km, source.north_shift / km, 'o')
        plt.show()
Example #2
0
    def off_test_synthetic(self):

        from pyrocko import gf

        km = 1000.
        nstations = 10
        edepth = 5*km
        store_id = 'crust2_d0'

        swin = 2.
        lwin = 9.*swin
        ks = 1.0
        kl = 1.0
        kd = 3.0

        engine = gf.get_engine()
        snorths = (num.random.random(nstations)-1.0) * 50*km
        seasts = (num.random.random(nstations)-1.0) * 50*km
        targets = []
        for istation, (snorths, seasts) in enumerate(zip(snorths, seasts)):
            targets.append(
                gf.Target(
                    quantity='displacement',
                    codes=('', 's%03i' % istation, '', 'Z'),
                    north_shift=float(snorths),
                    east_shift=float(seasts),
                    store_id=store_id,
                    interpolation='multilinear'))

        source = gf.DCSource(
            north_shift=50*km,
            east_shift=50*km,
            depth=edepth)

        store = engine.get_store(store_id)

        response = engine.process(source, targets)
        trs = []

        station_traces = defaultdict(list)
        station_targets = defaultdict(list)
        for source, target, tr in response.iter_results():
            tp = store.t('any_P', source, target)
            t = tp - 5 * tr.deltat + num.arange(11) * tr.deltat
            if False:
                gauss = trace.Trace(
                    tmin=t[0],
                    deltat=tr.deltat,
                    ydata=num.exp(-((t-tp)**2)/((2*tr.deltat)**2)))

                tr.ydata[:] = 0.0
                tr.add(gauss)

            trs.append(tr)
            station_traces[target.codes[:3]].append(tr)
            station_targets[target.codes[:3]].append(target)

        station_stalta_traces = {}
        for nsl, traces in station_traces.iteritems():
            etr = None
            for tr in traces:
                sqr_tr = tr.copy(data=False)
                sqr_tr.ydata = tr.ydata**2
                if etr is None:
                    etr = sqr_tr
                else:
                    etr += sqr_tr

            autopick.recursive_stalta(swin, lwin, ks, kl, kd, etr)
            etr.set_codes(channel='C')

            station_stalta_traces[nsl] = etr

        trace.snuffle(trs + station_stalta_traces.values())
        deltat = trs[0].deltat

        nnorth = 50
        neast = 50

        size = 400*km

        north = num.linspace(-size/2., size/2., nnorth)
        north2 = num.repeat(north, neast)
        east = num.linspace(-size/2., size/2., neast)
        east2 = num.tile(east, nnorth)
        depth = 5*km

        def tcal(target, i):
            try:
                return store.t(
                    'any_P',
                    gf.Location(
                        north_shift=north2[i],
                        east_shift=east2[i],
                        depth=depth),
                    target)

            except gf.OutOfBounds:
                return 0.0

        nsls = sorted(station_stalta_traces.keys())

        tts = num.fromiter((tcal(station_targets[nsl][0], i)
                           for i in xrange(nnorth*neast)
                           for nsl in nsls), dtype=num.float)

        arrays = [
            station_stalta_traces[nsl].ydata.astype(num.float) for nsl in nsls]
        offsets = num.array(
            [int(round(station_stalta_traces[nsl].tmin / deltat))
             for nsl in nsls], dtype=num.int32)
        shifts = -num.array(
            [int(round(tt / deltat))
             for tt in tts], dtype=num.int32).reshape(nnorth*neast, nstations)
        weights = num.ones((nnorth*neast, nstations))

        print shifts[25*neast + 25] * deltat

        print offsets.dtype, shifts.dtype, weights.dtype

        print 'stack start'
        mat, ioff = parstack(arrays, offsets, shifts, weights, 1)
        print 'stack stop'

        mat = num.reshape(mat, (nnorth, neast))

        from matplotlib import pyplot as plt

        fig = plt.figure()

        axes = fig.add_subplot(1, 1, 1, aspect=1.0)

        axes.contourf(east/km, north/km, mat)

        axes.plot(
            g(targets, 'east_shift')/km,
            g(targets, 'north_shift')/km, '^')
        axes.plot(source.east_shift/km, source.north_shift/km, 'o')
        plt.show()
Example #3
0
    def stalta(self):
        ''' 
        Based on stalta by Francesco Grigoli.
        '''

        tnow = time.time() 
        pile = self.get_view().pile
        if self._tlast_stalta is None:
            self._tlast_stalta = tnow
            return

        tmin = self._tlast_stalta
        tmax = tnow
        
        self._tlast_stalta = tnow

        swin, ratio = 0.07, 8
        lwin = swin * ratio
        
        tpad = lwin
        ks = 1.0
        kl = 1.8
        kd = 0.
        level = 6.0

        _numMarkers = 0
        
        self.markers = []
        for traces in pile.chopper_grouped(tmin=tmin, tmax=tmax, tpad=tpad, want_incomplete=True,
                gather=lambda tr: tr.nslc_id[:3]):

            etr = None
            nslcs = []
            deltat = 0.
            for trace in traces:
                if deltat == 0:
                    deltat = trace.deltat
                else:
                    if abs(deltat - trace.deltat) > 0.0001*deltat:
                        
                        logger.error('skipping trace %s.%s.%s.%s with unexpected sampling rate' % trace.nslc_id)
                        continue
                lowpass = 20
                highpass = 1
                trace.lowpass(4, lowpass)
                trace.highpass(4, highpass)
                 
                trace.ydata = trace.ydata**2
                trace.ydata = trace.ydata.astype(num.float32)
                if etr is None:
                    etr = trace
                else:
                    etr.add(trace)

                nslcs.append(trace.nslc_id)
            
            if etr is not None: 
                autopick.recursive_stalta(swin, lwin, ks, kl, kd, etr)                   
                etr.shift(-swin)
                etr.set_codes(channel='STA/LTA')
                etr.meta = { 'tabu': True }
                
                etr.chop(etr.tmin + lwin, etr.tmax - lwin)
                tpeaks, apeaks, tzeros = etr.peaks(level, swin*2., deadtime=True)

                for t, a in zip(tpeaks, apeaks):
                    staz=nslcs[0]
                    
                    mark = pile_viewer.Marker(nslcs, t,t)
                    print mark
                    self.markers.append(mark)
            print 'xx'

        v = self.get_view()
        _numMarkers+=len(self.markers)
        
        # emit signal, when Event was detected:
        if _numMarkers>=10:
            self.emit(SIGNAL('valueChanged(int)'),_numMarkers)

        v.add_markers(self.markers)
Example #4
0
    def preprocess(self, trs, wmin, wmax, tpad_new, deltat_cf):
        fsmooth = self.get_fsmooth()
        fnormalize = self.get_fnormalize()

        if self.trace_selector:
            trs = self.trace_selector(trs)

        if not trs:
            return []

        trs_filt = []
        for orig_tr in trs:
            tr = orig_tr.copy()
            tr.highpass(4, self.fmin, demean=True)
            tr.lowpass(4, self.fmax, demean=False)
            tr.ydata = tr.ydata**2

            trs_filt.append(tr)

        trs_by_nsl = common.grouped_by(trs_filt, lambda tr: tr.nslc_id[:3])

        swin = self.short_window
        lwin = self.window_ratio * swin

        dataset = []
        for nsl in sorted(trs_by_nsl.keys()):
            sumtr = None
            for tr in trs_by_nsl[nsl]:
                if sumtr is None:
                    sumtr = tr.copy()
                    sumtr.set_codes(channel='CF_%s' % self.name)
                else:
                    sumtr.add(tr)

            sumtr.set_ydata(sumtr.get_ydata().astype(num.float32))
            autopick.recursive_stalta(swin, lwin, 1.0, 4.0, 3.0, sumtr)

            sumtr.shift(-swin/2.)

            normtr = sumtr.copy()

            ntap_smooth = int(num.round(1./fsmooth / tr.deltat))
            ntap_normalize = int(num.round(1./fnormalize / tr.deltat))
            taper_smooth = num.hanning(ntap_smooth)
            taper_normalize = num.hanning(ntap_normalize)

            sumtr.shift(-(ntap_smooth / 2. * tr.deltat))
            normtr.shift(-(ntap_normalize / 2. * tr.deltat))

            sumtr.set_ydata(
                fftconvolve(sumtr.get_ydata()/len(trs_by_nsl), taper_smooth))

            normtr.set_ydata(
                fftconvolve(
                    normtr.get_ydata()/len(trs_by_nsl),
                    taper_normalize))

            normtr.set_codes(channel='normtr')

            tmin = max(sumtr.tmin, normtr.tmin)
            tmax = min(sumtr.tmax, normtr.tmax)
            sumtr.chop(tmin, tmax)
            normtr.chop(tmin, tmax)

            sumtr.set_ydata(sumtr.get_ydata() / normtr.get_ydata())

            downsample(sumtr, deltat_cf)

            sumtr.chop(wmin - tpad_new, wmax + tpad_new)

            dataset.append((nsl, sumtr))

        return dataset