示例#1
0
        def complete(data):
            try:
                t = calendar.timegm((data.year, data.month, data.day, data.hour, data.minute, data.seconds))
                m = num.array([data.mrr, data.mrt, data.mrp, 
                               data.mrt, data.mtt, data.mtp,
                               data.mrp, data.mtp, data.mpp],
                        dtype=num.float).reshape(3,3)

                m *= 10.0**(data.exponent-7)
                mt = MomentTensor(m_up_south_east=m)
                ev = model.Event(
                    lat=data.lat,
                    lon=data.lon, 
                    time=t,
                    name=data.eventname,
                    depth=data.depth_km*1000.,
                    magnitude=mt.moment_magnitude(),
                    duration=data.half_duration * 2.,
                    region=data.region.rstrip(),
                    catalog=data.catalog)

                ev.moment_tensor = mt
                events.append(ev)

            except AttributeError:
                pass
示例#2
0
 def forwardBackward(self, strike, dip, rake, scalar_moment):
     m1 = MomentTensor(strike=strike,
                       dip=dip,
                       rake=rake,
                       scalar_moment=scalar_moment)
     m2 = MomentTensor(m=m1.m())
     self.assertAnglesSame(m1, m2)
示例#3
0
 def testChile(self):
     m_use = symmat6(1.040, -0.030, -1.010, 0.227, -1.510,
                     -0.120) * 1e29 * dynecm
     mt = MomentTensor(m_up_south_east=m_use)
     sdr = mt.both_strike_dip_rake()
     self.assertSame(sdr[0], (174., 73., 83.), 1., 'chile fail 1')
     self.assertSame(sdr[1], (18., 18., 112.), 1., 'chile fail 2')
 def testChile(self):
     m_use = symmat6(
         1.040, -0.030, -1.010, 0.227, -1.510, -0.120)*1e29*dynecm
     mt = MomentTensor(m_up_south_east=m_use)
     sdr = mt.both_strike_dip_rake()
     self.assertSame(sdr[0], (174., 73., 83.), 1., 'chile fail 1')
     self.assertSame(sdr[1], (18., 18., 112.), 1., 'chile fail 2')
示例#5
0
        def complete(data):
            try:
                t = calendar.timegm((data.year, data.month, data.day,
                                     data.hour, data.minute, data.seconds))

                m = num.array([
                    data.mrr, data.mrt, data.mrp, data.mrt, data.mtt, data.mtp,
                    data.mrp, data.mtp, data.mpp
                ],
                              dtype=num.float).reshape(3, 3)

                m *= 10.0**(data.exponent - 7)
                mt = MomentTensor(m_up_south_east=m)
                ev = model.Event(lat=data.lat,
                                 lon=data.lon,
                                 time=t,
                                 name=data.eventname,
                                 depth=data.depth_km * 1000.,
                                 magnitude=float(mt.moment_magnitude()),
                                 duration=data.half_duration * 2.,
                                 region=data.region.rstrip(),
                                 catalog=data.catalog)

                ev.moment_tensor = mt
                events.append(ev)

            except AttributeError:
                pass
示例#6
0
    def __init__(self, store_dir, step, shared, block_size=None, tmp=None,
                 force=False):
        self.gfmapping = [
            (MomentTensor(m=symmat6(1, 0, 0, 1, 0, 0)),
             {'un': (0, -1), 'ue': (3, -1), 'uz': (5, -1)}),
            (MomentTensor(m=symmat6(0, 0, 0, 0, 1, 1)),
             {'un': (1, -1), 'ue': (4, -1), 'uz': (6, -1)}),
            (MomentTensor(m=symmat6(0, 0, 1, 0, 0, 0)),
             {'un': (2, -1), 'uz': (7, -1)}),
            (MomentTensor(m=symmat6(0, 1, 0, 0, 0, 0)),
             {'un': (8, -1), 'uz': (9, -1)}),
        ]

        self.store = gf.store.Store(store_dir, 'w')

        if step == 0:
            block_size = (1, 1, self.store.config.ndistances)
        else:
            if block_size is None:
                block_size = (1, 1, 51)

        if len(self.store.config.ns) == 2:
            block_size = block_size[1:]

        gf.builder.Builder.__init__(
            self, self.store.config, step, block_size=block_size, force=force)

        baseconf = self.store.get_extra('qssp')

        conf = QSSPConfigFull(**baseconf.items())
        conf.gf_directory = pjoin(store_dir, 'qssp_green')
        conf.earthmodel_1d = self.store.config.earthmodel_1d
        deltat = self.store.config.deltat

        if 'time_window' not in shared:
            d = self.store.make_timing_params(
                conf.time_region[0], conf.time_region[1],
                force=force)

            tmax = math.ceil(d['tmax'] / deltat) * deltat
            tmin = math.floor(d['tmin'] / deltat) * deltat

            shared['time_window'] = tmax - tmin
            shared['tstart'] = tmin

        self.tstart = shared['tstart']
        conf.time_window = shared['time_window']

        self.tmp = tmp
        if self.tmp is not None:
            util.ensuredir(self.tmp)

        util.ensuredir(conf.gf_directory)

        self.qssp_config = conf
