Beispiel #1
0
 def pyrocko_station(network_code, station, location):
     return model.Station(network=network_code,
                          station=station.code(),
                          location=location.code(),
                          lat=location.latitude(),
                          lon=location.longitude(),
                          elevation=location.elevation())
Beispiel #2
0
def grok_station_xml(data, tmin, tmax):

    stations = {}

    for (sta, sta_epo, cha, cha_epo) in xmlzip(data, (
            'Station', 'StationEpoch', 'Channel', 'Epoch')):

        sta_beg, sta_end, cha_beg, cha_end = [tdatetime(x) for x in (
            sta_epo.StartDate, sta_epo.EndDate, cha_epo.StartDate,
            cha_epo.EndDate)]

        if not (sta_beg <= tmin and tmax <= sta_end and
                cha_beg <= tmin and tmax <= cha_end):

            continue

        nslc = tuple([str(x.strip()) for x in (
            sta.net_code, sta.sta_code, cha.loc_code, cha.chan_code)])

        lat, lon, ele, dep, azi, dip = [
            float(cha_epo.attrs[x])
            for x in 'Lat Lon Elevation Depth Azimuth Dip'.split()]

        nsl = nslc[:3]
        if nsl not in stations:
            stations[nsl] = model.Station(
                nsl[0], nsl[1], nsl[2], lat, lon, ele, dep)

        stations[nsl].add_channel(model.Channel(nslc[-1], azi, dip))

    return stations.values()
def station_distribution(origin, rings, **kwargs):
    '''
    origin is a tuple with (lat, lon).
    rings is a list of lists with [radius, n stations].
    '''
    rotate = {}
    if kwargs.get('rotate', False):
        rotate = kwargs['rotate']

    stations = []
    olat, olon = origin
    for radius, N in rings:
        azis = [360. * (n + 1) / N for n in range(N)]

        try:
            azis = [azi + rotate[radius] for azi in azis]
            map((lambda x: x % 360), azis)
        except KeyError:
            pass

        for azi in azis:
            lat, lon = lat_lon_from_dist_azi(olat, olon, radius, azi)
            stations.append(
                model.Station(network=str(azi_to_location_digits(azi)),
                              station=str(x_to_station_digits(radius)),
                              lat=lat,
                              lon=lon))

    return stations
Beispiel #4
0
    def get_stations(self):
        if self._stations is None:

            if self.with_channels:
                channels = []
                for comp in ('BHN', 'BHE', 'BHZ'):
                    channels.append(model.station.Channel(comp))
            else:
                channels = None

            stations = []
            for istation in range(self.nstations):
                lat, lon = self.get_latlon(istation)

                net, sta, loc = self.nsl(istation)
                station = model.Station(net,
                                        sta,
                                        loc,
                                        lat=lat,
                                        lon=lon,
                                        channels=channels)

                stations.append(station)

            self._stations = stations

        return self._stations
Beispiel #5
0
    def testProjectionsZOnly(self):
        km = 1000.

        ev = model.Event(lat=-10, lon=150., depth=0.0)

        for azi in num.linspace(0., 360., 37):
            lat, lon = orthodrome.ne_to_latlon(ev.lat, ev.lon,
                                               10. * km * math.cos(azi),
                                               10. * km * math.sin(azi))

            sta = model.Station(lat=lat, lon=lon)
            sta.set_event_relative_data(ev)
            sta.set_channels_by_name('BHZ', 'BHN', 'BHE')
            traces = [
                trace.Trace(channel='BHZ', ydata=num.array([1.0])),
            ]

            projected = []
            for m, in_channels, out_channels in sta.guess_projections_to_enu():
                projected.extend(
                    trace.project(traces, m, in_channels, out_channels))

            def g(traces, cha):
                for tr in traces:
                    if tr.channel == cha:
                        return tr

            z = g(projected, 'U')
            assert (near(z.ydata[0], 1.0, 0.001))
Beispiel #6
0
    def get_stations(self):
        if self._stations is None:

            if self.channels:
                channels = [model.station.Channel(c) for c in self.channels]
            else:
                channels = None

            stations = []
            for istation in range(self.nstations):
                lat, lon = self.get_latlon(istation)

                net, sta, loc = self.nsl(istation)
                station = model.Station(net,
                                        sta,
                                        loc,
                                        lat=lat,
                                        lon=lon,
                                        channels=channels)

                stations.append(station)

            self._stations = stations

        return self._stations
Beispiel #7
0
    def get_stations(self):
        if self._stations is None:

            if self.channels:
                channels = [model.station.Channel(c) for c in self.channels]
            else:
                channels = None

            stations = []
            for istation in range(self.nstations):
                lat, lon, north_shift, east_shift, depth = map(
                    float, self.get_coordinates(istation))

                net, sta, loc = self.nsl(istation)
                station = model.Station(net,
                                        sta,
                                        loc,
                                        lat=lat,
                                        lon=lon,
                                        north_shift=north_shift,
                                        east_shift=east_shift,
                                        depth=depth,
                                        channels=channels)

                stations.append(station)

            self._stations = stations

        return self._stations
