예제 #1
0
    def test_explosion_source(self):

        target = gf.Target(interpolation='nearest_neighbor')

        ex = gf.ExplosionSource(magnitude=5., volume_change=4., depth=5 * km)

        with self.assertRaises(gf.DerivedMagnitudeError):
            ex.validate()

        ex = gf.ExplosionSource(depth=5 * km)

        ex.validate()

        self.assertEqual(ex.get_moment(), 1.0)

        # magnitude input
        magnitude = 3.
        ex = gf.ExplosionSource(magnitude=magnitude, depth=5 * km)

        store = self.dummy_store()

        with self.assertRaises(gf.DerivedMagnitudeError):
            ex.get_volume_change()

        volume_change = ex.get_volume_change(store, target)

        self.assertAlmostEqual(ex.get_magnitude(store, target), magnitude)

        # validate with MT source
        moment = ex.get_moment(store, target) * float(num.sqrt(2. / 3))

        mt = gf.MTSource(mnn=moment, mee=moment, mdd=moment)

        self.assertAlmostEqual(ex.get_magnitude(store, target),
                               mt.get_magnitude(store=store, target=target))

        # discretized sources
        d_ex = ex.discretize_basesource(store=store, target=target)
        d_mt = mt.discretize_basesource(store=store, target=target)

        d_ex_m6s = d_ex.get_source_terms('elastic10')
        d_mt_m6s = d_mt.get_source_terms('elastic10')

        numeq(d_ex_m6s, d_mt_m6s, 1e-20)

        # interpolation method
        with self.assertRaises(TypeError):
            ex.get_volume_change(store,
                                 gf.Target(interpolation='nearest_neighbour'))

        # volume change input
        ex = gf.ExplosionSource(volume_change=volume_change, depth=5 * km)

        self.assertAlmostEqual(ex.get_magnitude(store, target), 3.0)

        ex = gf.ExplosionSource(magnitude=3.0, depth=-5.)

        with self.assertRaises(gf.DerivedMagnitudeError):
            ex.get_volume_change(store, target)
예제 #2
0
def createSynthetics(moment_tensors,
                     stfs,
                     depths,
                     target,
                     engine,
                     noisy=False,
                     noise_factor=0.1):
    '''
    createSynthetics: Create synthetic seismograms for the seimic spectrogram clustering experiment
    
    :param moment_tensors: A list of pyrocko.moment_tensor.MomentTensor objects
    :param stfs: List of pyrocko SourceTimeFunction objects.
    :param depths: List of floats, the depths for each seismogram
    :param target: A pyrocko.gf.Target object with information on the receiver
    :param engine: A pyrocko.gf.LocalEngine object initialized with the Green's functions store
    :param noisy: Boolean, whether to add Gaussian noise to the resulting synthetic 
    :param noise_factor: Float, controls the relative strength of the noise to the signal.  This constant multiplied by the mean of the absolute value of the spectrogram scales to additive noise.  Formula is :math `noise_factor * mean(|seismogram|) * seismogram`
    :returns A list containing arrays of synthetic seismograms and corresponding spectrograms -> [seismograms, spectrograms]
    
    '''

    assert len(moment_tensors) == len(stfs) == len(depths), print(
        'moment_tensors, stfs, and depths must all be same length')

    seismograms = []

    for i, mt in enumerate(moment_tensors):
        source = gf.MTSource(lat=0,
                             lon=0,
                             depth=depths[i],
                             mnn=mt.mnn,
                             mee=mt.mee,
                             mdd=mt.mdd,
                             mne=mt.mne,
                             mnd=mt.mne,
                             med=mt.med,
                             stf=stfs[i])
        if noisy:
            seismograms.append(
                create_noisy_seismogram(source, target, engine, noise_factor))
        else:
            seismograms.append(create_noisy_seismogram(source, target, engine))

    seismograms = trim_seismograms(seismograms)
    df = 10
    #deltat_inverse = 1/seismogram[0].deltat

    spectrograms = [create_spectrogram(s, df) for s in seismograms]

    spectrograms = np.array(spectrograms)

    specshape = spectrograms.shape
    #spectrograms = spectrograms.reshape(specshape[2],specshape[0],specshape[1])
    seismograms = np.array(seismograms)

    return [seismograms, spectrograms]