示例#7
0
 def testENU(self):
     m = num.matrix(
         [[0.66, 0.53, -0.18], [0.53, -0.70, -0.35], [-0.18, -0.36, 0.04]],
         dtype=num.float)
     m_enu = MomentTensor(m_east_north_up=m)
     self.assertEqual(m[0, 0], m_enu.m()[1, 1])
     self.assertEqual(m[1, 1], m_enu.m()[0, 0])
     self.assertEqual(m[2, 2], m_enu.m()[2, 2])
     self.assertEqual(m[0, 1], m_enu.m()[0, 1])
     self.assertEqual(m[0, 2], -m_enu.m()[1, 2])
     self.assertEqual(m[1, 2], -m_enu.m()[0, 2])
示例#8
0
    def testNonPlainDoubleCouples(self):
        """Convert random MTs to plain double couples and compare angles."""
        for i in range(100):
            ms = [random.random() * 1.0e20 - 0.5e20 for j in range(6)]
            m = num.matrix([[ms[0], ms[3], ms[4]], [ms[3], ms[1], ms[5]], [ms[4], ms[5], ms[2]]], dtype=num.float)

            m1 = MomentTensor(m=m)
            m_plain = m1.m_plain_double_couple()
            m2 = MomentTensor(m=m_plain)

            self.assertAnglesSame(m1, m2)
示例#9
0
    def testNonPlainDoubleCouples(self):
        for i in range(100):
            ms = [random.random() * 1.0e20 - 0.5e20 for j in range(6)]
            m = num.matrix([[ms[0], ms[3], ms[4]], [ms[3], ms[1], ms[5]],
                            [ms[4], ms[5], ms[2]]],
                           dtype=num.float)

            m1 = MomentTensor(m=m)
            m_plain = m1.m_plain_double_couple()
            m2 = MomentTensor(m=m_plain)

            self.assertAnglesSame(m1, m2)
示例#10
0
 def testProps(self):
     m = MomentTensor()
     m.mnn = 1.
     m.mee = -1.
     m.mdd = 0.
     m.mne = 0.
     m.mnd = 0.
     m.med = 0.
     (s1, d1, _), (s2, d2, _) = m.both_strike_dip_rake()
     assert abs(s1 - 45.) < 0.1 or abs(s2 - 45.) < 0.1
示例#11
0
    def testMomentGetterSetter(self):
        m1 = MomentTensor()
        want_mom = 2E7
        m1.moment = want_mom
        sm2 = m1.scalar_moment()
        assert (sm2 == m1.moment)
        assert (abs(sm2 - want_mom) < 1E-8)

        mag = moment_to_magnitude(want_mom)
        assert (m1.magnitude == mag)

        want_mag = 3.5
        m1.magnitude = want_mag
        mom = magnitude_to_moment(want_mag)
        assert (m1.moment == mom)
    def testMomentGetterSetter(self):
        m1 = MomentTensor()
        want_mom = 2E7
        m1.moment = want_mom
        sm2 = m1.scalar_moment()
        assert(sm2 == m1.moment)
        assert(abs(sm2 - want_mom) < 1E-8)

        mag = moment_to_magnitude(want_mom)
        assert(m1.magnitude == mag)

        want_mag = 3.5
        m1.magnitude = want_mag
        mom = magnitude_to_moment(want_mag)
        assert(m1.moment == mom)
    def testRandomRotation(self):
        angles = []
        rstate = num.random.RandomState(10)
        for _ in range(100):
            mt1 = MomentTensor.random_mt(magnitude=-1.0)
            mt2 = mt1.random_rotated(10.0, rstate=rstate)
            angle = kagan_angle(mt1, mt2)
            angles.append(angle)

        assert abs(num.mean(angles) - 8.330) < 0.01

        mt1 = MomentTensor.random_mt(magnitude=-1.0)
        mt2 = mt1.random_rotated(angle=10.0)

        assert abs(kagan_angle(mt1, mt2) - 10.0) < 0.0001
示例#14
0
    def testMomentGetterSetter(self):
        m1 = MomentTensor()
        want_mom = 2e7
        m1.moment = want_mom
        sm2 = m1.scalar_moment()
        assert sm2 == m1.moment
        assert abs(sm2 - want_mom) < 1e-8

        mag = moment_to_magnitude(want_mom)
        assert m1.magnitude == mag

        want_mag = 3.5
        m1.magnitude = want_mag
        mom = magnitude_to_moment(want_mag)
        assert m1.moment == mom
示例#15
0
    def testRandomRotation(self):
        angles = []
        rstate = num.random.RandomState(10)
        for _ in range(100):
            mt1 = MomentTensor.random_mt(magnitude=-1.0)
            mt2 = mt1.random_rotated(10.0, rstate=rstate)
            angle = kagan_angle(mt1, mt2)
            angles.append(angle)

        assert abs(num.mean(angles) - 8.330) < 0.01

        mt1 = MomentTensor.random_mt(magnitude=-1.0)
        mt2 = mt1.random_rotated(angle=10.0)

        assert abs(kagan_angle(mt1, mt2) - 10.0) < 0.0001
示例#16
0
def gen_noise_events(targets, synthetics, engine, noise_sources=1, delay=40):

    noise_events = []
    noise_sources = num.random.choice(10, 1)
    for i in range(0, noise_sources[0]):
        event = gen_random_tectonic_event(i, magmin=-1., magmax=0.1)
        time = rand(event.time - delay, event.time + delay)
        mt = MomentTensor.random_dc(magnitude=event.magnitude)
        source = DCSource(lat=event.lat,
                          lon=event.lon,
                          depth=event.depth,
                          strike=mt.strike1,
                          dip=mt.dip1,
                          rake=mt.rake1,
                          time=time,
                          magnitude=event.magnitude)
        response = engine.process(source, targets)
        noise_traces = response.pyrocko_traces()
        for tr, tr_noise in zip(synthetics, noise_traces):
            noise = trace.Trace(deltat=tr.deltat,
                                tmin=tr.tmin,
                                ydata=tr_noise.ydata)
            choice_ev = num.random.choice(5, 1)
            if choice_ev == 0:
                tr.add(noise)
            else:
                pass
        noise_events.append(event)
    return (noise_events)