Beispiel #8
0
def setup_stations(lats, lons, names, networks, event, rotate=True):
    """
    Setup station objects, based on station coordinates and reference event.

    Parameters
    ----------
    lats : :class:`num.ndarray`
        of station location latitude
    lons : :class:`num.ndarray`
        of station location longitude
    names : list
        of strings of station names
    networks : list
        of strings of network names for each station
    event : :class:`pyrocko.model.Event`

    Results
    -------
    stations : list
        of :class:`pyrocko.model.Station`
    """

    stations = []
    for lat, lon, name, network in zip(lats, lons, names, networks):
        s = model.Station(lat=lat, lon=lon, station=name, network=network)
        s.set_event_relative_data(event)
        s.set_channels_by_name('E', 'N', 'Z')
        if rotate:
            p = s.guess_projections_to_rtu(out_channels=('R', 'T', 'Z'))
        s.set_channels(p[0][2])
        stations.append(s)

    return stations
Beispiel #9
0
    def test_conversions(self):

        from pyrocko import model
        from pyrocko.fdsn import station, resp, enhanced_sacpz

        t = util.str_to_time('2014-01-01 00:00:00')
        codes = 'GE', 'EIL', '', 'BHZ'

        resp_fpath = common.test_data_file('test1.resp')
        stations = [
            model.Station(*codes[:3],
                          lat=29.669901,
                          lon=34.951199,
                          elevation=210.0,
                          depth=0.0)
        ]

        sx_resp = resp.make_stationxml(stations,
                                       resp.iload_filename(resp_fpath))
        pr_sx_resp = sx_resp.get_pyrocko_response(codes,
                                                  time=t,
                                                  fake_input_units='M/S')
        pr_evresp = trace.Evalresp(resp_fpath,
                                   nslc_id=codes,
                                   target='vel',
                                   time=t)

        sacpz_fpath = common.test_data_file('test1.sacpz')
        sx_sacpz = enhanced_sacpz.make_stationxml(
            enhanced_sacpz.iload_filename(sacpz_fpath))
        pr_sx_sacpz = sx_sacpz.get_pyrocko_response(codes,
                                                    time=t,
                                                    fake_input_units='M/S')
        pr_sacpz = trace.PoleZeroResponse(*pz.read_sac_zpk(sacpz_fpath))
        try:
            pr_sacpz.zeros.remove(0.0j)
        except ValueError:
            pr_sacpz.poles.append(0.0j)

        sxml_geofon_fpath = common.test_data_file('test1.stationxml')
        sx_geofon = station.load_xml(filename=sxml_geofon_fpath)
        pr_sx_geofon = sx_geofon.get_pyrocko_response(codes,
                                                      time=t,
                                                      fake_input_units='M/S')

        sxml_iris_fpath = common.test_data_file('test2.stationxml')
        sx_iris = station.load_xml(filename=sxml_iris_fpath)
        pr_sx_iris = sx_iris.get_pyrocko_response(codes,
                                                  time=t,
                                                  fake_input_units='M/S')

        freqs = num.logspace(num.log10(0.001), num.log10(1.0), num=1000)
        tf_ref = pr_evresp.evaluate(freqs)
        for pr in [
                pr_sx_resp, pr_sx_sacpz, pr_sacpz, pr_sx_geofon, pr_sx_iris
        ]:
            tf = pr.evaluate(freqs)
            # plot_tfs(freqs, [tf_ref, tf])
            assert cnumeqrel(tf_ref, tf, 0.01)
Beispiel #10
0
def snuffle(config):
    global _lassie_config
    _lassie_config = copy.deepcopy(config)
    for _ifc in _lassie_config.image_function_contributions:
        _ifc.setup(config)

    def load_snuffling(win):
        s = LassieSnuffling()
        s.config = _lassie_config
        s.setup()
        win.pile_viewer.viewer.add_snuffling(s, reloaded=True)
        win.pile_viewer.viewer.add_blacklist_pattern('*.SMAX.i.*')
        for bl in _lassie_config.blacklist:
            win.pile_viewer.viewer.add_blacklist_pattern('%s.*' % bl)

        detections_path = _lassie_config.get_detections_path()

        if os.path.exists(detections_path):
            s.detections = detections_to_event_markers(detections_path)
            s.add_markers(s.detections)

        for _ifc in s.config.image_function_contributions:
            if isinstance(_ifc, ifc.ManualPickIFC):
                markers_path_extra = _ifc.picks_path
            elif isinstance(_ifc, ifc.TemplateMatchingIFC):
                markers_path_extra = _ifc.template_markers_path
            else:
                continue

            if os.path.exists(markers_path_extra):
                s.add_markers(pmarker.load_markers(markers_path_extra))
            else:
                logger.warn(
                    'No such file: %s (referenced in %s, named %s)' %
                    (markers_path_extra, _ifc.__class__.__name__, _ifc.name))

    receivers = config.get_receivers()
    stations = set()
    lats, lons = geo.points_coords(receivers, system='latlon')
    for ir, (lat, lon) in enumerate(zip(lats, lons)):
        n, s, l = receivers[ir].codes[:3]
        stations.add(
            model.Station(lat=lat, lon=lon, network=n, station=s, location=l))

    paths = config.expand_path(config.data_paths)
    paths.append(config.get_ifm_dir_path())

    p = pile.make_pile(paths=paths, fileformat='detect')

    meta = {'tabu': True}
    for tr in p.iter_traces(trace_selector=lambda x: x.station == 'SMAX'):
        if tr.meta:
            tr.meta.update(meta)
        else:
            tr.meta = meta

    snuffler.snuffle(p, stations=stations, launch_hook=load_snuffling)