def createFocalMechanisms(n,
                          depths,
                          durations,
                          target,
                          engine,
                          noisy=False,
                          noise_factor=0.1):
    n_0 = int(n / 3)

    seismograms = []

    moment_tensors = [createMT_DC(1) for i in range(n_0)] + \
              [createMT_CLVD(1) for i in range(n_0)] + \
              [createMT_Isotropic(1) for i in range(n_0)]

    focal_mechanisms = n_0 * ['DC'] + n_0 * ['CLVD'] + n_0 * ['Isotropic']

    for i, mt in enumerate(moment_tensors):
        source = gf.MTSource(lat=0,
                             lon=0,
                             depth=depths[i],
                             mnn=mt.mnn,
                             mee=mt.mee,
                             mdd=mt.mdd,
                             mne=mt.mne,
                             mnd=mt.mne,
                             med=mt.med,
                             stf=gf.BoxcarSTF(duration=durations[i]))
        if noisy:
            seismograms.append(
                create_noisy_seismogram(source, target, engine, noise_factor))
        else:
            seismograms.append(create_noisy_seismogram(source, target, engine))

    #seismograms = np.array(quakes)
    df = 20
    #deltat_inverse = 1/seismogram[0].deltat

    spectrograms = [create_spectrogram(s, df) for s in seismograms]
    #spectrograms = np.array(spectrograms)

    #specshape = spectrograms.shape
    #spectrograms = spectrograms.reshape(specshape[2],specshape[0],specshape[1])

    df = pd.DataFrame({
        'FocalMechanism': focal_mechanisms,
        'MomentTensor': moment_tensors,
        'Seismogram': seismograms,
        'Spectrogram': spectrograms,
        'Depth': depths,
        'Duration': durations
    })

    return df
예제 #4
0
    def test_outline(self):
        s = gf.MTSource(east_shift=5. * km,
                        north_shift=-3. * km,
                        depth=7. * km)

        outline = s.outline()
        numeq(outline, num.array([[-3000., 5000., 7000.]]), 1e-8)

        rs = gf.RectangularSource(length=2 * km, width=2 * km)

        outline = rs.outline()
        numeq(
            outline,
            num.array([[-1.e3, 0.0, 0.0], [1.e3, 0.0, 0.0], [1.e3, 0.0, 2.e3],
                       [-1.e3, 0.0, 2.e3], [-1.e3, 0.0, 0.0]]), 1e-8)