示例#17
0
 def testProps(self):
     m = MomentTensor()
     m.mnn = 1.0
     m.mee = -1.0
     m.mdd = 0.0
     m.mne = 0.0
     m.mnd = 0.0
     m.med = 0.0
     (s1, d1, _), (s2, d2, _) = m.both_strike_dip_rake()
     assert abs(s1 - 45.0) < 0.1 or abs(s2 - 45.0) < 0.1
示例#18
0
    def testKagan(self):
        eps = 0.01
        for _ in xrange(500):
            mt1 = MomentTensor.random_mt(magnitude=-1.0)
            assert 0.0 == kagan_angle(mt1, mt1)

            mt1 = MomentTensor.random_dc(magnitude=-1.0)
            assert 0.0 == kagan_angle(mt1, mt1)

            angle = random.random() * 90.0

            rot = rotation_from_angle_and_axis(angle, random_axis())

            mrot = rot.T * mt1.m() * rot
            mt2 = MomentTensor(m=mrot)
            angle2 = kagan_angle(mt1, mt2)

            assert abs(angle - angle2) < eps
示例#19
0
    def testKagan(self):
        eps = 0.01
        for _ in range(500):
            mt1 = MomentTensor.random_mt(magnitude=-1.0)
            assert 0.0 == kagan_angle(mt1, mt1)

            mt1 = MomentTensor.random_dc(magnitude=-1.0)
            assert 0.0 == kagan_angle(mt1, mt1)

            angle = random.random() * 90.

            rot = rotation_from_angle_and_axis(angle, random_axis())

            mrot = rot.T * mt1.m() * rot
            mt2 = MomentTensor(m=mrot)
            angle2 = kagan_angle(mt1, mt2)

            assert abs(angle - angle2) < eps
示例#20
0
    def __init__(self,
                 partial_db_path,
                 output_db_path,
                 gfdb_config,
                 block_nx,
                 qseis_config,
                 cutting=None,
                 extra_traces_dir=None,
                 tag='',
                 tmp=None):
        GFDBBuilder.__init__(self,
                             partial_db_path,
                             output_db_path,
                             gfdb_config,
                             block_nx,
                             extra_traces_dir=extra_traces_dir,
                             tmp=tmp)
        self.qseis_config = qseis_config
        self.tag = tag
        self.cutting = cutting
        self.gfmapping = [
            (MomentTensor(m=symmat6(1, 0, 0, 1, 0, 0)), {
                'r': (1, +1),
                't': (4, +1),
                'z': (6, +1)
            }),
            (MomentTensor(m=symmat6(0, 0, 0, 0, 1, 1)), {
                'r': (2, +1),
                't': (5, +1),
                'z': (7, +1)
            }),
            (MomentTensor(m=symmat6(0, 0, 1, 0, 0, 0)), {
                'r': (3, +1),
                'z': (8, +1)
            }),
        ]

        if gfdb_config['ng'] == 10:
            self.gfmapping.append((MomentTensor(m=symmat6(0, 1, 0, 0, 0, 0)), {
                'r': (9, +1),
                'z': (10, +1)
            }), )
示例#21
0
 def testENU(self):
     m_enu = num.matrix(
         [[0.66, 0.53, -0.18], [0.53, -0.70, -0.35], [-0.18, -0.36, 0.04]],
         dtype=num.float)
     m = MomentTensor(m_east_north_up=m_enu)
     self.assertEqual(m_enu[0, 0], m.m()[1, 1])
     self.assertEqual(m_enu[1, 1], m.m()[0, 0])
     self.assertEqual(m_enu[2, 2], m.m()[2, 2])
     self.assertEqual(m_enu[0, 1], m.m()[0, 1])
     self.assertEqual(m_enu[0, 2], -m.m()[1, 2])
     self.assertEqual(m_enu[1, 2], -m.m()[0, 2])
     self.assertEqual(m_enu[0, 0], m.m6_east_north_up()[0])
     self.assertEqual(m_enu[1, 1], m.m6_east_north_up()[1])
     self.assertEqual(m_enu[2, 2], m.m6_east_north_up()[2])
     self.assertEqual(m_enu[0, 1], m.m6_east_north_up()[3])
     self.assertEqual(m_enu[0, 2], m.m6_east_north_up()[4])
     self.assertEqual(m_enu[1, 2], m.m6_east_north_up()[5])
     self.assertSame(m_enu, m.m_east_north_up(), 1e-3, 'testENU fail')
示例#22
0
    def _parse_mt_page(self, page):
        d = {}
        for k in 'Scale', 'Mrr', 'Mtt', 'Mpp', 'Mrt', 'Mrp', 'Mtp':
            r = k.encode('ascii') + br'\s*=?\s*(\S+)'
            m = re.search(r, page)
            if m:
                s = m.group(1).replace(b'10**', b'1e')
                d[k.lower()] = float(s)

        m = symmat6(*(d[x] for x in 'mrr mtt mpp mrt mrp mtp'.split()))
        m *= d['scale']
        mt = MomentTensor(m_up_south_east=m)

        return mt