Beispiel #11
0
    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)

        nsamples = 10
        ntargets = 30
        npatches = 40
        sample_rate = 2.

        self.times = get_random_uniform(300., 500., ntargets)

        self.starttime_min = 0.
        self.starttime_max = 15.
        starttime_sampling = 0.5
        nstarttimes = int(
            (self.starttime_max - self.starttime_min) / starttime_sampling) + 1

        self.duration_min = 5.
        self.duration_max = 10.
        duration_sampling = 0.5
        self.ndurations = int(
            (self.duration_max - self.duration_min) / duration_sampling) + 1

        durations = num.linspace(self.duration_min, self.duration_max,
                                 self.ndurations)
        starttimes = num.linspace(self.starttime_min, self.starttime_max,
                                  nstarttimes)

        lats = num.random.randint(low=-90, high=90, size=ntargets)
        lons = num.random.randint(low=-180, high=180, size=ntargets)

        stations = [
            model.Station(lat=lat, lon=lon) for lat, lon in zip(lats, lons)
        ]

        targets = [
            DynamicTarget(store_id='Test_em_2.000_0') for i in range(ntargets)
        ]

        wavemap = WaveformMapping(name='any_P',
                                  stations=stations,
                                  targets=targets)

        # TODO needs updating
        #self.gfs = ffi.SeismicGFLibrary(
        #    wavemap=wavemap, component='uperp',
        #    duration_sampling=duration_sampling,
        #    starttime_sampling=starttime_sampling,
        #    starttime_min=self.starttime_min,
        #    duration_min=self.duration_min)
        #self.gfs.setup(
        #    ntargets, npatches, self.ndurations, nstarttimes,
        #    nsamples, allocate=True)

        tracedata = num.tile(num.arange(nsamples), nstarttimes).reshape(
            (nstarttimes, nsamples))
Beispiel #12
0
def receivers_to_stations(receivers):
    stations = []
    for rec in receivers:
        stations.append(
            model.Station(network=rec.get_network(),
                          station=rec.get_station(),
                          location=rec.get_location(),
                          lat=float(rec.lat),
                          lon=float(rec.lon),
                          depth=float(rec.depth)))
    return stations
Beispiel #13
0
    def testIOStations(self):
        tempdir = self.make_tempdir()
        fn = pjoin(tempdir, 'stations.txt')

        ne = model.Channel('NE', azimuth=45., dip=0.)
        se = model.Channel('SE', azimuth=135., dip=0.)
        stations = [
            model.Station('', sta, '', 0., 0., 0., channels=[ne, se])
            for sta in ['STA1', 'STA2']]

        model.dump_stations(stations, fn)
        stations = model.load_stations(fn)
Beispiel #14
0
def load_stations(fn):

    f = open(fn,'r')
    stations = []
    for line in f:

        data = line.split()
        s = model.Station(lat=float(data[1])/100000., lon=float(data[2])/100000., depth=-float(data[3]))
        s.my_x = float(data[4])
        s.my_y = float(data[5])

        stations.append(s)
    return stations
Beispiel #15
0
    def testMissingComponents(self):

        ne = model.Channel('NE', azimuth=45., dip=0.)
        se = model.Channel('SE', azimuth=135., dip=0.)

        station = model.Station('', 'STA', '', 0., 0., 0., channels=[ne, se])

        mat = station.projection_to_enu(('NE', 'SE', 'Z'), ('E', 'N', 'U'))[0]
        assertOrtho(mat[:, 0], mat[:, 1], mat[:, 2])

        n = model.Channel('D', azimuth=0., dip=90.)
        station.set_channels([n])
        mat = station.projection_to_enu(('N', 'E', 'D'), ('E', 'N', 'U'))[0]
        assertOrtho(mat[:, 0], mat[:, 1], mat[:, 2])
Beispiel #16
0
def receiver_to_station(rec):
    channels = []
    for comp in rec.components:
        channels.append(kiwi_channels[comp])

    sta = model.Station(rec.get_network(),
                        rec.get_station(),
                        rec.get_location(),
                        rec.lat,
                        rec.lon,
                        0.0,
                        depth=rec.depth,
                        channels=channels)
    return sta
Beispiel #17
0
def pyrocko_station_from_channels(nsl, channels, inconsistencies='warn'):

    pos = lat, lon, elevation, depth = \
        channels[0].position_values

    if not all(pos == x.position_values for x in channels):
        info = '\n'.join('    %s: %s' % (x.code, x.position_values)
                         for x in channels)

        mess = 'encountered inconsistencies in channel ' \
               'lat/lon/elevation/depth ' \
               'for %s.%s.%s: \n%s' % (nsl + (info,))

        if inconsistencies == 'raise':
            raise InconsistentChannelLocations(mess)

        elif inconsistencies == 'warn':
            logger.warn(mess)
            logger.warn(' -> using mean values')

    apos = num.array([x.position_values for x in channels], dtype=num.float)
    mlat, mlon, mele, mdep = num.nansum(apos, axis=0) \
        / num.sum(num.isfinite(apos), axis=0)

    groups = {}
    for channel in channels:
        if channel.code not in groups:
            groups[channel.code] = []

        groups[channel.code].append(channel)

    pchannels = []
    for code in sorted(groups.keys()):
        data = [(channel.code, value_or_none(channel.azimuth),
                 value_or_none(channel.dip)) for channel in groups[code]]

        azimuth, dip = util.consistency_merge(
            data,
            message='channel orientation values differ:',
            error=inconsistencies)

        pchannels.append(model.Channel(code, azimuth=azimuth, dip=dip))

    return model.Station(*nsl,
                         lat=mlat,
                         lon=mlon,
                         elevation=mele,
                         depth=mdep,
                         channels=pchannels)