예제 #5
0
    def test_pyrocko_gf_vs_qseis(self):
        random.seed(2017)

        mod = cake.LayeredModel.from_scanlines(
            cake.read_nd_model_str('''
 0. 5.8 3.46 2.6 1264. 600.
 20. 5.8 3.46 2.6 1264. 600.
 20. 6.5 3.85 2.9 1283. 600.
 35. 6.5 3.85 2.9 1283. 600.
mantle
 35. 8.04 4.48 3.58 1449. 600.
 77.5 8.045 4.49 3.5 1445. 600.
 77.5 8.045 4.49 3.5 180.6 75.
 120. 8.05 4.5 3.427 180. 75.
 120. 8.05 4.5 3.427 182.6 76.06
 165. 8.175 4.509 3.371 188.7 76.55
 210. 8.301 4.518 3.324 201. 79.4
 210. 8.3 4.52 3.321 336.9 133.3
 410. 9.03 4.871 3.504 376.5 146.1
 410. 9.36 5.08 3.929 414.1 162.7
 660. 10.2 5.611 3.918 428.5 172.9
 660. 10.79 5.965 4.229 1349. 549.6'''.lstrip()))

        store_dir = mkdtemp(prefix='gfstore')
        self.tempdirs.append(store_dir)

        qsconf = qseis.QSeisConfig()
        qsconf.qseis_version = '2006a'

        qsconf.time_region = (gf.meta.Timing('0'), gf.meta.Timing('end+100'))

        qsconf.cut = (gf.meta.Timing('0'), gf.meta.Timing('end+100'))

        qsconf.wavelet_duration_samples = 0.001
        qsconf.sw_flat_earth_transform = 0

        config = gf.meta.ConfigTypeA(id='qseis_test',
                                     sample_rate=0.25,
                                     receiver_depth=0. * km,
                                     source_depth_min=10 * km,
                                     source_depth_max=10 * km,
                                     source_depth_delta=1 * km,
                                     distance_min=550 * km,
                                     distance_max=560 * km,
                                     distance_delta=1 * km,
                                     modelling_code_id='qseis.2006a',
                                     earthmodel_1d=mod,
                                     tabulated_phases=[
                                         gf.meta.TPDef(
                                             id='begin',
                                             definition='p,P,p\\,P\\'),
                                         gf.meta.TPDef(id='end',
                                                       definition='2.5'),
                                     ])

        config.validate()
        gf.store.Store.create_editables(store_dir,
                                        config=config,
                                        extra={'qseis': qsconf})

        store = gf.store.Store(store_dir, 'r')
        store.make_ttt()
        store.close()

        try:
            qseis.build(store_dir, nworkers=1)
        except qseis.QSeisError as e:
            if str(e).find('could not start qseis') != -1:
                logger.warn('qseis not installed; '
                            'skipping test_pyrocko_gf_vs_qseis')
                return
            else:
                raise

        source = gf.MTSource(lat=0., lon=0., depth=10. * km)

        source.m6 = tuple(random.random() * 2. - 1. for x in range(6))

        azi = random.random() * 365.
        dist = 553. * km

        dnorth = dist * math.cos(azi * d2r)
        deast = dist * math.sin(azi * d2r)

        targets = []
        for cha in 'rtz':
            target = gf.Target(quantity='displacement',
                               codes=('', '0000', 'PG', cha),
                               north_shift=dnorth,
                               east_shift=deast,
                               depth=config.receiver_depth,
                               store_id='qseis_test')

            dist = source.distance_to(target)
            azi, bazi = source.azibazi_to(target)

            if cha == 'r':
                target.azimuth = bazi + 180.
                target.dip = 0.
            elif cha == 't':
                target.azimuth = bazi - 90.
                target.dip = 0.
            elif cha == 'z':
                target.azimuth = 0.
                target.dip = 90.

            targets.append(target)

        runner = qseis.QSeisRunner()
        conf = qseis.QSeisConfigFull()
        conf.qseis_version = '2006a'
        conf.receiver_distances = [dist / km]
        conf.receiver_azimuths = [azi]
        conf.source_depth = source.depth / km
        conf.time_start = 0.0
        conf.time_window = 508.
        conf.time_reduction_velocity = 0.0
        conf.nsamples = 128
        conf.source_mech = qseis.QSeisSourceMechMT(mnn=source.mnn,
                                                   mee=source.mee,
                                                   mdd=source.mdd,
                                                   mne=source.mne,
                                                   mnd=source.mnd,
                                                   med=source.med)
        conf.earthmodel_1d = mod

        conf.sw_flat_earth_transform = 0

        runner.run(conf)

        trs = runner.get_traces()
        for tr in trs:
            tr.shift(-config.deltat)
            tr.snap(interpolate=True)
            tr.lowpass(4, 0.05)
            tr.highpass(4, 0.01)

        engine = gf.LocalEngine(store_dirs=[store_dir])

        def process_wrap(nthreads=0):
            @benchmark.labeled('pyrocko.gf.process (nthreads-%d)' % nthreads)
            def process(nthreads):
                return engine.process(source, targets, nthreads=nthreads)\
                    .pyrocko_traces()

            return process(nthreads)

        for nthreads in range(1, cpu_count() + 1):
            trs2 = process_wrap(nthreads)
        # print benchmark

        for tr in trs2:
            tr.snap(interpolate=True)
            tr.lowpass(4, 0.05)
            tr.highpass(4, 0.01)

        # trace.snuffle(trs+trs2)

        for cha in 'rtz':
            t1 = g(trs, cha)
            t2 = g(trs2, cha)
            tmin = max(t1.tmin, t2.tmin)
            tmax = min(t1.tmax, t2.tmax)
            t1.chop(tmin, tmax)
            t2.chop(tmin, tmax)
            d = 2.0 * num.sum((t1.ydata - t2.ydata)**2) / \
                (num.sum(t1.ydata**2) + num.sum(t2.ydata**2))

            assert d < 0.05