示例#23
0
    def retrieve(self, **kwargs):
        import yaml

        kwargs['format'] = 'yaml'

        url = 'http://kinherd.org/quakes/%s' % self.catalog

        f = ws_request(url, **kwargs)

        names = []
        for eq in yaml.safe_load_all(f):
            tref_eq = calendar.timegm(eq['reference_time'].timetuple())
            pset = eq['parametersets'][0]
            tref = calendar.timegm(pset['reference_time'].timetuple())
            tpost = calendar.timegm(pset['posted_time'].timetuple())
            params = pset['parameters']

            mt = MomentTensor(
                    strike=params['strike'],
                    dip=params['dip'], 
                    rake=params['slip_rake'],
                    scalar_moment=params['moment'])

            event = model.Event(
                time = tref + params['time'],
                lat=params['latitude'],
                lon=params['longitude'],
                depth=params['depth'],
                magnitude=params['magnitude'],
                duration=params['rise_time'],
                name = eq['name'],
                catalog=self.catalog,
                moment_tensor = mt)

            event.ext_confidence_intervals = {}
            trans = { 'latitude': 'lat', 'longitude': 'lon' }
            for par in 'latitude longitude depth magnitude'.split():
                event.ext_confidence_intervals[trans.get(par, par)] = \
                        (params[par+'_ci_low'], params[par+'_ci_high'])

            event.ext_posted_time = tpost
            
            name = eq['name']
            self.events[name] = event
            names.append(name)

        return names
示例#24
0
def rand_source(event, SourceType="MT", pressure=None, volume=None):

    if event.moment_tensor is None:
        mt = MomentTensor.random_dc(magnitude=event.magnitude)
        event.moment_tensor = mt
    else:
        mt = event.moment_tensor

    if SourceType == "MT":
        source = MTSource(lat=event.lat,
                          lon=event.lon,
                          north_shift=event.north_shift,
                          east_shift=event.east_shift,
                          depth=event.depth,
                          m6=mt.m6(),
                          time=event.time)

    if SourceType == "explosion":
        source = ExplosionSource(lat=event.lat,
                                 lon=event.lon,
                                 north_shift=event.north_shift,
                                 east_shift=event.east_shift,
                                 depth=event.depth,
                                 time=event.time,
                                 moment=mt.moment)

    if SourceType == "VLVD":
        if volume is None or volume == 0:
            volume = num.random.uniform(0.001, 10000)
            pressure = pressure

        source = VLVDSource(
            lat=event.lat,
            lon=event.lon,
            north_shift=event.north_shift,
            east_shift=event.east_shift,
            depth=event.depth,
            azimuth=mt.strike1,
            dip=mt.dip1,
            time=event.time,
            volume_change=volume,  # here synthetic volume change
            clvd_moment=mt.moment)  # ?

    if SourceType == "PorePressurePointSource":
        source = PorePressurePointSource(
            lat=event.lat,
            lon=event.lon,
            north_shift=event.north_shift,
            east_shift=event.east_shift,
            depth=event.depth,
            pp=num.random.uniform(1, 1),  # here change in pa
            time=event.time)  # ?

    if SourceType == "PorePressureLineSource":
        source = PorePressureLineSource(
            lat=event.lat,
            lon=event.lon,
            north_shift=event.north_shift,
            east_shift=event.east_shift,
            depth=event.depth,
            azimuth=event.strike,
            dip=mt.dip1,
            pp=num.random.uniform(1, 1),  # here change in pa
            time=event.time,
            length=num.random.uniform(1, 20) * km)  # scaling!)

    if SourceType == "Rectangular":
        length = num.random.uniform(0.0001, 0.2) * km
        width = num.random.uniform(0.0001, 0.2) * km
        strike, dip, rake = pmt.random_strike_dip_rake()
        event.moment_tensor = MomentTensor(strike=strike, dip=dip, rake=rake)
        source = RectangularSource(lat=event.lat,
                                   lon=event.lon,
                                   north_shift=event.north_shift,
                                   east_shift=event.east_shift,
                                   depth=event.depth,
                                   strike=strike,
                                   dip=dip,
                                   rake=rake,
                                   length=length,
                                   width=width,
                                   time=event.time,
                                   magnitude=event.magnitude)

    return source, event
示例#25
0
 def testIO(self):
     m1 = MomentTensor(dip=90.0)
     sdr1 = m1.both_strike_dip_rake()
     m2 = guts.load(string=m1.dump())
     sdr2 = m2.both_strike_dip_rake()
     self.assertSame(sdr1, sdr2, 0.1, "failed io via guts")
示例#26
0
 def forwardBackward(self, strike, dip, rake, scalar_moment):
     m1 = MomentTensor(strike=strike, dip=dip, rake=rake, scalar_moment=scalar_moment)
     m2 = MomentTensor(m=m1.m())
     self.assertAnglesSame(m1, m2)
