Beispiel #1
0
 def test_source_dict(self):
     s1 = gf.DCSource(strike=0.)
     s1.strike = 10.
     s2 = s1.clone(strike=20.)
     s2.update(strike=30.)
     s2['strike'] = 40.
     d = dict(s2)
     s3 = gf.DCSource(**d)
     s3.strike
Beispiel #2
0
    def test_qssp_build_2020_rotational(self):
        qssp.init(self.tmpdir,
                  '2020',
                  config_params=dict(stored_quantity='rotation',
                                     source_depth_max=10e3,
                                     distance_min=500e3,
                                     distance_max=600e3))

        store = gf.store.Store(self.tmpdir, 'r')
        store.make_ttt()
        qssp.build(self.tmpdir)

        del store

        engine = gf.LocalEngine(store_dirs=[self.tmpdir])

        source = gf.DCSource(lat=0., lon=0., depth=10e3, magnitude=6.0)

        targets = [
            gf.Target(quantity='rotation',
                      codes=('', 'ROT', '', comp),
                      lat=0.,
                      lon=0.,
                      north_shift=500e3,
                      east_shift=100e3) for comp in 'NEZ'
        ]

        engine.process(source, targets)
Beispiel #3
0
    def test_sgrid2(self):
        expect = [10., 12., 14., 16., 18., 20.]
        source = gf.DCSource()
        sgrid = source.grid(dip=gf.Range(10, 20, 2))
        dips = []
        for source in sgrid:
            dips.append(source.dip)

        num.testing.assert_array_almost_equal(dips, expect)

        source = gf.DCSource(dip=10)
        sgrid = source.grid(dip=gf.Range(1, 2, 0.2, relative='mult'))
        dips = []
        for source in sgrid:
            dips.append(source.dip)

        num.testing.assert_array_almost_equal(dips, expect)
Beispiel #4
0
    def test_sgrid(self):

        r = gf.Range

        source = gf.DCSource()
        sgrid = source.grid(rake=r(-10, 10, 1),
                            strike=r(-100, 100, n=21),
                            depth=r('0k .. 100k : 10k'),
                            moment=r(1, 2, 1))

        sgrid = guts.load_string(sgrid.dump())
        n = len(sgrid)
        i = 0
        for source in sgrid:
            i += 1

        assert i == n
Beispiel #5
0
    def test_static_timing(self):
        src_length = 5 * km
        src_width = 2 * km
        nstations = 100
        day = 3600 * 24
        interp = ['nearest_neighbor', 'multilinear']
        interpolation = interp[0]

        source = gf.RectangularSource(
            lat=0., lon=0.,
            north_shift=0., east_shift=0., depth=6.5*km,
            width=src_width, length=src_length,
            dip=90., rake=90., strike=90.,
            slip=1.,
            time=time.time()-day)

        source = gf.DCSource(
            lat=0., lon=0.,
            north_shift=0., east_shift=0., depth=6.5*km,
            dip=90., rake=90., strike=90.,
            time=time.time()-day)

        lats = random.uniform(-.2, .2, nstations)
        lons = random.uniform(-.2, .2, nstations)

        target_1 = gf.StaticTarget(
            lats=lats,
            lons=lons,
            interpolation=interpolation,
            tsnapshot=time.time() + day)

        target_2 = gf.StaticTarget(
            lats=lats,
            lons=lons,
            interpolation=interpolation,
            tsnapshot=time.time())

        engine = gf.LocalEngine(store_dirs=[self.get_store_dir('pscmp')])
        res = engine.process(source, [target_1, target_2], nprocs=0)\

        statics_1, statics_2 = res.static_results()
        num.testing.assert_equal(
            statics_1.result['displacement.n'],
            statics_2.result['displacement.n'])