Beispiel #18
0
    def testIOStations(self):
        tempdir = tempfile.mkdtemp(prefix='pyrocko-model')
        fn = pjoin(tempdir, 'stations.txt')

        ne = model.Channel('NE', azimuth=45., dip=0.)
        se = model.Channel('SE', azimuth=135., dip=0.)
        stations = [
            model.Station('', sta, '', 0., 0., 0., channels=[ne, se])
            for sta in ['STA1', 'STA2']
        ]

        model.dump_stations(stations, fn)
        stations = model.load_stations(fn)

        shutil.rmtree(tempdir)
Beispiel #19
0
    def to_station(self):
        net, sta, loc, cha = self.sc_name.nslc()
        station = model.Station(
            network=net,
            station=sta,
            location=loc,
            lat=self.st_lat,
            lon=self.st_long,
            elevation=self.elev)

        station.add_channel(
            model.Channel(
                name=cha,
                azimuth=self.azim,
                dip=self.incid - 90.))

        return station
Beispiel #20
0
 def _get_stations_from_file(self):
     fn = pjoin(self._dirpath, 'stations.txt')
     f = open(fn, 'r')
     stations = []
     for line in f:
         if line.strip().startswith('#'): continue
         toks = line.split()
         if len(toks) != 5: continue
         net,sta,loc = toks[0].split('.')
         lat, lon, elevation, depth  =  [ float(x) for x in toks[1:] ]
         
         station = model.Station(net, sta, loc, lat, lon, elevation, depth=depth)
         stations.append(station)
         
     f.close()
     
     return stations
Beispiel #21
0
def gen_stations(nstations=5,
                 latmin=-90.,
                 latmax=90.,
                 lonmin=-180.,
                 lonmax=180.):

    stations = []
    for i in range(nstations):
        sta = 'S%02i' % i
        s = model.Station('',
                          sta,
                          '',
                          lat=randlat(latmin, latmax),
                          lon=rand(lonmin, lonmax))

        stations.append(s)

    return stations
Beispiel #22
0
def get_center_station(stations, select_closest=False):
    ''' gravitations center of *stations* list.'''
    n = len(stations)
    slats = num.empty(n)
    slons = num.empty(n)
    for i, s in enumerate(stations):
        slats[i] = s.lat
        slons[i] = s.lon

    center_lat, center_lon = ortho.geographic_midpoint(slats, slons)

    if select_closest:
        center_lats = num.ones(n) * center_lat
        center_lons = num.ones(n) * center_lon
        dists = ortho.distance_accurate50m_numpy(center_lats, center_lons,
                                                 slats, slons)

        return stations[num.argmin(dists)]
    else:
        return model.Station(center_lat, center_lon)
Beispiel #23
0
def pyrocko_station_from_channels(nsl, channels, inconsistencies='warn'):

    pos = lat, lon, elevation, depth = \
        channels[0].position_values

    if not all(pos == x.position_values for x in channels):
        info = '\n'.join('    %s: %s' % (x.code, x.position_values)
                         for x in channels)

        mess = 'encountered inconsistencies in channel ' \
               'lat/lon/elevation/depth ' \
               'for %s.%s.%s: \n%s' % (nsl + (info,))

        if inconsistencies == 'raise':
            raise InconsistentChannelLocations(mess)

        elif inconsistencies == 'warn':
            logger.warn(mess)
            logger.warn(' -> using mean values')

    apos = num.array([x.position_values for x in channels], dtype=num.float)
    mlat, mlon, mele, mdep = num.nansum(apos, axis=0) / num.sum(
        num.isfinite(apos), axis=0)

    pchannels = []
    for channel in channels:
        pchannels.append(
            model.Channel(channel.code,
                          azimuth=value_or_none(channel.azimuth),
                          dip=value_or_none(channel.dip)))

    return model.Station(*nsl,
                         lat=mlat,
                         lon=mlon,
                         elevation=mele,
                         depth=mdep,
                         channels=pchannels)
Beispiel #24
0
    def testProjections(self):
        km = 1000.

        ev = model.Event(lat=-10, lon=150., depth=0.0)

        for azi in num.linspace(0., 360., 37):
            lat, lon = orthodrome.ne_to_latlon(ev.lat, ev.lon,
                                               10. * km * math.cos(azi),
                                               10. * km * math.sin(azi))

            sta = model.Station(lat=lat, lon=lon)
            sta.set_event_relative_data(ev)
            sta.set_channels_by_name('BHZ', 'BHE', 'BHN')

            r = 1.
            t = 1.
            traces = [
                trace.Trace(channel='BHE',
                            ydata=num.array(
                                [math.sin(azi) * r + math.cos(azi) * t])),
                trace.Trace(channel='BHN',
                            ydata=num.array(
                                [math.cos(azi) * r - math.sin(azi) * t])),
            ]

            for m, in_channels, out_channels in sta.guess_projections_to_rtu():
                projected = trace.project(traces, m, in_channels, out_channels)

            def g(traces, cha):
                for tr in traces:
                    if tr.channel == cha:
                        return tr

            r = g(projected, 'R')
            t = g(projected, 'T')
            assert (near(r.ydata[0], 1.0, 0.001))
            assert (near(t.ydata[0], 1.0, 0.001))