示例#27
0
    def work_block(self, index):
        if len(self.store.config.ns) == 2:
            (sz, firstx), (sz, lastx), (ns, nx) = \
                self.get_block_extents(index)

            rz = self.store.config.receiver_depth
        else:
            (rz, sz, firstx), (rz, sz, lastx), (nr, ns, nx) = \
                self.get_block_extents(index)

        conf = copy.deepcopy(self.qseis_config)

        logger.info('Starting block %i / %i' % (index + 1, self.nblocks))

        conf.source_depth = float(sz / km)
        conf.receiver_depth = float(rz / km)

        runner = QSeisRunner(tmp=self.tmp)

        dx = self.gf_config.distance_delta

        distances = num.linspace(firstx, firstx + (nx - 1) * dx, nx).tolist()

        if distances[-1] < self.gf_config.distance_max:
            # add global max distance, because qseis does some adjustments with
            # this value
            distances.append(self.gf_config.distance_max)

        mmt1 = (MomentTensor(m=symmat6(1, 0, 0, 1, 0, 0)), {
            'r': (0, +1),
            't': (3, +1),
            'z': (5, +1)
        })
        mmt2 = (MomentTensor(m=symmat6(0, 0, 0, 0, 1, 1)), {
            'r': (1, +1),
            't': (4, +1),
            'z': (6, +1)
        })
        mmt3 = (MomentTensor(m=symmat6(0, 0, 1, 0, 0, 0)), {
            'r': (2, +1),
            'z': (7, +1)
        })
        mmt4 = (MomentTensor(m=symmat6(0, 1, 0, 0, 0, 0)), {
            'r': (8, +1),
            'z': (9, +1)
        })

        component_scheme = self.store.config.component_scheme
        off = 0
        if component_scheme == 'elastic8':
            off = 8
        elif component_scheme == 'elastic10':
            off = 10

        msf = (None, {
            'fz.tr': (off + 0, +1),
            'fh.tr': (off + 1, +1),
            'fh.tt': (off + 2, -1),
            'fz.tz': (off + 3, +1),
            'fh.tz': (off + 4, +1)
        })

        if component_scheme == 'elastic5':
            gfsneeded = (0, 0, 0, 0, 1, 1)
            gfmapping = [msf]

        elif component_scheme == 'elastic8':
            gfsneeded = (1, 1, 1, 1, 0, 0)
            gfmapping = [mmt1, mmt2, mmt3]

        elif component_scheme == 'elastic10':
            gfsneeded = (1, 1, 1, 1, 0, 0)
            gfmapping = [mmt1, mmt2, mmt3, mmt4]

        elif component_scheme == 'elastic13':
            gfsneeded = (1, 1, 1, 1, 1, 1)
            gfmapping = [mmt1, mmt2, mmt3, msf]

        elif component_scheme == 'elastic15':
            gfsneeded = (1, 1, 1, 1, 1, 1)
            gfmapping = [mmt1, mmt2, mmt3, mmt4, msf]

        conf.gf_sw_source_types = gfsneeded
        conf.receiver_distances = [d / km for d in distances]
        conf.receiver_azimuths = [0.0] * len(distances)

        for mt, gfmap in gfmapping:
            if mt:
                m = mt.m()
                f = float
                conf.source_mech = QSeisSourceMechMT(mnn=f(m[0, 0]),
                                                     mee=f(m[1, 1]),
                                                     mdd=f(m[2, 2]),
                                                     mne=f(m[0, 1]),
                                                     mnd=f(m[0, 2]),
                                                     med=f(m[1, 2]))
            else:
                conf.source_mech = None

            if any(conf.gf_sw_source_types) or conf.source_mech is not None:
                runner.run(conf)

            if any(c in gfmap for c in qseis_components):
                rawtraces = runner.get_traces('seis')
            else:
                rawtraces = runner.get_traces('gf')

            interrupted = []

            def signal_handler(signum, frame):
                interrupted.append(True)

            original = signal.signal(signal.SIGINT, signal_handler)
            self.store.lock()
            duplicate_inserts = 0
            try:
                for itr, tr in enumerate(rawtraces):
                    if tr.channel not in gfmap:
                        continue

                    x = tr.meta['distance']
                    if x > firstx + (nx - 1) * dx:
                        continue

                    ig, factor = gfmap[tr.channel]

                    if len(self.store.config.ns) == 2:
                        args = (sz, x, ig)
                    else:
                        args = (rz, sz, x, ig)

                    if conf.cut:
                        tmin = self.store.t(conf.cut[0], args[:-1])
                        tmax = self.store.t(conf.cut[1], args[:-1])

                        if None in (tmin, tmax):
                            continue

                        tr.chop(tmin, tmax)

                    tmin = tr.tmin
                    tmax = tr.tmax

                    if conf.fade:
                        ta, tb, tc, td = [
                            self.store.t(v, args[:-1]) for v in conf.fade
                        ]

                        if None in (ta, tb, tc, td):
                            continue

                        if not (ta <= tb and tb <= tc and tc <= td):
                            raise QSeisError('invalid fade configuration')

                        t = tr.get_xdata()
                        fin = num.interp(t, [ta, tb], [0., 1.])
                        fout = num.interp(t, [tc, td], [1., 0.])
                        anti_fin = 1. - fin
                        anti_fout = 1. - fout

                        y = tr.ydata

                        sum_anti_fin = num.sum(anti_fin)
                        sum_anti_fout = num.sum(anti_fout)

                        if sum_anti_fin != 0.0:
                            yin = num.sum(anti_fin * y) / sum_anti_fin
                        else:
                            yin = 0.0

                        if sum_anti_fout != 0.0:
                            yout = num.sum(anti_fout * y) / sum_anti_fout
                        else:
                            yout = 0.0

                        y2 = anti_fin * yin + fin * fout * y + anti_fout * yout

                        if conf.relevel_with_fade_in:
                            y2 -= yin

                        tr.set_ydata(y2)

                    gf_tr = gf.store.GFTrace.from_trace(tr)
                    gf_tr.data *= factor

                    try:
                        self.store.put(args, gf_tr)
                    except gf.store.DuplicateInsert:
                        duplicate_inserts += 1

            finally:
                if duplicate_inserts:
                    logger.warn('%i insertions skipped (duplicates)' %
                                duplicate_inserts)

                self.store.unlock()
                signal.signal(signal.SIGINT, original)

            if interrupted:
                raise KeyboardInterrupt()

            conf.gf_sw_source_types = (0, 0, 0, 0, 0, 0)

        logger.info('Done with block %i / %i' % (index + 1, self.nblocks))