Beispiel #6
0
    def get_source(self, ievent):
        rstate = self.get_rstate(ievent)
        time = rstate.uniform(self.time_min, self.time_max)
        lat, lon, north_shift, east_shift, depth = self.get_coordinates(ievent)
        depth = rstate.uniform(self.depth_min, self.depth_max)
        magnitude = self.draw_magnitude(rstate)

        if self.strike is None and self.dip is None and self.rake is None:
            mt = moment_tensor.MomentTensor.random_dc(x=rstate.uniform(size=3))
        else:
            if None in (self.strike, self.dip, self.rake):
                raise ScenarioError(
                    'DCSourceGenerator: '
                    'strike, dip, and rake must be used in combination.')

            mt = moment_tensor.MomentTensor(strike=self.strike,
                                            dip=self.dip,
                                            rake=self.rake)

            if self.perturbation_angle_std is not None:
                mt = mt.random_rotated(self.perturbation_angle_std,
                                       rstate=rstate)

        (s, d, r), (_, _, _) = mt.both_strike_dip_rake()

        source = gf.DCSource(name='ev%04i' % ievent,
                             time=float(time),
                             lat=float(lat),
                             lon=float(lon),
                             north_shift=float(north_shift),
                             east_shift=float(east_shift),
                             depth=float(depth),
                             magnitude=float(magnitude),
                             strike=float(s),
                             dip=float(d),
                             rake=float(r))

        return source
Beispiel #7
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()
    def call(self):
        '''Main work routine of the snuffling.'''
        self.cleanup()
        olat = 0.
        olon = 0.
        f = (0., 0., 0.)
        deltat = 1./self.fsampling
        if self.stf == 'Gauss':
            stf = Gauss(self.tau)
        elif self.stf == 'Impulse':
            stf = Impulse()

        viewer = self.get_viewer()
        event = viewer.get_active_event()
        if event:
            event, stations = self.get_active_event_and_stations(missing='warn')
        else:
            event = model.Event(lat=olat, lon=olon)
            stations = []

        if not stations:
            s = model.Station(lat=olat, lon=olon, station='AFG')
            stations = [s]
            viewer.add_stations(stations)

        source = gf.DCSource(
            time=event.time+self.time,
            lat=event.lat,
            lon=event.lon,
            north_shift=self.north_km*km,
            east_shift=self.east_km*km,
            depth=self.depth_km*km,
            magnitude=moment_tensor.moment_to_magnitude(self.moment),
            strike=self.strike,
            dip=self.dip,
            rake=self.rake)

        source.regularize()

        m = EventMarker(source.pyrocko_event())
        self.add_marker(m)

        targets = []

        mt = moment_tensor.MomentTensor(
            strike=source.strike,
            dip=source.dip,
            rake=source.rake,
            moment=self.moment)

        traces = []
        for station in stations:
            xyz = (self.north_km*km, self.east_km*km, self.depth_km*km)
            r = num.sqrt(xyz[0]**2 + xyz[1]**2 + xyz[2]**2)
            ns = math.ceil(r/self.vs/1.6)*2
            outx = num.zeros(int(ns))
            outy = num.zeros(int(ns))
            outz = num.zeros(int(ns))
            nsl = station.nsl()
            quantity = self.quantity.split()[0].lower()
            add_seismogram(
                self.vp*km, self.vs*km, self.density, self.qp, self.qs, xyz, f,
                mt.m6(), quantity, deltat, 0., outx, outy, outz,
                stf=stf, want_near=self.want_near,
                want_intermediate=self.want_intermediate,
                want_far=self.want_far)

            for channel, out in zip('NEZ', [outx, outy, outz]):
                tr = trace.Trace('', station.station, '', channel, deltat=deltat,
                                 tmin=source.time, ydata=out)
                traces.append(tr)
        self.add_traces(traces)