Beispiel #25
0
def to_pyrocko_stations(inventory):
    '''
    Convert ObsPy inventory to list of Pyrocko traces.

    :param inventory:
        :py:class:`obspy.Inventory <obspy.core.inventory.inventory.Inventory>`
        object
    :returns:
        list of :py:class:`pyrocko.model.Station` objects or ``None`` if
        inventory is ``None``
    '''

    obspy_inventory = inventory

    if obspy_inventory is None:
        return None

    from pyrocko import model
    stations = []
    for net in obspy_inventory.networks:
        for sta in net.stations:
            stations.append(
                model.Station(lat=sta.latitude,
                              lon=sta.longitude,
                              elevation=sta.elevation,
                              network=net.code,
                              station=sta.code,
                              location='',
                              channels=[
                                  model.station.Channel(name=cha.code,
                                                        azimuth=cha.azimuth,
                                                        dip=cha.dip)
                                  for cha in sta.channels
                              ]))

    return stations
Beispiel #26
0
def  doCalc_syn (flag,Config,WaveformDict,FilterMetaData,Gmint,Gmaxt,TTTGridMap,
                Folder,Origin, ntimes, switch, ev,arrayfolder, syn_in, parameter):
    '''
    method for calculating semblance of one station array
    '''
    Logfile.add ('PROCESS %d %s' % (flag,' Enters Semblance Calculation') )
    Logfile.add ('MINT  : %f  MAXT: %f Traveltime' % (Gmint,Gmaxt))

    cfg = ConfigObj (dict=Config)

    dimX   = cfg.dimX()         # ('dimx')
    dimY   = cfg.dimY()         # ('dimy')
    winlen = cfg.winlen ()      # ('winlen')
    step   = cfg.step()         # ('step')

    new_frequence   = cfg.newFrequency()          #('new_frequence')
    forerun= cfg.Int('forerun')
    duration= cfg.Int('duration')
    gridspacing = cfg.Float('gridspacing')

    nostat = len (WaveformDict)
    traveltimes = {}
    recordstarttime = ''
    minSampleCount  = 999999999

    if cfg.UInt ('forerun')>0:
        ntimes = int ((cfg.UInt ('forerun') + cfg.UInt ('duration') ) / cfg.UInt ('step') )
    else:
        ntimes = int ((cfg.UInt ('duration') ) / cfg.UInt ('step') )
    nsamp  = int (winlen * new_frequence)
    nstep  = int (step   * new_frequence)
    from pyrocko import obspy_compat
    from pyrocko import orthodrome, model
    obspy_compat.plant()

    ############################################################################
    calcStreamMap = WaveformDict

    stations = []
    py_trs = []
    for trace in calcStreamMap.keys():
        py_tr = obspy_compat.to_pyrocko_trace(calcStreamMap[trace])
        py_trs.append(py_tr)
        for il in FilterMetaData:
            if str(il) == str(trace):
                        szo = model.Station(lat=il.lat, lon=il.lon,
                                            station=il.sta, network=il.net,
                                            channels=py_tr.channel,
                                            elevation=il.ele, location=il.loc)
                        stations.append(szo) #right number of stations?

    store_id = syn_in.store()
    engine = LocalEngine(store_superdirs=[syn_in.store_superdirs()])

    targets = []
    for st in stations:
        target = Target(
                lat=st.lat,
                lon=st.lon,
                store_id=store_id,
                codes=(st.network, st.station, st.location, 'BHZ'),
                tmin=-1900,
                tmax=3900,
                interpolation='multilinear',
                quantity=cfg.quantity())
        targets.append(target)

    if syn_in.nsources() == 1:
        if syn_in.use_specific_stf() is True:
            stf = syn_in.stf()
            exec(stf)
        else:
            stf = STF()
        if syn_in.source() == 'RectangularSource':
                source = RectangularSource(
                    lat=float(syn_in.lat_0()),
                    lon=float(syn_in.lon_0()),
                    depth=syn_in.depth_syn_0()*1000.,
                    strike=syn_in.strike_0(),
                    dip=syn_in.dip_0(),
                    rake=syn_in.rake_0(),
                    width=syn_in.width_0()*1000.,
                    length=syn_in.length_0()*1000.,
                    nucleation_x=syn_in.nucleation_x_0(),
                    slip=syn_in.slip_0(),
                    nucleation_y=syn_in.nucleation_y_0(),
                    stf=stf,
                    time=util.str_to_time(syn_in.time_0()))
        if syn_in.source() == 'DCSource':
                source = DCSource(
                    lat=float(syn_in.lat_0()),
                    lon=float(syn_in.lon_0()),
                    depth=syn_in.depth_syn_0()*1000.,
                    strike=syn_in.strike_0(),
                    dip=syn_in.dip_0(),
                    rake=syn_in.rake_0(),
                    stf=stf,
                    time=util.str_to_time(syn_in.time_0()),
                    magnitude=syn_in.magnitude_0())

    else:
        sources = []
        for i in range(syn_in.nsources()):
            if syn_in.use_specific_stf() is True:
                stf = syn_in.stf()
                exec(stf)

            else:
                stf = STF()
            if syn_in.source() == 'RectangularSource':
                    sources.append(RectangularSource(
                        lat=float(syn_in.lat_1(i)),
                        lon=float(syn_in.lon_1(i)),
                        depth=syn_in.depth_syn_1(i)*1000.,
                        strike=syn_in.strike_1(i),
                        dip=syn_in.dip_1(i),
                        rake=syn_in.rake_1(i),
                        width=syn_in.width_1(i)*1000.,
                        length=syn_in.length_1(i)*1000.,
                        nucleation_x=syn_in.nucleation_x_1(i),
                        slip=syn_in.slip_1(i),
                        nucleation_y=syn_in.nucleation_y_1(i),
                        stf=stf,
                        time=util.str_to_time(syn_in.time_1(i))))

            if syn_in.source() == 'DCSource':
                    sources.append(DCSource(
                        lat=float(syn_in.lat_1(i)),
                        lon=float(syn_in.lon_1(i)),
                        depth=syn_in.depth_1(i)*1000.,
                        strike=syn_in.strike_1(i),
                        dip=syn_in.dip_1(i),
                        rake=syn_in.rake_1(i),
                        stf=stf,
                        time=util.str_to_time(syn_in.time_1(i)),
                        magnitude=syn_in.magnitude_1(i)))
        source = CombiSource(subsources=sources)
    response = engine.process(source, targets)

    synthetic_traces = response.pyrocko_traces()
    if cfg.Bool('synthetic_test_add_noise') is True:
        from noise_addition import add_noise
        trs_orgs = []
        calcStreamMapsyn = calcStreamMap.copy()
        #from pyrocko import trace
        for tracex in calcStreamMapsyn.keys():
                for trl in synthetic_traces:
                    if str(trl.name()[4:12]) == str(tracex[4:]):
                        tr_org = obspy_compat.to_pyrocko_trace(calcStreamMapsyn[tracex])
                        tr_org.downsample_to(2.0)
                        trs_orgs.append(tr_org)
        store_id = syn_in.store()
        engine = LocalEngine(store_superdirs=[syn_in.store_superdirs()])
        synthetic_traces = add_noise(trs_orgs, engine, source.pyrocko_event(),
                                     stations,
                                     store_id, phase_def='P')
    trs_org = []
    trs_orgs = []
    fobj = os.path.join(arrayfolder, 'shift.dat')
    xy = num.loadtxt(fobj, usecols=1, delimiter=',')
    calcStreamMapsyn = calcStreamMap.copy()
    #from pyrocko import trace
    for tracex in calcStreamMapsyn.keys():
            for trl in synthetic_traces:
                if str(trl.name()[4:12])== str(tracex[4:]):
                    mod = trl

                    recordstarttime = calcStreamMapsyn[tracex].stats.starttime.timestamp
                    recordendtime = calcStreamMapsyn[tracex].stats.endtime.timestamp
                    tr_org = obspy_compat.to_pyrocko_trace(calcStreamMapsyn[tracex])
                    trs_orgs.append(tr_org)

                    tr_org_add = mod.chop(recordstarttime, recordendtime, inplace=False)
                    synthetic_obs_tr = obspy_compat.to_obspy_trace(tr_org_add)
                    calcStreamMapsyn[tracex] = synthetic_obs_tr
                    trs_org.append(tr_org_add)
    calcStreamMap = calcStreamMapsyn

    if cfg.Bool('shift_by_phase_pws') == True:
        calcStreamMapshifted= calcStreamMap.copy()
        from obspy.core import stream
        stream = stream.Stream()
        for trace in calcStreamMapshifted.keys():
            stream.append(calcStreamMapshifted[trace])
        pws_stack = PWS_stack([stream], weight=2, normalize=True)
        for tr in pws_stack:
            for trace in calcStreamMapshifted.keys():
                    calcStreamMapshifted[trace]=tr
        calcStreamMap = calcStreamMapshifted


    if cfg.Bool('shift_by_phase_onset') == True:
        pjoin = os.path.join
        timeev = util.str_to_time(ev.time)
        trs_orgs= []
        calcStreamMapshifted= calcStreamMap.copy()
        for trace in calcStreamMapshifted.keys():
                tr_org = obspy_compat.to_pyrocko_trace(calcStreamMapshifted[trace])
                trs_orgs.append(tr_org)

        timing = CakeTiming(
           phase_selection='first(p|P|PP|P(cmb)P(icb)P(icb)p(cmb)p)-20',
           fallback_time=100.)
        traces = trs_orgs

        event = model.Event(lat=float(ev.lat), lon=float(ev.lon), depth=ev.depth*1000., time=timeev)
        directory = arrayfolder
        bf = BeamForming(stations, traces, normalize=True)
        shifted_traces = bf.process(event=event,
                  timing=timing,
                  fn_dump_center=pjoin(directory, 'array_center.pf'),
                  fn_beam=pjoin(directory, 'beam.mseed'))
        i = 0
        store_id = syn_in.store()
        engine = LocalEngine(store_superdirs=[syn_in.store_superdirs()])
        for trace in calcStreamMapshifted.keys():
            recordstarttime = calcStreamMapshifted[trace].stats.starttime.timestamp
            recordendtime = calcStreamMapshifted[trace].stats.endtime.timestamp
            mod = shifted_traces[i]
            extracted = mod.chop(recordstarttime, recordendtime, inplace=False)
            shifted_obs_tr = obspy_compat.to_obspy_trace(extracted)
            calcStreamMapshifted[trace]=shifted_obs_tr
            i = i+1

        calcStreamMap = calcStreamMapshifted


    weight = 0.
    if cfg.Bool('weight_by_noise') == True:
        from noise_analyser import analyse
        pjoin = os.path.join
        timeev = util.str_to_time(ev.time)
        trs_orgs= []
        calcStreamMapshifted= calcStreamMap.copy()
        for trace in calcStreamMapshifted.keys():
                tr_org = obspy_compat.to_pyrocko_trace(calcStreamMapshifted[trace])
                trs_orgs.append(tr_org)

        timing = CakeTiming(
           phase_selection='first(p|P|PP|P(cmb)P(icb)P(icb)p(cmb)p)-20',
           fallback_time=100.)
        traces = trs_orgs
        event = model.Event(lat=float(ev.lat), lon=float(ev.lon), depth=ev.depth*1000., time=timeev)
        directory = arrayfolder
        bf = BeamForming(stations, traces, normalize=True)
        shifted_traces = bf.process(event=event,
                  timing=timing,
                  fn_dump_center=pjoin(directory, 'array_center.pf'),
                  fn_beam=pjoin(directory, 'beam.mseed'))
        i = 0
        store_id = syn_in.store()
        engine = LocalEngine(store_superdirs=[syn_in.store_superdirs()])
        weight = analyse(shifted_traces, engine, event, stations,
         100., store_id, nwindows=1,
         check_events=True, phase_def='P')

    for trace in calcStreamMap.keys():
        recordstarttime = calcStreamMap[trace].stats.starttime
        d = calcStreamMap[trace].stats.starttime
        d = d.timestamp

        if calcStreamMap[trace].stats.npts < minSampleCount:
            minSampleCount = calcStreamMap[trace].stats.npts

    ############################################################################
    traces = num.ndarray (shape=(len(calcStreamMap), minSampleCount), dtype=float)
    traveltime = num.ndarray (shape=(len(calcStreamMap), dimX*dimY), dtype=float)
    latv   = num.ndarray (dimX*dimY, dtype=float)
    lonv   = num.ndarray (dimX*dimY, dtype=float)
    ############################################################################


    c=0
    streamCounter = 0

    for key in calcStreamMap.keys():
        streamID = key
        c2   = 0

        for o in calcStreamMap[key]:
            if c2 < minSampleCount:
                traces[c][c2] = o

                c2 += 1


        for key in TTTGridMap.keys():

            if streamID == key:
                traveltimes[streamCounter] = TTTGridMap[key]
            else:
                "NEIN", streamID, key


        if not streamCounter in traveltimes :
           continue                              #hs : thread crashed before

        g = traveltimes[streamCounter]
        dimZ  = g.dimZ
        mint  = g.mint
        maxt  = g.maxt
        Latul = g.Latul
        Lonul = g.Lonul
        Lator = g.Lator
        Lonor = g.Lonor

        gridElem = g.GridArray

        for x in range(dimX):
            for y in range(dimY):
                elem = gridElem[x, y]

                traveltime [c][x * dimY + y] = elem.tt
                latv [x * dimY + y] = elem.lat
                lonv [x * dimY + y] = elem.lon
        #endfor

        c += 1
        streamCounter += 1

    #endfor


    ############################## CALCULATE PARAMETER FOR SEMBLANCE CALCULATION ##################
    nsamp = winlen * new_frequence

    nstep = int (step*new_frequence)
    migpoints = dimX * dimY

    dimZ = 0
    new_frequence = cfg.newFrequency ()              # ['new_frequence']
    maxp = int (Config['ncore'])


    Logfile.add ('PROCESS %d  NTIMES: %d' % (flag,ntimes))

    if False :
       print ('nostat ',nostat,type(nostat))
       print ('nsamp ',nsamp,type(nsamp))
       print ('ntimes ',ntimes,type(ntimes))
       print ('nstep ',nstep,type(nstep))
       print ('dimX ',dimX,type(dimX))
       print ('dimY ',dimY,type(dimY))
       print ('mint ',Gmint,type(mint))
       print ('new_freq ',new_frequence,type(new_frequence))
       print ('minSampleCount ',minSampleCount,type(minSampleCount))
       print ('latv ',latv,type(latv))
       print ('traces',traces,type(traces))
       print ('traveltime',traveltime,type(traveltime))