예제 #6
0
    def test_qseis_vs_ahfull(self):
        random.seed(23)

        vp = 5.8 * km
        vs = 3.46 * km

        mod = cake.LayeredModel.from_scanlines(
            cake.read_nd_model_str('''
  0. %(vp)g %(vs)g 2.6 1264. 600.
 20. %(vp)g %(vs)g 2.6 1264. 600.'''.lstrip() % dict(vp=vp / km, vs=vs / km)))

        store_id_qseis = 'homogeneous_qseis'
        store_id_ahfull = 'homogeneous_ahfull'

        qsconf = qseis.QSeisConfig()
        qsconf.qseis_version = '2006a'

        textra = 5.0

        qsconf.time_region = (gf.meta.Timing('{vel:%g}-%g' %
                                             (vp / km, textra)),
                              gf.meta.Timing('{vel:%g}+%g' %
                                             (vs / km, textra)))

        qsconf.cut = (gf.meta.Timing('{vel:%g}-%g' % (vp / km, textra)),
                      gf.meta.Timing('{vel:%g}+%g' % (vs / km, textra)))

        qsconf.relevel_with_fade_in = True

        qsconf.fade = (gf.meta.Timing('{vel:%g}-%g' % (vp / km, textra)),
                       gf.meta.Timing('{vel:%g}-%g' % (vp / km, 0.)),
                       gf.meta.Timing('{vel:%g}+%g' % (vs / km, 0.)),
                       gf.meta.Timing('{vel:%g}+%g' % (vs / km, textra)))

        qsconf.wavelet_duration_samples = 0.001
        qsconf.sw_flat_earth_transform = 0
        qsconf.filter_surface_effects = 1
        qsconf.wavenumber_sampling = 5.
        qsconf.aliasing_suppression_factor = 0.01

        sample_rate = 10.

        config = gf.meta.ConfigTypeA(
            id=store_id_qseis,
            sample_rate=sample_rate,
            receiver_depth=0. * km,
            source_depth_min=1. * km,
            source_depth_max=19 * km,
            source_depth_delta=6. * km,
            distance_min=2. * km,
            distance_max=20 * km,
            distance_delta=2 * km,
            modelling_code_id='qseis.2006a',
            earthmodel_1d=mod,
            tabulated_phases=[
                gf.meta.TPDef(id='begin', definition='p,P,p\\,P\\'),
                gf.meta.TPDef(id='end', definition='s,S,s\\,S\\'),
            ])

        config.validate()

        store_dir_qseis = mkdtemp(prefix=store_id_qseis)
        self.tempdirs.append(store_dir_qseis)

        gf.store.Store.create_editables(store_dir_qseis,
                                        config=config,
                                        extra={'qseis': qsconf})

        store = gf.store.Store(store_dir_qseis, 'r')
        store.make_ttt()
        store.close()

        try:
            qseis.build(store_dir_qseis, nworkers=1)
        except qseis.QSeisError as e:
            if str(e).find('could not start qseis') != -1:
                logger.warn('qseis not installed; '
                            'skipping test_pyrocko_gf_vs_qseis')
                return
            else:
                raise

        config = gf.meta.ConfigTypeA(
            id=store_id_ahfull,
            sample_rate=sample_rate,
            receiver_depth=0. * km,
            source_depth_min=1. * km,
            source_depth_max=19 * km,
            source_depth_delta=6. * km,
            distance_min=2. * km,
            distance_max=20 * km,
            distance_delta=2 * km,
            modelling_code_id='ahfullgreen',
            earthmodel_1d=mod,
            tabulated_phases=[
                gf.meta.TPDef(id='begin', definition='p,P,p\\,P\\'),
                gf.meta.TPDef(id='end', definition='s,S,s\\,S\\'),
            ])

        config.validate()

        store_dir_ahfull = mkdtemp(prefix=store_id_qseis)
        self.tempdirs.append(store_dir_ahfull)

        gf.store.Store.create_editables(store_dir_ahfull, config=config)

        store = gf.store.Store(store_dir_ahfull, 'r')
        store.make_ttt()
        store.close()

        ahfullgreen.build(store_dir_ahfull, nworkers=1)

        sdepth = rand(config.source_depth_min, config.source_depth_max)
        sdepth = round(
            (sdepth - config.source_depth_min)
            / config.source_depth_delta) * config.source_depth_delta \
            + config.source_depth_min

        source = gf.MTSource(lat=0., lon=0., depth=sdepth)

        source.m6 = tuple(rand(-1., 1.) for x in range(6))

        for ii in range(5):
            azi = random.random() * 365.
            dist = rand(config.distance_min, config.distance_max)
            dist = round(dist / config.distance_delta) * config.distance_delta

            dnorth = dist * math.cos(azi * d2r)
            deast = dist * math.sin(azi * d2r)

            targets = []
            for cha in 'rtz':
                target = gf.Target(quantity='displacement',
                                   codes=('', '0000', 'PG', cha),
                                   north_shift=dnorth,
                                   east_shift=deast,
                                   depth=config.receiver_depth,
                                   store_id=store_id_ahfull)

                dist = source.distance_to(target)
                azi, bazi = source.azibazi_to(target)

                if cha == 'r':
                    target.azimuth = bazi + 180.
                    target.dip = 0.
                elif cha == 't':
                    target.azimuth = bazi - 90.
                    target.dip = 0.
                elif cha == 'z':
                    target.azimuth = 0.
                    target.dip = 90.

                targets.append(target)

            runner = qseis.QSeisRunner()
            conf = qseis.QSeisConfigFull()
            conf.qseis_version = '2006a'
            conf.receiver_distances = [dist / km]
            conf.receiver_azimuths = [azi]
            conf.receiver_depth = config.receiver_depth / km
            conf.source_depth = source.depth / km

            distance_3d_max = math.sqrt(config.distance_max**2 +
                                        (config.source_depth_max -
                                         config.source_depth_min)**2)

            nsamples = trace.nextpow2(
                int(
                    math.ceil(distance_3d_max / vs * 2.0 + 2. * textra) *
                    config.sample_rate))

            conf.time_start = -textra
            conf.time_window = (nsamples - 1) / config.sample_rate
            conf.time_reduction_velocity = 0.0
            conf.nsamples = nsamples
            conf.source_mech = qseis.QSeisSourceMechMT(mnn=source.mnn,
                                                       mee=source.mee,
                                                       mdd=source.mdd,
                                                       mne=source.mne,
                                                       mnd=source.mnd,
                                                       med=source.med)
            conf.earthmodel_1d = mod

            conf.sw_flat_earth_transform = 0
            conf.filter_surface_effects = 1
            conf.wavenumber_sampling = 10.
            conf.wavelet_duration_samples = 0.001
            conf.aliasing_suppression_factor = 0.01

            conf.validate()

            runner.run(conf)

            trs = runner.get_traces()
            for tr in trs:
                pass
                tr.lowpass(4, config.sample_rate / 8., demean=False)
                tr.highpass(4, config.sample_rate / 80.)

            engine = gf.LocalEngine(
                store_dirs=[store_dir_ahfull, store_dir_qseis])

            trs2 = engine.process(source, targets).pyrocko_traces()
            for tr in trs2:
                tr.shift(config.deltat)
                tr.lowpass(4, config.sample_rate / 8., demean=False)
                tr.highpass(4, config.sample_rate / 80.)

            # trace.snuffle(trs+trs2)

            tmin = store.t('{vel:%g}' %
                           (vp / km), source, target) - textra * 0.2
            tmax = store.t('{vel:%g}' %
                           (vs / km), source, target) + textra * 0.2

            for tr in trs + trs2:
                tr.chop(tmin, tmax)

            denom = 0.0
            for cha in 'rtz':
                t1 = g(trs, cha)
                t2 = g(trs2, cha)
                denom += num.sum(t1.ydata**2) + num.sum(t2.ydata**2)

            ds = []
            for cha in 'rtz':
                t1 = g(trs, cha)
                t2 = g(trs2, cha)
                ds.append(2.0 * num.sum((t1.ydata - t2.ydata)**2) / denom)

            ds = num.array(ds)

            # if not num.all(ds < 0.05):
            #    trace.snuffle(trs+trs2)

            assert num.all(ds < 0.05)