示例#28
0
    def work_block(self, index):
        if len(self.store.config.ns) == 2:
            (sz, firstx), (sz, lastx), (ns, nx) = \
                self.get_block_extents(index)

            rz = self.store.config.receiver_depth
        else:
            (rz, sz, firstx), (rz, sz, lastx), (nr, ns, nx) = \
                self.get_block_extents(index)

        conf = copy.deepcopy(self.ahfullgreen_config)

        logger.info('Starting block %i / %i' % (index + 1, self.nblocks))

        conf.source_depth = float(sz)
        conf.receiver_depth = float(rz)

        runner = AhfullgreenRunner(tmp=self.tmp)

        dx = self.gf_config.distance_delta

        distances = num.linspace(firstx, firstx + (nx - 1) * dx, nx).tolist()

        mmt1 = (MomentTensor(m=symmat6(1, 0, 0, 1, 0, 0)), {
            'r': (0, +1),
            't': (3, +1),
            'z': (5, +1)
        })
        mmt2 = (MomentTensor(m=symmat6(0, 0, 0, 0, 1, 1)), {
            'r': (1, +1),
            't': (4, +1),
            'z': (6, +1)
        })
        mmt3 = (MomentTensor(m=symmat6(0, 0, 1, 0, 0, 0)), {
            'r': (2, +1),
            'z': (7, +1)
        })
        mmt4 = (MomentTensor(m=symmat6(0, 1, 0, 0, 0, 0)), {
            'r': (8, +1),
            'z': (9, +1)
        })

        component_scheme = self.store.config.component_scheme

        if component_scheme == 'elastic8':
            gfmapping = [mmt1, mmt2, mmt3]

        if component_scheme == 'elastic10':
            gfmapping = [mmt1, mmt2, mmt3, mmt4]

        conf.receiver_distances = distances

        for mt, gfmap in gfmapping:
            if mt:
                conf.source_mech = mt
            else:
                conf.source_mech = None

            if conf.source_mech is not None:
                runner.run(conf)

            rawtraces = runner.get_traces()
            interrupted = []

            def signal_handler(signum, frame):
                interrupted.append(True)

            original = signal.signal(signal.SIGINT, signal_handler)
            self.store.lock()
            duplicate_inserts = 0
            try:
                for itr, tr in enumerate(rawtraces):
                    if tr.channel not in gfmap:
                        logger.debug('%s not in gfmap' % tr.channel)
                        continue

                    x = tr.meta['distance']
                    if x > firstx + (nx - 1) * dx:
                        logger.error("x out of range")
                        continue

                    ig, factor = gfmap[tr.channel]

                    if len(self.store.config.ns) == 2:
                        args = (sz, x, ig)
                    else:
                        args = (rz, sz, x, ig)
                    if conf.cut:
                        tmin = self.store.t(conf.cut[0], args[:-1])
                        tmin = math.floor(tmin / conf.deltat) * conf.deltat
                        tmax = self.store.t(conf.cut[1], args[:-1])
                        tmax = math.ceil(tmax / conf.deltat) * conf.deltat
                        if None in (tmin, tmax):
                            continue
                        tr.chop(tmin, tmax)

                    tr = tr.snap()

                    if conf.fade:
                        ta, tb, tc, td = [
                            self.store.t(v, args[:-1]) for v in conf.fade
                        ]

                        if None in (ta, tb, tc, td):
                            continue

                        if not (ta <= tb and tb <= tc and tc <= td):
                            raise AhfullgreenError(
                                'invalid fade configuration')

                        t = tr.get_xdata()
                        fin = num.interp(t, [ta, tb], [0., 1.])
                        fout = num.interp(t, [tc, td], [1., 0.])
                        anti_fin = 1. - fin
                        anti_fout = 1. - fout

                        y = tr.ydata

                        sum_anti_fin = num.sum(anti_fin)
                        sum_anti_fout = num.sum(anti_fout)

                        if sum_anti_fin != 0.0:
                            yin = num.sum(anti_fin * y) / sum_anti_fin
                        else:
                            yin = 0.0

                        if sum_anti_fout != 0.0:
                            yout = num.sum(anti_fout * y) / sum_anti_fout
                        else:
                            yout = 0.0

                        y2 = anti_fin * yin + fin * fout * y + anti_fout * yout

                        if conf.relevel_with_fade_in:
                            y2 -= yin

                        tr.set_ydata(y2)
                    gf_tr = gf.store.GFTrace.from_trace(tr)
                    gf_tr.data *= factor

                    try:
                        self.store.put(args, gf_tr)
                    except gf.store.DuplicateInsert:
                        duplicate_inserts += 1

            finally:
                if duplicate_inserts:
                    logger.warn('%i insertions skipped (duplicates)' %
                                duplicate_inserts)

                self.store.unlock()
                signal.signal(signal.SIGINT, original)

            if interrupted:
                raise KeyboardInterrupt()

            conf.gf_sw_source_types = (0, 0, 0, 0, 0, 0)

        logger.info('Done with block %i / %i' % (index + 1, self.nblocks))