#==================================semblance calculation========================================

    t1 = time.time()
    traces = traces.reshape   (1,nostat*minSampleCount)
    traveltime = traveltime.reshape (1,nostat*dimX*dimY)
    USE_C_CODE = True
    try:
        if USE_C_CODE :
            import Cm
            import CTrig
            start_time = time.time()
            k  = Cm.otest (maxp,nostat,nsamp,ntimes,nstep,dimX,dimY,Gmint,new_frequence,
                          minSampleCount,latv,lonv,traveltime,traces)
            print("--- %s seconds ---" % (time.time() - start_time))
        else :
            start_time = time.time()
            k = otest (maxp,nostat,nsamp,ntimes,nstep,dimX,dimY,Gmint,new_frequence,
                      minSampleCount,latv,lonv,traveltime,traces)                       #hs
            print("--- %s seconds ---" % (time.time() - start_time))
    except:
        print("loaded tttgrid has probably wrong dimensions or stations, delete\
                ttgrid or exchange")

    t2 = time.time()


    partSemb = k

    partSemb_syn  = partSemb.reshape (ntimes,migpoints)


    return partSemb_syn
Beispiel #27
0
    def get_pyrocko_stations(self,
                             nslcs=None,
                             nsls=None,
                             time=None,
                             timespan=None,
                             inconsistencies='warn'):

        assert inconsistencies in ('raise', 'warn')

        if nslcs is not None:
            nslcs = set(nslcs)

        if nsls is not None:
            nsls = set(nsls)

        tt = ()
        if time is not None:
            tt = (time, )
        elif timespan is not None:
            tt = timespan

        pstations = []
        for network in self.network_list:
            if not network.spans(*tt):
                continue

            for station in network.station_list:
                if not station.spans(*tt):
                    continue

                if station.channel_list:
                    loc_to_channels = {}
                    for channel in station.channel_list:
                        if not channel.spans(*tt):
                            continue

                        loc = channel.location_code.strip()
                        if loc not in loc_to_channels:
                            loc_to_channels[loc] = []

                        loc_to_channels[loc].append(channel)

                    for loc in sorted(loc_to_channels.keys()):
                        channels = loc_to_channels[loc]
                        if nslcs is not None:
                            channels = [
                                channel for channel in channels
                                if (network.code, station.code, loc,
                                    channel.code) in nslcs
                            ]

                        if not channels:
                            continue

                        nsl = network.code, station.code, loc
                        if nsls is not None and nsl not in nsls:
                            continue

                        pstations.append(
                            pyrocko_station_from_channels(
                                nsl, channels,
                                inconsistencies=inconsistencies))
                else:
                    pstations.append(
                        model.Station(network.code,
                                      station.code,
                                      '*',
                                      lat=station.latitude.value,
                                      lon=station.longitude.value,
                                      elevation=value_or_none(
                                          station.elevation),
                                      name=station.description or ''))

        return pstations