예제 #7
0
def default_source(S, **kwargs):
    if S is not gf.CombiSource:
        return S(**kwargs)
    else:
        return S([gf.MTSource(**kwargs)])
예제 #8
0
파일: pyrocko_gf.py 프로젝트: miili/kite
 def __init__(self, *args, **kwargs):
     SandboxSource.__init__(self, *args, **kwargs)
     self.pyrocko_source = gf.MTSource(**self._src_args)
예제 #9
0
def model(
        engine,
        store_id,
        magnitude_min, magnitude_max,
        moment_tensor,
        stress_drop_min, stress_drop_max,
        rupture_velocity_min, rupture_velocity_max,
        depth_min, depth_max,
        distance_min, distance_max,
        measures,
        nsources=400,
        nreceivers=1,
        apply_source_response_via_spectra=True,
        debug=True):

    d2r = math.pi / 180.

    components = set()
    for measure in measures:
        if not measure.components:
            raise Exception('no components given in measurement rule')

        for component in measure.components:
            components.add(component)

    components = list(components)

    data = []
    nerrors = 0
    traces_debug = []
    markers_debug = []
    for isource in xrange(nsources):
        magnitude = num.random.uniform(
            magnitude_min, magnitude_max)
        stress_drop = num.random.uniform(
            stress_drop_min, stress_drop_max)
        rupture_velocity = num.random.uniform(
            rupture_velocity_min, rupture_velocity_max)

        radius = (pmt.magnitude_to_moment(magnitude) * 7./16. /
                  stress_drop)**(1./3.)

        duration = 1.5 * radius / rupture_velocity

        if moment_tensor is None:
            mt = pmt.MomentTensor.random_dc(magnitude=magnitude)
        else:
            mt = copy.deepcopy(moment_tensor)
            mt.magnitude = magnitude

        depth = num.random.uniform(depth_min, depth_max)
        if apply_source_response_via_spectra:
            source = gf.MTSource(
                m6=mt.m6(),
                depth=depth)

            extra_responses = [
                wmeasure.BruneResponse(duration=duration)]
        else:
            source = gf.MTSource(
                m6=mt.m6(),
                depth=depth,
                stf=gf.HalfSinusoidSTF(effective_duration=duration))

            extra_responses = []

        for ireceiver in xrange(nreceivers):
            angle = num.random.uniform(0., 360.)
            distance = num.exp(num.random.uniform(
                math.log(distance_min), math.log(distance_max)))

            targets = []
            for comp in components:
                targets.append(gf.Target(
                    quantity='displacement',
                    codes=('', '%i_%i' % (isource, ireceiver), '', comp),
                    north_shift=distance*math.cos(d2r*angle),
                    east_shift=distance*math.sin(d2r*angle),
                    depth=0.,
                    store_id=store_id))

            resp = engine.process(source, targets)
            amps = []
            for measure in measures:
                comp_to_tt = {}
                for (source, target, tr) in resp.iter_results():
                    comp_to_tt[target.codes[-1]] = (target, tr)

                targets, trs = zip(*(
                    comp_to_tt[c] for c in measure.components))

                try:
                    result = wmeasure.evaluate(
                        engine, source, targets, trs,
                        extra_responses,
                        debug=debug)

                    if not debug:
                        amps.append(result)
                    else:
                        amp, trs, marker = result
                        amps.append(amp)
                        traces_debug.extend(trs)
                        markers_debug.append(marker)

                except wmeasure.AmplitudeMeasurementFailed:
                    nerrors += 1
                    amps.append(None)

            data.append([magnitude, duration, depth, distance] + amps)

    if debug:
        trace.snuffle(traces_debug, markers=markers_debug)

    return num.array(data, dtype=num.float)