示例#29
0
    def work_block(self, index):
        if len(self.store.config.ns) == 2:
            (sz, firstx), (sz, lastx), (ns, nx) = \
                self.get_block_extents(index)

            rz = self.store.config.receiver_depth
        else:
            (rz, sz, firstx), (rz, sz, lastx), (nr, ns, nx) = \
                self.get_block_extents(index)

        logger.info('Starting block %i / %i' % (index + 1, self.nblocks))

        dx = self.gf_config.distance_delta

        distances = num.linspace(firstx, firstx + (nx - 1) * dx, nx).tolist()

        mmt1 = (MomentTensor(m=symmat6(1, 0, 0, 1, 0, 0)), {
            'r': (0, +1),
            't': (3, +1),
            'z': (5, +1)
        })
        mmt2 = (MomentTensor(m=symmat6(0, 0, 0, 0, 1, 1)), {
            'r': (1, +1),
            't': (4, +1),
            'z': (6, +1)
        })
        mmt3 = (MomentTensor(m=symmat6(0, 0, 1, 0, 0, 0)), {
            'r': (2, +1),
            'z': (7, +1)
        })
        mmt4 = (MomentTensor(m=symmat6(0, 1, 0, 0, 0, 0)), {
            'r': (8, +1),
            'z': (9, +1)
        })
        mmt0 = (MomentTensor(m=symmat6(1, 1, 1, 0, 0, 0)), {
            'r': (0, +1),
            'z': (1, +1)
        })

        component_scheme = self.store.config.component_scheme

        if component_scheme == 'elastic8':
            gfmapping = [mmt1, mmt2, mmt3]

        elif component_scheme == 'elastic10':
            gfmapping = [mmt1, mmt2, mmt3, mmt4]

        elif component_scheme == 'elastic2':
            gfmapping = [mmt0]

        elif component_scheme == 'elastic5':
            gfmapping = [((1., 1., 0.), {
                'r': (1, +1),
                'z': (4, +1),
                't': (2, +1)
            }), ((0., 0., 1.), {
                'r': (0, +1),
                'z': (3, +1)
            })]

        else:
            raise gf.UnavailableScheme(
                'fomosto backend "ahfullgreen" cannot handle component scheme '
                '"%s"' % component_scheme)

        for source_mech, gfmap in gfmapping:

            rawtraces = make_traces(
                self.store.config.earthmodel_1d.require_homogeneous(),
                source_mech, 1.0 / self.store.config.sample_rate, distances,
                num.zeros_like(distances), sz, rz)

            interrupted = []

            def signal_handler(signum, frame):
                interrupted.append(True)

            original = signal.signal(signal.SIGINT, signal_handler)
            self.store.lock()
            duplicate_inserts = 0
            try:
                for itr, tr in enumerate(rawtraces):
                    if tr.channel not in gfmap:
                        logger.debug('%s not in gfmap' % tr.channel)
                        continue

                    x = tr.meta['distance']
                    if x > firstx + (nx - 1) * dx:
                        logger.error("x out of range")
                        continue

                    ig, factor = gfmap[tr.channel]

                    if len(self.store.config.ns) == 2:
                        args = (sz, x, ig)
                    else:
                        args = (rz, sz, x, ig)

                    tr = tr.snap()

                    gf_tr = gf.store.GFTrace.from_trace(tr)
                    gf_tr.data *= factor

                    try:
                        self.store.put(args, gf_tr)
                    except gf.store.DuplicateInsert:
                        duplicate_inserts += 1

            finally:
                if duplicate_inserts:
                    logger.warn('%i insertions skipped (duplicates)' %
                                duplicate_inserts)

                self.store.unlock()
                signal.signal(signal.SIGINT, original)

            if interrupted:
                raise KeyboardInterrupt()

        logger.info('Done with block %i / %i' % (index + 1, self.nblocks))
示例#30
0
 def testIO(self):
     m1 = MomentTensor(dip=90.)
     sdr1 = m1.both_strike_dip_rake()
     m2 = guts.load(string=m1.dump())
     sdr2 = m2.both_strike_dip_rake()
     self.assertSame(sdr1, sdr2, 0.1, 'failed io via guts')