Beispiel #9
0
    def test_calc_timeseries(self):
        from pyrocko.gf import store_ext
        benchmark.show_factor = True

        rstate = num.random.RandomState(123)

        def test_timeseries(store,
                            source,
                            dim,
                            ntargets,
                            interpolation,
                            nthreads,
                            niter=1,
                            random_itmin=False,
                            random_nsamples=False):

            source = gf.RectangularSource(lat=0.,
                                          lon=0.,
                                          depth=3 * km,
                                          length=dim,
                                          width=dim,
                                          anchor='top')

            targets = [
                gf.Target(lat=rstate.uniform(), lon=rstate.uniform())
                for x in range(ntargets)
            ]

            dsource = source.discretize_basesource(store, targets[0])
            source_coords_arr = dsource.coords5()
            mts_arr = dsource.m6s

            receiver_coords_arr = num.empty((len(targets), 5))
            for itarget, target in enumerate(targets):
                receiver = target.receiver(store)
                receiver_coords_arr[itarget, :] = \
                    [receiver.lat, receiver.lon, receiver.north_shift,
                     receiver.east_shift, receiver.depth]
            nsources = mts_arr.shape[0]
            delays = num.zeros(nsources)

            itmin = num.zeros(ntargets, dtype=num.int32)
            nsamples = num.full(ntargets, -1, dtype=num.int32)

            if random_itmin:
                itmin = num.random.randint(-20,
                                           5,
                                           size=ntargets,
                                           dtype=num.int32)

            if random_nsamples:
                nsamples = num.random.randint(10,
                                              100,
                                              size=ntargets,
                                              dtype=num.int32)

            @benchmark.labeled('calc_timeseries-%s' % interpolation)
            def calc_timeseries():
                return store_ext.store_calc_timeseries(
                    store.cstore, source_coords_arr, mts_arr, delays,
                    receiver_coords_arr, 'elastic10', interpolation, itmin,
                    nsamples, nthreads)

            @benchmark.labeled('sum_timeseries-%s' % interpolation)
            def sum_timeseries():
                results = []
                for itarget, target in enumerate(targets):
                    params = store_ext.make_sum_params(
                        store.cstore, source_coords_arr, mts_arr,
                        target.coords5[num.newaxis, :].copy(), 'elastic10',
                        interpolation, nthreads)
                    for weights, irecords in params:
                        d = num.zeros(irecords.shape[0], dtype=num.float32)
                        r = store_ext.store_sum(store.cstore, irecords, d,
                                                weights, int(itmin[itarget]),
                                                int(nsamples[itarget]))
                        results.append(r)

                return results

            for _ in range(niter):
                res_calc = calc_timeseries()
            for _ in range(niter):
                res_sum = sum_timeseries()

            for c, s in zip(res_calc, res_sum):
                num.testing.assert_equal(c[0], s[0], verbose=True)
                for cc, cs in zip(c[1:-1], s[1:]):
                    continue
                    assert cc == cs

        store = gf.Store(self.get_pulse_store_dir())
        store.open()

        sources = [
            gf.DCSource(lat=0., lon=0., depth=1 * km, magnitude=8.),
            gf.RectangularSource(lat=0.,
                                 lon=0.,
                                 anchor='top',
                                 depth=5 * km,
                                 width=10 * km,
                                 length=20 * km)
        ]

        for source in sources:
            for interp in ['multilinear', 'nearest_neighbor']:
                for random_itmin in [True, False]:
                    for random_nsamples in [True, False]:
                        test_timeseries(store,
                                        source,
                                        dim=10 * km,
                                        niter=1,
                                        ntargets=20,
                                        interpolation=interp,
                                        nthreads=0,
                                        random_itmin=random_itmin,
                                        random_nsamples=random_nsamples)
                print(benchmark)
                benchmark.clear()

        def plot(res):
            import matplotlib.pyplot as plt
            plt.plot(res[0])
            plt.show()
Beispiel #10
0
 def __init__(self, *args, **kwargs):
     SandboxSource.__init__(self, *args, **kwargs)
     self.pyrocko_source = gf.DCSource(**self._src_args)