예제 #10
0
        gf.store.Store.create_editables(store_dir_ahfull, config=config)

        store = gf.store.Store(store_dir_ahfull, 'r')
        store.make_ttt()
        store.close()

        ahfullgreen.build(store_dir_ahfull, nworkers=1)

        sdepth = rand(config.source_depth_min, config.source_depth_max)
        sdepth = round(
            (sdepth - config.source_depth_min)
            / config.source_depth_delta) * config.source_depth_delta \
            + config.source_depth_min

        source = gf.MTSource(lat=0., lon=0., depth=sdepth)

        source.m6 = tuple(rand(-1., 1.) for x in xrange(6))

        for ii in xrange(5):
            azi = random.random() * 365.
            dist = rand(config.distance_min, config.distance_max)
            dist = round(dist / config.distance_delta) * config.distance_delta

            dnorth = dist * math.cos(azi * d2r)
            deast = dist * math.sin(azi * d2r)

            targets = []
            for cha in 'rtz':
                target = gf.Target(quantity='displacement',
                                   codes=('', '0000', 'PG', cha),
예제 #11
0
    depths = np.round((max_depth - min_depth) *
                      (np.random.rand(len(moment_tensors))) + min_depth,
                      0)  #depths from 1 km to 35 km

    min_duration = 1  # seconds
    max_duration = 10
    durations = np.random.randint(min_duration, max_duration + 1,
                                  len(moment_tensors))

    # use a boxcar source-time function
    for i, mt in enumerate(moment_tensors):
        source = gf.MTSource(lat=0,
                             lon=0,
                             depth=depths[i],
                             mnn=mt.mnn,
                             mee=mt.mee,
                             mdd=mt.mdd,
                             mne=mt.mne,
                             mnd=mt.mne,
                             med=mt.med,
                             stf=gf.BoxcarSTF(duration=durations[i]))
        quakes_by_mechanism.append(process(source, target))

    seismograms = np.array([q.ydata[:1000] for q in quakes_by_mechanism
                            ])  #trim to 1000 samples
    df = 20
    deltat_inverse = 1 / quakes_by_mechanism[0].deltat

    spectrograms = [
        spectrogram(s, fs=deltat_inverse, nperseg=df * 2,
                    scaling='spectrum')[2] for s in seismograms
    ]
예제 #12
0
    def test_pyrocko_gf_vs_qseis2d(self):

        mod = cake.LayeredModel.from_scanlines(
            cake.read_nd_model_str('''
 0. 5.8 3.46 2.6 1264. 600.
 20. 5.8 3.46 2.6 1264. 600.
 20. 6.5 3.85 2.9 1283. 600.
 35. 6.5 3.85 2.9 1283. 600.
mantle
 35. 8.04 4.48 3.58 1449. 600.
 660. 8.04 4.48 3.58 1449. 600.
 660. 10.79 5.965 4.229 1349. 549.6'''.lstrip()))

        receiver_mod = cake.LayeredModel.from_scanlines(
            cake.read_nd_model_str('''
 0. 5.8 3.46 2.6 1264. 600.
 20. 5.8 3.46 2.6 1264. 600.
 20. 6.5 3.85 2.9 1283. 600.
 35. 6.5 3.85 2.9 1283. 600.
'''.lstrip()))

        q2_store_dir = mkdtemp(prefix='gfstore')
        q_store_dir = mkdtemp(prefix='gfstore')
        self.tempdirs.append(q2_store_dir)
        self.tempdirs.append(q_store_dir)

        # qseis2d
        q2conf = qseis2d.QSeis2dConfig()
        q2conf.gf_directory = os.path.join(q2_store_dir, 'qseisS_green')

        qss = q2conf.qseis_s_config
        qss.receiver_basement_depth = 35.
        qss.calc_slowness_window = 0
        qss.slowness_window = slowness_window

        q2conf.time_region = (gf.meta.Timing('0'), gf.meta.Timing('end+100'))

        q2conf.cut = (gf.meta.Timing('0'), gf.meta.Timing('end+100'))

        qss.sw_flat_earth_transform = 0

        config_q2 = gf.meta.ConfigTypeA(id='qseis2d_test_q2',
                                        ncomponents=10,
                                        sample_rate=0.1,
                                        receiver_depth=0. * km,
                                        source_depth_min=10. * km,
                                        source_depth_max=10. * km,
                                        source_depth_delta=1. * km,
                                        distance_min=5529. * km,
                                        distance_max=5531. * km,
                                        distance_delta=1. * km,
                                        modelling_code_id='qseis2d',
                                        earthmodel_1d=mod,
                                        earthmodel_receiver_1d=receiver_mod,
                                        tabulated_phases=[
                                            gf.meta.TPDef(
                                                id='begin',
                                                definition='p,P,p\\,P\\'),
                                            gf.meta.TPDef(id='end',
                                                          definition='2.5'),
                                        ])

        config_q2.validate()
        gf.store.Store.create_editables(q2_store_dir,
                                        config=config_q2,
                                        extra={'qseis2d': q2conf})

        store = gf.store.Store(q2_store_dir, 'r')
        store.make_ttt()
        store.close()

        # build store
        try:
            qseis2d.build(q2_store_dir, nworkers=1)
        except qseis2d.QSeis2dError as e:
            if str(e).find('could not start qseis2d') != -1:
                logger.warn('qseis2d not installed; '
                            'skipping test_pyrocko_qseis_vs_qseis2d')
                logger.warn(e)
                return
            else:
                raise

        # qseis
        config_q = copy.deepcopy(config_q2)
        config_q.id = 'qseis2d_test_q'
        config_q.modelling_code_id = 'qseis.2006a'

        qconf = qseis.QSeisConfig()
        qconf.qseis_version = '2006a'

        qconf.slowness_window = slowness_window

        qconf.time_region = (gf.meta.Timing('0'), gf.meta.Timing('end+100'))

        qconf.cut = (gf.meta.Timing('0'), gf.meta.Timing('end+100'))

        qconf.sw_flat_earth_transform = 0

        config_q.validate()
        gf.store.Store.create_editables(q_store_dir,
                                        config=config_q,
                                        extra={'qseis': qconf})

        store = gf.store.Store(q_store_dir, 'r')
        store.make_ttt()
        store.close()

        # build store
        try:
            qseis.build(q_store_dir, nworkers=1)
        except qseis.QSeisError as e:
            if str(e).find('could not start qseis') != -1:
                logger.warn('qseis not installed; '
                            'skipping test_pyrocko_qseis_vs_qseis2d')
                logger.warn(e)
                return
            else:
                raise

        # forward model
        source = gf.MTSource(lat=0., lon=0., depth=10. * km)

        source.m6 = tuple(random.random() * 2. - 1. for x in range(6))

        azi = 0.  # QSeis2d only takes one receiver without azimuth variable
        dist = 5530. * km

        dnorth = dist * math.cos(azi * d2r)
        deast = dist * math.sin(azi * d2r)

        targets_q = []
        targets_q2 = []
        for cha in 'rtz':
            target_q2 = gf.Target(quantity='displacement',
                                  codes=('', '0000', 'Q2', cha),
                                  north_shift=dnorth,
                                  east_shift=deast,
                                  store_id='qseis2d_test_q2')

            dist = source.distance_to(target_q2)
            azi, bazi = source.azibazi_to(target_q2)

            if cha == 'r':
                target_q2.azimuth = bazi + 180.
                target_q2.dip = 0.
            elif cha == 't':
                target_q2.azimuth = bazi - 90.
                target_q2.dip = 0.
            elif cha == 'z':
                target_q2.azimuth = 0.
                target_q2.dip = 90.

            target_q = copy.deepcopy(target_q2)
            target_q.store_id = 'qseis2d_test_q'
            target_q.codes = ('', '0000', 'Q', cha)
            targets_q2.append(target_q2)
            targets_q.append(target_q)

        targets = targets_q + targets_q2
        engine = gf.LocalEngine(store_dirs=[q2_store_dir, q_store_dir])
        response = engine.process(source, targets)

        qtrcs = []
        q2trcs = []
        for s, target, trc in response.iter_results():
            if target.codes[2] == 'Q':
                qtrcs.append(trc)
            else:
                q2trcs.append(trc)

        for q, q2 in zip(qtrcs, q2trcs):
            num.testing.assert_allclose(q.ydata, q2.ydata, atol=4e-23)
예제 #13
0
        store.make_ttt()
        store.close()

        # build store
        try:
            qseis.build(q_store_dir, nworkers=1)
        except qseis.QSeisError, e:
            if str(e).find('could not start qseis') != -1:
                logger.warn('qseis not installed; '
                            'skipping test_pyrocko_qseis_vs_qseis2d')
                return
            else:
                raise

        # forward model
        source = gf.MTSource(lat=0., lon=0., depth=10. * km)

        source.m6 = tuple(random.random() * 2. - 1. for x in xrange(6))

        azi = 0.  # QSeis2d only takes one receiver without azimuth variable
        dist = 5530. * km

        dnorth = dist * math.cos(azi * d2r)
        deast = dist * math.sin(azi * d2r)

        targets_q = []
        targets_q2 = []
        for cha in 'rtz':
            target_q2 = gf.Target(quantity='displacement',
                                  codes=('', '0000', 'Q2', cha),
                                  north_shift=dnorth,