from pyrocko import orthodrome, model

e = model.Event(lat=10., lon=20.)
s = model.Station(lat=15., lon=120.)

# one possibility:
d = orthodrome.distance_accurate50m(e, s)
print('Distance between e and s is %g km' % (d / 1000.))

# another possibility:
s.set_event_relative_data(e)
print('Distance between e and s is %g km' % (s.dist_m / 1000.))
    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 #30
0
    def call(self):
        '''Main work routine of the snuffling.'''
        self.cleanup()

        # get time range visible in viewer
        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=self.lat, lon=self.lon)
            event = model.Event(lat=0., lon=0.)
            stations = []

        stations = self.get_stations()

        s2c = {}
        for traces in self.chopper_selected_traces(fallback=True,
                                                   mode='visible'):
            for tr in traces:
                net, sta, loc, cha = tr.nslc_id
                ns = net, sta
                if ns not in s2c:
                    s2c[ns] = set()

                s2c[ns].add((loc, cha))

        if not stations:
            stations = []
            for (lat, lon) in [(5., 0.), (-5., 0.)]:
                s = model.Station(station='(%g, %g)' % (lat, lon),
                                  lat=lat,
                                  lon=lon)
                stations.append(s)
                viewer.add_stations(stations)

        for s in stations:
            ns = s.nsl()[:2]
            if ns not in s2c:
                s2c[ns] = set()

            for cha in 'NEZ':
                s2c[ns].add(('', cha))

        source = gf.RectangularSource(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=self.magnitude,
                                      strike=self.strike,
                                      dip=self.dip,
                                      rake=self.rake,
                                      length=self.length,
                                      width=self.width,
                                      nucleation_x=self.nucleation_x,
                                      velocity=self.velocity,
                                      stf=self.get_stf())

        source.regularize()

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

        targets = []

        if self.store_id == '<not loaded yet>':
            self.fail('Select a GF Store first')

        for station in stations:

            nsl = station.nsl()
            if nsl[:2] not in s2c:
                continue

            for loc, cha in s2c[nsl[:2]]:

                target = gf.Target(codes=(station.network, station.station,
                                          loc + '-syn', cha),
                                   quantity='displacement',
                                   lat=station.lat,
                                   lon=station.lon,
                                   depth=station.depth,
                                   store_id=self.store_id,
                                   optimization='enable',
                                   interpolation='nearest_neighbor')

                _, bazi = source.azibazi_to(target)

                if cha.endswith('T'):
                    dip = 0.
                    azi = bazi + 270.
                elif cha.endswith('R'):
                    dip = 0.
                    azi = bazi + 180.
                elif cha.endswith('1'):
                    dip = 0.
                    azi = 0.
                elif cha.endswith('2'):
                    dip = 0.
                    azi = 90.
                else:
                    dip = None
                    azi = None

                target.azimuth = azi
                target.dip = dip

                targets.append(target)

        req = gf.Request(sources=[source], targets=targets)

        req.regularize()

        try:
            resp = self.get_engine().process(req)
        except (gf.meta.OutOfBounds, gf.store_ext.StoreExtError) as e:
            self.fail(e)

        traces = resp.pyrocko_traces()

        if self.waveform_type.startswith('Velocity'):
            for tr in traces:
                tr.set_ydata(num.diff(tr.ydata) / tr.deltat)

        elif self.waveform_type.startswith('Acceleration'):
            for tr in traces:
                tr.set_ydata(num.diff(num.diff(tr.ydata)) / tr.deltat**2)

        if self.waveform_type.endswith('[nm]') or \
                self.waveform_type.endswith('[nm/s]') or \
                self.waveform_type.endswith('[nm/s^2]'):

            for tr in traces:
                tr.set_ydata(tr.ydata * 1e9)

        self.add_traces(traces)