Beispiel #11
0
    def test_regional(self):
        engine = gf.get_engine()
        store_id = 'crust2_mf'
        try:
            engine.get_store(store_id)
        except gf.NoSuchStore:
            logger.warn('GF Store %s not available - skipping test' % store_id)
            return

        nsources = 10
        nstations = 10

        print 'cache source channels par wallclock seismograms_per_second'
        nprocs_max = multiprocessing.cpu_count()

        for sourcetype, channels in [
                ['point', 'Z'],
                ['point', 'NEZ'],
                ['rect', 'Z'],
                ['rect', 'NEZ']]:

            for nprocs in [1, 2, 4, 8, 16, 32]:
                if nprocs > nprocs_max:
                    continue

                sources = []
                for isource in xrange(nsources):
                    m = pmt.MomentTensor.random_dc()
                    strike, dip, rake = map(float, m.both_strike_dip_rake()[0])

                    if sourcetype == 'point':
                        source = gf.DCSource(
                            north_shift=rand(-20.*km, 20*km),
                            east_shift=rand(-20.*km, 20*km),
                            depth=rand(10*km, 20*km),
                            strike=strike,
                            dip=dip,
                            rake=rake,
                            magnitude=rand(4.0, 5.0))

                    elif sourcetype == 'rect':
                        source = gf.RectangularSource(
                            north_shift=rand(-20.*km, 20*km),
                            east_shift=rand(-20.*km, 20*km),
                            depth=rand(10*km, 20*km),
                            length=10*km,
                            width=5*km,
                            nucleation_x=0.,
                            nucleation_y=-1.,
                            strike=strike,
                            dip=dip,
                            rake=rake,
                            magnitude=rand(4.0, 5.0))
                    else:
                        assert False

                    sources.append(source)

                targets = []
                for istation in xrange(nstations):
                    dist = rand(40.*km, 900*km)
                    azi = rand(-180., 180.)

                    north_shift = dist * math.cos(azi*d2r)
                    east_shift = dist * math.sin(azi*d2r)

                    for cha in channels:
                        target = gf.Target(
                            codes=('', 'S%04i' % istation, '', cha),
                            north_shift=north_shift,
                            east_shift=east_shift,
                            quantity='displacement',
                            interpolation='multilinear',
                            optimization='enable',
                            store_id=store_id)

                        targets.append(target)

                ntraces = len(targets) * len(sources)
                for temperature in ['cold', 'hot']:
                    t0 = time.time()
                    resp = engine.process(sources, targets, nprocs=nprocs)
                    # print resp.stats

                    t1 = time.time()
                    duration = t1 - t0
                    sps = ntraces / duration
                    if temperature == 'hot':
                        if nprocs == 1:
                            sps_ref = sps
                        print '%-5s %-6s %-8s %3i %9.3f %12.1f %12.1f' % (
                            temperature, sourcetype, channels, nprocs, t1-t0,
                            sps, sps/sps_ref)

                    del resp
Beispiel #12
0
from matplotlib import transforms, pyplot as plt
from pyrocko import gf
from pyrocko.plot import beachball

# create source object
source1 = gf.DCSource(depth=35e3, strike=0., dip=90., rake=0.)

# set size of beachball
sz = 20.
# set beachball offset in points (one point from each axis)
szpt = (sz / 2.) / 72. + 1. / 72.

fig = plt.figure(figsize=(10., 4.))
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)

# get the bounding point (left-top)
x0 = ax.get_xlim()[0]
y1 = ax.get_ylim()[1]

# create a translation matrix, based on the final figure size and
# beachball location
move_trans = transforms.ScaledTranslation(szpt, -szpt, fig.dpi_scale_trans)

# get the inverse matrix for the axis where the beachball will be plotted
inv_trans = ax.transData.inverted()

# set the bouding point relative to the plotted axis of the beachball
x0, y1 = inv_trans.transform(
    move_trans.transform(ax.transData.transform((x0, y1))))
Beispiel #13
0
#sources = [
#   gf.MTSource(
#   lat=10.0,
#   lon=lat,
#   depth=depth,
#   mnn=1.,
#   mee=0.3,
#   mdd=0.1,
#   mne=0.,
#   med=0.,
#   mnd=0.) for depth in [5e3, 10e3, 15e3] for lat in [11.0,11.1,11.2]]
sources = [
    gf.DCSource(lat=10.0,
                lon=10.0,
                depth=depth,
                magnitude=magnitude,
                strike=33.,
                dip=80.,
                rake=5.) for depth in [5e3, 10e3, 15e3]
    for magnitude in [5., 6., 7.]
]

targets = [
    gf.Target(
        codes=('', 'STA', '', component),
        lat=11.0,
        lon=10.0,
        store_id='local1',
    ) for component in 'NEZ'
]
print targets[0].codes