示例#31
0
    def work_block(self, iblock):
        if len(self.store.config.ns) == 2:
            (sz, firstx), (sz, lastx), (ns, nx) = \
                self.get_block_extents(iblock)

            rz = self.store.config.receiver_depth
        else:
            (rz, sz, firstx), (rz, sz, lastx), (nr, ns, nx) = \
                self.get_block_extents(iblock)

        source_depth = float(sz / km)
        conf_s = copy.deepcopy(self.qseis_s_config)
        conf_r = copy.deepcopy(self.qseis_r_config)

        gf_directory = op.abspath(self.qseis_baseconf.gf_directory)

        fk_path = op.join(gf_directory, 'green_%.3fkm.fk' % source_depth)
        info_path = op.join(gf_directory, 'green_%.3fkm.info' % source_depth)

        conf_s.fk_path = fk_path
        conf_s.info_path = info_path

        conf_r.fk_path = fk_path
        conf_r.info_path = info_path

        if self.step == 0 and os.path.isfile(fk_path):
            logger.info('Skipping step %i / %i, block %i / %i'
                        '(GF already exists)' %
                        (self.step + 1, self.nsteps, iblock + 1, self.nblocks))
            return

        logger.info('Starting step %i / %i, block %i / %i' %
                    (self.step + 1, self.nsteps, iblock + 1, self.nblocks))

        dx = self.gf_config.distance_delta
        conf_r.wavelet_duration = 0.001 * self.gf_config.sample_rate

        if self.step == 0:
            conf_s.source_depth = source_depth
            runner = QSeisSRunner(tmp=self.tmp)
            runner.run(conf_s)

        else:
            conf_r.receiver = QSeisRReceiver(lat=90 - firstx * cake.m2d,
                                             lon=180.,
                                             tstart=0.0,
                                             distance=firstx)
            conf_r.source = QSeis2dSource(lat=90 - 0.001 * dx * cake.m2d,
                                          lon=0.0,
                                          depth=source_depth)

            runner = QSeisRRunner(tmp=self.tmp)

            mmt1 = (MomentTensor(m=symmat6(1, 0, 0, 1, 0, 0)), {
                'r': (0, 1),
                't': (3, 1),
                'z': (5, 1)
            })
            mmt2 = (MomentTensor(m=symmat6(0, 0, 0, 0, 1, 1)), {
                'r': (1, 1),
                't': (4, 1),
                'z': (6, 1)
            })
            mmt3 = (MomentTensor(m=symmat6(0, 0, 1, 0, 0, 0)), {
                'r': (2, 1),
                'z': (7, 1)
            })
            mmt4 = (MomentTensor(m=symmat6(0, 1, 0, 0, 0, 0)), {
                'r': (8, 1),
                'z': (9, 1)
            })

            gfmapping = [mmt1, mmt2, mmt3, mmt4]

            for mt, gfmap in gfmapping:
                if mt:
                    m = mt.m()
                    f = float
                    conf_r.source_mech = QSeisRSourceMechMT(mnn=f(m[0, 0]),
                                                            mee=f(m[1, 1]),
                                                            mdd=f(m[2, 2]),
                                                            mne=f(m[0, 1]),
                                                            mnd=f(m[0, 2]),
                                                            med=f(m[1, 2]))
                else:
                    conf_r.source_mech = None

                if conf_r.source_mech is not None:
                    runner.run(conf_r)

                rawtraces = runner.get_traces()

                interrupted = []

                def signal_handler(signum, frame):
                    interrupted.append(True)

                original = signal.signal(signal.SIGINT, signal_handler)
                self.store.lock()
                duplicate_inserts = 0
                try:
                    for itr, tr in enumerate(rawtraces):
                        if tr.channel not in gfmap:
                            continue

                        x = tr.meta['distance']
                        if x > firstx + (nx - 1) * dx:
                            continue

                        ig, factor = gfmap[tr.channel]

                        if len(self.store.config.ns) == 2:
                            args = (sz, x, ig)
                        else:
                            args = (rz, sz, x, ig)

                        if self.qseis_baseconf.cut:
                            tmin = self.store.t(self.qseis_baseconf.cut[0],
                                                args[:-1])
                            tmax = self.store.t(self.qseis_baseconf.cut[1],
                                                args[:-1])

                            if None in (tmin, tmax):
                                continue

                            tr.chop(tmin, tmax)

                        tmin = tr.tmin
                        tmax = tr.tmax

                        if self.qseis_baseconf.fade:
                            ta, tb, tc, td = [
                                self.store.t(v, args[:-1])
                                for v in self.qseis_baseconf.fade
                            ]

                            if None in (ta, tb, tc, td):
                                continue

                            if not (ta <= tb and tb <= tc and tc <= td):
                                raise QSeis2dError(
                                    'invalid fade configuration')

                            t = tr.get_xdata()
                            fin = num.interp(t, [ta, tb], [0., 1.])
                            fout = num.interp(t, [tc, td], [1., 0.])
                            anti_fin = 1. - fin
                            anti_fout = 1. - fout

                            y = tr.ydata

                            sum_anti_fin = num.sum(anti_fin)
                            sum_anti_fout = num.sum(anti_fout)

                            if sum_anti_fin != 0.0:
                                yin = num.sum(anti_fin * y) / sum_anti_fin
                            else:
                                yin = 0.0

                            if sum_anti_fout != 0.0:
                                yout = num.sum(anti_fout * y) / sum_anti_fout
                            else:
                                yout = 0.0

                            y2 = anti_fin * yin + \
                                fin * fout * y + \
                                anti_fout * yout

                            if self.qseis_baseconf.relevel_with_fade_in:
                                y2 -= yin

                            tr.set_ydata(y2)

                        gf_tr = gf.store.GFTrace.from_trace(tr)
                        gf_tr.data *= factor

                        try:
                            self.store.put(args, gf_tr)
                        except gf.store.DuplicateInsert:
                            duplicate_inserts += 1

                finally:
                    if duplicate_inserts:
                        logger.warn('%i insertions skipped (duplicates)' %
                                    duplicate_inserts)

                    self.store.unlock()
                    signal.signal(signal.SIGINT, original)

                if interrupted:
                    raise KeyboardInterrupt()

            logger.info('Done with step %i / %i, block %i / %i' %
                        (self.step + 1, self.nsteps, iblock + 1, self.nblocks))